Unnamed: 0
int64 0
6.45k
| func
stringlengths 37
161k
| target
class label 2
classes | project
stringlengths 33
167
|
---|---|---|---|
514 |
public class SystemTime {
private static final TimeSource defaultTimeSource = new DefaultTimeSource();
private static TimeSource globalTimeSource = null;
private static final InheritableThreadLocal<TimeSource> localTimeSource = new InheritableThreadLocal<TimeSource>();
public static TimeSource getTimeSource() {
TimeSource applicableTimeSource;
TimeSource localTS = localTimeSource.get();
if (localTS != null) {
applicableTimeSource = localTS;
} else if (globalTimeSource != null) {
applicableTimeSource = globalTimeSource;
} else {
applicableTimeSource = defaultTimeSource;
}
return applicableTimeSource;
}
public static void setGlobalTimeSource(final TimeSource globalTS) {
SystemTime.globalTimeSource = globalTS;
}
public static void resetGlobalTimeSource() {
setGlobalTimeSource(null);
}
public static void setLocalTimeSource(final TimeSource localTS) {
SystemTime.localTimeSource.set(localTS);
}
public static void resetLocalTimeSource() {
SystemTime.localTimeSource.remove();
}
public static void reset() {
resetGlobalTimeSource();
resetLocalTimeSource();
}
public static long asMillis() {
return asMillis(true);
}
public static long asMillis(boolean includeTime) {
if (includeTime) {
return getTimeSource().timeInMillis();
}
return asCalendar(includeTime).getTimeInMillis();
}
public static Date asDate() {
return asDate(true);
}
public static Date asDate(boolean includeTime) {
if (includeTime) {
return new Date(asMillis());
}
return asCalendar(includeTime).getTime();
}
public static Calendar asCalendar() {
return asCalendar(true);
}
public static Calendar asCalendar(boolean includeTime) {
return asCalendar(Locale.getDefault(), TimeZone.getDefault(), includeTime);
}
public static Calendar asCalendar(Locale locale) {
return asCalendar(locale, TimeZone.getDefault(), true);
}
public static Calendar asCalendar(TimeZone timeZone) {
return asCalendar(Locale.getDefault(), timeZone, true);
}
/**
* Returns false if the current time source is a {@link FixedTimeSource} indicating that the
* time is being overridden. For example to preview items in a later time.
*
* @return
*/
public static boolean shouldCacheDate() {
if (SystemTime.getTimeSource() instanceof FixedTimeSource) {
return false;
} else {
return true;
}
}
/**
* Many DAO objects in Broadleaf use a cached time concept. Since most entities have an active
* start and end date, the DAO may ask for a representation of "NOW" that is within some
* threshold.
*
* By default, most entities cache active-date queries to every 10 seconds. These DAO
* classes can be overridden to extend or decrease this default.
*
* @return
*/
public static Date getCurrentDateWithinTimeResolution(Date cachedDate, Long dateResolutionMillis) {
Date returnDate = SystemTime.asDate();
if (cachedDate == null || (SystemTime.getTimeSource() instanceof FixedTimeSource)) {
return returnDate;
}
if (returnDate.getTime() > (cachedDate.getTime() + dateResolutionMillis)) {
return returnDate;
} else {
return cachedDate;
}
}
public static Calendar asCalendar(Locale locale, TimeZone timeZone, boolean includeTime) {
Calendar calendar = Calendar.getInstance(timeZone, locale);
calendar.setTimeInMillis(asMillis());
if (!includeTime) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
}
return calendar;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_time_SystemTime.java
|
3,207 |
public class ReplicatedMapDataSerializerHook
implements DataSerializerHook {
public static final int F_ID = FactoryIdHelper.getFactoryId(FactoryIdHelper.REPLICATED_MAP_DS_FACTORY, -22);
public static final int VECTOR = 0;
public static final int RECORD = 1;
public static final int REPL_UPDATE_MESSAGE = 2;
public static final int REPL_CLEAR_MESSAGE = 3;
public static final int REPL_MULTI_UPDATE_MESSAGE = 4;
public static final int OP_INIT_CHUNK = 5;
public static final int OP_POST_JOIN = 6;
public static final int OP_CLEAR = 7;
public static final int MAP_STATS = 8;
private static final int LEN = MAP_STATS + 1;
@Override
public int getFactoryId() {
return F_ID;
}
@Override
public DataSerializableFactory createFactory() {
ConstructorFunction<Integer, IdentifiedDataSerializable>[] constructors = new ConstructorFunction[LEN];
constructors[VECTOR] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new VectorClock();
}
};
constructors[RECORD] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new ReplicatedRecord();
}
};
constructors[REPL_UPDATE_MESSAGE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new ReplicationMessage();
}
};
constructors[REPL_CLEAR_MESSAGE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new VectorClock();
}
};
constructors[REPL_MULTI_UPDATE_MESSAGE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
@Override
public IdentifiedDataSerializable createNew(Integer arg) {
return new MultiReplicationMessage();
}
};
constructors[OP_INIT_CHUNK] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
@Override
public IdentifiedDataSerializable createNew(Integer arg) {
return new ReplicatedMapInitChunkOperation();
}
};
constructors[OP_POST_JOIN] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
@Override
public IdentifiedDataSerializable createNew(Integer arg) {
return new ReplicatedMapPostJoinOperation();
}
};
constructors[OP_CLEAR] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
@Override
public IdentifiedDataSerializable createNew(Integer arg) {
return new ReplicatedMapClearOperation();
}
};
constructors[MAP_STATS] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
@Override
public IdentifiedDataSerializable createNew(Integer arg) {
return new LocalReplicatedMapStatsImpl();
}
};
return new ArrayDataSerializableFactory(constructors);
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_replicatedmap_operation_ReplicatedMapDataSerializerHook.java
|
1,234 |
public interface AdminClient {
/**
* A client allowing to perform actions/operations against the cluster.
*/
ClusterAdminClient cluster();
/**
* A client allowing to perform actions/operations against the indices.
*/
IndicesAdminClient indices();
}
| 0true
|
src_main_java_org_elasticsearch_client_AdminClient.java
|
737 |
public class CollectionRemoveRequest extends CollectionRequest {
private Data value;
public CollectionRemoveRequest() {
}
public CollectionRemoveRequest(String name, Data value) {
super(name);
this.value = value;
}
@Override
protected Operation prepareOperation() {
return new CollectionRemoveOperation(name, value);
}
@Override
public int getClassId() {
return CollectionPortableHook.COLLECTION_REMOVE;
}
public void write(PortableWriter writer) throws IOException {
super.write(writer);
value.writeData(writer.getRawDataOutput());
}
public void read(PortableReader reader) throws IOException {
super.read(reader);
value = new Data();
value.readData(reader.getRawDataInput());
}
@Override
public String getRequiredAction() {
return ActionConstants.ACTION_REMOVE;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_client_CollectionRemoveRequest.java
|
537 |
executorService.execute(new Runnable() {
public void run() {
try {
txn(client);
} catch (Exception e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_txn_ClientXaTest.java
|
1,329 |
@ClusterScope(scope = Scope.TEST, numNodes = 0)
public class SpecificMasterNodesTests extends ElasticsearchIntegrationTest {
protected final ImmutableSettings.Builder settingsBuilder() {
return ImmutableSettings.builder().put("discovery.type", "zen");
}
@Test
public void simpleOnlyMasterNodeElection() {
logger.info("--> start data node / non master node");
cluster().startNode(settingsBuilder().put("node.data", true).put("node.master", false).put("discovery.initial_state_timeout", "1s"));
try {
assertThat(client().admin().cluster().prepareState().setMasterNodeTimeout("100ms").execute().actionGet().getState().nodes().masterNodeId(), nullValue());
fail("should not be able to find master");
} catch (MasterNotDiscoveredException e) {
// all is well, no master elected
}
logger.info("--> start master node");
final String masterNodeName = cluster().startNode(settingsBuilder().put("node.data", false).put("node.master", true));
assertThat(cluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(masterNodeName));
assertThat(cluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(masterNodeName));
logger.info("--> stop master node");
cluster().stopCurrentMasterNode();
try {
assertThat(client().admin().cluster().prepareState().setMasterNodeTimeout("100ms").execute().actionGet().getState().nodes().masterNodeId(), nullValue());
fail("should not be able to find master");
} catch (MasterNotDiscoveredException e) {
// all is well, no master elected
}
logger.info("--> start master node");
final String nextMasterEligableNodeName = cluster().startNode(settingsBuilder().put("node.data", false).put("node.master", true));
assertThat(cluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(nextMasterEligableNodeName));
assertThat(cluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(nextMasterEligableNodeName));
}
@Test
public void electOnlyBetweenMasterNodes() {
logger.info("--> start data node / non master node");
cluster().startNode(settingsBuilder().put("node.data", true).put("node.master", false).put("discovery.initial_state_timeout", "1s"));
try {
assertThat(client().admin().cluster().prepareState().setMasterNodeTimeout("100ms").execute().actionGet().getState().nodes().masterNodeId(), nullValue());
fail("should not be able to find master");
} catch (MasterNotDiscoveredException e) {
// all is well, no master elected
}
logger.info("--> start master node (1)");
final String masterNodeName = cluster().startNode(settingsBuilder().put("node.data", false).put("node.master", true));
assertThat(cluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(masterNodeName));
assertThat(cluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(masterNodeName));
logger.info("--> start master node (2)");
final String nextMasterEligableNodeName = cluster().startNode(settingsBuilder().put("node.data", false).put("node.master", true));
assertThat(cluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(masterNodeName));
assertThat(cluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(masterNodeName));
assertThat(cluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(masterNodeName));
logger.info("--> closing master node (1)");
cluster().stopCurrentMasterNode();
assertThat(cluster().nonMasterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(nextMasterEligableNodeName));
assertThat(cluster().masterClient().admin().cluster().prepareState().execute().actionGet().getState().nodes().masterNode().name(), equalTo(nextMasterEligableNodeName));
}
/**
* Tests that putting custom default mapping and then putting a type mapping will have the default mapping merged
* to the type mapping.
*/
@Test
public void testCustomDefaultMapping() throws Exception {
logger.info("--> start master node / non data");
cluster().startNode(settingsBuilder().put("node.data", false).put("node.master", true));
logger.info("--> start data node / non master node");
cluster().startNode(settingsBuilder().put("node.data", true).put("node.master", false));
assertAcked(client().admin().indices().prepareCreate("test").setSettings("number_of_shards", 1).get());
assertAcked(client().admin().indices().preparePutMapping("test").setType("_default_").setSource("_timestamp", "enabled=true"));
MappingMetaData defaultMapping = client().admin().cluster().prepareState().get().getState().getMetaData().getIndices().get("test").getMappings().get("_default_");
assertThat(defaultMapping.getSourceAsMap().get("_timestamp"), notNullValue());
assertAcked(client().admin().indices().preparePutMapping("test").setType("_default_").setSource("_timestamp", "enabled=true"));
assertAcked(client().admin().indices().preparePutMapping("test").setType("type1").setSource("foo", "enabled=true"));
MappingMetaData type1Mapping = client().admin().cluster().prepareState().get().getState().getMetaData().getIndices().get("test").getMappings().get("type1");
assertThat(type1Mapping.getSourceAsMap().get("_timestamp"), notNullValue());
}
@Test
public void testAliasFilterValidation() throws Exception {
logger.info("--> start master node / non data");
cluster().startNode(settingsBuilder().put("node.data", false).put("node.master", true));
logger.info("--> start data node / non master node");
cluster().startNode(settingsBuilder().put("node.data", true).put("node.master", false));
assertAcked(prepareCreate("test").addMapping("type1", "{\"type1\" : {\"properties\" : {\"table_a\" : { \"type\" : \"nested\", \"properties\" : {\"field_a\" : { \"type\" : \"string\" },\"field_b\" :{ \"type\" : \"string\" }}}}}}"));
client().admin().indices().prepareAliases().addAlias("test", "a_test", FilterBuilders.nestedFilter("table_a", FilterBuilders.termFilter("table_a.field_b", "y"))).get();
}
}
| 0true
|
src_test_java_org_elasticsearch_cluster_SpecificMasterNodesTests.java
|
683 |
constructors[COLLECTION_REMOVE_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new CollectionRemoveBackupOperation();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
|
1,479 |
public class OSQLFunctionOut extends OSQLFunctionMove {
public static final String NAME = "out";
public OSQLFunctionOut() {
super(NAME, 0, -1);
}
@Override
protected Object move(final OrientBaseGraph graph, final OIdentifiable iRecord, final String[] iLabels) {
return v2v(graph, iRecord, Direction.OUT, iLabels);
}
}
| 1no label
|
graphdb_src_main_java_com_orientechnologies_orient_graph_sql_functions_OSQLFunctionOut.java
|
1,557 |
public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> {
private Collection<Long> ids;
@Override
public void setup(final Mapper.Context context) throws IOException, InterruptedException {
//todo: make as list and double up repeats
this.ids = VertexMap.Map.getLongCollection(context.getConfiguration(), IDS, new HashSet<Long>());
}
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException {
if (this.ids.contains(value.getLongId())) {
value.startPath();
DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_PROCESSED, 1L);
} else {
value.clearPaths();
}
context.write(NullWritable.get(), value);
}
private static Collection<Long> getLongCollection(final Configuration conf, final String key, final Collection<Long> collection) {
for (final String value : conf.getStrings(key)) {
collection.add(Long.valueOf(value));
}
return collection;
}
}
| 1no label
|
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_transform_VertexMap.java
|
832 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_ORDER_ITEM_DTL_ADJ")
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements")
@AdminPresentationMergeOverrides(
{
@AdminPresentationMergeOverride(name = "", mergeEntries =
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.READONLY,
booleanOverrideValue = true))
}
)
public class OrderItemPriceDetailAdjustmentImpl implements OrderItemPriceDetailAdjustment, CurrencyCodeIdentifiable {
public static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "OrderItemPriceDetailAdjustmentId")
@GenericGenerator(
name = "OrderItemPriceDetailAdjustmentId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name = "segment_value", value = "OrderItemPriceDetailAdjustmentImpl"),
@Parameter(name = "entity_name", value = "org.broadleafcommerce.core.offer.domain.OrderItemPriceDetailAdjustmentImpl")
}
)
@Column(name = "ORDER_ITEM_DTL_ADJ_ID")
protected Long id;
@ManyToOne(targetEntity = OrderItemPriceDetailImpl.class)
@JoinColumn(name = "ORDER_ITEM_PRICE_DTL_ID")
@AdminPresentation(excluded = true)
protected OrderItemPriceDetail orderItemPriceDetail;
@ManyToOne(targetEntity = OfferImpl.class, optional=false)
@JoinColumn(name = "OFFER_ID")
@AdminPresentation(friendlyName = "OrderItemPriceDetailAdjustmentImpl_Offer", order=1000,
prominent = true, gridOrder = 1000)
@AdminPresentationToOneLookup()
protected Offer offer;
@Column(name = "OFFER_NAME")
protected String offerName;
@Column(name = "ADJUSTMENT_REASON", nullable=false)
@AdminPresentation(friendlyName = "OrderItemPriceDetailAdjustmentImpl_reason", order = 1,
group = "OrderItemPriceDetailAdjustmentImpl_Description")
protected String reason;
@Column(name = "ADJUSTMENT_VALUE", nullable=false, precision=19, scale=5)
@AdminPresentation(friendlyName = "OrderItemPriceDetailAdjustmentImpl_value", order = 2,
group = "OrderItemPriceDetailAdjustmentImpl_Description", fieldType = SupportedFieldType.MONEY, prominent = true)
protected BigDecimal value = Money.ZERO.getAmount();
@Column(name = "APPLIED_TO_SALE_PRICE")
@AdminPresentation(friendlyName = "OrderItemPriceDetailAdjustmentImpl_appliedToSalePrice", order = 3,
group = "OrderItemPriceDetailAdjustmentImpl_Description")
protected boolean appliedToSalePrice;
@Transient
protected Money retailValue;
@Transient
protected Money salesValue;
@Override
public void init(OrderItemPriceDetail orderItemPriceDetail, Offer offer, String reason) {
this.orderItemPriceDetail = orderItemPriceDetail;
setOffer(offer);
if (reason == null) {
this.reason = reason;
this.reason = offer.getName();
}
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public OrderItemPriceDetail getOrderItemPriceDetail() {
return orderItemPriceDetail;
}
@Override
public Offer getOffer() {
return offer;
}
@Override
public String getOfferName() {
return offerName;
}
@Override
public String getReason() {
return reason;
}
@Override
public void setReason(String reason) {
this.reason = reason;
}
@Override
public void setOrderItemPriceDetail(OrderItemPriceDetail orderItemPriceDetail) {
this.orderItemPriceDetail = orderItemPriceDetail;
}
public void setOffer(Offer offer) {
this.offer = offer;
if (offer != null) {
this.offerName = offer.getMarketingMessage() != null ? offer.getMarketingMessage() : offer.getName();
}
}
@Override
public void setOfferName(String offerName) {
this.offerName = offer.getName();
}
protected BroadleafCurrency getCurrency() {
return getOrderItemPriceDetail().getOrderItem().getOrder().getCurrency();
}
@Override
public Money getValue() {
return value == null ? null : BroadleafCurrencyUtils.getMoney(value, getCurrency());
}
@Override
public void setValue(Money value) {
this.value = value.getAmount();
}
@Override
public boolean isAppliedToSalePrice() {
return appliedToSalePrice;
}
@Override
public void setAppliedToSalePrice(boolean appliedToSalePrice) {
this.appliedToSalePrice = appliedToSalePrice;
}
@Override
public Money getRetailPriceValue() {
if (retailValue == null) {
return BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, getCurrency());
}
return this.retailValue;
}
@Override
public void setRetailPriceValue(Money retailPriceValue) {
this.retailValue = retailPriceValue;
}
@Override
public Money getSalesPriceValue() {
if (salesValue == null) {
return BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, getCurrency());
}
return salesValue;
}
@Override
public void setSalesPriceValue(Money salesPriceValue) {
this.salesValue = salesPriceValue;
}
@Override
public String getCurrencyCode() {
if (getCurrency() != null) {
return getCurrency().getCurrencyCode();
}
return null;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((offer == null) ? 0 : offer.hashCode());
result = prime * result + ((orderItemPriceDetail == null) ? 0 : orderItemPriceDetail.hashCode());
result = prime * result + ((reason == null) ? 0 : reason.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
OrderItemPriceDetailAdjustmentImpl other = (OrderItemPriceDetailAdjustmentImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (offer == null) {
if (other.offer != null) {
return false;
}
} else if (!offer.equals(other.offer)) {
return false;
}
if (orderItemPriceDetail == null) {
if (other.orderItemPriceDetail != null) {
return false;
}
} else if (!orderItemPriceDetail.equals(other.orderItemPriceDetail)) {
return false;
}
if (reason == null) {
if (other.reason != null) {
return false;
}
} else if (!reason.equals(other.reason)) {
return false;
}
if (value == null) {
if (other.value != null) {
return false;
}
} else if (!value.equals(other.value)) {
return false;
}
return true;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_OrderItemPriceDetailAdjustmentImpl.java
|
29 |
static final class ThenAcceptBoth<T,U> extends Completion {
final CompletableFuture<? extends T> src;
final CompletableFuture<? extends U> snd;
final BiAction<? super T,? super U> fn;
final CompletableFuture<Void> dst;
final Executor executor;
ThenAcceptBoth(CompletableFuture<? extends T> src,
CompletableFuture<? extends U> snd,
BiAction<? super T,? super U> fn,
CompletableFuture<Void> dst,
Executor executor) {
this.src = src; this.snd = snd;
this.fn = fn; this.dst = dst;
this.executor = executor;
}
public final void run() {
final CompletableFuture<? extends T> a;
final CompletableFuture<? extends U> b;
final BiAction<? super T,? super U> fn;
final CompletableFuture<Void> dst;
Object r, s; T t; U u; Throwable ex;
if ((dst = this.dst) != null &&
(fn = this.fn) != null &&
(a = this.src) != null &&
(r = a.result) != null &&
(b = this.snd) != null &&
(s = b.result) != null &&
compareAndSet(0, 1)) {
if (r instanceof AltResult) {
ex = ((AltResult)r).ex;
t = null;
}
else {
ex = null;
@SuppressWarnings("unchecked") T tr = (T) r;
t = tr;
}
if (ex != null)
u = null;
else if (s instanceof AltResult) {
ex = ((AltResult)s).ex;
u = null;
}
else {
@SuppressWarnings("unchecked") U us = (U) s;
u = us;
}
Executor e = executor;
if (ex == null) {
try {
if (e != null)
e.execute(new AsyncAcceptBoth<T,U>(t, u, fn, dst));
else
fn.accept(t, u);
} catch (Throwable rex) {
ex = rex;
}
}
if (e == null || ex != null)
dst.internalComplete(null, ex);
}
}
private static final long serialVersionUID = 5232453952276885070L;
}
| 0true
|
src_main_java_jsr166e_CompletableFuture.java
|
515 |
public class OConfigurationException extends OException {
private static final long serialVersionUID = -8486291378415776372L;
public OConfigurationException(String message, Throwable cause) {
super(message, cause);
}
public OConfigurationException(String message) {
super(message);
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_exception_OConfigurationException.java
|
131 |
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(1, clientService.getConnectedClients().size());
}
}, 4);
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_ClientServiceTest.java
|
166 |
public interface URLHandler extends Serializable{
public abstract Long getId();
public abstract void setId(Long id);
public abstract String getIncomingURL();
public abstract void setIncomingURL(String incomingURL);
public abstract String getNewURL();
public abstract void setNewURL(String newURL);
public abstract URLRedirectType getUrlRedirectType();
public void setUrlRedirectType(URLRedirectType redirectType);
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_url_domain_URLHandler.java
|
141 |
final class GenericClientExceptionConverter implements ClientExceptionConverter {
@Override
public Object convert(Throwable t) {
StringWriter s = new StringWriter();
t.printStackTrace(new PrintWriter(s));
String clazzName = t.getClass().getName();
return new GenericError(clazzName, t.getMessage(), s.toString(), 0);
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_client_GenericClientExceptionConverter.java
|
263 |
@Service("blEmailService")
public class EmailServiceImpl implements EmailService {
@Resource(name = "blEmailTrackingManager")
protected EmailTrackingManager emailTrackingManager;
@Resource(name = "blServerInfo")
protected ServerInfo serverInfo;
protected EmailServiceProducer emailServiceProducer;
@Resource(name = "blMessageCreator")
protected MessageCreator messageCreator;
@Resource(name = "blEmailReportingDao")
protected EmailReportingDao emailReportingDao;
public boolean sendTemplateEmail(EmailTarget emailTarget, EmailInfo emailInfo, HashMap<String, Object> props) {
if (props == null) {
props = new HashMap<String, Object>();
}
if (emailInfo == null) {
emailInfo = new EmailInfo();
}
props.put(EmailPropertyType.INFO.getType(), emailInfo);
props.put(EmailPropertyType.USER.getType(), emailTarget);
Long emailId = emailTrackingManager.createTrackedEmail(emailTarget.getEmailAddress(), emailInfo.getEmailType(), null);
props.put("emailTrackingId", emailId);
return sendBasicEmail(emailInfo, emailTarget, props);
}
public boolean sendTemplateEmail(String emailAddress, EmailInfo emailInfo, HashMap<String, Object> props) {
if (!(emailInfo instanceof NullEmailInfo)) {
EmailTarget emailTarget = emailReportingDao.createTarget();
emailTarget.setEmailAddress(emailAddress);
return sendTemplateEmail(emailTarget, emailInfo, props);
} else {
return true;
}
}
public boolean sendBasicEmail(EmailInfo emailInfo, EmailTarget emailTarget, HashMap<String, Object> props) {
if (props == null) {
props = new HashMap<String, Object>();
}
if (emailInfo == null) {
emailInfo = new EmailInfo();
}
props.put(EmailPropertyType.INFO.getType(), emailInfo);
props.put(EmailPropertyType.USER.getType(), emailTarget);
if (Boolean.parseBoolean(emailInfo.getSendEmailReliableAsync())) {
if (emailServiceProducer == null) {
throw new EmailException("The property sendEmailReliableAsync on EmailInfo is true, but the EmailService does not have an instance of JMSEmailServiceProducer set.");
}
emailServiceProducer.send(props);
} else {
messageCreator.sendMessage(props);
}
return true;
}
/**
* @return the emailTrackingManager
*/
public EmailTrackingManager getEmailTrackingManager() {
return emailTrackingManager;
}
/**
* @param emailTrackingManager the emailTrackingManager to set
*/
public void setEmailTrackingManager(EmailTrackingManager emailTrackingManager) {
this.emailTrackingManager = emailTrackingManager;
}
/**
* @return the serverInfo
*/
public ServerInfo getServerInfo() {
return serverInfo;
}
/**
* @param serverInfo the serverInfo to set
*/
public void setServerInfo(ServerInfo serverInfo) {
this.serverInfo = serverInfo;
}
/**
* @return the emailServiceProducer
*/
public EmailServiceProducer getEmailServiceProducer() {
return emailServiceProducer;
}
/**
* @param emailServiceProducer the emailServiceProducer to set
*/
public void setEmailServiceProducer(EmailServiceProducer emailServiceProducer) {
this.emailServiceProducer = emailServiceProducer;
}
/**
* @return the messageCreator
*/
public MessageCreator getMessageCreator() {
return messageCreator;
}
/**
* @param messageCreator the messageCreator to set
*/
public void setMessageCreator(MessageCreator messageCreator) {
this.messageCreator = messageCreator;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_email_service_EmailServiceImpl.java
|
102 |
static class Traverser<K,V> {
Node<K,V>[] tab; // current table; updated if resized
Node<K,V> next; // the next entry to use
TableStack<K,V> stack, spare; // to save/restore on ForwardingNodes
int index; // index of bin to use next
int baseIndex; // current index of initial table
int baseLimit; // index bound for initial table
final int baseSize; // initial table size
Traverser(Node<K,V>[] tab, int size, int index, int limit) {
this.tab = tab;
this.baseSize = size;
this.baseIndex = this.index = index;
this.baseLimit = limit;
this.next = null;
}
/**
* Advances if possible, returning next valid node, or null if none.
*/
final Node<K,V> advance() {
Node<K,V> e;
if ((e = next) != null)
e = e.next;
for (;;) {
Node<K,V>[] t; int i, n; // must use locals in checks
if (e != null)
return next = e;
if (baseIndex >= baseLimit || (t = tab) == null ||
(n = t.length) <= (i = index) || i < 0)
return next = null;
if ((e = tabAt(t, i)) != null && e.hash < 0) {
if (e instanceof ForwardingNode) {
tab = ((ForwardingNode<K,V>)e).nextTable;
e = null;
pushState(t, i, n);
continue;
}
else if (e instanceof TreeBin)
e = ((TreeBin<K,V>)e).first;
else
e = null;
}
if (stack != null)
recoverState(n);
else if ((index = i + baseSize) >= n)
index = ++baseIndex; // visit upper slots if present
}
}
/**
* Saves traversal state upon encountering a forwarding node.
*/
private void pushState(Node<K,V>[] t, int i, int n) {
TableStack<K,V> s = spare; // reuse if possible
if (s != null)
spare = s.next;
else
s = new TableStack<K,V>();
s.tab = t;
s.length = n;
s.index = i;
s.next = stack;
stack = s;
}
/**
* Possibly pops traversal state.
*
* @param n length of current table
*/
private void recoverState(int n) {
TableStack<K,V> s; int len;
while ((s = stack) != null && (index += (len = s.length)) >= n) {
n = len;
index = s.index;
tab = s.tab;
s.tab = null;
TableStack<K,V> next = s.next;
s.next = spare; // save for reuse
stack = next;
spare = s;
}
if (s == null && (index += baseSize) >= n)
index = ++baseIndex;
}
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
370 |
public class GetRepositoriesRequestBuilder extends MasterNodeReadOperationRequestBuilder<GetRepositoriesRequest, GetRepositoriesResponse, GetRepositoriesRequestBuilder> {
/**
* Creates new get repository request builder
*
* @param clusterAdminClient cluster admin client
*/
public GetRepositoriesRequestBuilder(ClusterAdminClient clusterAdminClient) {
super((InternalClusterAdminClient) clusterAdminClient, new GetRepositoriesRequest());
}
/**
* Creates new get repository request builder
*
* @param clusterAdminClient cluster admin client
* @param repositories list of repositories to get
*/
public GetRepositoriesRequestBuilder(ClusterAdminClient clusterAdminClient, String... repositories) {
super((InternalClusterAdminClient) clusterAdminClient, new GetRepositoriesRequest(repositories));
}
/**
* Sets list of repositories to get
*
* @param repositories list of repositories
* @return builder
*/
public GetRepositoriesRequestBuilder setRepositories(String... repositories) {
request.repositories(repositories);
return this;
}
/**
* Adds repositories to the list of repositories to get
*
* @param repositories list of repositories
* @return builder
*/
public GetRepositoriesRequestBuilder addRepositories(String... repositories) {
request.repositories(ObjectArrays.concat(request.repositories(), repositories, String.class));
return this;
}
@Override
protected void doExecute(ActionListener<GetRepositoriesResponse> listener) {
((ClusterAdminClient) client).getRepositories(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_repositories_get_GetRepositoriesRequestBuilder.java
|
643 |
public class BroadleafResourceHttpRequestHandler extends ResourceHttpRequestHandler {
private static final Log LOG = LogFactory.getLog(BroadleafResourceHttpRequestHandler.class);
// XML Configured generated resource handlers
protected List<AbstractGeneratedResourceHandler> handlers;
@javax.annotation.Resource(name = "blResourceBundlingService")
protected ResourceBundlingService bundlingService;
/**
* Checks to see if the requested path corresponds to a registered bundle. If so, returns the generated bundle.
* Otherwise, checks to see if any of the configured GeneratedResourceHandlers can handle the given request.
* If neither of those cases match, delegates to the normal ResourceHttpRequestHandler
*/
@Override
protected Resource getResource(HttpServletRequest request) {
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
if (bundlingService.hasBundle(path)) {
return bundlingService.getBundle(path);
}
if (handlers != null) {
for (AbstractGeneratedResourceHandler handler : handlers) {
if (handler.canHandle(path)) {
return handler.getResource(path, getLocations());
}
}
}
return super.getResource(request);
}
public boolean isBundleRequest(HttpServletRequest request) {
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
return bundlingService.hasBundle(path);
}
/**
* @return a clone of the locations list that is in {@link ResourceHttpRequestHandler}. Note that we must use
* reflection to access this field as it is marked private.
*/
@SuppressWarnings("unchecked")
public List<Resource> getLocations() {
try {
List<Resource> locations = (List<Resource>) FieldUtils.readField(this, "locations", true);
return new ArrayList<Resource>(locations);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/* *********** */
/* BOILERPLATE */
/* *********** */
public List<AbstractGeneratedResourceHandler> getHandlers() {
return handlers;
}
public void setHandlers(List<AbstractGeneratedResourceHandler> handlers) {
this.handlers = handlers;
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_web_resource_BroadleafResourceHttpRequestHandler.java
|
646 |
public class CollectionCompareAndRemoveOperation extends CollectionBackupAwareOperation {
private boolean retain;
private Set<Data> valueSet;
private Map<Long, Data> itemIdMap;
public CollectionCompareAndRemoveOperation() {
}
public CollectionCompareAndRemoveOperation(String name, boolean retain, Set<Data> valueSet) {
super(name);
this.retain = retain;
this.valueSet = valueSet;
}
@Override
public boolean shouldBackup() {
return !itemIdMap.isEmpty();
}
@Override
public Operation getBackupOperation() {
return new CollectionClearBackupOperation(name, itemIdMap.keySet());
}
@Override
public int getId() {
return CollectionDataSerializerHook.COLLECTION_COMPARE_AND_REMOVE;
}
@Override
public void beforeRun() throws Exception {
}
@Override
public void run() throws Exception {
itemIdMap = getOrCreateContainer().compareAndRemove(retain, valueSet);
response = !itemIdMap.isEmpty();
}
@Override
public void afterRun() throws Exception {
for (Data value : itemIdMap.values()) {
publishEvent(ItemEventType.REMOVED, value);
}
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeBoolean(retain);
out.writeInt(valueSet.size());
for (Data value : valueSet) {
value.writeData(out);
}
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
retain = in.readBoolean();
final int size = in.readInt();
valueSet = new HashSet<Data>(size);
for (int i = 0; i < size; i++) {
final Data value = new Data();
value.readData(in);
valueSet.add(value);
}
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionCompareAndRemoveOperation.java
|
535 |
static enum FrameworkType {
PERSISTENCE,
GENERAL,
LOGGING,
UI,
XML,
UTILITY,
SCHEDULER,
CACHE,
RULES,
ECOMMERCE,
OTHER
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_util_PomEvaluator.java
|
171 |
public interface BaseTransactionConfigurable extends BaseTransaction {
/**
* Get the configuration for this transaction
*
* @return
*/
public BaseTransactionConfig getConfiguration();
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_BaseTransactionConfigurable.java
|
37 |
@Component("blFulfillmentTypeOptionsExtensionListener")
public class FulfillmentTypeEnumOptionsExtensionListener extends AbstractRuleBuilderEnumOptionsExtensionListener {
@Override
protected Map<String, Class<? extends BroadleafEnumerationType>> getValuesToGenerate() {
Map<String, Class<? extends BroadleafEnumerationType>> map =
new HashMap<String, Class<? extends BroadleafEnumerationType>>();
map.put("blcOptions_FulfillmentType", FulfillmentType.class);
return map;
}
}
| 0true
|
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_web_rulebuilder_service_options_FulfillmentTypeEnumOptionsExtensionListener.java
|
93 |
private static class ResourceElement
{
private Xid xid = null;
private XAResource resource = null;
private int status;
ResourceElement( Xid xid, XAResource resource )
{
this.xid = xid;
this.resource = resource;
status = RS_ENLISTED;
}
Xid getXid()
{
return xid;
}
XAResource getResource()
{
return resource;
}
int getStatus()
{
return status;
}
void setStatus( int status )
{
this.status = status;
}
@Override
public String toString()
{
String statusString;
switch ( status )
{
case RS_ENLISTED:
statusString = "ENLISTED";
break;
case RS_DELISTED:
statusString = "DELISTED";
break;
case RS_SUSPENDED:
statusString = "SUSPENDED";
break;
case RS_READONLY:
statusString = "READONLY";
break;
default:
statusString = "UNKNOWN";
}
return "Xid[" + xid + "] XAResource[" + resource + "] Status["
+ statusString + "]";
}
}
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_ReadOnlyTransactionImpl.java
|
1,240 |
public interface InternalClusterAdminClient extends ClusterAdminClient, InternalGenericClient {
}
| 0true
|
src_main_java_org_elasticsearch_client_internal_InternalClusterAdminClient.java
|
1,175 |
public class OQueryOperatorContainsKey extends OQueryOperatorEqualityNotNulls {
public OQueryOperatorContainsKey() {
super("CONTAINSKEY", 5, false);
}
@Override
@SuppressWarnings("unchecked")
protected boolean evaluateExpression(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft,
final Object iRight, OCommandContext iContext) {
if (iLeft instanceof Map<?, ?>) {
final Map<String, ?> map = (Map<String, ?>) iLeft;
return map.containsKey(iRight);
} else if (iRight instanceof Map<?, ?>) {
final Map<String, ?> map = (Map<String, ?>) iRight;
return map.containsKey(iLeft);
}
return false;
}
@Override
public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) {
return OIndexReuseType.INDEX_METHOD;
}
@Override
public Object executeIndexQuery(OCommandContext iContext, OIndex<?> index, INDEX_OPERATION_TYPE iOperationType,
List<Object> keyParams, IndexResultListener resultListener, int fetchLimit) {
final OIndexDefinition indexDefinition = index.getDefinition();
final OIndexInternal<?> internalIndex = index.getInternal();
if (!internalIndex.canBeUsedInEqualityOperators())
return null;
final Object result;
if (indexDefinition.getParamCount() == 1) {
if (!((indexDefinition instanceof OPropertyMapIndexDefinition) && ((OPropertyMapIndexDefinition) indexDefinition)
.getIndexBy() == OPropertyMapIndexDefinition.INDEX_BY.KEY))
return null;
final Object key = ((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(keyParams.get(0));
if (key == null)
return null;
final Object indexResult = index.get(key);
result = convertIndexResult(indexResult);
} else {
// in case of composite keys several items can be returned in case of we perform search
// using part of composite key stored in index.
final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition;
if (!((compositeIndexDefinition.getMultiValueDefinition() instanceof OPropertyMapIndexDefinition) && ((OPropertyMapIndexDefinition) compositeIndexDefinition
.getMultiValueDefinition()).getIndexBy() == OPropertyMapIndexDefinition.INDEX_BY.KEY))
return null;
final Object keyOne = compositeIndexDefinition.createSingleValue(keyParams);
if (keyOne == null)
return null;
if (internalIndex.hasRangeQuerySupport()) {
final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams);
if (resultListener != null) {
index.getValuesBetween(keyOne, true, keyTwo, true, resultListener);
result = resultListener.getResult();
} else
result = index.getValuesBetween(keyOne, true, keyTwo, true);
} else {
if (indexDefinition.getParamCount() == keyParams.size()) {
final Object indexResult = index.get(keyOne);
result = convertIndexResult(indexResult);
} else
return null;
}
}
updateProfiler(iContext, index, keyParams, indexDefinition);
return result;
}
private Object convertIndexResult(Object indexResult) {
Object result;
if (indexResult instanceof Collection)
result = indexResult;
else if (indexResult == null)
result = Collections.emptyList();
else
result = Collections.singletonList((OIdentifiable) indexResult);
return result;
}
@Override
public ORID getBeginRidRange(Object iLeft, Object iRight) {
return null;
}
@Override
public ORID getEndRidRange(Object iLeft, Object iRight) {
return null;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryOperatorContainsKey.java
|
1,492 |
public class AddIncrementallyTests extends ElasticsearchAllocationTestCase {
private final ESLogger logger = Loggers.getLogger(AddIncrementallyTests.class);
@Test
public void testAddNodesAndIndices() {
ImmutableSettings.Builder settings = settingsBuilder();
settings.put("cluster.routing.allocation.allow_rebalance", ClusterRebalanceAllocationDecider.ClusterRebalanceType.ALWAYS.toString());
AllocationService service = createAllocationService(settings.build());
ClusterState clusterState = initCluster(service, 1, 3, 3, 1);
assertThat(clusterState.routingNodes().node("node0").shardsWithState(STARTED).size(), Matchers.equalTo(9));
assertThat(clusterState.routingNodes().unassigned().size(), Matchers.equalTo(9));
int nodeOffset = 1;
clusterState = addNodes(clusterState, service, 1, nodeOffset++);
assertThat(clusterState.routingNodes().node("node0").shardsWithState(STARTED).size(), Matchers.equalTo(9));
assertThat(clusterState.routingNodes().node("node1").shardsWithState(STARTED).size(), Matchers.equalTo(9));
assertThat(clusterState.routingNodes().unassigned().size(), Matchers.equalTo(0));
assertNumIndexShardsPerNode(clusterState, Matchers.equalTo(3));
clusterState = addNodes(clusterState, service, 1, nodeOffset++);
assertNumIndexShardsPerNode(clusterState, Matchers.equalTo(2));
clusterState = addNodes(clusterState, service, 1, nodeOffset++);
assertNumIndexShardsPerNode(clusterState, Matchers.lessThanOrEqualTo(2));
assertAtLeastOneIndexShardPerNode(clusterState);
clusterState = removeNodes(clusterState, service, 1);
assertNumIndexShardsPerNode(clusterState, Matchers.equalTo(2));
clusterState = addIndex(clusterState, service, 3, 2, 3);
assertThat(clusterState.routingNodes().unassigned().size(), Matchers.equalTo(2));
assertNumIndexShardsPerNode(clusterState, "test3", Matchers.equalTo(2));
assertNumIndexShardsPerNode(clusterState, Matchers.lessThanOrEqualTo(2));
clusterState = addIndex(clusterState, service, 4, 2, 3);
assertThat(clusterState.routingNodes().unassigned().size(), Matchers.equalTo(4));
assertNumIndexShardsPerNode(clusterState, "test4", Matchers.equalTo(2));
assertNumIndexShardsPerNode(clusterState, Matchers.lessThanOrEqualTo(2));
clusterState = addNodes(clusterState, service, 1, nodeOffset++);
assertNumIndexShardsPerNode(clusterState, Matchers.lessThanOrEqualTo(2));
assertThat(clusterState.routingNodes().unassigned().size(), Matchers.equalTo(0));
clusterState = removeNodes(clusterState, service, 1);
assertThat(clusterState.routingNodes().unassigned().size(), Matchers.equalTo(4));
assertNumIndexShardsPerNode(clusterState, Matchers.lessThanOrEqualTo(2));
clusterState = addNodes(clusterState, service, 1, nodeOffset++);
assertNumIndexShardsPerNode(clusterState, Matchers.lessThanOrEqualTo(2));
assertThat(clusterState.routingNodes().unassigned().size(), Matchers.equalTo(0));
logger.debug("ClusterState: {}", clusterState.getRoutingNodes().prettyPrint());
}
@Test
public void testMinimalRelocations() {
ImmutableSettings.Builder settings = settingsBuilder();
settings.put("cluster.routing.allocation.allow_rebalance", ClusterRebalanceAllocationDecider.ClusterRebalanceType.ALWAYS.toString())
.put("cluster.routing.allocation.node_concurrent_recoveries", 2);
AllocationService service = createAllocationService(settings.build());
ClusterState clusterState = initCluster(service, 1, 3, 3, 1);
assertThat(clusterState.routingNodes().node("node0").shardsWithState(STARTED).size(), Matchers.equalTo(9));
assertThat(clusterState.routingNodes().unassigned().size(), Matchers.equalTo(9));
int nodeOffset = 1;
clusterState = addNodes(clusterState, service, 1, nodeOffset++);
assertThat(clusterState.routingNodes().node("node0").shardsWithState(STARTED).size(), Matchers.equalTo(9));
assertThat(clusterState.routingNodes().node("node1").shardsWithState(STARTED).size(), Matchers.equalTo(9));
assertThat(clusterState.routingNodes().unassigned().size(), Matchers.equalTo(0));
assertNumIndexShardsPerNode(clusterState, Matchers.equalTo(3));
logger.info("now, start one more node, check that rebalancing will happen because we set it to always");
DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(clusterState.nodes());
nodes.put(newNode("node2"));
clusterState = ClusterState.builder(clusterState).nodes(nodes.build()).build();
RoutingTable routingTable = service.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
RoutingNodes routingNodes = clusterState.routingNodes();
assertThat(clusterState.routingNodes().node("node2").shardsWithState(INITIALIZING).size(), Matchers.equalTo(2));
assertThat(clusterState.routingNodes().node("node0").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(clusterState.routingNodes().node("node1").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
RoutingTable prev = routingTable;
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prev, Matchers.not(Matchers.sameInstance(routingTable)));
assertThat(clusterState.routingNodes().node("node2").shardsWithState(STARTED).size(), Matchers.equalTo(2));
assertThat(clusterState.routingNodes().node("node2").shardsWithState(INITIALIZING).size(), Matchers.equalTo(2));
assertThat(clusterState.routingNodes().node("node0").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(clusterState.routingNodes().node("node1").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(prev, Matchers.not(Matchers.sameInstance(routingTable)));
prev = routingTable;
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(clusterState.routingNodes().node("node2").shardsWithState(STARTED).size(), Matchers.equalTo(4));
assertThat(clusterState.routingNodes().node("node2").shardsWithState(INITIALIZING).size(), Matchers.equalTo(2));
assertThat(clusterState.routingNodes().node("node0").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(clusterState.routingNodes().node("node1").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(prev, Matchers.not(Matchers.sameInstance(routingTable)));
prev = routingTable;
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(clusterState.routingNodes().node("node2").shardsWithState(STARTED).size(), Matchers.equalTo(6));
assertThat(clusterState.routingNodes().node("node2").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(clusterState.routingNodes().node("node0").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(clusterState.routingNodes().node("node1").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(prev, Matchers.not(Matchers.sameInstance(routingTable)));
prev = routingTable;
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prev, Matchers.sameInstance(routingTable));
assertNumIndexShardsPerNode(clusterState, Matchers.equalTo(2));
logger.debug("ClusterState: {}", clusterState.getRoutingNodes().prettyPrint());
}
@Test
public void testMinimalRelocationsNoLimit() {
ImmutableSettings.Builder settings = settingsBuilder();
settings.put("cluster.routing.allocation.allow_rebalance", ClusterRebalanceAllocationDecider.ClusterRebalanceType.ALWAYS.toString())
.put("cluster.routing.allocation.node_concurrent_recoveries", 100)
.put("cluster.routing.allocation.node_initial_primaries_recoveries", 100);
AllocationService service = createAllocationService(settings.build());
ClusterState clusterState = initCluster(service, 1, 3, 3, 1);
assertThat(clusterState.routingNodes().node("node0").shardsWithState(STARTED).size(), Matchers.equalTo(9));
assertThat(clusterState.routingNodes().unassigned().size(), Matchers.equalTo(9));
int nodeOffset = 1;
clusterState = addNodes(clusterState, service, 1, nodeOffset++);
assertThat(clusterState.routingNodes().node("node0").shardsWithState(STARTED).size(), Matchers.equalTo(9));
assertThat(clusterState.routingNodes().node("node1").shardsWithState(STARTED).size(), Matchers.equalTo(9));
assertThat(clusterState.routingNodes().unassigned().size(), Matchers.equalTo(0));
assertNumIndexShardsPerNode(clusterState, Matchers.equalTo(3));
logger.info("now, start one more node, check that rebalancing will happen because we set it to always");
DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(clusterState.nodes());
nodes.put(newNode("node2"));
clusterState = ClusterState.builder(clusterState).nodes(nodes.build()).build();
RoutingTable routingTable = service.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
RoutingNodes routingNodes = clusterState.routingNodes();
assertThat(clusterState.routingNodes().node("node2").shardsWithState(INITIALIZING).size(), Matchers.equalTo(2));
assertThat(clusterState.routingNodes().node("node0").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(clusterState.routingNodes().node("node1").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
RoutingTable prev = routingTable;
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prev, Matchers.not(Matchers.sameInstance(routingTable)));
assertThat(clusterState.routingNodes().node("node2").shardsWithState(STARTED).size(), Matchers.equalTo(2));
assertThat(clusterState.routingNodes().node("node2").shardsWithState(INITIALIZING).size(), Matchers.equalTo(2));
assertThat(clusterState.routingNodes().node("node0").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(clusterState.routingNodes().node("node1").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(prev, Matchers.not(Matchers.sameInstance(routingTable)));
prev = routingTable;
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(clusterState.routingNodes().node("node2").shardsWithState(STARTED).size(), Matchers.equalTo(4));
assertThat(clusterState.routingNodes().node("node2").shardsWithState(INITIALIZING).size(), Matchers.equalTo(2));
assertThat(clusterState.routingNodes().node("node0").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(clusterState.routingNodes().node("node1").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(prev, Matchers.not(Matchers.sameInstance(routingTable)));
prev = routingTable;
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(clusterState.routingNodes().node("node2").shardsWithState(STARTED).size(), Matchers.equalTo(6));
assertThat(clusterState.routingNodes().node("node2").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(clusterState.routingNodes().node("node0").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(clusterState.routingNodes().node("node1").shardsWithState(INITIALIZING).size(), Matchers.equalTo(0));
assertThat(prev, Matchers.not(Matchers.sameInstance(routingTable)));
prev = routingTable;
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prev, Matchers.sameInstance(routingTable));
assertNumIndexShardsPerNode(clusterState, Matchers.equalTo(2));
logger.debug("ClusterState: {}", clusterState.getRoutingNodes().prettyPrint());
}
private void assertNumIndexShardsPerNode(ClusterState state, Matcher<Integer> matcher) {
for (String index : state.routingTable().indicesRouting().keySet()) {
assertNumIndexShardsPerNode(state, index, matcher);
}
}
private void assertNumIndexShardsPerNode(ClusterState state, String index, Matcher<Integer> matcher) {
for (RoutingNode node : state.routingNodes()) {
assertThat(node.shardsWithState(index, STARTED).size(), matcher);
}
}
private void assertAtLeastOneIndexShardPerNode(ClusterState state) {
for (String index : state.routingTable().indicesRouting().keySet()) {
for (RoutingNode node : state.routingNodes()) {
assertThat(node.shardsWithState(index, STARTED).size(), Matchers.greaterThanOrEqualTo(1));
}
}
}
private ClusterState addNodes(ClusterState clusterState, AllocationService service, int numNodes, int nodeOffset) {
logger.info("now, start [{}] more node, check that rebalancing will happen because we set it to always", numNodes);
DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(clusterState.nodes());
for (int i = 0; i < numNodes; i++) {
nodes.put(newNode("node" + (i + nodeOffset)));
}
clusterState = ClusterState.builder(clusterState).nodes(nodes.build()).build();
RoutingTable routingTable = service.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
RoutingNodes routingNodes = clusterState.routingNodes();
// move initializing to started
RoutingTable prev = routingTable;
while (true) {
logger.debug("ClusterState: {}", clusterState.getRoutingNodes().prettyPrint());
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
if (routingTable == prev)
break;
prev = routingTable;
}
return clusterState;
}
private ClusterState initCluster(AllocationService service, int numberOfNodes, int numberOfIndices, int numberOfShards,
int numberOfReplicas) {
MetaData.Builder metaDataBuilder = MetaData.builder();
RoutingTable.Builder routingTableBuilder = RoutingTable.builder();
for (int i = 0; i < numberOfIndices; i++) {
IndexMetaData.Builder index = IndexMetaData.builder("test" + i).numberOfShards(numberOfShards).numberOfReplicas(
numberOfReplicas);
metaDataBuilder = metaDataBuilder.put(index);
}
MetaData metaData = metaDataBuilder.build();
for (ObjectCursor<IndexMetaData> cursor : metaData.indices().values()) {
routingTableBuilder.addAsNew(cursor.value);
}
RoutingTable routingTable = routingTableBuilder.build();
logger.info("start " + numberOfNodes + " nodes");
DiscoveryNodes.Builder nodes = DiscoveryNodes.builder();
for (int i = 0; i < numberOfNodes; i++) {
nodes.put(newNode("node" + i));
}
ClusterState clusterState = ClusterState.builder().nodes(nodes).metaData(metaData).routingTable(routingTable).build();
routingTable = service.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
RoutingNodes routingNodes = clusterState.routingNodes();
logger.info("restart all the primary shards, replicas will start initializing");
routingNodes = clusterState.routingNodes();
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
logger.info("start the replica shards");
routingNodes = clusterState.routingNodes();
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
logger.info("complete rebalancing");
RoutingTable prev = routingTable;
while (true) {
logger.debug("ClusterState: {}", clusterState.getRoutingNodes().prettyPrint());
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
if (routingTable == prev)
break;
prev = routingTable;
}
return clusterState;
}
private ClusterState addIndex(ClusterState clusterState, AllocationService service, int indexOrdinal, int numberOfShards,
int numberOfReplicas) {
MetaData.Builder metaDataBuilder = MetaData.builder(clusterState.getMetaData());
RoutingTable.Builder routingTableBuilder = RoutingTable.builder(clusterState.routingTable());
IndexMetaData.Builder index = IndexMetaData.builder("test" + indexOrdinal).numberOfShards(numberOfShards).numberOfReplicas(
numberOfReplicas);
IndexMetaData imd = index.build();
metaDataBuilder = metaDataBuilder.put(imd, true);
routingTableBuilder.addAsNew(imd);
MetaData metaData = metaDataBuilder.build();
RoutingTable routingTable = routingTableBuilder.build();
clusterState = ClusterState.builder(clusterState).metaData(metaData).routingTable(routingTable).build();
routingTable = service.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
RoutingNodes routingNodes = clusterState.routingNodes();
logger.info("restart all the primary shards, replicas will start initializing");
routingNodes = clusterState.routingNodes();
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
logger.info("start the replica shards");
routingNodes = clusterState.routingNodes();
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
logger.info("complete rebalancing");
RoutingTable prev = routingTable;
while (true) {
logger.debug("ClusterState: {}", clusterState.getRoutingNodes().prettyPrint());
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
if (routingTable == prev)
break;
prev = routingTable;
}
return clusterState;
}
private ClusterState removeNodes(ClusterState clusterState, AllocationService service, int numNodes) {
logger.info("Removing [{}] nodes", numNodes);
DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(clusterState.nodes());
ArrayList<DiscoveryNode> discoveryNodes = Lists.newArrayList(clusterState.nodes());
Collections.shuffle(discoveryNodes, getRandom());
for (DiscoveryNode node : discoveryNodes) {
nodes.remove(node.id());
numNodes--;
if (numNodes <= 0) {
break;
}
}
clusterState = ClusterState.builder(clusterState).nodes(nodes.build()).build();
RoutingNodes routingNodes = clusterState.routingNodes();
logger.info("start all the primary shards, replicas will start initializing");
RoutingTable routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
logger.info("start the replica shards");
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
logger.info("rebalancing");
routingTable = service.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
logger.info("complete rebalancing");
RoutingTable prev = routingTable;
while (true) {
logger.debug("ClusterState: {}", clusterState.getRoutingNodes().prettyPrint());
routingTable = service.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
if (routingTable == prev)
break;
prev = routingTable;
}
return clusterState;
}
}
| 0true
|
src_test_java_org_elasticsearch_cluster_routing_allocation_AddIncrementallyTests.java
|
512 |
public class MinuteType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, MinuteType> TYPES = new LinkedHashMap<String, MinuteType>();
public static final MinuteType ZERO = new MinuteType("0", "00");
public static final MinuteType ONE = new MinuteType("1", "01");
public static final MinuteType TWO = new MinuteType("2", "02");
public static final MinuteType THREE = new MinuteType("3", "03");
public static final MinuteType FOUR = new MinuteType("4", "04");
public static final MinuteType FIVE = new MinuteType("5", "05");
public static final MinuteType SIX = new MinuteType("6", "06");
public static final MinuteType SEVEN = new MinuteType("7", "07");
public static final MinuteType EIGHT = new MinuteType("8", "08");
public static final MinuteType NINE = new MinuteType("9", "09");
public static final MinuteType TEN = new MinuteType("10", "10");
public static final MinuteType ELEVEN = new MinuteType("11", "11");
public static final MinuteType TWELVE = new MinuteType("12", "12");
public static final MinuteType THIRTEEN = new MinuteType("13", "13");
public static final MinuteType FOURTEEN = new MinuteType("14", "14");
public static final MinuteType FIFTEEN = new MinuteType("15", "15");
public static final MinuteType SIXTEEN = new MinuteType("16", "16");
public static final MinuteType SEVENTEEN = new MinuteType("17", "17");
public static final MinuteType EIGHTEEN = new MinuteType("18", "18");
public static final MinuteType NINETEEN = new MinuteType("19", "19");
public static final MinuteType TWENTY = new MinuteType("20", "20");
public static final MinuteType TWENTYONE = new MinuteType("21", "21");
public static final MinuteType TWNETYTWO = new MinuteType("22", "22");
public static final MinuteType TWENTYTHREE = new MinuteType("23", "23");
public static final MinuteType TWENTYFOUR = new MinuteType("24", "24");
public static final MinuteType TWENTYFIVE = new MinuteType("25", "25");
public static final MinuteType TWENTYSIX = new MinuteType("26", "26");
public static final MinuteType TWENTYSEVEN = new MinuteType("27", "27");
public static final MinuteType TWENTYEIGHT = new MinuteType("28", "28");
public static final MinuteType TWENTYNINE = new MinuteType("29", "29");
public static final MinuteType THIRTY = new MinuteType("30", "30");
public static final MinuteType THIRTYONE = new MinuteType("31", "31");
public static final MinuteType THIRTYTWO = new MinuteType("32", "32");
public static final MinuteType THIRTYTHREE = new MinuteType("33", "33");
public static final MinuteType THIRTYFOUR = new MinuteType("34", "34");
public static final MinuteType THIRTYFIVE = new MinuteType("35", "35");
public static final MinuteType THIRTYSIX = new MinuteType("36", "36");
public static final MinuteType THIRTYSEVEN = new MinuteType("37", "37");
public static final MinuteType THIRTYEIGHT = new MinuteType("38", "38");
public static final MinuteType THIRTYNINE = new MinuteType("39", "39");
public static final MinuteType FOURTY = new MinuteType("40", "40");
public static final MinuteType FOURTYONE = new MinuteType("41", "41");
public static final MinuteType FOURTYTWO = new MinuteType("42", "42");
public static final MinuteType FOURTYTHREE = new MinuteType("43", "43");
public static final MinuteType FOURTYFOUR = new MinuteType("44", "44");
public static final MinuteType FOURTYFIVE = new MinuteType("45", "45");
public static final MinuteType FOURTYSIX = new MinuteType("46", "46");
public static final MinuteType FOURTYSEVEN = new MinuteType("47", "47");
public static final MinuteType FOURTYEIGHT = new MinuteType("48", "48");
public static final MinuteType FOURTYNINE = new MinuteType("49", "49");
public static final MinuteType FIFTY = new MinuteType("50", "50");
public static final MinuteType FIFTYONE = new MinuteType("51", "51");
public static final MinuteType FIFTYTWO = new MinuteType("52", "52");
public static final MinuteType FIFTYTHREE = new MinuteType("53", "53");
public static final MinuteType FIFTYFOUR = new MinuteType("54", "54");
public static final MinuteType FIFTYFIVE = new MinuteType("55", "55");
public static final MinuteType FIFTYSIX = new MinuteType("56", "56");
public static final MinuteType FIFTYSEVEN = new MinuteType("57", "57");
public static final MinuteType FIFTYEIGHT = new MinuteType("58", "58");
public static final MinuteType FIFTYNINE = new MinuteType("59", "59");
public static MinuteType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public MinuteType() {
//do nothing
}
public MinuteType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
public String getType() {
return type;
}
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
} else {
throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName());
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MinuteType other = (MinuteType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_time_MinuteType.java
|
12 |
static final class AscendingSubMap<K, V> extends NavigableSubMap<K, V> {
private static final long serialVersionUID = 912986545866124060L;
AscendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd,
K hi, final boolean hiInclusive) {
super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive);
}
public Comparator<? super K> comparator() {
return m.comparator();
}
public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) {
if (!inRange(fromKey, fromInclusive))
throw new IllegalArgumentException("fromKey out of range");
if (!inRange(toKey, toInclusive))
throw new IllegalArgumentException("toKey out of range");
return new AscendingSubMap<K, V>(m, false, fromKey, fromInclusive, false, toKey, toInclusive);
}
public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) {
if (!inRange(toKey, inclusive))
throw new IllegalArgumentException("toKey out of range");
return new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, toKey, inclusive);
}
public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) {
if (!inRange(fromKey, inclusive))
throw new IllegalArgumentException("fromKey out of range");
return new AscendingSubMap<K, V>(m, false, fromKey, inclusive, toEnd, hi, hiInclusive);
}
public ONavigableMap<K, V> descendingMap() {
ONavigableMap<K, V> mv = descendingMapView;
return (mv != null) ? mv : (descendingMapView = new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi,
hiInclusive));
}
@Override
OLazyIterator<K> keyIterator() {
return new SubMapKeyIterator(absLowest(), absHighFence());
}
@Override
OLazyIterator<K> descendingKeyIterator() {
return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
}
final class AscendingEntrySetView extends EntrySetView {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new SubMapEntryIterator(absLowest(), absHighFence());
}
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
EntrySetView es = entrySetView;
return (es != null) ? es : new AscendingEntrySetView();
}
@Override
OMVRBTreeEntry<K, V> subLowest() {
return absLowest().entry;
}
@Override
OMVRBTreeEntry<K, V> subHighest() {
return absHighest().entry;
}
@Override
OMVRBTreeEntry<K, V> subCeiling(final K key) {
return absCeiling(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subHigher(final K key) {
return absHigher(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subFloor(final K key) {
return absFloor(key).entry;
}
@Override
OMVRBTreeEntry<K, V> subLower(final K key) {
return absLower(key).entry;
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
|
277 |
@RunWith(HazelcastSerialClassRunner.class)
@Category(SlowTest.class)
public class ClientExecutionPoolSizeLowTest {
static final int COUNT = 1000;
static HazelcastInstance server1;
static HazelcastInstance server2;
static HazelcastInstance client;
static IMap map;
@Before
public void init() {
Config config = new Config();
server1 = Hazelcast.newHazelcastInstance(config);
ClientConfig clientConfig = new ClientConfig();
clientConfig.setExecutorPoolSize(1);
clientConfig.getNetworkConfig().setRedoOperation(true);
client = HazelcastClient.newHazelcastClient(clientConfig);
server2 = Hazelcast.newHazelcastInstance(config);
map = client.getMap(randomString());
}
@After
public void destroy() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testNodeTerminate() throws InterruptedException, ExecutionException {
for (int i = 0; i < COUNT; i++) {
map.put(i, i);
if (i == COUNT / 2) {
server2.getLifecycleService().terminate();
}
}
assertEquals(COUNT, map.size());
}
@Test
public void testOwnerNodeTerminate() throws InterruptedException, ExecutionException {
for (int i = 0; i < COUNT; i++) {
map.put(i, i);
if (i == COUNT / 2) {
server1.getLifecycleService().terminate();
}
}
assertEquals(COUNT, map.size());
}
@Test
public void testNodeTerminateWithAsyncOperations() throws InterruptedException, ExecutionException {
for (int i = 0; i < COUNT; i++) {
map.putAsync(i, i);
if (i == COUNT / 2) {
server2.getLifecycleService().terminate();
}
}
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(COUNT, map.size());
}
});
}
@Test
public void testOwnerNodeTerminateWithAsyncOperations() throws InterruptedException, ExecutionException {
for (int i = 0; i < COUNT; i++) {
map.putAsync(i, i);
if (i == COUNT / 2) {
server1.getLifecycleService().terminate();
}
}
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(COUNT, map.size());
}
});
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_io_ClientExecutionPoolSizeLowTest.java
|
848 |
new Visitor() {
private boolean needsParens = false;
@Override
public void visit(Tree.Variable that) {
if (that.getType() instanceof Tree.SyntheticVariable) {
TypedDeclaration od =
that.getDeclarationModel().getOriginalDeclaration();
if (od!=null && od.equals(declaration) && delete) {
Integer startIndex =
that.getSpecifierExpression().getStartIndex();
tfc.addEdit(new InsertEdit(startIndex,
that.getIdentifier().getText()+" = "));
}
}
super.visit(that);
}
@Override
public void visit(Tree.MemberOrTypeExpression that) {
super.visit(that);
inlineDefinition(tokens, declarationTokens, term,
tfc, null, that, needsParens);
}
@Override
public void visit(Tree.OperatorExpression that) {
boolean onp = needsParens;
needsParens=true;
super.visit(that);
needsParens = onp;
}
@Override
public void visit(Tree.StatementOrArgument that) {
boolean onp = needsParens;
needsParens = false;
super.visit(that);
needsParens = onp;
}
@Override
public void visit(Tree.Expression that) {
boolean onp = needsParens;
needsParens = false;
super.visit(that);
needsParens = onp;
}
}.visit(pu);
| 1no label
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_refactor_InlineRefactoring.java
|
1,209 |
public static enum Type {
SOFT_THREAD_LOCAL {
@Override
<T> Recycler<T> build(Recycler.C<T> c, int limit, int availableProcessors) {
return threadLocal(softFactory(dequeFactory(c, limit)));
}
},
THREAD_LOCAL {
@Override
<T> Recycler<T> build(Recycler.C<T> c, int limit, int availableProcessors) {
return threadLocal(dequeFactory(c, limit));
}
},
QUEUE {
@Override
<T> Recycler<T> build(Recycler.C<T> c, int limit, int availableProcessors) {
return concurrentDeque(c, limit);
}
},
SOFT_CONCURRENT {
@Override
<T> Recycler<T> build(Recycler.C<T> c, int limit, int availableProcessors) {
return concurrent(softFactory(dequeFactory(c, limit)), availableProcessors);
}
},
CONCURRENT {
@Override
<T> Recycler<T> build(Recycler.C<T> c, int limit, int availableProcessors) {
return concurrent(dequeFactory(c, limit), availableProcessors);
}
},
NONE {
@Override
<T> Recycler<T> build(Recycler.C<T> c, int limit, int availableProcessors) {
return none(c);
}
};
public static Type parse(String type) {
if (Strings.isNullOrEmpty(type)) {
return SOFT_CONCURRENT;
}
try {
return Type.valueOf(type.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
throw new ElasticsearchIllegalArgumentException("no type support [" + type + "]");
}
}
abstract <T> Recycler<T> build(Recycler.C<T> c, int limit, int availableProcessors);
}
| 0true
|
src_main_java_org_elasticsearch_cache_recycler_CacheRecycler.java
|
715 |
constructors[COLLECTION_ADD_LISTENER] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new CollectionAddListenerRequest();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java
|
332 |
public class TransportNodesInfoAction extends TransportNodesOperationAction<NodesInfoRequest, NodesInfoResponse, TransportNodesInfoAction.NodeInfoRequest, NodeInfo> {
private final NodeService nodeService;
@Inject
public TransportNodesInfoAction(Settings settings, ClusterName clusterName, ThreadPool threadPool,
ClusterService clusterService, TransportService transportService,
NodeService nodeService) {
super(settings, clusterName, threadPool, clusterService, transportService);
this.nodeService = nodeService;
}
@Override
protected String executor() {
return ThreadPool.Names.MANAGEMENT;
}
@Override
protected String transportAction() {
return NodesInfoAction.NAME;
}
@Override
protected NodesInfoResponse newResponse(NodesInfoRequest nodesInfoRequest, AtomicReferenceArray responses) {
final List<NodeInfo> nodesInfos = new ArrayList<NodeInfo>();
for (int i = 0; i < responses.length(); i++) {
Object resp = responses.get(i);
if (resp instanceof NodeInfo) {
nodesInfos.add((NodeInfo) resp);
}
}
return new NodesInfoResponse(clusterName, nodesInfos.toArray(new NodeInfo[nodesInfos.size()]));
}
@Override
protected NodesInfoRequest newRequest() {
return new NodesInfoRequest();
}
@Override
protected NodeInfoRequest newNodeRequest() {
return new NodeInfoRequest();
}
@Override
protected NodeInfoRequest newNodeRequest(String nodeId, NodesInfoRequest request) {
return new NodeInfoRequest(nodeId, request);
}
@Override
protected NodeInfo newNodeResponse() {
return new NodeInfo();
}
@Override
protected NodeInfo nodeOperation(NodeInfoRequest nodeRequest) throws ElasticsearchException {
NodesInfoRequest request = nodeRequest.request;
return nodeService.info(request.settings(), request.os(), request.process(), request.jvm(), request.threadPool(),
request.network(), request.transport(), request.http(), request.plugin());
}
@Override
protected boolean accumulateExceptions() {
return false;
}
static class NodeInfoRequest extends NodeOperationRequest {
NodesInfoRequest request;
NodeInfoRequest() {
}
NodeInfoRequest(String nodeId, NodesInfoRequest request) {
super(request, nodeId);
this.request = request;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
request = new NodesInfoRequest();
request.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
request.writeTo(out);
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_node_info_TransportNodesInfoAction.java
|
469 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name="BLC_SANDBOX")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blSandBoxElements")
public class SandBoxImpl implements SandBox {
private static final Log LOG = LogFactory.getLog(SandBoxImpl.class);
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "SandBoxId")
@GenericGenerator(
name="SandBoxId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="SandBoxImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.common.sandbox.domain.SandBoxImpl")
}
)
@Column(name = "SANDBOX_ID")
@AdminPresentation(visibility = VisibilityEnum.HIDDEN_ALL)
protected Long id;
@Column(name = "SANDBOX_NAME")
@Index(name="SANDBOX_NAME_INDEX", columnNames={"SANDBOX_NAME"})
protected String name;
@Column(name="AUTHOR")
protected Long author;
@ManyToOne(targetEntity = SiteImpl.class)
@JoinTable(name = "BLC_SITE_SANDBOX", joinColumns = @JoinColumn(name = "SANDBOX_ID"), inverseJoinColumns = @JoinColumn(name = "SITE_ID"))
protected Site site;
@Column(name = "SANDBOX_TYPE")
@AdminPresentation(friendlyName = "SandBoxImpl_SandBox_Type", group = "SandBoxImpl_Description", fieldType= SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration="org.broadleafcommerce.common.sandbox.domain.SandBoxType")
protected String sandboxType;
/* (non-Javadoc)
* @see org.broadleafcommerce.openadmin.domain.SandBox#getId()
*/
@Override
public Long getId() {
return id;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.openadmin.domain.SandBox#setId(java.lang.Long)
*/
@Override
public void setId(Long id) {
this.id = id;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.openadmin.domain.SandBox#getName()
*/
@Override
public String getName() {
return name;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.openadmin.domain.SandBox#setName(java.lang.String)
*/
@Override
public void setName(String name) {
this.name = name;
}
@Override
public SandBoxType getSandBoxType() {
return SandBoxType.getInstance(sandboxType);
}
@Override
public void setSandBoxType(final SandBoxType sandboxType) {
if (sandboxType != null) {
this.sandboxType = sandboxType.getType();
}
}
@Override
public Long getAuthor() {
return author;
}
@Override
public void setAuthor(Long author) {
this.author = author;
}
@Override
public Site getSite() {
return site;
}
@Override
public void setSite(Site site) {
this.site = site;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SandBoxImpl other = (SandBoxImpl) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public void checkCloneable(SandBox sandBox) throws CloneNotSupportedException, SecurityException, NoSuchMethodException {
Method cloneMethod = sandBox.getClass().getMethod("clone", new Class[]{});
if (cloneMethod.getDeclaringClass().getName().startsWith("org.broadleafcommerce") && !sandBox.getClass().getName().startsWith("org.broadleafcommerce")) {
//subclass is not implementing the clone method
throw new CloneNotSupportedException("Custom extensions and implementations should implement clone.");
}
}
@Override
public SandBox clone() {
SandBox clone;
try {
clone = (SandBox) Class.forName(this.getClass().getName()).newInstance();
try {
checkCloneable(clone);
} catch (CloneNotSupportedException e) {
LOG.warn("Clone implementation missing in inheritance hierarchy outside of Broadleaf: " + clone.getClass().getName(), e);
}
clone.setId(id);
clone.setName(name);
clone.setAuthor(author);
clone.setSandBoxType(getSandBoxType());
if (site != null) {
clone.setSite(site.clone());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return clone;
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_sandbox_domain_SandBoxImpl.java
|
1,137 |
public class TermsAggregationSearchBenchmark {
static long COUNT = SizeValue.parseSizeValue("2m").singles();
static int BATCH = 1000;
static int QUERY_WARMUP = 10;
static int QUERY_COUNT = 100;
static int NUMBER_OF_TERMS = 200;
static int NUMBER_OF_MULTI_VALUE_TERMS = 10;
static int STRING_TERM_SIZE = 5;
static Client client;
private enum Method {
FACET {
@Override
SearchRequestBuilder addTermsAgg(SearchRequestBuilder builder, String name, String field, String executionHint) {
return builder.addFacet(termsFacet(name).field(field).executionHint(executionHint));
}
@Override
SearchRequestBuilder addTermsStatsAgg(SearchRequestBuilder builder, String name, String keyField, String valueField) {
return builder.addFacet(termsStatsFacet(name).keyField(keyField).valueField(valueField));
}
},
AGGREGATION {
@Override
SearchRequestBuilder addTermsAgg(SearchRequestBuilder builder, String name, String field, String executionHint) {
return builder.addAggregation(AggregationBuilders.terms(name).executionHint(executionHint).field(field));
}
@Override
SearchRequestBuilder addTermsStatsAgg(SearchRequestBuilder builder, String name, String keyField, String valueField) {
return builder.addAggregation(AggregationBuilders.terms(name).field(keyField).subAggregation(AggregationBuilders.stats("stats").field(valueField)));
}
};
abstract SearchRequestBuilder addTermsAgg(SearchRequestBuilder builder, String name, String field, String executionHint);
abstract SearchRequestBuilder addTermsStatsAgg(SearchRequestBuilder builder, String name, String keyField, String valueField);
}
public static void main(String[] args) throws Exception {
Random random = new Random();
Settings settings = settingsBuilder()
.put("index.refresh_interval", "-1")
.put("gateway.type", "local")
.put(SETTING_NUMBER_OF_SHARDS, 1)
.put(SETTING_NUMBER_OF_REPLICAS, 0)
.build();
String clusterName = TermsAggregationSearchBenchmark.class.getSimpleName();
Node[] nodes = new Node[1];
for (int i = 0; i < nodes.length; i++) {
nodes[i] = nodeBuilder().clusterName(clusterName)
.settings(settingsBuilder().put(settings).put("name", "node" + i))
.node();
}
Node clientNode = nodeBuilder()
.clusterName(clusterName)
.settings(settingsBuilder().put(settings).put("name", "client")).client(true).node();
client = clientNode.client();
long[] lValues = new long[NUMBER_OF_TERMS];
for (int i = 0; i < NUMBER_OF_TERMS; i++) {
lValues[i] = ThreadLocalRandom.current().nextLong();
}
String[] sValues = new String[NUMBER_OF_TERMS];
for (int i = 0; i < NUMBER_OF_TERMS; i++) {
sValues[i] = RandomStrings.randomAsciiOfLength(random, STRING_TERM_SIZE);
}
Thread.sleep(10000);
try {
client.admin().indices().create(createIndexRequest("test").mapping("type1", jsonBuilder()
.startObject()
.startObject("type1")
.startObject("properties")
.startObject("s_value_dv")
.field("type", "string")
.field("index", "no")
.startObject("fielddata")
.field("format", "doc_values")
.endObject()
.endObject()
.startObject("sm_value_dv")
.field("type", "string")
.field("index", "no")
.startObject("fielddata")
.field("format", "doc_values")
.endObject()
.endObject()
.startObject("l_value_dv")
.field("type", "long")
.field("index", "no")
.startObject("fielddata")
.field("format", "doc_values")
.endObject()
.endObject()
.startObject("lm_value_dv")
.field("type", "long")
.field("index", "no")
.startObject("fielddata")
.field("format", "doc_values")
.endObject()
.endObject()
.endObject()
.endObject()
.endObject())).actionGet();
StopWatch stopWatch = new StopWatch().start();
System.out.println("--> Indexing [" + COUNT + "] ...");
long ITERS = COUNT / BATCH;
long i = 1;
int counter = 0;
for (; i <= ITERS; i++) {
BulkRequestBuilder request = client.prepareBulk();
for (int j = 0; j < BATCH; j++) {
counter++;
XContentBuilder builder = jsonBuilder().startObject();
builder.field("id", Integer.toString(counter));
final String sValue = sValues[counter % sValues.length];
final long lValue = lValues[counter % lValues.length];
builder.field("s_value", sValue);
builder.field("l_value", lValue);
builder.field("s_value_dv", sValue);
builder.field("l_value_dv", lValue);
for (String field : new String[] {"sm_value", "sm_value_dv"}) {
builder.startArray(field);
for (int k = 0; k < NUMBER_OF_MULTI_VALUE_TERMS; k++) {
builder.value(sValues[ThreadLocalRandom.current().nextInt(sValues.length)]);
}
builder.endArray();
}
for (String field : new String[] {"lm_value", "lm_value_dv"}) {
builder.startArray(field);
for (int k = 0; k < NUMBER_OF_MULTI_VALUE_TERMS; k++) {
builder.value(lValues[ThreadLocalRandom.current().nextInt(sValues.length)]);
}
builder.endArray();
}
builder.endObject();
request.add(Requests.indexRequest("test").type("type1").id(Integer.toString(counter))
.source(builder));
}
BulkResponse response = request.execute().actionGet();
if (response.hasFailures()) {
System.err.println("--> failures...");
}
if (((i * BATCH) % 10000) == 0) {
System.out.println("--> Indexed " + (i * BATCH) + " took " + stopWatch.stop().lastTaskTime());
stopWatch.start();
}
}
System.out.println("--> Indexing took " + stopWatch.totalTime() + ", TPS " + (((double) (COUNT)) / stopWatch.totalTime().secondsFrac()));
} catch (Exception e) {
System.out.println("--> Index already exists, ignoring indexing phase, waiting for green");
ClusterHealthResponse clusterHealthResponse = client.admin().cluster().prepareHealth().setWaitForGreenStatus().setTimeout("10m").execute().actionGet();
if (clusterHealthResponse.isTimedOut()) {
System.err.println("--> Timed out waiting for cluster health");
}
}
client.admin().indices().prepareRefresh().execute().actionGet();
COUNT = client.prepareCount().setQuery(matchAllQuery()).execute().actionGet().getCount();
System.out.println("--> Number of docs in index: " + COUNT);
List<StatsResult> stats = Lists.newArrayList();
stats.add(terms("terms_facet_s", Method.FACET, "s_value", null));
stats.add(terms("terms_facet_s_dv", Method.FACET, "s_value_dv", null));
stats.add(terms("terms_facet_map_s", Method.FACET, "s_value", "map"));
stats.add(terms("terms_facet_map_s_dv", Method.FACET, "s_value_dv", "map"));
stats.add(terms("terms_agg_s", Method.AGGREGATION, "s_value", null));
stats.add(terms("terms_agg_s_dv", Method.AGGREGATION, "s_value_dv", null));
stats.add(terms("terms_agg_map_s", Method.AGGREGATION, "s_value", "map"));
stats.add(terms("terms_agg_map_s_dv", Method.AGGREGATION, "s_value_dv", "map"));
stats.add(terms("terms_facet_l", Method.FACET, "l_value", null));
stats.add(terms("terms_facet_l_dv", Method.FACET, "l_value_dv", null));
stats.add(terms("terms_agg_l", Method.AGGREGATION, "l_value", null));
stats.add(terms("terms_agg_l_dv", Method.AGGREGATION, "l_value_dv", null));
stats.add(terms("terms_facet_sm", Method.FACET, "sm_value", null));
stats.add(terms("terms_facet_sm_dv", Method.FACET, "sm_value_dv", null));
stats.add(terms("terms_facet_map_sm", Method.FACET, "sm_value", "map"));
stats.add(terms("terms_facet_map_sm_dv", Method.FACET, "sm_value_dv", "map"));
stats.add(terms("terms_agg_sm", Method.AGGREGATION, "sm_value", null));
stats.add(terms("terms_agg_sm_dv", Method.AGGREGATION, "sm_value_dv", null));
stats.add(terms("terms_agg_map_sm", Method.AGGREGATION, "sm_value", "map"));
stats.add(terms("terms_agg_map_sm_dv", Method.AGGREGATION, "sm_value_dv", "map"));
stats.add(terms("terms_facet_lm", Method.FACET, "lm_value", null));
stats.add(terms("terms_facet_lm_dv", Method.FACET, "lm_value_dv", null));
stats.add(terms("terms_agg_lm", Method.AGGREGATION, "lm_value", null));
stats.add(terms("terms_agg_lm_dv", Method.AGGREGATION, "lm_value_dv", null));
stats.add(termsStats("terms_stats_facet_s_l", Method.FACET, "s_value", "l_value", null));
stats.add(termsStats("terms_stats_facet_s_l_dv", Method.FACET, "s_value_dv", "l_value_dv", null));
stats.add(termsStats("terms_stats_agg_s_l", Method.AGGREGATION, "s_value", "l_value", null));
stats.add(termsStats("terms_stats_agg_s_l_dv", Method.AGGREGATION, "s_value_dv", "l_value_dv", null));
stats.add(termsStats("terms_stats_facet_s_lm", Method.FACET, "s_value", "lm_value", null));
stats.add(termsStats("terms_stats_facet_s_lm_dv", Method.FACET, "s_value_dv", "lm_value_dv", null));
stats.add(termsStats("terms_stats_agg_s_lm", Method.AGGREGATION, "s_value", "lm_value", null));
stats.add(termsStats("terms_stats_agg_s_lm_dv", Method.AGGREGATION, "s_value_dv", "lm_value_dv", null));
stats.add(termsStats("terms_stats_facet_sm_l", Method.FACET, "sm_value", "l_value", null));
stats.add(termsStats("terms_stats_facet_sm_l_dv", Method.FACET, "sm_value_dv", "l_value_dv", null));
stats.add(termsStats("terms_stats_agg_sm_l", Method.AGGREGATION, "sm_value", "l_value", null));
stats.add(termsStats("terms_stats_agg_sm_l_dv", Method.AGGREGATION, "sm_value_dv", "l_value_dv", null));
System.out.println("------------------ SUMMARY -------------------------------");
System.out.format("%25s%10s%10s\n", "name", "took", "millis");
for (StatsResult stat : stats) {
System.out.format("%25s%10s%10d\n", stat.name, TimeValue.timeValueMillis(stat.took), (stat.took / QUERY_COUNT));
}
System.out.println("------------------ SUMMARY -------------------------------");
clientNode.close();
for (Node node : nodes) {
node.close();
}
}
static class StatsResult {
final String name;
final long took;
StatsResult(String name, long took) {
this.name = name;
this.took = took;
}
}
private static StatsResult terms(String name, Method method, String field, String executionHint) {
long totalQueryTime;// LM VALUE
client.admin().indices().prepareClearCache().setFieldDataCache(true).execute().actionGet();
System.out.println("--> Warmup (" + name + ")...");
// run just the child query, warm up first
for (int j = 0; j < QUERY_WARMUP; j++) {
SearchResponse searchResponse = method.addTermsAgg(client.prepareSearch()
.setSearchType(SearchType.COUNT)
.setQuery(matchAllQuery()), name, field, executionHint)
.execute().actionGet();
if (j == 0) {
System.out.println("--> Loading (" + field + "): took: " + searchResponse.getTook());
}
if (searchResponse.getHits().totalHits() != COUNT) {
System.err.println("--> mismatch on hits");
}
}
System.out.println("--> Warmup (" + name + ") DONE");
System.out.println("--> Running (" + name + ")...");
totalQueryTime = 0;
for (int j = 0; j < QUERY_COUNT; j++) {
SearchResponse searchResponse = method.addTermsAgg(client.prepareSearch()
.setSearchType(SearchType.COUNT)
.setQuery(matchAllQuery()), name, field, executionHint)
.execute().actionGet();
if (searchResponse.getHits().totalHits() != COUNT) {
System.err.println("--> mismatch on hits");
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> Terms Agg (" + name + "): " + (totalQueryTime / QUERY_COUNT) + "ms");
return new StatsResult(name, totalQueryTime);
}
private static StatsResult termsStats(String name, Method method, String keyField, String valueField, String executionHint) {
long totalQueryTime;
client.admin().indices().prepareClearCache().setFieldDataCache(true).execute().actionGet();
System.out.println("--> Warmup (" + name + ")...");
// run just the child query, warm up first
for (int j = 0; j < QUERY_WARMUP; j++) {
SearchResponse searchResponse = method.addTermsStatsAgg(client.prepareSearch()
.setSearchType(SearchType.COUNT)
.setQuery(matchAllQuery()), name, keyField, valueField)
.execute().actionGet();
if (j == 0) {
System.out.println("--> Loading (" + name + "): took: " + searchResponse.getTook());
}
if (searchResponse.getHits().totalHits() != COUNT) {
System.err.println("--> mismatch on hits");
}
}
System.out.println("--> Warmup (" + name + ") DONE");
System.out.println("--> Running (" + name + ")...");
totalQueryTime = 0;
for (int j = 0; j < QUERY_COUNT; j++) {
SearchResponse searchResponse = method.addTermsStatsAgg(client.prepareSearch()
.setSearchType(SearchType.COUNT)
.setQuery(matchAllQuery()), name, keyField, valueField)
.execute().actionGet();
if (searchResponse.getHits().totalHits() != COUNT) {
System.err.println("--> mismatch on hits");
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> Terms stats agg (" + name + "): " + (totalQueryTime / QUERY_COUNT) + "ms");
return new StatsResult(name, totalQueryTime);
}
}
| 0true
|
src_test_java_org_elasticsearch_benchmark_search_aggregations_TermsAggregationSearchBenchmark.java
|
716 |
class ShardCountResponse extends BroadcastShardOperationResponse {
private long count;
ShardCountResponse() {
}
public ShardCountResponse(String index, int shardId, long count) {
super(index, shardId);
this.count = count;
}
public long getCount() {
return this.count;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
count = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVLong(count);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_count_ShardCountResponse.java
|
747 |
public abstract class TxnCollectionRequest extends BaseTransactionRequest implements Portable, SecureRequest {
String name;
Data value;
public TxnCollectionRequest() {
}
public TxnCollectionRequest(String name) {
this.name = name;
}
public TxnCollectionRequest(String name, Data value) {
this(name);
this.value = value;
}
@Override
public int getFactoryId() {
return CollectionPortableHook.F_ID;
}
public void write(PortableWriter writer) throws IOException {
super.write(writer);
writer.writeUTF("n", name);
IOUtil.writeNullableData(writer.getRawDataOutput(), value);
}
public void read(PortableReader reader) throws IOException {
super.read(reader);
name = reader.readUTF("n");
value = IOUtil.readNullableData(reader.getRawDataInput());
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_client_TxnCollectionRequest.java
|
175 |
static final class AdaptedCallable<T> extends ForkJoinTask<T>
implements RunnableFuture<T> {
final Callable<? extends T> callable;
T result;
AdaptedCallable(Callable<? extends T> callable) {
if (callable == null) throw new NullPointerException();
this.callable = callable;
}
public final T getRawResult() { return result; }
public final void setRawResult(T v) { result = v; }
public final boolean exec() {
try {
result = callable.call();
return true;
} catch (Error err) {
throw err;
} catch (RuntimeException rex) {
throw rex;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public final void run() { invoke(); }
private static final long serialVersionUID = 2838392045355241008L;
}
| 0true
|
src_main_java_jsr166y_ForkJoinTask.java
|
108 |
private class Worker extends OtherThreadExecutor<State>
{
public Worker()
{
super( "other thread", new State( getGraphDb() ) );
}
void beginTx() throws Exception
{
execute( new WorkerCommand<State, Void>()
{
@Override
public Void doWork( State state )
{
state.tx = state.graphDb.beginTx();
return null;
}
} );
}
void finishTx() throws Exception
{
execute( new WorkerCommand<State, Void>()
{
@Override
public Void doWork( State state )
{
state.tx.success();
state.tx.finish();
return null;
}
} );
}
void setProperty( final Node node, final String key, final Object value ) throws Exception
{
execute( new WorkerCommand<State, Object>()
{
@Override
public Object doWork( State state )
{
node.setProperty( key, value );
return null;
}
}, 200, MILLISECONDS );
}
}
| 0true
|
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestManualAcquireLock.java
|
2,665 |
final class DataSerializer implements StreamSerializer<DataSerializable> {
private static final String FACTORY_ID = "com.hazelcast.DataSerializerHook";
private final Map<Integer, DataSerializableFactory> factories = new HashMap<Integer, DataSerializableFactory>();
DataSerializer(Map<Integer, ? extends DataSerializableFactory> dataSerializableFactories, ClassLoader classLoader) {
try {
final Iterator<DataSerializerHook> hooks = ServiceLoader.iterator(DataSerializerHook.class, FACTORY_ID, classLoader);
while (hooks.hasNext()) {
DataSerializerHook hook = hooks.next();
final DataSerializableFactory factory = hook.createFactory();
if (factory != null) {
register(hook.getFactoryId(), factory);
}
}
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
if (dataSerializableFactories != null) {
for (Map.Entry<Integer, ? extends DataSerializableFactory> entry : dataSerializableFactories.entrySet()) {
register(entry.getKey(), entry.getValue());
}
}
}
private void register(int factoryId, DataSerializableFactory factory) {
final DataSerializableFactory current = factories.get(factoryId);
if (current != null) {
if (current.equals(factory)) {
Logger.getLogger(getClass()).warning("DataSerializableFactory[" + factoryId + "] is already registered! Skipping "
+ factory);
} else {
throw new IllegalArgumentException("DataSerializableFactory[" + factoryId + "] is already registered! "
+ current + " -> " + factory);
}
} else {
factories.put(factoryId, factory);
}
}
public int getTypeId() {
return CONSTANT_TYPE_DATA;
}
public DataSerializable read(ObjectDataInput in) throws IOException {
final DataSerializable ds;
final boolean identified = in.readBoolean();
int id = 0;
int factoryId = 0;
String className = null;
try {
if (identified) {
factoryId = in.readInt();
final DataSerializableFactory dsf = factories.get(factoryId);
if (dsf == null) {
throw new HazelcastSerializationException("No DataSerializerFactory registered for namespace: " + factoryId);
}
id = in.readInt();
ds = dsf.create(id);
if (ds == null) {
throw new HazelcastSerializationException(dsf
+ " is not be able to create an instance for id: " + id + " on factoryId: " + factoryId);
}
// TODO: @mm - we can check if DS class is final.
} else {
className = in.readUTF();
ds = ClassLoaderUtil.newInstance(in.getClassLoader(), className);
}
ds.readData(in);
return ds;
} catch (Exception e) {
if (e instanceof IOException) {
throw (IOException) e;
}
if (e instanceof HazelcastSerializationException) {
throw (HazelcastSerializationException) e;
}
throw new HazelcastSerializationException("Problem while reading DataSerializable, namespace: "
+ factoryId
+ ", id: " + id
+ ", class: " + className
+ ", exception: " + e.getMessage(), e);
}
}
public void write(ObjectDataOutput out, DataSerializable obj) throws IOException {
final boolean identified = obj instanceof IdentifiedDataSerializable;
out.writeBoolean(identified);
if (identified) {
final IdentifiedDataSerializable ds = (IdentifiedDataSerializable) obj;
out.writeInt(ds.getFactoryId());
out.writeInt(ds.getId());
} else {
out.writeUTF(obj.getClass().getName());
}
obj.writeData(out);
}
public void destroy() {
factories.clear();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_nio_serialization_DataSerializer.java
|
305 |
public enum OGlobalConfiguration {
// ENVIRONMENT
ENVIRONMENT_DUMP_CFG_AT_STARTUP("environment.dumpCfgAtStartup", "Dumps the configuration at application startup", Boolean.class,
Boolean.FALSE),
ENVIRONMENT_CONCURRENT("environment.concurrent",
"Specifies if running in multi-thread environment. Setting this to false turns off the internal lock management",
Boolean.class, Boolean.TRUE),
// MEMORY
MEMORY_USE_UNSAFE("memory.useUnsafe", "Indicates whether Unsafe will be used if it is present", Boolean.class, true),
DIRECT_MEMORY_UNSAFE_MODE(
"memory.directMemory.unsafeMode",
"Indicates whether to do perform range check before each direct memory update, it is false by default, "
+ "but usually it can be safely put to true. It is needed to set to true only after dramatic changes in storage structures.",
Boolean.class, false),
JVM_GC_DELAY_FOR_OPTIMIZE("jvm.gc.delayForOptimize",
"Minimal amount of time (seconds) since last System.gc() when called after tree optimization", Long.class, 600),
// STORAGE
DISK_CACHE_SIZE("storage.diskCache.bufferSize", "Size of disk buffer in megabytes", Integer.class, 4 * 1024),
DISK_WRITE_CACHE_PART("storage.diskCache.writeCachePart", "Percent of disk cache which is use as write cache", Integer.class, 30),
DISK_WRITE_CACHE_PAGE_TTL("storage.diskCache.writeCachePageTTL",
"Max time till page will be flushed from write cache in seconds", Long.class, 24 * 60 * 60),
DISK_WRITE_CACHE_PAGE_FLUSH_INTERVAL("storage.diskCache.writeCachePageFlushInterval",
"Interval between flushing of pages from write cache in ms.", Integer.class, 100),
DISK_WRITE_CACHE_FLUSH_LOCK_TIMEOUT("storage.diskCache.writeCacheFlushLockTimeout",
"Maximum amount of time till write cache will be wait before page flush in ms.", Integer.class, -1),
STORAGE_COMPRESSION_METHOD("storage.compressionMethod", "Record compression method is used in storage."
+ " Possible values : gzip, nothing, snappy, snappy-native. Default is snappy.", String.class, "snappy"),
USE_WAL("storage.useWAL", "Whether WAL should be used in paginated storage", Boolean.class, true),
WAL_CACHE_SIZE("storage.wal.cacheSize",
"Maximum size of WAL cache (in amount of WAL pages, each page is 64k) <= 0 means that caching will be switched off.",
Integer.class, 3000),
WAL_MAX_SEGMENT_SIZE("storage.wal.maxSegmentSize", "Maximum size of single WAL segment in megabytes.", Integer.class, 256),
WAL_MAX_SIZE("storage.wal.maxSize", "Maximum size of WAL on disk in megabytes.", Integer.class, 4 * 1024),
WAL_COMMIT_TIMEOUT("storage.wal.commitTimeout", "Maximum interval between WAL commits (in ms.)", Integer.class, 1000),
WAL_SHUTDOWN_TIMEOUT("storage.wal.shutdownTimeout", "Maximum wait interval between events when background flush thread"
+ " will receive shutdown command and when background flush will be stopped (in ms.)", Integer.class, 10000),
WAL_FUZZY_CHECKPOINT_INTERVAL("storage.wal.fuzzyCheckpointInterval", "Interval between fuzzy checkpoints (in seconds)",
Integer.class, 2592000),
WAL_FUZZY_CHECKPOINT_SHUTDOWN_TIMEOUT("storage.wal.fuzzyCheckpointShutdownWait",
"Interval which we should wait till shutdown (in seconds)", Integer.class, 60 * 10),
WAL_FULL_CHECKPOINT_SHUTDOWN_TIMEOUT("storage.wal.fullCheckpointShutdownTimeout",
"Timeout till DB will wait that full checkpoint is finished during DB close (in seconds))", Integer.class, 60 * 10),
WAL_LOCATION("storage.wal.path", "Path to the wal file on the disk, by default is placed in DB directory but"
+ " it is highly recomended to use separate disk to store log operations", String.class, null),
STORAGE_MAKE_FULL_CHECKPOINT_AFTER_CREATE("storage.makeFullCheckpointAfterCreate",
"Indicates whether full checkpoint should be performed if storage was opened.", Boolean.class, true),
STORAGE_MAKE_FULL_CHECKPOINT_AFTER_CLUSTER_CREATE("storage.makeFullCheckpointAfterClusterCreate",
"Indicates whether full checkpoint should be performed if storage was opened.", Boolean.class, true),
DISK_CACHE_PAGE_SIZE("storage.diskCache.pageSize", "Size of page of disk buffer in kilobytes", Integer.class, 64),
PAGINATED_STORAGE_LOWEST_FREELIST_BOUNDARY("storage.lowestFreeListBound", "The minimal amount of free space (in kb)"
+ " in page which is tracked in paginated storage", Integer.class, 16),
USE_NODE_ID_CLUSTER_POSITION("storage.cluster.useNodeIdAsClusterPosition", "Indicates whether cluster position should be"
+ " treated as node id not as long value.", Boolean.class, Boolean.FALSE),
STORAGE_KEEP_OPEN(
"storage.keepOpen",
"Tells to the engine to not close the storage when a database is closed. Storages will be closed when the process shuts down",
Boolean.class, Boolean.TRUE),
STORAGE_LOCK_TIMEOUT("storage.lockTimeout", "Maximum timeout in milliseconds to lock the storage", Integer.class, 600000),
STORAGE_RECORD_LOCK_TIMEOUT("storage.record.lockTimeout", "Maximum timeout in milliseconds to lock a shared record",
Integer.class, 5000),
STORAGE_USE_TOMBSTONES("storage.useTombstones", "When record will be deleted its cluster"
+ " position will not be freed but tombstone will be placed instead", Boolean.class, false),
// RECORDS
RECORD_DOWNSIZING_ENABLED(
"record.downsizing.enabled",
"On updates if the record size is lower than before, reduces the space taken accordlying. If enabled this could increase defragmentation, but it reduces the used space",
Boolean.class, true),
// CACHE
CACHE_LEVEL1_ENABLED("cache.level1.enabled", "Use the level-1 cache", Boolean.class, true),
CACHE_LEVEL1_SIZE("cache.level1.size", "Size of the cache that keeps the record in memory", Integer.class, 1000),
CACHE_LEVEL2_ENABLED("cache.level2.enabled", "Use the level-2 cache", Boolean.class, false),
CACHE_LEVEL2_SIZE("cache.level2.size", "Size of the cache that keeps the record in memory", Integer.class, 0),
CACHE_LEVEL2_IMPL("cache.level2.impl", "Actual implementation of secondary cache", String.class, ODefaultCache.class
.getCanonicalName()),
CACHE_LEVEL2_STRATEGY("cache.level2.strategy",
"Strategy to use when a database requests a record: 0 = pop the record, 1 = copy the record", Integer.class, 0,
new OConfigurationChangeCallback() {
public void change(final Object iCurrentValue, final Object iNewValue) {
// UPDATE ALL THE OPENED STORAGES SETTING THE NEW STRATEGY
// for (OStorage s : com.orientechnologies.orient.core.Orient.instance().getStorages()) {
// s.getCache().setStrategy((Integer) iNewValue);
// }
}
}),
// DATABASE
OBJECT_SAVE_ONLY_DIRTY("object.saveOnlyDirty", "Object Database only saves objects bound to dirty records", Boolean.class, false),
// DATABASE
DB_POOL_MIN("db.pool.min", "Default database pool minimum size", Integer.class, 1),
DB_POOL_MAX("db.pool.max", "Default database pool maximum size", Integer.class, 20),
DB_POOL_IDLE_TIMEOUT("db.pool.idleTimeout", "Default database pool maximum size", Integer.class, 0),
DB_POOL_IDLE_CHECK_DELAY("db.pool.idleCheckDelay", "Default database pool maximum size", Integer.class, 0),
@Deprecated
DB_MVCC("db.mvcc", "Enables or disables MVCC (Multi-Version Concurrency Control) even outside transactions", Boolean.class, true),
DB_MVCC_THROWFAST(
"db.mvcc.throwfast",
"Use fast-thrown exceptions for MVCC OConcurrentModificationExceptions. No context information will be available, use where these exceptions are handled and the detail is not neccessary",
Boolean.class, false),
DB_VALIDATION("db.validation", "Enables or disables validation of records", Boolean.class, true),
DB_USE_DISTRIBUTED_VERSION("db.use.distributedVersion", "Use extended version that is safe in distributed environment",
Boolean.class, Boolean.FALSE),
// SETTINGS OF NON-TRANSACTIONAL MODE
NON_TX_RECORD_UPDATE_SYNCH("nonTX.recordUpdate.synch",
"Executes a synch against the file-system at every record operation. This slows down records updates "
+ "but guarantee reliability on unreliable drives", Boolean.class, Boolean.FALSE),
NON_TX_CLUSTERS_SYNC_IMMEDIATELY("nonTX.clusters.sync.immediately",
"List of clusters to sync immediately after update separated by commas. Can be useful for manual index", String.class,
OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME),
// TRANSACTIONS
TX_USE_LOG("tx.useLog", "Transactions use log file to store temporary data to be rolled back in case of crash", Boolean.class,
true),
TX_AUTO_RETRY("tx.autoRetry",
"Maximum number of automatic retry if some resource has been locked in the middle of the transaction (Timeout exception)",
Integer.class, 1),
TX_LOG_TYPE("tx.log.fileType", "File type to handle transaction logs: mmap or classic", String.class, "classic"),
TX_LOG_SYNCH(
"tx.log.synch",
"Executes a synch against the file-system at every log entry. This slows down transactions but guarantee transaction reliability on unreliable drives",
Boolean.class, Boolean.FALSE),
TX_COMMIT_SYNCH("tx.commit.synch", "Synchronizes the storage after transaction commit", Boolean.class, false),
// INDEX
HASH_TABLE_SPLIT_BUCKETS_BUFFER_LENGTH("hashTable.slitBucketsBuffer.length", "Length of buffer (in pages) where buckets "
+ "that were splited but not flushed to the disk are kept. This buffer is used to minimize random IO overhead.",
Integer.class, 1500),
INDEX_AUTO_REBUILD_AFTER_NOTSOFTCLOSE("index.auto.rebuildAfterNotSoftClose",
"Auto rebuild all automatic indexes after upon database open when wasn't closed properly", Boolean.class, true),
INDEX_SYNCHRONOUS_AUTO_REBUILD("index.auto.synchronousAutoRebuild",
"Synchronous execution of auto rebuilding of indexes in case of db crash.", Boolean.class, Boolean.TRUE),
INDEX_AUTO_LAZY_UPDATES(
"index.auto.lazyUpdates",
"Configure the TreeMaps for automatic indexes as buffered or not. -1 means buffered until tx.commit() or db.close() are called",
Integer.class, 10000),
INDEX_MANUAL_LAZY_UPDATES("index.manual.lazyUpdates",
"Configure the TreeMaps for manual indexes as buffered or not. -1 means buffered until tx.commit() or db.close() are called",
Integer.class, 1),
INDEX_DURABLE_IN_NON_TX_MODE("index.durableInNonTxMode",
"Indicates whether index implementation for plocal storage will be durable in non-Tx mode, false by default", Boolean.class,
false),
INDEX_TX_MODE("index.txMode",
"Indicates index durability level in TX mode. Can be ROLLBACK_ONLY or FULL (ROLLBACK_ONLY by default)", String.class,
"ROLLBACK_ONLY"),
INDEX_USE_SBTREE_BY_DEFAULT("index.useSBTreeByDefault",
"Whether new SBTree index implementation should be used instead of old MVRB-Tree", Boolean.class, true),
INDEX_NOTUNIQUE_USE_SBTREE_CONTAINER_BY_DEFAULT("index.notunique.useSBTreeContainerByDefault",
"Prefer SBTree based algorithm instead MVRBTree for storing sets of RID", Boolean.class, true),
// TREEMAP
MVRBTREE_TIMEOUT("mvrbtree.timeout", "Maximum timeout to get lock against the OMVRB-Tree", Integer.class, 5000),
MVRBTREE_NODE_PAGE_SIZE("mvrbtree.nodePageSize",
"Page size of each node. 256 means that 256 entries can be stored inside each node", Integer.class, 256),
MVRBTREE_LOAD_FACTOR("mvrbtree.loadFactor", "HashMap load factor", Float.class, 0.7f),
MVRBTREE_OPTIMIZE_THRESHOLD(
"mvrbtree.optimizeThreshold",
"Auto optimize the TreeMap every X tree rotations. This forces the optimization of the tree after many changes to recompute entry points. -1 means never",
Integer.class, 100000),
MVRBTREE_ENTRYPOINTS("mvrbtree.entryPoints", "Number of entry points to start searching entries", Integer.class, 64),
MVRBTREE_OPTIMIZE_ENTRYPOINTS_FACTOR("mvrbtree.optimizeEntryPointsFactor",
"Multiplicand factor to apply to entry-points list (parameter mvrbtree.entrypoints) to determine optimization is needed",
Float.class, 1.0f),
MVRBTREE_ENTRY_KEYS_IN_MEMORY("mvrbtree.entryKeysInMemory", "Keep unserialized keys in memory", Boolean.class, Boolean.FALSE),
MVRBTREE_ENTRY_VALUES_IN_MEMORY("mvrbtree.entryValuesInMemory", "Keep unserialized values in memory", Boolean.class,
Boolean.FALSE),
// TREEMAP OF RIDS
MVRBTREE_RID_BINARY_THRESHOLD(
"mvrbtree.ridBinaryThreshold",
"Valid for set of rids. It's the threshold as number of entries to use the binary streaming instead of classic string streaming. -1 means never use binary streaming",
Integer.class, 8),
MVRBTREE_RID_NODE_PAGE_SIZE("mvrbtree.ridNodePageSize",
"Page size of each treeset node. 16 means that 16 entries can be stored inside each node", Integer.class, 64),
MVRBTREE_RID_NODE_SAVE_MEMORY("mvrbtree.ridNodeSaveMemory",
"Save memory usage by avoid keeping RIDs in memory but creating them at every access", Boolean.class, Boolean.FALSE),
// SBTREE
SBTREE_MAX_KEY_SIZE("sbtree.maxKeySize", "Maximum size of key which can be put in SBTree in bytes (10240 by default)",
Integer.class, 10240),
SBTREE_MAX_EMBEDDED_VALUE_SIZE("sbtree.maxEmbeddedValueSize",
"Maximum size of value which can be put in SBTree without creation link to standalone page in bytes (40960 by default)",
Integer.class, 40960),
SBTREEBONSAI_BUCKET_SIZE("sbtreebonsai.bucketSize",
"Size of bucket in OSBTreeBonsai in kB. Contract: bucketSize < storagePageSize, storagePageSize % bucketSize == 0.",
Integer.class, 2),
// COLLECTIONS
LAZYSET_WORK_ON_STREAM("lazyset.workOnStream", "Upon add avoid unmarshalling set", Boolean.class, true),
PREFER_SBTREE_SET("collections.preferSBTreeSet", "This config is experimental.", Boolean.class, false),
// FILE
FILE_LOCK("file.lock", "Locks files when used. Default is false", boolean.class, true),
FILE_DEFRAG_STRATEGY("file.defrag.strategy", "Strategy to recycle free space: 0 = synchronous defrag, 1 = asynchronous defrag, ",
Integer.class, 0),
FILE_DEFRAG_HOLE_MAX_DISTANCE(
"file.defrag.holeMaxDistance",
"Max distance in bytes between holes to cause their defrag. Set it to -1 to use dynamic size. Beware that if the db is huge moving blocks to defrag could be expensive",
Integer.class, 32768),
FILE_MMAP_USE_OLD_MANAGER("file.mmap.useOldManager",
"Manager that will be used to handle mmap files. true = USE OLD MANAGER, false = USE NEW MANAGER", boolean.class, false),
FILE_MMAP_AUTOFLUSH_TIMER("file.mmap.autoFlush.timer", "Auto flushes memory mapped blocks every X seconds. 0 = disabled",
int.class, 30),
FILE_MMAP_AUTOFLUSH_UNUSED_TIME("file.mmap.autoFlush.unusedTime",
"Remove memory mapped blocks with unused time major than this value. Time is in seconds", int.class, 30),
FILE_MMAP_LOCK_MEMORY("file.mmap.lockMemory",
"When using new map manager this parameter specify prevent memory swap or not. true = LOCK MEMORY, false = NOT LOCK MEMORY",
boolean.class, true),
FILE_MMAP_STRATEGY(
"file.mmap.strategy",
"Strategy to use with memory mapped files. 0 = USE MMAP ALWAYS, 1 = USE MMAP ON WRITES OR ON READ JUST WHEN THE BLOCK POOL IS FREE, 2 = USE MMAP ON WRITES OR ON READ JUST WHEN THE BLOCK IS ALREADY AVAILABLE, 3 = USE MMAP ONLY IF BLOCK IS ALREADY AVAILABLE, 4 = NEVER USE MMAP",
Integer.class, 0),
FILE_MMAP_BLOCK_SIZE("file.mmap.blockSize", "Size of the memory mapped block, default is 1Mb", Integer.class, 1048576,
new OConfigurationChangeCallback() {
public void change(final Object iCurrentValue, final Object iNewValue) {
OMMapManagerOld.setBlockSize(((Number) iNewValue).intValue());
}
}),
FILE_MMAP_BUFFER_SIZE("file.mmap.bufferSize", "Size of the buffer for direct access to the file through the channel",
Integer.class, 8192),
FILE_MMAP_MAX_MEMORY(
"file.mmap.maxMemory",
"Max memory allocatable by memory mapping manager. Note that on 32bit operating systems, the limit is 2Gb but will vary between operating systems",
Long.class, 134217728, new OConfigurationChangeCallback() {
public void change(final Object iCurrentValue, final Object iNewValue) {
OMMapManagerOld.setMaxMemory(OFileUtils.getSizeAsNumber(iNewValue));
}
}),
FILE_MMAP_OVERLAP_STRATEGY(
"file.mmap.overlapStrategy",
"Strategy to use when a request overlaps in-memory buffers: 0 = Use the channel access, 1 = force the in-memory buffer and use the channel access, 2 = always create an overlapped in-memory buffer (default)",
Integer.class, 2, new OConfigurationChangeCallback() {
public void change(final Object iCurrentValue, final Object iNewValue) {
OMMapManagerOld.setOverlapStrategy((Integer) iNewValue);
}
}),
FILE_MMAP_FORCE_DELAY("file.mmap.forceDelay",
"Delay time in ms to wait for another forced flush of the memory-mapped block to disk", Integer.class, 10),
FILE_MMAP_FORCE_RETRY("file.mmap.forceRetry", "Number of times the memory-mapped block will try to flush to disk", Integer.class,
50),
JNA_DISABLE_USE_SYSTEM_LIBRARY("jna.disable.system.library",
"This property disable to using JNA installed in your system. And use JNA bundled with database.", boolean.class, true),
// NETWORK
NETWORK_MAX_CONCURRENT_SESSIONS("network.maxConcurrentSessions", "Maximum number of concurrent sessions", Integer.class, 1000),
NETWORK_SOCKET_BUFFER_SIZE("network.socketBufferSize", "TCP/IP Socket buffer size", Integer.class, 32768),
NETWORK_LOCK_TIMEOUT("network.lockTimeout", "Timeout in ms to acquire a lock against a channel", Integer.class, 15000),
NETWORK_SOCKET_TIMEOUT("network.socketTimeout", "TCP/IP Socket timeout in ms", Integer.class, 15000),
NETWORK_SOCKET_RETRY("network.retry", "Number of times the client retries its connection to the server on failure",
Integer.class, 5),
NETWORK_SOCKET_RETRY_DELAY("network.retryDelay", "Number of ms the client waits before reconnecting to the server on failure",
Integer.class, 500),
NETWORK_BINARY_DNS_LOADBALANCING_ENABLED("network.binary.loadBalancing.enabled",
"Asks for DNS TXT record to determine if load balancing is supported", Boolean.class, Boolean.FALSE),
NETWORK_BINARY_DNS_LOADBALANCING_TIMEOUT("network.binary.loadBalancing.timeout",
"Maximum time (in ms) to wait for the answer from DNS about the TXT record for load balancing", Integer.class, 2000),
NETWORK_BINARY_MAX_CONTENT_LENGTH("network.binary.maxLength", "TCP/IP max content length in bytes of BINARY requests",
Integer.class, 32736),
NETWORK_BINARY_READ_RESPONSE_MAX_TIMES("network.binary.readResponse.maxTimes",
"Maximum times to wait until response will be read. Otherwise response will be dropped from chanel", Integer.class, 20),
NETWORK_BINARY_DEBUG("network.binary.debug", "Debug mode: print all data incoming on the binary channel", Boolean.class, false),
NETWORK_HTTP_MAX_CONTENT_LENGTH("network.http.maxLength", "TCP/IP max content length in bytes for HTTP requests", Integer.class,
1000000),
NETWORK_HTTP_CONTENT_CHARSET("network.http.charset", "Http response charset", String.class, "utf-8"),
NETWORK_HTTP_SESSION_EXPIRE_TIMEOUT("network.http.sessionExpireTimeout",
"Timeout after which an http session is considered tp have expired (seconds)", Integer.class, 300),
// PROFILER
PROFILER_ENABLED("profiler.enabled", "Enable the recording of statistics and counters", Boolean.class, false,
new OConfigurationChangeCallback() {
public void change(final Object iCurrentValue, final Object iNewValue) {
if ((Boolean) iNewValue)
Orient.instance().getProfiler().startRecording();
else
Orient.instance().getProfiler().stopRecording();
}
}),
PROFILER_CONFIG("profiler.config", "Configures the profiler as <seconds-for-snapshot>,<archive-snapshot-size>,<summary-size>",
String.class, null, new OConfigurationChangeCallback() {
public void change(final Object iCurrentValue, final Object iNewValue) {
Orient.instance().getProfiler().configure(iNewValue.toString());
}
}),
PROFILER_AUTODUMP_INTERVAL("profiler.autoDump.interval",
"Dumps the profiler values at regular intervals. Time is expressed in seconds", Integer.class, 0,
new OConfigurationChangeCallback() {
public void change(final Object iCurrentValue, final Object iNewValue) {
Orient.instance().getProfiler().setAutoDump((Integer) iNewValue);
}
}),
// LOG
LOG_CONSOLE_LEVEL("log.console.level", "Console logging level", String.class, "info", new OConfigurationChangeCallback() {
public void change(final Object iCurrentValue, final Object iNewValue) {
OLogManager.instance().setLevel((String) iNewValue, ConsoleHandler.class);
}
}),
LOG_FILE_LEVEL("log.file.level", "File logging level", String.class, "fine", new OConfigurationChangeCallback() {
public void change(final Object iCurrentValue, final Object iNewValue) {
OLogManager.instance().setLevel((String) iNewValue, FileHandler.class);
}
}),
// COMMAND
COMMAND_TIMEOUT("command.timeout", "Default timeout for commands expressed in milliseconds", Long.class, 0),
// CLIENT
CLIENT_CHANNEL_MIN_POOL("client.channel.minPool", "Minimum pool size", Integer.class, 1),
CLIENT_CHANNEL_MAX_POOL("client.channel.maxPool", "Maximum channel pool size", Integer.class, 20),
CLIENT_CONNECT_POOL_WAIT_TIMEOUT("client.connectionPool.waitTimeout",
"Maximum time which client should wait connection from the pool", Integer.class, 5000),
CLIENT_DB_RELEASE_WAIT_TIMEOUT("client.channel.dbReleaseWaitTimeout",
"Delay in ms. after which data modification command will be resent if DB was frozen", Integer.class, 10000),
// SERVER
SERVER_CHANNEL_CLEAN_DELAY("server.channel.cleanDelay", "Time in ms of delay to check pending closed connections", Integer.class,
5000),
SERVER_CACHE_FILE_STATIC("server.cache.staticFile", "Cache static resources loading", Boolean.class, false),
SERVER_CACHE_INCREASE_ON_DEMAND("server.cache.2q.increaseOnDemand", "Increase 2q cache on demand", Boolean.class, true),
SERVER_CACHE_INCREASE_STEP("server.cache.2q.increaseStep",
"Increase 2q cache step in percent. Will only work if server.cache.2q.increaseOnDemand is true", Float.class, 0.1f),
SERVER_LOG_DUMP_CLIENT_EXCEPTION_LEVEL(
"server.log.dumpClientExceptionLevel",
"Logs client exceptions. Use any level supported by Java java.util.logging.Level class: OFF, FINE, CONFIG, INFO, WARNING, SEVERE",
Level.class, Level.FINE),
SERVER_LOG_DUMP_CLIENT_EXCEPTION_FULLSTACKTRACE("server.log.dumpClientExceptionFullStackTrace",
"Dumps the full stack trace of the exception to sent to the client", Level.class, Boolean.TRUE),
// DISTRIBUTED
DISTRIBUTED_THREAD_QUEUE_SIZE("distributed.threadQueueSize", "Size of the queue for internal thread dispatching", Integer.class,
10000),
DISTRIBUTED_CRUD_TASK_SYNCH_TIMEOUT("distributed.crudTaskTimeout",
"Maximum timeout in milliseconds to wait for CRUD remote tasks", Integer.class, 3000l),
DISTRIBUTED_COMMAND_TASK_SYNCH_TIMEOUT("distributed.commandTaskTimeout",
"Maximum timeout in milliseconds to wait for Command remote tasks", Integer.class, 5000l),
DISTRIBUTED_QUEUE_TIMEOUT("distributed.queueTimeout", "Maximum timeout in milliseconds to wait for the response in replication",
Integer.class, 5000l),
DISTRIBUTED_ASYNCH_RESPONSES_TIMEOUT("distributed.asynchResponsesTimeout",
"Maximum timeout in milliseconds to collect all the asynchronous responses from replication", Integer.class, 15000l),
DISTRIBUTED_PURGE_RESPONSES_TIMER_DELAY("distributed.purgeResponsesTimerDelay",
"Maximum timeout in milliseconds to collect all the asynchronous responses from replication", Integer.class, 15000l);
private final String key;
private final Object defValue;
private final Class<?> type;
private Object value = null;
private String description;
private OConfigurationChangeCallback changeCallback = null;
// AT STARTUP AUTO-CONFIG
static {
readConfiguration();
autoConfig();
}
OGlobalConfiguration(final String iKey, final String iDescription, final Class<?> iType, final Object iDefValue,
final OConfigurationChangeCallback iChangeAction) {
this(iKey, iDescription, iType, iDefValue);
changeCallback = iChangeAction;
}
OGlobalConfiguration(final String iKey, final String iDescription, final Class<?> iType, final Object iDefValue) {
key = iKey;
description = iDescription;
defValue = iDefValue;
type = iType;
}
public void setValue(final Object iValue) {
Object oldValue = value;
if (iValue != null)
if (type == Boolean.class)
value = Boolean.parseBoolean(iValue.toString());
else if (type == Integer.class)
value = Integer.parseInt(iValue.toString());
else if (type == Float.class)
value = Float.parseFloat(iValue.toString());
else if (type == String.class)
value = iValue.toString();
else
value = iValue;
if (changeCallback != null)
changeCallback.change(oldValue, value);
}
public Object getValue() {
return value != null ? value : defValue;
}
public boolean getValueAsBoolean() {
final Object v = value != null ? value : defValue;
return v instanceof Boolean ? ((Boolean) v).booleanValue() : Boolean.parseBoolean(v.toString());
}
public String getValueAsString() {
return value != null ? value.toString() : defValue != null ? defValue.toString() : null;
}
public int getValueAsInteger() {
final Object v = value != null ? value : defValue;
return (int) (v instanceof Number ? ((Number) v).intValue() : OFileUtils.getSizeAsNumber(v.toString()));
}
public long getValueAsLong() {
final Object v = value != null ? value : defValue;
return v instanceof Number ? ((Number) v).longValue() : OFileUtils.getSizeAsNumber(v.toString());
}
public float getValueAsFloat() {
final Object v = value != null ? value : defValue;
return v instanceof Float ? ((Float) v).floatValue() : Float.parseFloat(v.toString());
}
public String getKey() {
return key;
}
public Class<?> getType() {
return type;
}
public String getDescription() {
return description;
}
public static void dumpConfiguration(final PrintStream out) {
out.print("OrientDB ");
out.print(OConstants.getVersion());
out.println(" configuration dump:");
String lastSection = "";
for (OGlobalConfiguration v : values()) {
final String section = v.key.substring(0, v.key.indexOf('.'));
if (!lastSection.equals(section)) {
out.print("- ");
out.println(section.toUpperCase());
lastSection = section;
}
out.print(" + ");
out.print(v.key);
out.print(" = ");
out.println(v.getValue());
}
}
/**
* Find the OGlobalConfiguration instance by the key. Key is case insensitive.
*
* @param iKey
* Key to find. It's case insensitive.
* @return OGlobalConfiguration instance if found, otherwise null
*/
public static OGlobalConfiguration findByKey(final String iKey) {
for (OGlobalConfiguration v : values()) {
if (v.getKey().equalsIgnoreCase(iKey))
return v;
}
return null;
}
/**
* Changes the configuration values in one shot by passing a Map of values. Keys can be the Java ENUM names or the string
* representation of configuration values
*/
public static void setConfiguration(final Map<String, Object> iConfig) {
for (Entry<String, Object> config : iConfig.entrySet()) {
for (OGlobalConfiguration v : values()) {
if (v.getKey().equals(config.getKey())) {
v.setValue(config.getValue());
break;
} else if (v.name().equals(config.getKey())) {
v.setValue(config.getValue());
break;
}
}
}
}
/**
* Assign configuration values by reading system properties.
*/
private static void readConfiguration() {
String prop;
for (OGlobalConfiguration config : values()) {
prop = System.getProperty(config.key);
if (prop != null)
config.setValue(prop);
}
}
private static void autoConfig() {
if (System.getProperty("os.arch").indexOf("64") > -1) {
// 64 BIT
if (FILE_MMAP_MAX_MEMORY.getValueAsInteger() == 134217728) {
final OperatingSystemMXBean bean = java.lang.management.ManagementFactory.getOperatingSystemMXBean();
try {
final Class<?> cls = Class.forName("com.sun.management.OperatingSystemMXBean");
if (cls.isAssignableFrom(bean.getClass())) {
final Long maxOsMemory = (Long) cls.getMethod("getTotalPhysicalMemorySize", new Class[] {}).invoke(bean);
final long maxProcessMemory = Runtime.getRuntime().maxMemory();
long mmapBestMemory = (maxOsMemory.longValue() - maxProcessMemory) / 2;
FILE_MMAP_MAX_MEMORY.setValue(mmapBestMemory);
}
} catch (Exception e) {
// SUN JMX CLASS NOT AVAILABLE: CAN'T AUTO TUNE THE ENGINE
}
}
} else {
// 32 BIT, USE THE DEFAULT CONFIGURATION
}
System.setProperty(MEMORY_USE_UNSAFE.getKey(), MEMORY_USE_UNSAFE.getValueAsString());
System.setProperty(DIRECT_MEMORY_UNSAFE_MODE.getKey(), DIRECT_MEMORY_UNSAFE_MODE.getValueAsString());
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_config_OGlobalConfiguration.java
|
1,145 |
public class ChildSearchBenchmark {
public static void main(String[] args) throws Exception {
Settings settings = settingsBuilder()
.put("index.refresh_interval", "-1")
.put("gateway.type", "local")
.put(SETTING_NUMBER_OF_SHARDS, 1)
.put(SETTING_NUMBER_OF_REPLICAS, 0)
.build();
String clusterName = ChildSearchBenchmark.class.getSimpleName();
Node node1 = nodeBuilder().clusterName(clusterName)
.settings(settingsBuilder().put(settings).put("name", "node1")).node();
Client client = node1.client();
int COUNT = (int) SizeValue.parseSizeValue("2m").singles();
int CHILD_COUNT = 15;
int QUERY_VALUE_RATIO = 3;
int QUERY_WARMUP = 10;
int QUERY_COUNT = 20;
String indexName = "test";
ParentChildIndexGenerator parentChildIndexGenerator = new ParentChildIndexGenerator(client, COUNT, CHILD_COUNT, QUERY_VALUE_RATIO);
client.admin().cluster().prepareHealth(indexName).setWaitForGreenStatus().setTimeout("10s").execute().actionGet();
try {
client.admin().indices().create(createIndexRequest(indexName)).actionGet();
client.admin().indices().preparePutMapping(indexName).setType("child").setSource(XContentFactory.jsonBuilder().startObject().startObject("child")
.startObject("_parent").field("type", "parent").endObject()
.endObject().endObject()).execute().actionGet();
Thread.sleep(5000);
long startTime = System.currentTimeMillis();
parentChildIndexGenerator.index();
System.out.println("--> Indexing took " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds.");
} catch (IndexAlreadyExistsException e) {
System.out.println("--> Index already exists, ignoring indexing phase, waiting for green");
ClusterHealthResponse clusterHealthResponse = client.admin().cluster().prepareHealth(indexName).setWaitForGreenStatus().setTimeout("10m").execute().actionGet();
if (clusterHealthResponse.isTimedOut()) {
System.err.println("--> Timed out waiting for cluster health");
}
}
client.admin().indices().prepareRefresh().execute().actionGet();
System.out.println("--> Number of docs in index: " + client.prepareCount(indexName).setQuery(matchAllQuery()).execute().actionGet().getCount());
System.out.println("--> Running just child query");
// run just the child query, warm up first
for (int j = 0; j < QUERY_WARMUP; j++) {
client.prepareSearch(indexName).setQuery(termQuery("child.tag", "tag1")).execute().actionGet();
}
long totalQueryTime = 0;
for (int j = 0; j < QUERY_COUNT; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName).setQuery(termQuery("child.tag", "tag1")).execute().actionGet();
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> Just Child Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
NodesStatsResponse statsResponse = client.admin().cluster().prepareNodesStats()
.setJvm(true).execute().actionGet();
System.out.println("--> Committed heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapCommitted());
System.out.println("--> Used heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapUsed());
// run parent child constant query
for (int j = 0; j < QUERY_WARMUP; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName)
.setQuery(
filteredQuery(
matchAllQuery(),
hasChildFilter("child", termQuery("field2", parentChildIndexGenerator.getQueryValue()))
)
)
.execute().actionGet();
if (searchResponse.getFailedShards() > 0) {
System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
}
}
totalQueryTime = 0;
for (int j = 0; j < QUERY_COUNT; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName)
.setQuery(
filteredQuery(
matchAllQuery(),
hasChildFilter("child", termQuery("field2", parentChildIndexGenerator.getQueryValue()))
)
)
.execute().actionGet();
if (searchResponse.getFailedShards() > 0) {
System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
}
if (j % 10 == 0) {
System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> has_child filter Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
System.out.println("--> Running has_child filter with match_all child query");
totalQueryTime = 0;
for (int j = 1; j <= QUERY_COUNT; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName)
.setQuery(
filteredQuery(
matchAllQuery(),
hasChildFilter("child", matchAllQuery())
)
)
.execute().actionGet();
if (searchResponse.getFailedShards() > 0) {
System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
}
if (j % 10 == 0) {
System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> has_child filter with match_all child query, Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
// run parent child constant query
for (int j = 0; j < QUERY_WARMUP; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName)
.setQuery(
filteredQuery(
matchAllQuery(),
hasParentFilter("parent", termQuery("field1", parentChildIndexGenerator.getQueryValue()))
)
)
.execute().actionGet();
if (searchResponse.getFailedShards() > 0) {
System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
}
}
totalQueryTime = 0;
for (int j = 1; j <= QUERY_COUNT; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName)
.setQuery(
filteredQuery(
matchAllQuery(),
hasParentFilter("parent", termQuery("field1", parentChildIndexGenerator.getQueryValue()))
)
)
.execute().actionGet();
if (searchResponse.getFailedShards() > 0) {
System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
}
if (j % 10 == 0) {
System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> has_parent filter Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
System.out.println("--> Running has_parent filter with match_all parent query ");
totalQueryTime = 0;
for (int j = 1; j <= QUERY_COUNT; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName)
.setQuery(filteredQuery(
matchAllQuery(),
hasParentFilter("parent", matchAllQuery())
))
.execute().actionGet();
if (searchResponse.getFailedShards() > 0) {
System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures()));
}
if (j % 10 == 0) {
System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> has_parent filter with match_all parent query, Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
System.out.println("--> Running top_children query");
// run parent child score query
for (int j = 0; j < QUERY_WARMUP; j++) {
client.prepareSearch(indexName).setQuery(topChildrenQuery("child", termQuery("field2", parentChildIndexGenerator.getQueryValue()))).execute().actionGet();
}
totalQueryTime = 0;
for (int j = 0; j < QUERY_COUNT; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName).setQuery(topChildrenQuery("child", termQuery("field2", parentChildIndexGenerator.getQueryValue()))).execute().actionGet();
if (j % 10 == 0) {
System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> top_children Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
System.out.println("--> Running top_children query, with match_all as child query");
// run parent child score query
for (int j = 0; j < QUERY_WARMUP; j++) {
client.prepareSearch(indexName).setQuery(topChildrenQuery("child", matchAllQuery())).execute().actionGet();
}
totalQueryTime = 0;
for (int j = 0; j < QUERY_COUNT; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName).setQuery(topChildrenQuery("child", matchAllQuery())).execute().actionGet();
if (j % 10 == 0) {
System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> top_children, with match_all Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
statsResponse = client.admin().cluster().prepareNodesStats()
.setJvm(true).setIndices(true).execute().actionGet();
System.out.println("--> Id cache size: " + statsResponse.getNodes()[0].getIndices().getIdCache().getMemorySize());
System.out.println("--> Used heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapUsed());
System.out.println("--> Running has_child query with score type");
// run parent child score query
for (int j = 0; j < QUERY_WARMUP; j++) {
client.prepareSearch(indexName).setQuery(hasChildQuery("child", termQuery("field2", parentChildIndexGenerator.getQueryValue())).scoreType("max")).execute().actionGet();
}
totalQueryTime = 0;
for (int j = 0; j < QUERY_COUNT; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName).setQuery(hasChildQuery("child", termQuery("field2", parentChildIndexGenerator.getQueryValue())).scoreType("max")).execute().actionGet();
if (j % 10 == 0) {
System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> has_child Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
totalQueryTime = 0;
for (int j = 0; j < QUERY_COUNT; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName).setQuery(hasChildQuery("child", matchAllQuery()).scoreType("max")).execute().actionGet();
if (j % 10 == 0) {
System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> has_child query with match_all Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
System.out.println("--> Running has_parent query with score type");
// run parent child score query
for (int j = 0; j < QUERY_WARMUP; j++) {
client.prepareSearch(indexName).setQuery(hasParentQuery("parent", termQuery("field1", parentChildIndexGenerator.getQueryValue())).scoreType("score")).execute().actionGet();
}
totalQueryTime = 0;
for (int j = 1; j < QUERY_COUNT; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName).setQuery(hasParentQuery("parent", termQuery("field1", parentChildIndexGenerator.getQueryValue())).scoreType("score")).execute().actionGet();
if (j % 10 == 0) {
System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> has_parent Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
totalQueryTime = 0;
for (int j = 1; j < QUERY_COUNT; j++) {
SearchResponse searchResponse = client.prepareSearch(indexName).setQuery(hasParentQuery("parent", matchAllQuery()).scoreType("score")).execute().actionGet();
if (j % 10 == 0) {
System.out.println("--> hits [" + j + "], got [" + searchResponse.getHits().totalHits() + "]");
}
totalQueryTime += searchResponse.getTookInMillis();
}
System.out.println("--> has_parent query with match_all Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms");
System.gc();
statsResponse = client.admin().cluster().prepareNodesStats()
.setJvm(true).setIndices(true).execute().actionGet();
System.out.println("--> Id cache size: " + statsResponse.getNodes()[0].getIndices().getIdCache().getMemorySize());
System.out.println("--> Used heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapUsed());
client.close();
node1.close();
}
}
| 0true
|
src_test_java_org_elasticsearch_benchmark_search_child_ChildSearchBenchmark.java
|
5,808 |
public class FastVectorHighlighter implements Highlighter {
private static final SimpleBoundaryScanner DEFAULT_BOUNDARY_SCANNER = new SimpleBoundaryScanner();
private static final String CACHE_KEY = "highlight-fsv";
private final Boolean termVectorMultiValue;
@Inject
public FastVectorHighlighter(Settings settings) {
this.termVectorMultiValue = settings.getAsBoolean("search.highlight.term_vector_multi_value", true);
}
@Override
public String[] names() {
return new String[]{"fvh", "fast-vector-highlighter"};
}
@Override
public HighlightField highlight(HighlighterContext highlighterContext) {
SearchContextHighlight.Field field = highlighterContext.field;
SearchContext context = highlighterContext.context;
FetchSubPhase.HitContext hitContext = highlighterContext.hitContext;
FieldMapper<?> mapper = highlighterContext.mapper;
if (!(mapper.fieldType().storeTermVectors() && mapper.fieldType().storeTermVectorOffsets() && mapper.fieldType().storeTermVectorPositions())) {
throw new ElasticsearchIllegalArgumentException("the field [" + field.field() + "] should be indexed with term vector with position offsets to be used with fast vector highlighter");
}
Encoder encoder = field.encoder().equals("html") ? HighlightUtils.Encoders.HTML : HighlightUtils.Encoders.DEFAULT;
if (!hitContext.cache().containsKey(CACHE_KEY)) {
hitContext.cache().put(CACHE_KEY, new HighlighterEntry());
}
HighlighterEntry cache = (HighlighterEntry) hitContext.cache().get(CACHE_KEY);
try {
FieldQuery fieldQuery;
if (field.requireFieldMatch()) {
if (cache.fieldMatchFieldQuery == null) {
// we use top level reader to rewrite the query against all readers, with use caching it across hits (and across readers...)
cache.fieldMatchFieldQuery = new CustomFieldQuery(highlighterContext.query.originalQuery(), hitContext.topLevelReader(), true, field.requireFieldMatch());
}
fieldQuery = cache.fieldMatchFieldQuery;
} else {
if (cache.noFieldMatchFieldQuery == null) {
// we use top level reader to rewrite the query against all readers, with use caching it across hits (and across readers...)
cache.noFieldMatchFieldQuery = new CustomFieldQuery(highlighterContext.query.originalQuery(), hitContext.topLevelReader(), true, field.requireFieldMatch());
}
fieldQuery = cache.noFieldMatchFieldQuery;
}
MapperHighlightEntry entry = cache.mappers.get(mapper);
if (entry == null) {
FragListBuilder fragListBuilder;
BaseFragmentsBuilder fragmentsBuilder;
BoundaryScanner boundaryScanner = DEFAULT_BOUNDARY_SCANNER;
if (field.boundaryMaxScan() != SimpleBoundaryScanner.DEFAULT_MAX_SCAN || field.boundaryChars() != SimpleBoundaryScanner.DEFAULT_BOUNDARY_CHARS) {
boundaryScanner = new SimpleBoundaryScanner(field.boundaryMaxScan(), field.boundaryChars());
}
if (field.numberOfFragments() == 0) {
fragListBuilder = new SingleFragListBuilder();
if (!field.forceSource() && mapper.fieldType().stored()) {
fragmentsBuilder = new SimpleFragmentsBuilder(mapper, field.preTags(), field.postTags(), boundaryScanner);
} else {
fragmentsBuilder = new SourceSimpleFragmentsBuilder(mapper, context, field.preTags(), field.postTags(), boundaryScanner);
}
} else {
fragListBuilder = field.fragmentOffset() == -1 ? new SimpleFragListBuilder() : new SimpleFragListBuilder(field.fragmentOffset());
if (field.scoreOrdered()) {
if (!field.forceSource() && mapper.fieldType().stored()) {
fragmentsBuilder = new ScoreOrderFragmentsBuilder(field.preTags(), field.postTags(), boundaryScanner);
} else {
fragmentsBuilder = new SourceScoreOrderFragmentsBuilder(mapper, context, field.preTags(), field.postTags(), boundaryScanner);
}
} else {
if (!field.forceSource() && mapper.fieldType().stored()) {
fragmentsBuilder = new SimpleFragmentsBuilder(mapper, field.preTags(), field.postTags(), boundaryScanner);
} else {
fragmentsBuilder = new SourceSimpleFragmentsBuilder(mapper, context, field.preTags(), field.postTags(), boundaryScanner);
}
}
}
fragmentsBuilder.setDiscreteMultiValueHighlighting(termVectorMultiValue);
entry = new MapperHighlightEntry();
entry.fragListBuilder = fragListBuilder;
entry.fragmentsBuilder = fragmentsBuilder;
if (cache.fvh == null) {
// parameters to FVH are not requires since:
// first two booleans are not relevant since they are set on the CustomFieldQuery (phrase and fieldMatch)
// fragment builders are used explicitly
cache.fvh = new org.apache.lucene.search.vectorhighlight.FastVectorHighlighter();
}
CustomFieldQuery.highlightFilters.set(field.highlightFilter());
cache.mappers.put(mapper, entry);
}
cache.fvh.setPhraseLimit(field.phraseLimit());
String[] fragments;
// a HACK to make highlighter do highlighting, even though its using the single frag list builder
int numberOfFragments = field.numberOfFragments() == 0 ? Integer.MAX_VALUE : field.numberOfFragments();
int fragmentCharSize = field.numberOfFragments() == 0 ? Integer.MAX_VALUE : field.fragmentCharSize();
// we highlight against the low level reader and docId, because if we load source, we want to reuse it if possible
// Only send matched fields if they were requested to save time.
if (field.matchedFields() != null && !field.matchedFields().isEmpty()) {
fragments = cache.fvh.getBestFragments(fieldQuery, hitContext.reader(), hitContext.docId(), mapper.names().indexName(), field.matchedFields(), fragmentCharSize,
numberOfFragments, entry.fragListBuilder, entry.fragmentsBuilder, field.preTags(), field.postTags(), encoder);
} else {
fragments = cache.fvh.getBestFragments(fieldQuery, hitContext.reader(), hitContext.docId(), mapper.names().indexName(), fragmentCharSize,
numberOfFragments, entry.fragListBuilder, entry.fragmentsBuilder, field.preTags(), field.postTags(), encoder);
}
if (fragments != null && fragments.length > 0) {
return new HighlightField(field.field(), StringText.convertFromStringArray(fragments));
}
int noMatchSize = highlighterContext.field.noMatchSize();
if (noMatchSize > 0) {
// Essentially we just request that a fragment is built from 0 to noMatchSize using the normal fragmentsBuilder
FieldFragList fieldFragList = new SimpleFieldFragList(-1 /*ignored*/);
fieldFragList.add(0, noMatchSize, Collections.<WeightedPhraseInfo>emptyList());
fragments = entry.fragmentsBuilder.createFragments(hitContext.reader(), hitContext.docId(), mapper.names().indexName(),
fieldFragList, 1, field.preTags(), field.postTags(), encoder);
if (fragments != null && fragments.length > 0) {
return new HighlightField(field.field(), StringText.convertFromStringArray(fragments));
}
}
return null;
} catch (Exception e) {
throw new FetchPhaseExecutionException(context, "Failed to highlight field [" + highlighterContext.fieldName + "]", e);
}
}
private class MapperHighlightEntry {
public FragListBuilder fragListBuilder;
public FragmentsBuilder fragmentsBuilder;
public org.apache.lucene.search.highlight.Highlighter highlighter;
}
private class HighlighterEntry {
public org.apache.lucene.search.vectorhighlight.FastVectorHighlighter fvh;
public FieldQuery noFieldMatchFieldQuery;
public FieldQuery fieldMatchFieldQuery;
public Map<FieldMapper, MapperHighlightEntry> mappers = Maps.newHashMap();
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_highlight_FastVectorHighlighter.java
|
1,374 |
doWithBindings(new ActionOnMethodBinding() {
@Override
public void doWithBinding(IType declaringClassModel,
ReferenceBinding declaringClass,
MethodBinding method) {
if (CharOperation.equals(declaringClass.readableName(), "ceylon.language.Identifiable".toCharArray())) {
if ("equals".equals(name)
|| "hashCode".equals(name)) {
isOverriding = true;
return;
}
}
if (CharOperation.equals(declaringClass.readableName(), "ceylon.language.Object".toCharArray())) {
if ("equals".equals(name)
|| "hashCode".equals(name)
|| "toString".equals(name)) {
isOverriding = false;
return;
}
}
// try the superclass first
if (isDefinedInSuperClasses(declaringClass, method)) {
isOverriding = true;
}
if (isDefinedInSuperInterfaces(declaringClass, method)) {
isOverriding = true;
}
}
});
| 1no label
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_model_mirror_JDTMethod.java
|
327 |
public class MergeException extends Exception {
private static final long serialVersionUID = 1L;
public MergeException() {
super();
}
public MergeException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public MergeException(String arg0) {
super(arg0);
}
public MergeException(Throwable arg0) {
super(arg0);
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_exceptions_MergeException.java
|
522 |
public class ORecordNotFoundException extends OException {
private static final long serialVersionUID = -265573123216968L;
public ORecordNotFoundException(final String string) {
super(string);
}
public ORecordNotFoundException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_exception_ORecordNotFoundException.java
|
325 |
public class NodesInfoRequest extends NodesOperationRequest<NodesInfoRequest> {
private boolean settings = true;
private boolean os = true;
private boolean process = true;
private boolean jvm = true;
private boolean threadPool = true;
private boolean network = true;
private boolean transport = true;
private boolean http = true;
private boolean plugin = true;
public NodesInfoRequest() {
}
/**
* Get information from nodes based on the nodes ids specified. If none are passed, information
* for all nodes will be returned.
*/
public NodesInfoRequest(String... nodesIds) {
super(nodesIds);
}
/**
* Clears all info flags.
*/
public NodesInfoRequest clear() {
settings = false;
os = false;
process = false;
jvm = false;
threadPool = false;
network = false;
transport = false;
http = false;
plugin = false;
return this;
}
/**
* Sets to return all the data.
*/
public NodesInfoRequest all() {
settings = true;
os = true;
process = true;
jvm = true;
threadPool = true;
network = true;
transport = true;
http = true;
plugin = true;
return this;
}
/**
* Should the node settings be returned.
*/
public boolean settings() {
return this.settings;
}
/**
* Should the node settings be returned.
*/
public NodesInfoRequest settings(boolean settings) {
this.settings = settings;
return this;
}
/**
* Should the node OS be returned.
*/
public boolean os() {
return this.os;
}
/**
* Should the node OS be returned.
*/
public NodesInfoRequest os(boolean os) {
this.os = os;
return this;
}
/**
* Should the node Process be returned.
*/
public boolean process() {
return this.process;
}
/**
* Should the node Process be returned.
*/
public NodesInfoRequest process(boolean process) {
this.process = process;
return this;
}
/**
* Should the node JVM be returned.
*/
public boolean jvm() {
return this.jvm;
}
/**
* Should the node JVM be returned.
*/
public NodesInfoRequest jvm(boolean jvm) {
this.jvm = jvm;
return this;
}
/**
* Should the node Thread Pool info be returned.
*/
public boolean threadPool() {
return this.threadPool;
}
/**
* Should the node Thread Pool info be returned.
*/
public NodesInfoRequest threadPool(boolean threadPool) {
this.threadPool = threadPool;
return this;
}
/**
* Should the node Network be returned.
*/
public boolean network() {
return this.network;
}
/**
* Should the node Network be returned.
*/
public NodesInfoRequest network(boolean network) {
this.network = network;
return this;
}
/**
* Should the node Transport be returned.
*/
public boolean transport() {
return this.transport;
}
/**
* Should the node Transport be returned.
*/
public NodesInfoRequest transport(boolean transport) {
this.transport = transport;
return this;
}
/**
* Should the node HTTP be returned.
*/
public boolean http() {
return this.http;
}
/**
* Should the node HTTP be returned.
*/
public NodesInfoRequest http(boolean http) {
this.http = http;
return this;
}
/**
* Should information about plugins be returned
* @param plugin true if you want info
* @return The request
*/
public NodesInfoRequest plugin(boolean plugin) {
this.plugin = plugin;
return this;
}
/**
* @return true if information about plugins is requested
*/
public boolean plugin() {
return plugin;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
settings = in.readBoolean();
os = in.readBoolean();
process = in.readBoolean();
jvm = in.readBoolean();
threadPool = in.readBoolean();
network = in.readBoolean();
transport = in.readBoolean();
http = in.readBoolean();
plugin = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(settings);
out.writeBoolean(os);
out.writeBoolean(process);
out.writeBoolean(jvm);
out.writeBoolean(threadPool);
out.writeBoolean(network);
out.writeBoolean(transport);
out.writeBoolean(http);
out.writeBoolean(plugin);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_node_info_NodesInfoRequest.java
|
5,406 |
public static class SortedAndUnique extends Bytes implements ReaderContextAware {
private final FieldDataSource delegate;
private final MetaData metaData;
private BytesValues bytesValues;
public SortedAndUnique(FieldDataSource delegate) {
this.delegate = delegate;
this.metaData = MetaData.builder(delegate.metaData()).uniqueness(MetaData.Uniqueness.UNIQUE).build();
}
@Override
public MetaData metaData() {
return metaData;
}
@Override
public void setNextReader(AtomicReaderContext reader) {
bytesValues = null; // order may change per-segment -> reset
}
@Override
public org.elasticsearch.index.fielddata.BytesValues bytesValues() {
if (bytesValues == null) {
bytesValues = delegate.bytesValues();
if (bytesValues.isMultiValued() &&
(!delegate.metaData().uniqueness.unique() || bytesValues.getOrder() != Order.BYTES)) {
bytesValues = new SortedUniqueBytesValues(bytesValues);
}
}
return bytesValues;
}
static class SortedUniqueBytesValues extends FilterBytesValues {
final BytesRef spare;
int[] sortedIds;
final BytesRefHash bytes;
int numUniqueValues;
int pos = Integer.MAX_VALUE;
public SortedUniqueBytesValues(BytesValues delegate) {
super(delegate);
bytes = new BytesRefHash();
spare = new BytesRef();
}
@Override
public int setDocument(int docId) {
final int numValues = super.setDocument(docId);
if (numValues == 0) {
sortedIds = null;
return 0;
}
bytes.clear();
bytes.reinit();
for (int i = 0; i < numValues; ++i) {
bytes.add(super.nextValue(), super.currentValueHash());
}
numUniqueValues = bytes.size();
sortedIds = bytes.sort(BytesRef.getUTF8SortedAsUnicodeComparator());
pos = 0;
return numUniqueValues;
}
@Override
public BytesRef nextValue() {
bytes.get(sortedIds[pos++], spare);
return spare;
}
@Override
public int currentValueHash() {
return spare.hashCode();
}
@Override
public Order getOrder() {
return Order.BYTES;
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_support_FieldDataSource.java
|
4,964 |
public static PathTrie.Decoder REST_DECODER = new PathTrie.Decoder() {
@Override
public String decode(String value) {
return RestUtils.decodeComponent(value);
}
};
| 1no label
|
src_main_java_org_elasticsearch_rest_support_RestUtils.java
|
2,079 |
public class EmailOpenTrackingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Log LOG = LogFactory.getLog(EmailOpenTrackingServlet.class);
/*
* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest , javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = request.getPathInfo();
Long emailId = null;
String imageUrl = "";
// Parse the URL for the Email ID and Image URL
if (url != null) {
String[] items = url.split("/");
emailId = Long.valueOf(items[1]);
StringBuffer sb = new StringBuffer();
for (int j = 2; j < items.length; j++) {
sb.append("/");
sb.append(items[j]);
}
imageUrl = sb.toString();
}
// Record the open
if (emailId != null && !"null".equals(emailId)) {
if (LOG.isDebugEnabled()) {
LOG.debug("service() => Recording Open for Email[" + emailId + "]");
}
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
EmailTrackingManager emailTrackingManager = (EmailTrackingManager) context.getBean("blEmailTrackingManager");
String userAgent = request.getHeader("USER-AGENT");
Map<String, String> extraValues = new HashMap<String, String>();
extraValues.put("userAgent", userAgent);
emailTrackingManager.recordOpen(emailId, extraValues);
}
if ("".equals(imageUrl)) {
response.setContentType("image/gif");
BufferedInputStream bis = null;
OutputStream out = response.getOutputStream();
try {
bis = new BufferedInputStream(EmailOpenTrackingServlet.class.getResourceAsStream("clear_dot.gif"));
boolean eof = false;
while (!eof) {
int temp = bis.read();
if (temp == -1) {
eof = true;
} else {
out.write(temp);
}
}
} finally {
if (bis != null) {
try{ bis.close(); } catch (Throwable e) {
LOG.error("Unable to close output stream in EmailOpenTrackingServlet", e);
}
}
//Don't close the output stream controlled by the container. The container will
//handle this.
}
} else {
RequestDispatcher dispatcher = request.getRequestDispatcher(imageUrl);
dispatcher.forward(request, response);
}
}
}
| 1no label
|
core_broadleaf-profile-web_src_main_java_org_broadleafcommerce_profile_web_email_EmailOpenTrackingServlet.java
|
1,527 |
public class ShardVersioningTests extends ElasticsearchAllocationTestCase {
private final ESLogger logger = Loggers.getLogger(ShardVersioningTests.class);
@Test
public void simple() {
AllocationService strategy = createAllocationService(settingsBuilder().put("cluster.routing.allocation.allow_rebalance", ClusterRebalanceAllocationDecider.ClusterRebalanceType.ALWAYS.toString()).build());
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test1").numberOfShards(1).numberOfReplicas(1))
.put(IndexMetaData.builder("test2").numberOfShards(1).numberOfReplicas(1))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test1"))
.addAsNew(metaData.index("test2"))
.build();
ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build();
logger.info("start two nodes");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2"))).build();
RoutingTable prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
for (int i = 0; i < routingTable.index("test1").shards().size(); i++) {
assertThat(routingTable.index("test1").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).primaryShard().state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test1").shard(i).primaryShard().version(), equalTo(1l));
assertThat(routingTable.index("test1").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED));
}
for (int i = 0; i < routingTable.index("test2").shards().size(); i++) {
assertThat(routingTable.index("test2").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test2").shard(i).primaryShard().state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test2").shard(i).primaryShard().version(), equalTo(1l));
assertThat(routingTable.index("test2").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED));
}
logger.info("start all the primary shards for test1, replicas will start initializing");
RoutingNodes routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState("test1", INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
for (int i = 0; i < routingTable.index("test1").shards().size(); i++) {
assertThat(routingTable.index("test1").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test1").shard(i).primaryShard().state(), equalTo(STARTED));
assertThat(routingTable.index("test1").shard(i).primaryShard().version(), equalTo(2l));
assertThat(routingTable.index("test1").shard(i).replicaShards().get(0).state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test1").shard(i).replicaShards().get(0).version(), equalTo(2l));
}
for (int i = 0; i < routingTable.index("test2").shards().size(); i++) {
assertThat(routingTable.index("test2").shard(i).shards().size(), equalTo(2));
assertThat(routingTable.index("test2").shard(i).primaryShard().state(), equalTo(INITIALIZING));
assertThat(routingTable.index("test2").shard(i).primaryShard().version(), equalTo(1l));
assertThat(routingTable.index("test2").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED));
assertThat(routingTable.index("test2").shard(i).replicaShards().get(0).version(), equalTo(1l));
}
}
}
| 0true
|
src_test_java_org_elasticsearch_cluster_routing_allocation_ShardVersioningTests.java
|
1,229 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_SHIPPING_RATE")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@Deprecated
public class ShippingRateImpl implements ShippingRate {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "ShippingRateId")
@GenericGenerator(
name="ShippingRateId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="ShippingRateImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.pricing.domain.ShippingRateImpl")
}
)
@Column(name = "ID")
protected Long id;
@Column(name = "FEE_TYPE", nullable=false)
@Index(name="SHIPPINGRATE_FEE_INDEX", columnNames={"FEE_TYPE"})
protected String feeType;
@Column(name = "FEE_SUB_TYPE")
@Index(name="SHIPPINGRATE_FEESUB_INDEX", columnNames={"FEE_SUB_TYPE"})
protected String feeSubType;
@Column(name = "FEE_BAND", nullable=false)
protected Integer feeBand;
@Column(name = "BAND_UNIT_QTY", nullable=false)
protected BigDecimal bandUnitQuantity;
@Column(name = "BAND_RESULT_QTY", nullable=false)
protected BigDecimal bandResultQuantity;
@Column(name = "BAND_RESULT_PCT", nullable=false)
protected Integer bandResultPercent;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getFeeType() {
return feeType;
}
@Override
public void setFeeType(String feeType) {
this.feeType = feeType;
}
@Override
public String getFeeSubType() {
return feeSubType;
}
@Override
public void setFeeSubType(String feeSubType) {
this.feeSubType = feeSubType;
}
@Override
public Integer getFeeBand() {
return feeBand;
}
@Override
public void setFeeBand(Integer feeBand) {
this.feeBand = feeBand;
}
@Override
public BigDecimal getBandUnitQuantity() {
return bandUnitQuantity;
}
@Override
public void setBandUnitQuantity(BigDecimal bandUnitQuantity) {
this.bandUnitQuantity = bandUnitQuantity;
}
@Override
public BigDecimal getBandResultQuantity() {
return bandResultQuantity;
}
@Override
public void setBandResultQuantity(BigDecimal bandResultQuantity) {
this.bandResultQuantity = bandResultQuantity;
}
@Override
public Integer getBandResultPercent() {
return bandResultPercent;
}
@Override
public void setBandResultPercent(Integer bandResultPercent) {
this.bandResultPercent = bandResultPercent;
}
@Override
public String toString() {
return getFeeSubType() + " " + getBandResultQuantity() + " " + getBandResultPercent();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bandResultPercent == null) ? 0 : bandResultPercent.hashCode());
result = prime * result + ((bandResultQuantity == null) ? 0 : bandResultQuantity.hashCode());
result = prime * result + ((bandUnitQuantity == null) ? 0 : bandUnitQuantity.hashCode());
result = prime * result + ((feeBand == null) ? 0 : feeBand.hashCode());
result = prime * result + ((feeSubType == null) ? 0 : feeSubType.hashCode());
result = prime * result + ((feeType == null) ? 0 : feeType.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ShippingRateImpl other = (ShippingRateImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (bandResultPercent == null) {
if (other.bandResultPercent != null)
return false;
} else if (!bandResultPercent.equals(other.bandResultPercent))
return false;
if (bandResultQuantity == null) {
if (other.bandResultQuantity != null)
return false;
} else if (!bandResultQuantity.equals(other.bandResultQuantity))
return false;
if (bandUnitQuantity == null) {
if (other.bandUnitQuantity != null)
return false;
} else if (!bandUnitQuantity.equals(other.bandUnitQuantity))
return false;
if (feeBand == null) {
if (other.feeBand != null)
return false;
} else if (!feeBand.equals(other.feeBand))
return false;
if (feeSubType == null) {
if (other.feeSubType != null)
return false;
} else if (!feeSubType.equals(other.feeSubType))
return false;
if (feeType == null) {
if (other.feeType != null)
return false;
} else if (!feeType.equals(other.feeType))
return false;
return true;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_domain_ShippingRateImpl.java
|
6 |
static final class AndCompletion extends Completion {
final CompletableFuture<?> src;
final CompletableFuture<?> snd;
final CompletableFuture<Void> dst;
AndCompletion(CompletableFuture<?> src,
CompletableFuture<?> snd,
CompletableFuture<Void> dst) {
this.src = src; this.snd = snd; this.dst = dst;
}
public final void run() {
final CompletableFuture<?> a;
final CompletableFuture<?> b;
final CompletableFuture<Void> dst;
Object r, s; Throwable ex;
if ((dst = this.dst) != null &&
(a = this.src) != null &&
(r = a.result) != null &&
(b = this.snd) != null &&
(s = b.result) != null &&
compareAndSet(0, 1)) {
if (r instanceof AltResult)
ex = ((AltResult)r).ex;
else
ex = null;
if (ex == null && (s instanceof AltResult))
ex = ((AltResult)s).ex;
dst.internalComplete(null, ex);
}
}
private static final long serialVersionUID = 5232453952276885070L;
}
| 0true
|
src_main_java_jsr166e_CompletableFuture.java
|
1,471 |
public class PlainShardIterator extends PlainShardsIterator implements ShardIterator {
private final ShardId shardId;
/**
* Creates a {@link PlainShardIterator} instance that iterates over a subset of the given shards
* this the a given <code>shardId</code>.
*
* @param shardId shard id of the group
* @param shards shards to iterate
*/
public PlainShardIterator(ShardId shardId, List<ShardRouting> shards) {
super(shards);
this.shardId = shardId;
}
/**
* Creates a {@link PlainShardIterator} instance that iterates over a subset of the given shards
* this the a given <code>shardId</code>.
*
* @param shardId shard id of the group
* @param shards shards to iterate
* @param index the offset in the shards list to start the iteration from
*/
public PlainShardIterator(ShardId shardId, List<ShardRouting> shards, int index) {
super(shards, index);
this.shardId = shardId;
}
@Override
public ShardId shardId() {
return this.shardId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
ShardIterator that = (ShardIterator) o;
return shardId.equals(that.shardId());
}
@Override
public int hashCode() {
return shardId.hashCode();
}
}
| 1no label
|
src_main_java_org_elasticsearch_cluster_routing_PlainShardIterator.java
|
4,193 |
private class RestoreContext extends Context {
private final Store store;
private final RecoveryStatus recoveryStatus;
/**
* Constructs new restore context
*
* @param snapshotId snapshot id
* @param shardId shard to be restored
* @param snapshotShardId shard in the snapshot that data should be restored from
* @param recoveryStatus recovery status to report progress
*/
public RestoreContext(SnapshotId snapshotId, ShardId shardId, ShardId snapshotShardId, RecoveryStatus recoveryStatus) {
super(snapshotId, shardId, snapshotShardId);
store = indicesService.indexServiceSafe(shardId.getIndex()).shardInjectorSafe(shardId.id()).getInstance(Store.class);
this.recoveryStatus = recoveryStatus;
}
/**
* Performs restore operation
*/
public void restore() {
logger.debug("[{}] [{}] restoring to [{}] ...", snapshotId, repositoryName, shardId);
BlobStoreIndexShardSnapshot snapshot;
try {
snapshot = readSnapshot(blobContainer.readBlobFully(snapshotBlobName(snapshotId)));
} catch (IOException ex) {
throw new IndexShardRestoreFailedException(shardId, "failed to read shard snapshot file", ex);
}
recoveryStatus.updateStage(RecoveryStatus.Stage.INDEX);
int numberOfFiles = 0;
long totalSize = 0;
int numberOfReusedFiles = 0;
long reusedTotalSize = 0;
List<FileInfo> filesToRecover = Lists.newArrayList();
for (FileInfo fileInfo : snapshot.indexFiles()) {
String fileName = fileInfo.physicalName();
StoreFileMetaData md = null;
try {
md = store.metaData(fileName);
} catch (IOException e) {
// no file
}
numberOfFiles++;
// we don't compute checksum for segments, so always recover them
if (!fileName.startsWith("segments") && md != null && fileInfo.isSame(md)) {
totalSize += md.length();
numberOfReusedFiles++;
reusedTotalSize += md.length();
if (logger.isTraceEnabled()) {
logger.trace("not_recovering [{}], exists in local store and is same", fileInfo.physicalName());
}
} else {
totalSize += fileInfo.length();
filesToRecover.add(fileInfo);
if (logger.isTraceEnabled()) {
if (md == null) {
logger.trace("recovering [{}], does not exists in local store", fileInfo.physicalName());
} else {
logger.trace("recovering [{}], exists in local store but is different", fileInfo.physicalName());
}
}
}
}
recoveryStatus.index().files(numberOfFiles, totalSize, numberOfReusedFiles, reusedTotalSize);
if (filesToRecover.isEmpty()) {
logger.trace("no files to recover, all exists within the local store");
}
if (logger.isTraceEnabled()) {
logger.trace("[{}] [{}] recovering_files [{}] with total_size [{}], reusing_files [{}] with reused_size [{}]", shardId, snapshotId, numberOfFiles, new ByteSizeValue(totalSize), numberOfReusedFiles, new ByteSizeValue(reusedTotalSize));
}
final CountDownLatch latch = new CountDownLatch(filesToRecover.size());
final CopyOnWriteArrayList<Throwable> failures = new CopyOnWriteArrayList<Throwable>();
for (final FileInfo fileToRecover : filesToRecover) {
logger.trace("[{}] [{}] restoring file [{}]", shardId, snapshotId, fileToRecover.name());
restoreFile(fileToRecover, latch, failures);
}
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (!failures.isEmpty()) {
throw new IndexShardRestoreFailedException(shardId, "Failed to recover index", failures.get(0));
}
// read the snapshot data persisted
long version = -1;
try {
if (Lucene.indexExists(store.directory())) {
version = Lucene.readSegmentInfos(store.directory()).getVersion();
}
} catch (IOException e) {
throw new IndexShardRestoreFailedException(shardId, "Failed to fetch index version after copying it over", e);
}
recoveryStatus.index().updateVersion(version);
/// now, go over and clean files that are in the store, but were not in the snapshot
try {
for (String storeFile : store.directory().listAll()) {
if (!snapshot.containPhysicalIndexFile(storeFile)) {
try {
store.directory().deleteFile(storeFile);
} catch (IOException e) {
// ignore
}
}
}
} catch (IOException e) {
// ignore
}
}
/**
* Restores a file
* This is asynchronous method. Upon completion of the operation latch is getting counted down and any failures are
* added to the {@code failures} list
*
* @param fileInfo file to be restored
* @param latch latch that should be counted down once file is snapshoted
* @param failures thread-safe list of failures
*/
private void restoreFile(final FileInfo fileInfo, final CountDownLatch latch, final List<Throwable> failures) {
final IndexOutput indexOutput;
try {
// we create an output with no checksum, this is because the pure binary data of the file is not
// the checksum (because of seek). We will create the checksum file once copying is done
indexOutput = store.createOutputRaw(fileInfo.physicalName());
} catch (IOException e) {
failures.add(e);
latch.countDown();
return;
}
String firstFileToRecover = fileInfo.partName(0);
final AtomicInteger partIndex = new AtomicInteger();
blobContainer.readBlob(firstFileToRecover, new BlobContainer.ReadBlobListener() {
@Override
public synchronized void onPartial(byte[] data, int offset, int size) throws IOException {
recoveryStatus.index().addCurrentFilesSize(size);
indexOutput.writeBytes(data, offset, size);
if (restoreRateLimiter != null) {
rateLimiterListener.onRestorePause(restoreRateLimiter.pause(size));
}
}
@Override
public synchronized void onCompleted() {
int part = partIndex.incrementAndGet();
if (part < fileInfo.numberOfParts()) {
String partName = fileInfo.partName(part);
// continue with the new part
blobContainer.readBlob(partName, this);
return;
} else {
// we are done...
try {
indexOutput.close();
// write the checksum
if (fileInfo.checksum() != null) {
store.writeChecksum(fileInfo.physicalName(), fileInfo.checksum());
}
store.directory().sync(Collections.singleton(fileInfo.physicalName()));
} catch (IOException e) {
onFailure(e);
return;
}
}
latch.countDown();
}
@Override
public void onFailure(Throwable t) {
failures.add(t);
latch.countDown();
}
});
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_snapshots_blobstore_BlobStoreIndexShardRepository.java
|
778 |
private final SchemaCache.StoreRetrieval typeCacheRetrieval = new SchemaCache.StoreRetrieval() {
@Override
public Long retrieveSchemaByName(String typeName, StandardTitanTx tx) {
tx.getTxHandle().disableCache(); //Disable cache to make sure that schema is only cached once and cache eviction works!
TitanVertex v = Iterables.getOnlyElement(tx.getVertices(BaseKey.SchemaName, typeName),null);
tx.getTxHandle().enableCache();
return v!=null?v.getLongId():null;
}
@Override
public EntryList retrieveSchemaRelations(final long schemaId, final BaseRelationType type, final Direction dir, final StandardTitanTx tx) {
SliceQuery query = queryCache.getQuery(type,dir);
tx.getTxHandle().disableCache(); //Disable cache to make sure that schema is only cached once!
EntryList result = edgeQuery(schemaId, query, tx.getTxHandle());
tx.getTxHandle().enableCache();
return result;
}
};
| 1no label
|
titan-core_src_main_java_com_thinkaurelius_titan_graphdb_database_StandardTitanGraph.java
|
204 |
public class ClientConnection implements Connection, Closeable {
private static final int SLEEP_TIME = 10;
private volatile boolean live = true;
private final ILogger logger = Logger.getLogger(ClientConnection.class);
private final ClientWriteHandler writeHandler;
private final ClientReadHandler readHandler;
private final ClientConnectionManagerImpl connectionManager;
private final int connectionId;
private final SocketChannelWrapper socketChannelWrapper;
private volatile Address remoteEndpoint;
private final ConcurrentMap<Integer, ClientCallFuture> callIdMap
= new ConcurrentHashMap<Integer, ClientCallFuture>();
private final ConcurrentMap<Integer, ClientCallFuture> eventHandlerMap
= new ConcurrentHashMap<Integer, ClientCallFuture>();
private final ByteBuffer readBuffer;
private final SerializationService serializationService;
private final ClientExecutionService executionService;
private final ClientInvocationServiceImpl invocationService;
private boolean readFromSocket = true;
private final AtomicInteger packetCount = new AtomicInteger(0);
private volatile int failedHeartBeat;
public ClientConnection(ClientConnectionManagerImpl connectionManager, IOSelector in, IOSelector out,
int connectionId, SocketChannelWrapper socketChannelWrapper, ClientExecutionService executionService,
ClientInvocationServiceImpl invocationService) throws IOException {
final Socket socket = socketChannelWrapper.socket();
this.connectionManager = connectionManager;
this.serializationService = connectionManager.getSerializationService();
this.executionService = executionService;
this.invocationService = invocationService;
this.socketChannelWrapper = socketChannelWrapper;
this.connectionId = connectionId;
this.readHandler = new ClientReadHandler(this, in, socket.getReceiveBufferSize());
this.writeHandler = new ClientWriteHandler(this, out, socket.getSendBufferSize());
this.readBuffer = ByteBuffer.allocate(socket.getReceiveBufferSize());
}
public void incrementPacketCount() {
packetCount.incrementAndGet();
}
public void decrementPacketCount() {
packetCount.decrementAndGet();
}
public void registerCallId(ClientCallFuture future) {
final int callId = connectionManager.newCallId();
future.getRequest().setCallId(callId);
callIdMap.put(callId, future);
if (future.getHandler() != null) {
eventHandlerMap.put(callId, future);
}
}
public ClientCallFuture deRegisterCallId(int callId) {
return callIdMap.remove(callId);
}
public ClientCallFuture deRegisterEventHandler(int callId) {
return eventHandlerMap.remove(callId);
}
public EventHandler getEventHandler(int callId) {
final ClientCallFuture future = eventHandlerMap.get(callId);
if (future == null) {
return null;
}
return future.getHandler();
}
@Override
public boolean write(SocketWritable packet) {
if (!live) {
if (logger.isFinestEnabled()) {
logger.finest("Connection is closed, won't write packet -> " + packet);
}
return false;
}
if (!isHeartBeating()) {
if (logger.isFinestEnabled()) {
logger.finest("Connection is not heart-beating, won't write packet -> " + packet);
}
return false;
}
writeHandler.enqueueSocketWritable(packet);
return true;
}
public void init() throws IOException {
final ByteBuffer buffer = ByteBuffer.allocate(6);
buffer.put(stringToBytes(Protocols.CLIENT_BINARY));
buffer.put(stringToBytes(ClientTypes.JAVA));
buffer.flip();
socketChannelWrapper.write(buffer);
}
public void write(Data data) throws IOException {
final int totalSize = data.totalSize();
final int bufferSize = ClientConnectionManagerImpl.BUFFER_SIZE;
final ByteBuffer buffer = ByteBuffer.allocate(totalSize > bufferSize ? bufferSize : totalSize);
final DataAdapter packet = new DataAdapter(data);
boolean complete = false;
while (!complete) {
complete = packet.writeTo(buffer);
buffer.flip();
try {
socketChannelWrapper.write(buffer);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
buffer.clear();
}
}
public Data read() throws IOException {
ClientPacket packet = new ClientPacket(serializationService.getSerializationContext());
while (true) {
if (readFromSocket) {
int readBytes = socketChannelWrapper.read(readBuffer);
if (readBytes == -1) {
throw new EOFException("Remote socket closed!");
}
readBuffer.flip();
}
boolean complete = packet.readFrom(readBuffer);
if (complete) {
if (readBuffer.hasRemaining()) {
readFromSocket = false;
} else {
readBuffer.compact();
readFromSocket = true;
}
return packet.getData();
}
readFromSocket = true;
readBuffer.clear();
}
}
@Override
public Address getEndPoint() {
return remoteEndpoint;
}
@Override
public boolean live() {
return live;
}
@Override
public long lastReadTime() {
return readHandler.getLastHandle();
}
@Override
public long lastWriteTime() {
return writeHandler.getLastHandle();
}
@Override
public void close() {
close(null);
}
@Override
public ConnectionType getType() {
return ConnectionType.JAVA_CLIENT;
}
@Override
public boolean isClient() {
return true;
}
@Override
public InetAddress getInetAddress() {
return socketChannelWrapper.socket().getInetAddress();
}
@Override
public InetSocketAddress getRemoteSocketAddress() {
return (InetSocketAddress) socketChannelWrapper.socket().getRemoteSocketAddress();
}
@Override
public int getPort() {
return socketChannelWrapper.socket().getPort();
}
public SocketChannelWrapper getSocketChannelWrapper() {
return socketChannelWrapper;
}
public ClientConnectionManagerImpl getConnectionManager() {
return connectionManager;
}
public ClientReadHandler getReadHandler() {
return readHandler;
}
public void setRemoteEndpoint(Address remoteEndpoint) {
this.remoteEndpoint = remoteEndpoint;
}
public Address getRemoteEndpoint() {
return remoteEndpoint;
}
public InetSocketAddress getLocalSocketAddress() {
return (InetSocketAddress) socketChannelWrapper.socket().getLocalSocketAddress();
}
void innerClose() throws IOException {
if (!live) {
return;
}
live = false;
if (socketChannelWrapper.isOpen()) {
socketChannelWrapper.close();
}
readHandler.shutdown();
writeHandler.shutdown();
if (socketChannelWrapper.isBlocking()) {
return;
}
if (connectionManager.isLive()) {
try {
executionService.executeInternal(new CleanResourcesTask());
} catch (RejectedExecutionException e) {
logger.warning("Execution rejected ", e);
}
} else {
cleanResources(new HazelcastException("Client is shutting down!!!"));
}
}
private class CleanResourcesTask implements Runnable {
@Override
public void run() {
waitForPacketsProcessed();
cleanResources(new TargetDisconnectedException(remoteEndpoint));
}
private void waitForPacketsProcessed() {
final long begin = System.currentTimeMillis();
int count = packetCount.get();
while (count != 0) {
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
logger.warning(e);
break;
}
long elapsed = System.currentTimeMillis() - begin;
if (elapsed > 5000) {
logger.warning("There are packets which are not processed " + count);
break;
}
count = packetCount.get();
}
}
}
private void cleanResources(HazelcastException response) {
final Iterator<Map.Entry<Integer, ClientCallFuture>> iter = callIdMap.entrySet().iterator();
while (iter.hasNext()) {
final Map.Entry<Integer, ClientCallFuture> entry = iter.next();
iter.remove();
entry.getValue().notify(response);
eventHandlerMap.remove(entry.getKey());
}
final Iterator<ClientCallFuture> iterator = eventHandlerMap.values().iterator();
while (iterator.hasNext()) {
final ClientCallFuture future = iterator.next();
iterator.remove();
future.notify(response);
}
}
public void close(Throwable t) {
if (!live) {
return;
}
try {
innerClose();
} catch (Exception e) {
logger.warning(e);
}
String message = "Connection [" + socketChannelWrapper.socket().getRemoteSocketAddress() + "] lost. Reason: ";
if (t != null) {
message += t.getClass().getName() + "[" + t.getMessage() + "]";
} else {
message += "Socket explicitly closed";
}
logger.warning(message);
if (!socketChannelWrapper.isBlocking()) {
connectionManager.destroyConnection(this);
}
}
//failedHeartBeat is incremented in single thread.
@edu.umd.cs.findbugs.annotations.SuppressWarnings("VO_VOLATILE_INCREMENT")
void heartBeatingFailed() {
failedHeartBeat++;
if (failedHeartBeat == connectionManager.maxFailedHeartbeatCount) {
connectionManager.connectionMarkedAsNotResponsive(this);
final Iterator<ClientCallFuture> iterator = eventHandlerMap.values().iterator();
final TargetDisconnectedException response = new TargetDisconnectedException(remoteEndpoint);
while (iterator.hasNext()) {
final ClientCallFuture future = iterator.next();
iterator.remove();
future.notify(response);
}
}
}
void heartBeatingSucceed() {
if (failedHeartBeat != 0) {
if (failedHeartBeat >= connectionManager.maxFailedHeartbeatCount) {
try {
final RemoveDistributedObjectListenerRequest request = new RemoveDistributedObjectListenerRequest();
request.setName(RemoveDistributedObjectListenerRequest.CLEAR_LISTENERS_COMMAND);
final ICompletableFuture future = invocationService.send(request, ClientConnection.this);
future.get(1500, TimeUnit.MILLISECONDS);
} catch (Exception e) {
logger.warning("Clearing listeners upon recovering from heart-attack failed", e);
}
}
failedHeartBeat = 0;
}
}
public boolean isHeartBeating() {
return failedHeartBeat < connectionManager.maxFailedHeartbeatCount;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ClientConnection)) {
return false;
}
ClientConnection that = (ClientConnection) o;
if (connectionId != that.connectionId) {
return false;
}
return true;
}
@Override
public int hashCode() {
return connectionId;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ClientConnection{");
sb.append("live=").append(live);
sb.append(", writeHandler=").append(writeHandler);
sb.append(", readHandler=").append(readHandler);
sb.append(", connectionId=").append(connectionId);
sb.append(", socketChannel=").append(socketChannelWrapper);
sb.append(", remoteEndpoint=").append(remoteEndpoint);
sb.append('}');
return sb.toString();
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientConnection.java
|
591 |
public interface OIndexCallback {
Object getDocumentValueToIndex(ODocument iDocument);
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_index_OIndexCallback.java
|
3,135 |
public class QueueProxyImpl<E> extends QueueProxySupport implements IQueue<E>, InitializingObject {
public QueueProxyImpl(String name, QueueService queueService, NodeEngine nodeEngine) {
super(name, queueService, nodeEngine);
}
@Override
public LocalQueueStats getLocalQueueStats() {
return getService().createLocalQueueStats(name, partitionId);
}
@Override
public boolean add(E e) {
if (offer(e)) {
return true;
}
throw new IllegalStateException("Queue is full!");
}
@Override
public boolean offer(E e) {
try {
return offer(e, 0, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
return false;
}
}
@Override
public void put(E e) throws InterruptedException {
offer(e, -1, TimeUnit.MILLISECONDS);
}
@Override
public boolean offer(E e, long timeout, TimeUnit timeUnit) throws InterruptedException {
final NodeEngine nodeEngine = getNodeEngine();
final Data data = nodeEngine.toData(e);
return offerInternal(data, timeUnit.toMillis(timeout));
}
@Override
public E take() throws InterruptedException {
return poll(-1, TimeUnit.MILLISECONDS);
}
@Override
public E poll(long timeout, TimeUnit timeUnit) throws InterruptedException {
final NodeEngine nodeEngine = getNodeEngine();
final Object data = pollInternal(timeUnit.toMillis(timeout));
return nodeEngine.toObject(data);
}
@Override
public int remainingCapacity() {
return config.getMaxSize() - size();
}
@Override
public boolean remove(Object o) {
final NodeEngine nodeEngine = getNodeEngine();
final Data data = nodeEngine.toData(o);
return removeInternal(data);
}
@Override
public boolean contains(Object o) {
final NodeEngine nodeEngine = getNodeEngine();
final Data data = nodeEngine.toData(o);
List<Data> dataSet = new ArrayList<Data>(1);
dataSet.add(data);
return containsInternal(dataSet);
}
@Override
public int drainTo(Collection<? super E> objects) {
return drainTo(objects, -1);
}
@Override
public int drainTo(Collection<? super E> objects, int i) {
final NodeEngine nodeEngine = getNodeEngine();
if (this.equals(objects)) {
throw new IllegalArgumentException("Can not drain to same Queue");
}
Collection<Data> dataList = drainInternal(i);
for (Data data : dataList) {
E e = nodeEngine.toObject(data);
objects.add(e);
}
return dataList.size();
}
@Override
public E remove() {
final E res = poll();
if (res == null) {
throw new NoSuchElementException("Queue is empty!");
}
return res;
}
@Override
public E poll() {
try {
return poll(0, TimeUnit.SECONDS);
} catch (InterruptedException e) {
//todo: interrupt status is lost
return null;
}
}
@Override
public E element() {
final E res = peek();
if (res == null) {
throw new NoSuchElementException("Queue is empty!");
}
return res;
}
@Override
public E peek() {
final NodeEngine nodeEngine = getNodeEngine();
final Object data = peekInternal();
return nodeEngine.toObject(data);
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public Iterator<E> iterator() {
final NodeEngine nodeEngine = getNodeEngine();
return new QueueIterator<E>(listInternal().iterator(), nodeEngine.getSerializationService(), false);
}
@Override
public Object[] toArray() {
final NodeEngine nodeEngine = getNodeEngine();
List<Data> list = listInternal();
int size = list.size();
Object[] array = new Object[size];
for (int i = 0; i < size; i++) {
array[i] = nodeEngine.toObject(list.get(i));
}
return array;
}
@Override
public <T> T[] toArray(T[] ts) {
final NodeEngine nodeEngine = getNodeEngine();
List<Data> list = listInternal();
int size = list.size();
if (ts.length < size) {
ts = (T[]) java.lang.reflect.Array.newInstance(ts.getClass().getComponentType(), size);
}
for (int i = 0; i < size; i++) {
ts[i] = nodeEngine.toObject(list.get(i));
}
return ts;
}
@Override
public boolean containsAll(Collection<?> objects) {
return containsInternal(getDataList(objects));
}
@Override
public boolean addAll(Collection<? extends E> es) {
return addAllInternal(getDataList(es));
}
@Override
public boolean removeAll(Collection<?> objects) {
return compareAndRemove(getDataList(objects), false);
}
@Override
public boolean retainAll(Collection<?> objects) {
return compareAndRemove(getDataList(objects), true);
}
private List<Data> getDataList(Collection<?> objects) {
final NodeEngine nodeEngine = getNodeEngine();
List<Data> dataList = new ArrayList<Data>(objects.size());
for (Object o : objects) {
dataList.add(nodeEngine.toData(o));
}
return dataList;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("IQueue");
sb.append("{name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_queue_proxy_QueueProxyImpl.java
|
94 |
class ConvertToConcatenationProposal extends CorrectionProposal {
private ConvertToConcatenationProposal(String name, Change change) {
super(name, change, null);
}
static void addConvertToConcatenationProposal(Collection<ICompletionProposal> proposals,
IFile file, Tree.CompilationUnit cu, final Node node, IDocument doc) {
class TemplateVisitor extends Visitor {
Tree.StringTemplate result;
@Override
public void visit(Tree.StringTemplate that) {
if (that.getStartIndex()<=node.getStartIndex() &&
that.getStopIndex()>=node.getStopIndex()) {
result = that;
}
super.visit(that);
}
}
TemplateVisitor tv = new TemplateVisitor();
tv.visit(cu);
Tree.StringTemplate template = tv.result;
if (template!=null) {
TextFileChange change = new TextFileChange("Convert to Concatenation", file);
change.setEdit(new MultiTextEdit());
List<Tree.StringLiteral> literals = template.getStringLiterals();
List<Tree.Expression> expressions = template.getExpressions();
for (int i=0; i<literals.size(); i++) {
Tree.StringLiteral s = literals.get(i);
int stt = s.getToken().getType();
if (stt==STRING_END||stt==STRING_MID) {
change.addEdit(new ReplaceEdit(s.getStartIndex(), 2, " + \""));
}
if (stt==STRING_START||stt==STRING_MID) {
change.addEdit(new ReplaceEdit(s.getStopIndex()-1, 2, "\" + "));
}
if (i<expressions.size()) {
Tree.Expression e = expressions.get(i);
if (!e.getTypeModel().isSubtypeOf(node.getUnit().getStringDeclaration().getType())) {
change.addEdit(new InsertEdit(e.getStopIndex()+1, ".string"));
}
}
}
proposals.add(new ConvertToConcatenationProposal("Convert to string concatenation", change));
}
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertToConcatenationProposal.java
|
774 |
mappingUpdatedAction.execute(mappingRequest, new ActionListener<MappingUpdatedAction.MappingUpdatedResponse>() {
@Override
public void onResponse(MappingUpdatedAction.MappingUpdatedResponse mappingUpdatedResponse) {
// all is well
latch.countDown();
}
@Override
public void onFailure(Throwable e) {
latch.countDown();
logger.warn("Failed to update master on updated mapping for {}", e, mappingRequest);
}
});
| 0true
|
src_main_java_org_elasticsearch_action_index_TransportIndexAction.java
|
1,223 |
public abstract class OStorageEmbedded extends OStorageAbstract {
protected final ORecordLockManager lockManager;
protected final String PROFILER_CREATE_RECORD;
protected final String PROFILER_READ_RECORD;
protected final String PROFILER_UPDATE_RECORD;
protected final String PROFILER_DELETE_RECORD;
public OStorageEmbedded(final String iName, final String iFilePath, final String iMode) {
super(iName, iFilePath, iMode, OGlobalConfiguration.STORAGE_LOCK_TIMEOUT.getValueAsInteger(), new OCacheLevelTwoLocatorLocal());
lockManager = new ORecordLockManager(OGlobalConfiguration.STORAGE_RECORD_LOCK_TIMEOUT.getValueAsInteger());
PROFILER_CREATE_RECORD = "db." + name + ".createRecord";
PROFILER_READ_RECORD = "db." + name + ".readRecord";
PROFILER_UPDATE_RECORD = "db." + name + ".updateRecord";
PROFILER_DELETE_RECORD = "db." + name + ".deleteRecord";
}
public abstract OCluster getClusterByName(final String iClusterName);
protected abstract ORawBuffer readRecord(final OCluster iClusterSegment, final ORecordId iRid, boolean iAtomicLock,
boolean loadTombstones);
/**
* Closes the storage freeing the lock manager first.
*/
@Override
public void close(final boolean iForce) {
if (checkForClose(iForce))
lockManager.clear();
super.close(iForce);
}
/**
* Executes the command request and return the result back.
*/
public Object command(final OCommandRequestText iCommand) {
final OCommandExecutor executor = OCommandManager.instance().getExecutor(iCommand);
// COPY THE CONTEXT FROM THE REQUEST
executor.setContext(iCommand.getContext());
executor.setProgressListener(iCommand.getProgressListener());
executor.parse(iCommand);
return executeCommand(iCommand, executor);
}
public Object executeCommand(final OCommandRequestText iCommand, final OCommandExecutor executor) {
if (iCommand.isIdempotent() && !executor.isIdempotent())
throw new OCommandExecutionException("Cannot execute non idempotent command");
long beginTime = Orient.instance().getProfiler().startChrono();
try {
return executor.execute(iCommand.getParameters());
} catch (OException e) {
// PASS THROUGHT
throw e;
} catch (Exception e) {
throw new OCommandExecutionException("Error on execution of command: " + iCommand, e);
} finally {
if (Orient.instance().getProfiler().isRecording())
Orient
.instance()
.getProfiler()
.stopChrono("db." + ODatabaseRecordThreadLocal.INSTANCE.get().getName() + ".command." + iCommand.toString(),
"Command executed against the database", beginTime, "db.*.command.*");
}
}
@Override
public OPhysicalPosition[] higherPhysicalPositions(int currentClusterId, OPhysicalPosition physicalPosition) {
if (currentClusterId == -1)
return null;
checkOpeness();
lock.acquireSharedLock();
try {
final OCluster cluster = getClusterById(currentClusterId);
return cluster.higherPositions(physicalPosition);
} catch (IOException ioe) {
throw new OStorageException("Cluster Id " + currentClusterId + " is invalid in storage '" + name + '\'', ioe);
} finally {
lock.releaseSharedLock();
}
}
@Override
public OPhysicalPosition[] ceilingPhysicalPositions(int clusterId, OPhysicalPosition physicalPosition) {
if (clusterId == -1)
return null;
checkOpeness();
lock.acquireSharedLock();
try {
final OCluster cluster = getClusterById(clusterId);
return cluster.ceilingPositions(physicalPosition);
} catch (IOException ioe) {
throw new OStorageException("Cluster Id " + clusterId + " is invalid in storage '" + name + '\'', ioe);
} finally {
lock.releaseSharedLock();
}
}
@Override
public OPhysicalPosition[] lowerPhysicalPositions(int currentClusterId, OPhysicalPosition physicalPosition) {
if (currentClusterId == -1)
return null;
checkOpeness();
lock.acquireSharedLock();
try {
final OCluster cluster = getClusterById(currentClusterId);
return cluster.lowerPositions(physicalPosition);
} catch (IOException ioe) {
throw new OStorageException("Cluster Id " + currentClusterId + " is invalid in storage '" + name + '\'', ioe);
} finally {
lock.releaseSharedLock();
}
}
@Override
public OPhysicalPosition[] floorPhysicalPositions(int clusterId, OPhysicalPosition physicalPosition) {
if (clusterId == -1)
return null;
checkOpeness();
lock.acquireSharedLock();
try {
final OCluster cluster = getClusterById(clusterId);
return cluster.floorPositions(physicalPosition);
} catch (IOException ioe) {
throw new OStorageException("Cluster Id " + clusterId + " is invalid in storage '" + name + '\'', ioe);
} finally {
lock.releaseSharedLock();
}
}
public void acquireWriteLock(final ORID iRid) {
lockManager.acquireLock(Thread.currentThread(), iRid, LOCK.EXCLUSIVE);
}
public void releaseWriteLock(final ORID iRid) {
lockManager.releaseLock(Thread.currentThread(), iRid, LOCK.EXCLUSIVE);
}
public void acquireReadLock(final ORID iRid) {
lockManager.acquireLock(Thread.currentThread(), iRid, LOCK.SHARED);
}
public void releaseReadLock(final ORID iRid) {
lockManager.releaseLock(Thread.currentThread(), iRid, LOCK.SHARED);
}
@Override
public ORecordMetadata getRecordMetadata(ORID rid) {
if (rid.isNew())
throw new OStorageException("Passed record with id " + rid + " is new and can not be stored.");
checkOpeness();
final OCluster cluster = getClusterById(rid.getClusterId());
lock.acquireSharedLock();
try {
lockManager.acquireLock(Thread.currentThread(), rid, LOCK.SHARED);
try {
final OPhysicalPosition ppos = cluster.getPhysicalPosition(new OPhysicalPosition(rid.getClusterPosition()));
if (ppos == null || ppos.dataSegmentId < 0)
return null;
return new ORecordMetadata(rid, ppos.recordVersion);
} finally {
lockManager.releaseLock(Thread.currentThread(), rid, LOCK.SHARED);
}
} catch (IOException ioe) {
OLogManager.instance().error(this, "Retrieval of record '" + rid + "' cause: " + ioe.getMessage(), ioe);
} finally {
lock.releaseSharedLock();
}
return null;
}
/**
* Checks if the storage is open. If it's closed an exception is raised.
*/
protected void checkOpeness() {
if (status != STATUS.OPEN)
throw new OStorageException("Storage " + name + " is not opened.");
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_storage_OStorageEmbedded.java
|
458 |
public interface ResourceBundlingService {
/**
* For the given versioned bundle name, returns a Resource that holds the contents of the combined, and
* possibly minified (if enabled) bundle.
*
* @param versionedBundleName
* @return the Resource
*/
public Resource getBundle(String versionedBundleName);
/**
* For a given unversioned bundle name, such as "global.js", returns the currently known versioned bundle
* name, such as "global12345.js".
*
* @param unversionedBundleName
* @return the versioned bundle name
*/
public String getVersionedBundleName(String unversionedBundleName);
/**
* Registers a new bundle with the given name to its files. Will utilize the locations map in handler as well as
* any configured generated resource handlers in the handler to determine legitimate paths for each of the files
* in the list.
*
* @param bundleName
* @param files
* @param handler
* @return the versioned bundle name
* @throws IOException
*/
public String registerBundle(String bundleName, List<String> files, BroadleafResourceHttpRequestHandler handler)
throws IOException;
/**
* @param versionedBundle
* @return whether or not the given versioned bundle name is currently registered in the system
*/
public boolean hasBundle(String versionedBundle);
/**
* @param bundleName
* @return a list of additional files that are registered for the given bundle name
*/
public List<String> getAdditionalBundleFiles(String bundleName);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_resource_service_ResourceBundlingService.java
|
422 |
public class ClientMapReduceProxy
extends ClientProxy
implements JobTracker {
private final ConcurrentMap<String, ClientTrackableJob> trackableJobs = new ConcurrentHashMap<String, ClientTrackableJob>();
public ClientMapReduceProxy(String instanceName, String serviceName, String objectName) {
super(instanceName, serviceName, objectName);
}
@Override
protected void onDestroy() {
for (ClientTrackableJob trackableJob : trackableJobs.values()) {
trackableJob.completableFuture.cancel(false);
}
}
@Override
public <K, V> Job<K, V> newJob(KeyValueSource<K, V> source) {
return new ClientJob<K, V>(getName(), source);
}
@Override
public <V> TrackableJob<V> getTrackableJob(String jobId) {
return trackableJobs.get(jobId);
}
@Override
public String toString() {
return "JobTracker{" + "name='" + getName() + '\'' + '}';
}
/*
* Removed for now since it is moved to Hazelcast 3.3
@Override
public <K, V> ProcessJob<K, V> newProcessJob(KeyValueSource<K, V> source) {
// TODO
return null;
}*/
private <T> T invoke(InvocationClientRequest request, String jobId) throws Exception {
ClientContext context = getContext();
ClientInvocationService cis = context.getInvocationService();
ClientTrackableJob trackableJob = trackableJobs.get(jobId);
if (trackableJob != null) {
Address runningMember = trackableJob.jobOwner;
ICompletableFuture<T> future = cis.invokeOnTarget(request, runningMember);
return future.get();
}
return null;
}
private class ClientJob<KeyIn, ValueIn> extends AbstractJob<KeyIn, ValueIn> {
public ClientJob(String name, KeyValueSource<KeyIn, ValueIn> keyValueSource) {
super(name, ClientMapReduceProxy.this, keyValueSource);
}
@Override
protected <T> JobCompletableFuture<T> invoke(final Collator collator) {
try {
final String jobId = UuidUtil.buildRandomUuidString();
ClientContext context = getContext();
ClientInvocationService cis = context.getInvocationService();
ClientMapReduceRequest request = new ClientMapReduceRequest(name, jobId, keys,
predicate, mapper, combinerFactory, reducerFactory, keyValueSource,
chunkSize, topologyChangedStrategy);
final ClientCompletableFuture completableFuture = new ClientCompletableFuture(jobId);
ClientCallFuture future = (ClientCallFuture) cis.invokeOnRandomTarget(request, null);
future.andThen(new ExecutionCallback() {
@Override
public void onResponse(Object response) {
try {
if (collator != null) {
response = collator.collate(((Map) response).entrySet());
}
} finally {
completableFuture.setResult(response);
trackableJobs.remove(jobId);
}
}
@Override
public void onFailure(Throwable t) {
try {
if (t instanceof ExecutionException
&& t.getCause() instanceof CancellationException) {
t = t.getCause();
}
completableFuture.setResult(t);
} finally {
trackableJobs.remove(jobId);
}
}
});
Address runningMember = future.getConnection().getRemoteEndpoint();
trackableJobs.putIfAbsent(jobId, new ClientTrackableJob<T>(jobId, runningMember, completableFuture));
return completableFuture;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private class ClientCompletableFuture<V>
extends AbstractCompletableFuture<V>
implements JobCompletableFuture<V> {
private final String jobId;
private final CountDownLatch latch;
private volatile boolean cancelled;
protected ClientCompletableFuture(String jobId) {
super(null, Logger.getLogger(ClientCompletableFuture.class));
this.jobId = jobId;
this.latch = new CountDownLatch(1);
}
@Override
public String getJobId() {
return jobId;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
try {
cancelled = (Boolean) invoke(new ClientCancellationRequest(getName(), jobId), jobId);
} catch (Exception ignore) {
}
return cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public void setResult(Object result) {
super.setResult(result);
latch.countDown();
}
@Override
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
ValidationUtil.isNotNull(unit, "unit");
if (!latch.await(timeout, unit) || !isDone()) {
throw new TimeoutException("timeout reached");
}
return getResult();
}
@Override
protected ExecutorService getAsyncExecutor() {
return getContext().getExecutionService().getAsyncExecutor();
}
}
private final class ClientTrackableJob<V>
implements TrackableJob<V> {
private final String jobId;
private final Address jobOwner;
private final AbstractCompletableFuture<V> completableFuture;
private ClientTrackableJob(String jobId, Address jobOwner,
AbstractCompletableFuture<V> completableFuture) {
this.jobId = jobId;
this.jobOwner = jobOwner;
this.completableFuture = completableFuture;
}
@Override
public JobTracker getJobTracker() {
return ClientMapReduceProxy.this;
}
@Override
public String getName() {
return ClientMapReduceProxy.this.getName();
}
@Override
public String getJobId() {
return jobId;
}
@Override
public ICompletableFuture<V> getCompletableFuture() {
return completableFuture;
}
@Override
public JobProcessInformation getJobProcessInformation() {
try {
return invoke(new ClientJobProcessInformationRequest(getName(), jobId), jobId);
} catch (Exception ignore) {
}
return null;
}
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientMapReduceProxy.java
|
894 |
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
Tuple<String, Long>[] context1 = scrollId.getContext();
for (int i = 0; i < context1.length; i++) {
Tuple<String, Long> target = context1[i];
DiscoveryNode node = nodes.get(target.v1());
if (node != null && nodes.localNodeId().equals(node.id())) {
executePhase(i, node, target.v2());
}
}
}
});
| 0true
|
src_main_java_org_elasticsearch_action_search_type_TransportSearchScrollScanAction.java
|
1,066 |
class TransportHandler extends BaseTransportRequestHandler<MultiTermVectorsRequest> {
@Override
public MultiTermVectorsRequest newInstance() {
return new MultiTermVectorsRequest();
}
@Override
public void messageReceived(final MultiTermVectorsRequest request, final TransportChannel channel) throws Exception {
// no need to use threaded listener, since we just send a response
request.listenerThreaded(false);
execute(request, new ActionListener<MultiTermVectorsResponse>() {
@Override
public void onResponse(MultiTermVectorsResponse response) {
try {
channel.sendResponse(response);
} catch (Throwable t) {
onFailure(t);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Throwable t) {
logger.warn("Failed to send error response for action [" + MultiTermVectorsAction.NAME + "] and request ["
+ request + "]", t);
}
}
});
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_termvector_TransportMultiTermVectorsAction.java
|
764 |
public class ListSetOperation extends CollectionBackupAwareOperation {
private int index;
private Data value;
private long itemId = -1;
private long oldItemId = -1;
public ListSetOperation() {
}
public ListSetOperation(String name, int index, Data value) {
super(name);
this.index = index;
this.value = value;
}
@Override
public boolean shouldBackup() {
return true;
}
@Override
public Operation getBackupOperation() {
return new ListSetBackupOperation(name, oldItemId, itemId, value);
}
@Override
public int getId() {
return CollectionDataSerializerHook.LIST_SET;
}
@Override
public void beforeRun() throws Exception {
}
@Override
public void run() throws Exception {
final ListContainer container = getOrCreateListContainer();
itemId = container.nextId();
final CollectionItem item = container.set(index, itemId, value);
oldItemId = item.getItemId();
response = item.getValue();
}
@Override
public void afterRun() throws Exception {
publishEvent(ItemEventType.REMOVED, (Data) response);
publishEvent(ItemEventType.ADDED, value);
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeInt(index);
value.writeData(out);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
index = in.readInt();
value = new Data();
value.readData(in);
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_list_ListSetOperation.java
|
567 |
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
firedEvents.add(event);
}
});
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_index_OCompositeIndexDefinitionTest.java
|
2,496 |
EntryListener listener = new EntryAdapter() {
@Override
public void onEntryEvent(EntryEvent event) {
send(event);
}
private void send(EntryEvent event) {
if (endpoint.live()) {
Data key = clientEngine.toData(event.getKey());
Data value = clientEngine.toData(event.getValue());
Data oldValue = clientEngine.toData(event.getOldValue());
final EntryEventType type = event.getEventType();
final String uuid = event.getMember().getUuid();
PortableEntryEvent portableEntryEvent = new PortableEntryEvent(key, value, oldValue, type, uuid);
endpoint.sendEvent(portableEntryEvent, getCallId());
}
}
};
| 1no label
|
hazelcast_src_main_java_com_hazelcast_multimap_operations_client_AddEntryListenerRequest.java
|
1,376 |
public static class Builder {
private String alias;
private CompressedString filter;
private String indexRouting;
private String searchRouting;
public Builder(String alias) {
this.alias = alias;
}
public Builder(AliasMetaData aliasMetaData) {
this(aliasMetaData.alias());
filter = aliasMetaData.filter();
indexRouting = aliasMetaData.indexRouting();
searchRouting = aliasMetaData.searchRouting();
}
public String alias() {
return alias;
}
public Builder filter(CompressedString filter) {
this.filter = filter;
return this;
}
public Builder filter(String filter) {
if (!Strings.hasLength(filter)) {
this.filter = null;
return this;
}
try {
XContentParser parser = XContentFactory.xContent(filter).createParser(filter);
try {
filter(parser.mapOrdered());
} finally {
parser.close();
}
return this;
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + filter + "]", e);
}
}
public Builder filter(Map<String, Object> filter) {
if (filter == null || filter.isEmpty()) {
this.filter = null;
return this;
}
try {
XContentBuilder builder = XContentFactory.jsonBuilder().map(filter);
this.filter = new CompressedString(builder.bytes());
return this;
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to build json for alias request", e);
}
}
public Builder filter(XContentBuilder filterBuilder) {
try {
return filter(filterBuilder.string());
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to build json for alias request", e);
}
}
public Builder routing(String routing) {
this.indexRouting = routing;
this.searchRouting = routing;
return this;
}
public Builder indexRouting(String indexRouting) {
this.indexRouting = indexRouting;
return this;
}
public Builder searchRouting(String searchRouting) {
this.searchRouting = searchRouting;
return this;
}
public AliasMetaData build() {
return new AliasMetaData(alias, filter, indexRouting, searchRouting);
}
public static void toXContent(AliasMetaData aliasMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.startObject(aliasMetaData.alias(), XContentBuilder.FieldCaseConversion.NONE);
boolean binary = params.paramAsBoolean("binary", false);
if (aliasMetaData.filter() != null) {
if (binary) {
builder.field("filter", aliasMetaData.filter.compressed());
} else {
byte[] data = aliasMetaData.filter().uncompressed();
XContentParser parser = XContentFactory.xContent(data).createParser(data);
Map<String, Object> filter = parser.mapOrdered();
parser.close();
builder.field("filter", filter);
}
}
if (aliasMetaData.indexRouting() != null) {
builder.field("index_routing", aliasMetaData.indexRouting());
}
if (aliasMetaData.searchRouting() != null) {
builder.field("search_routing", aliasMetaData.searchRouting());
}
builder.endObject();
}
public static AliasMetaData fromXContent(XContentParser parser) throws IOException {
Builder builder = new Builder(parser.currentName());
String currentFieldName = null;
XContentParser.Token token = parser.nextToken();
if (token == null) {
// no data...
return builder.build();
}
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("filter".equals(currentFieldName)) {
Map<String, Object> filter = parser.mapOrdered();
builder.filter(filter);
}
} else if (token == XContentParser.Token.VALUE_EMBEDDED_OBJECT) {
if ("filter".equals(currentFieldName)) {
builder.filter(new CompressedString(parser.binaryValue()));
}
} else if (token == XContentParser.Token.VALUE_STRING) {
if ("routing".equals(currentFieldName)) {
builder.routing(parser.text());
} else if ("index_routing".equals(currentFieldName) || "indexRouting".equals(currentFieldName)) {
builder.indexRouting(parser.text());
} else if ("search_routing".equals(currentFieldName) || "searchRouting".equals(currentFieldName)) {
builder.searchRouting(parser.text());
}
}
}
return builder.build();
}
public static void writeTo(AliasMetaData aliasMetaData, StreamOutput out) throws IOException {
out.writeString(aliasMetaData.alias());
if (aliasMetaData.filter() != null) {
out.writeBoolean(true);
aliasMetaData.filter.writeTo(out);
} else {
out.writeBoolean(false);
}
if (aliasMetaData.indexRouting() != null) {
out.writeBoolean(true);
out.writeString(aliasMetaData.indexRouting());
} else {
out.writeBoolean(false);
}
if (aliasMetaData.searchRouting() != null) {
out.writeBoolean(true);
out.writeString(aliasMetaData.searchRouting());
} else {
out.writeBoolean(false);
}
}
public static AliasMetaData readFrom(StreamInput in) throws IOException {
String alias = in.readString();
CompressedString filter = null;
if (in.readBoolean()) {
filter = CompressedString.readCompressedString(in);
}
String indexRouting = null;
if (in.readBoolean()) {
indexRouting = in.readString();
}
String searchRouting = null;
if (in.readBoolean()) {
searchRouting = in.readString();
}
return new AliasMetaData(alias, filter, indexRouting, searchRouting);
}
}
| 0true
|
src_main_java_org_elasticsearch_cluster_metadata_AliasMetaData.java
|
9 |
public class OLazyIteratorListWrapper<T> implements OLazyIterator<T> {
private ListIterator<T> underlying;
public OLazyIteratorListWrapper(ListIterator<T> iUnderlying) {
underlying = iUnderlying;
}
public boolean hasNext() {
return underlying.hasNext();
}
public T next() {
return underlying.next();
}
public void remove() {
underlying.remove();
}
public T update(T e) {
underlying.set(e);
return null;
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_collection_OLazyIteratorListWrapper.java
|
68 |
public interface TitanProperty extends TitanRelation {
/**
* Returns the property key of this property
*
* @return property key of this property
* @see PropertyKey
*/
public PropertyKey getPropertyKey();
/**
* Returns the vertex on which this property is incident.
*
* @return The vertex of this property.
*/
public TitanVertex getVertex();
/**
* Returns the value of this property (possibly cast to the expected type).
*
* @return value of this property
* @throws ClassCastException if the value cannot be cast to the expected type
*/
public<O> O getValue();
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_TitanProperty.java
|
154 |
public class TransactionMonitorTest
{
@Test
public void shouldCountCommittedTransactions() throws Exception
{
GraphDatabaseService db = new TestGraphDatabaseFactory().newImpermanentDatabase();
Monitors monitors = ((GraphDatabaseAPI) db).getDependencyResolver().resolveDependency( Monitors.class );
EideticTransactionMonitor monitor = new EideticTransactionMonitor();
monitors.addMonitorListener( monitor, XaResourceManager.class.getName(), NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME );
Transaction tx = db.beginTx();
db.createNode();
tx.success();
tx.finish();
assertEquals( 1, monitor.getCommitCount() );
assertEquals( 0, monitor.getInjectOnePhaseCommitCount() );
assertEquals( 0, monitor.getInjectTwoPhaseCommitCount() );
}
@Test
public void shouldNotCountRolledBackTransactions() throws Exception
{
GraphDatabaseService db = new TestGraphDatabaseFactory().newImpermanentDatabase();
Monitors monitors = ((GraphDatabaseAPI) db).getDependencyResolver().resolveDependency( Monitors.class );
EideticTransactionMonitor monitor = new EideticTransactionMonitor();
monitors.addMonitorListener( monitor, XaResourceManager.class.getName(), NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME );
Transaction tx = db.beginTx();
db.createNode();
tx.failure();
tx.finish();
assertEquals( 0, monitor.getCommitCount() );
assertEquals( 0, monitor.getInjectOnePhaseCommitCount() );
assertEquals( 0, monitor.getInjectTwoPhaseCommitCount() );
}
}
| 0true
|
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TransactionMonitorTest.java
|
993 |
@SuppressWarnings("serial")
public abstract class ORecordSerializerStringAbstract implements ORecordSerializer, Serializable {
protected static final OProfilerMBean PROFILER = Orient.instance().getProfiler();
private static final char DECIMAL_SEPARATOR = '.';
private static final String MAX_INTEGER_AS_STRING = String.valueOf(Integer.MAX_VALUE);
private static final int MAX_INTEGER_DIGITS = MAX_INTEGER_AS_STRING.length();
protected abstract StringBuilder toString(final ORecordInternal<?> iRecord, final StringBuilder iOutput, final String iFormat,
final OUserObject2RecordHandler iObjHandler, final Set<ODocument> iMarshalledRecords, boolean iOnlyDelta,
boolean autoDetectCollectionType);
public abstract ORecordInternal<?> fromString(String iContent, ORecordInternal<?> iRecord, String[] iFields);
public StringBuilder toString(final ORecordInternal<?> iRecord, final String iFormat) {
return toString(iRecord, new StringBuilder(), iFormat, ODatabaseRecordThreadLocal.INSTANCE.get(),
OSerializationSetThreadLocal.INSTANCE.get(), false, true);
}
public StringBuilder toString(final ORecordInternal<?> iRecord, final String iFormat, final boolean autoDetectCollectionType) {
return toString(iRecord, new StringBuilder(), iFormat, ODatabaseRecordThreadLocal.INSTANCE.get(),
OSerializationSetThreadLocal.INSTANCE.get(), false, autoDetectCollectionType);
}
public StringBuilder toString(final ORecordInternal<?> iRecord, final StringBuilder iOutput, final String iFormat) {
return toString(iRecord, iOutput, iFormat, null, OSerializationSetThreadLocal.INSTANCE.get(), false, true);
}
public ORecordInternal<?> fromString(final String iSource) {
return fromString(iSource, (ORecordInternal<?>) ODatabaseRecordThreadLocal.INSTANCE.get().newInstance(), null);
}
public ORecordInternal<?> fromStream(final byte[] iSource, final ORecordInternal<?> iRecord, final String[] iFields) {
final long timer = PROFILER.startChrono();
try {
return fromString(OBinaryProtocol.bytes2string(iSource), iRecord, iFields);
} finally {
PROFILER
.stopChrono(PROFILER.getProcessMetric("serializer.record.string.fromStream"), "Deserialize record from stream", timer);
}
}
public byte[] toStream(final ORecordInternal<?> iRecord, boolean iOnlyDelta) {
final long timer = PROFILER.startChrono();
try {
return OBinaryProtocol.string2bytes(toString(iRecord, new StringBuilder(), null, null,
OSerializationSetThreadLocal.INSTANCE.get(), iOnlyDelta, true).toString());
} finally {
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.toStream"), "Serialize record to stream", timer);
}
}
public static Object fieldTypeFromStream(final ODocument iDocument, OType iType, final Object iValue) {
if (iValue == null)
return null;
if (iType == null)
iType = OType.EMBEDDED;
switch (iType) {
case STRING:
case INTEGER:
case BOOLEAN:
case FLOAT:
case DECIMAL:
case LONG:
case DOUBLE:
case SHORT:
case BYTE:
case BINARY:
case DATE:
case DATETIME:
case LINK:
return simpleValueFromStream(iValue, iType);
case EMBEDDED: {
// EMBEDED RECORD
final ODocument doc = ((ODocument) OStringSerializerEmbedded.INSTANCE.fromStream((String) iValue));
if (doc != null)
return doc.addOwner(iDocument);
return null;
}
case CUSTOM:
// RECORD
final Object result = OStringSerializerAnyStreamable.INSTANCE.fromStream((String) iValue);
if (result instanceof ODocument)
((ODocument) result).addOwner(iDocument);
return result;
case EMBEDDEDSET:
case EMBEDDEDLIST: {
final String value = (String) iValue;
return ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedCollectionFromStream(iDocument, iType, null, null, value);
}
case EMBEDDEDMAP: {
final String value = (String) iValue;
return ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedMapFromStream(iDocument, null, value, null);
}
}
throw new IllegalArgumentException("Type " + iType + " not supported to convert value: " + iValue);
}
public static Object convertValue(final String iValue, final OType iExpectedType) {
final Object v = getTypeValue((String) iValue);
return OType.convert(v, iExpectedType.getDefaultJavaType());
}
public static void fieldTypeToString(final StringBuilder iBuffer, OType iType, final Object iValue) {
if (iValue == null)
return;
final long timer = PROFILER.startChrono();
if (iType == null) {
if (iValue instanceof ORID)
iType = OType.LINK;
else
iType = OType.EMBEDDED;
}
switch (iType) {
case STRING:
simpleValueToStream(iBuffer, iType, iValue);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.string2string"), "Serialize string to string", timer);
break;
case BOOLEAN:
simpleValueToStream(iBuffer, iType, iValue);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.bool2string"), "Serialize boolean to string", timer);
break;
case INTEGER:
simpleValueToStream(iBuffer, iType, iValue);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.int2string"), "Serialize integer to string", timer);
break;
case FLOAT:
simpleValueToStream(iBuffer, iType, iValue);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.float2string"), "Serialize float to string", timer);
break;
case DECIMAL:
simpleValueToStream(iBuffer, iType, iValue);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.decimal2string"), "Serialize decimal to string",
timer);
break;
case LONG:
simpleValueToStream(iBuffer, iType, iValue);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.long2string"), "Serialize long to string", timer);
break;
case DOUBLE:
simpleValueToStream(iBuffer, iType, iValue);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.double2string"), "Serialize double to string", timer);
break;
case SHORT:
simpleValueToStream(iBuffer, iType, iValue);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.short2string"), "Serialize short to string", timer);
break;
case BYTE:
simpleValueToStream(iBuffer, iType, iValue);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.byte2string"), "Serialize byte to string", timer);
break;
case BINARY:
simpleValueToStream(iBuffer, iType, iValue);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.binary2string"), "Serialize binary to string", timer);
break;
case DATE:
simpleValueToStream(iBuffer, iType, iValue);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.date2string"), "Serialize date to string", timer);
break;
case DATETIME:
simpleValueToStream(iBuffer, iType, iValue);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.datetime2string"), "Serialize datetime to string",
timer);
break;
case LINK:
if (iValue instanceof ORecordId)
((ORecordId) iValue).toString(iBuffer);
else
((ORecord<?>) iValue).getIdentity().toString(iBuffer);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.link2string"), "Serialize link to string", timer);
break;
case EMBEDDEDSET:
ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedCollectionToStream(ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(),
null, iBuffer, null, null, iValue, null, true, true);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedSet2string"), "Serialize embeddedset to string",
timer);
break;
case EMBEDDEDLIST:
ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedCollectionToStream(ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(),
null, iBuffer, null, null, iValue, null, true, false);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedList2string"),
"Serialize embeddedlist to string", timer);
break;
case EMBEDDEDMAP:
ORecordSerializerSchemaAware2CSV.INSTANCE.embeddedMapToStream(ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(), null,
iBuffer, null, null, iValue, null, true);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embedMap2string"), "Serialize embeddedmap to string",
timer);
break;
case EMBEDDED:
OStringSerializerEmbedded.INSTANCE.toStream(iBuffer, iValue);
PROFILER
.stopChrono(PROFILER.getProcessMetric("serializer.record.string.embed2string"), "Serialize embedded to string", timer);
break;
case CUSTOM:
OStringSerializerAnyStreamable.INSTANCE.toStream(iBuffer, iValue);
PROFILER.stopChrono(PROFILER.getProcessMetric("serializer.record.string.custom2string"), "Serialize custom to string", timer);
break;
default:
throw new IllegalArgumentException("Type " + iType + " not supported to convert value: " + iValue);
}
}
/**
* Parses a string returning the closer type. Numbers by default are INTEGER if haven't decimal separator, otherwise FLOAT. To
* treat all the number types numbers are postponed with a character that tells the type: b=byte, s=short, l=long, f=float,
* d=double, t=date.
*
* @param iUnusualSymbols
* Localized decimal number separators
* @param iValue
* Value to parse
* @return The closest type recognized
*/
public static OType getType(final String iValue) {
if (iValue.length() == 0)
return null;
final char firstChar = iValue.charAt(0);
if (firstChar == ORID.PREFIX)
// RID
return OType.LINK;
else if (firstChar == '\'' || firstChar == '"')
return OType.STRING;
else if (firstChar == OStringSerializerHelper.BINARY_BEGINEND)
return OType.BINARY;
else if (firstChar == OStringSerializerHelper.EMBEDDED_BEGIN)
return OType.EMBEDDED;
else if (firstChar == OStringSerializerHelper.LINK)
return OType.LINK;
else if (firstChar == OStringSerializerHelper.LIST_BEGIN)
return OType.EMBEDDEDLIST;
else if (firstChar == OStringSerializerHelper.SET_BEGIN)
return OType.EMBEDDEDSET;
else if (firstChar == OStringSerializerHelper.MAP_BEGIN)
return OType.EMBEDDEDMAP;
else if (firstChar == OStringSerializerHelper.CUSTOM_TYPE)
return OType.CUSTOM;
// BOOLEAN?
if (iValue.equalsIgnoreCase("true") || iValue.equalsIgnoreCase("false"))
return OType.BOOLEAN;
// NUMBER OR STRING?
boolean integer = true;
for (int index = 0; index < iValue.length(); ++index) {
final char c = iValue.charAt(index);
if (c < '0' || c > '9')
if ((index == 0 && (c == '+' || c == '-')))
continue;
else if (c == DECIMAL_SEPARATOR)
integer = false;
else {
if (index > 0)
if (!integer && c == 'E') {
// CHECK FOR SCIENTIFIC NOTATION
if (index < iValue.length()) {
if (iValue.charAt(index + 1) == '-')
// JUMP THE DASH IF ANY (NOT MANDATORY)
index++;
continue;
}
} else if (c == 'f')
return OType.FLOAT;
else if (c == 'c')
return OType.DECIMAL;
else if (c == 'l')
return OType.LONG;
else if (c == 'd')
return OType.DOUBLE;
else if (c == 'b')
return OType.BYTE;
else if (c == 'a')
return OType.DATE;
else if (c == 't')
return OType.DATETIME;
else if (c == 's')
return OType.SHORT;
return OType.STRING;
}
}
if (integer) {
// AUTO CONVERT TO LONG IF THE INTEGER IS TOO BIG
final int numberLength = iValue.length();
if (numberLength > MAX_INTEGER_DIGITS || (numberLength == MAX_INTEGER_DIGITS && iValue.compareTo(MAX_INTEGER_AS_STRING) > 0))
return OType.LONG;
}
return integer ? OType.INTEGER : OType.FLOAT;
}
/**
* Parses the field type char returning the closer type. Default is STRING. b=binary if iValue.lenght() >= 4 b=byte if
* iValue.lenght() <= 3 s=short, l=long f=float d=double a=date t=datetime
*
* @param iValue
* Value to parse
* @param iCharType
* Char value indicating the type
* @return The closest type recognized
*/
public static OType getType(final String iValue, final char iCharType) {
if (iCharType == 'f')
return OType.FLOAT;
else if (iCharType == 'c')
return OType.DECIMAL;
else if (iCharType == 'l')
return OType.LONG;
else if (iCharType == 'd')
return OType.DOUBLE;
else if (iCharType == 'b') {
if (iValue.length() >= 1 && iValue.length() <= 3)
return OType.BYTE;
else
return OType.BINARY;
} else if (iCharType == 'a')
return OType.DATE;
else if (iCharType == 't')
return OType.DATETIME;
else if (iCharType == 's')
return OType.SHORT;
else if (iCharType == 'e')
return OType.EMBEDDEDSET;
return OType.STRING;
}
/**
* Parses a string returning the value with the closer type. Numbers by default are INTEGER if haven't decimal separator,
* otherwise FLOAT. To treat all the number types numbers are postponed with a character that tells the type: b=byte, s=short,
* l=long, f=float, d=double, t=date. If starts with # it's a RecordID. Most of the code is equals to getType() but has been
* copied to speed-up it.
*
* @param iUnusualSymbols
* Localized decimal number separators
* @param iValue
* Value to parse
* @return The closest type recognized
*/
public static Object getTypeValue(final String iValue) {
if (iValue == null)
return null;
if (iValue.length() == 0)
return "";
if (iValue.length() > 1)
if (iValue.charAt(0) == '"' && iValue.charAt(iValue.length() - 1) == '"')
// STRING
return OStringSerializerHelper.decode(iValue.substring(1, iValue.length() - 1));
else if (iValue.charAt(0) == OStringSerializerHelper.BINARY_BEGINEND
&& iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.BINARY_BEGINEND)
// STRING
return OStringSerializerHelper.getBinaryContent(iValue);
else if (iValue.charAt(0) == OStringSerializerHelper.LIST_BEGIN
&& iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.LIST_END) {
// LIST
final ArrayList<String> coll = new ArrayList<String>();
OStringSerializerHelper.getCollection(iValue, 0, coll, OStringSerializerHelper.LIST_BEGIN,
OStringSerializerHelper.LIST_END, OStringSerializerHelper.COLLECTION_SEPARATOR);
return coll;
} else if (iValue.charAt(0) == OStringSerializerHelper.SET_BEGIN
&& iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.SET_END) {
// SET
final Set<String> coll = new HashSet<String>();
OStringSerializerHelper.getCollection(iValue, 0, coll, OStringSerializerHelper.SET_BEGIN, OStringSerializerHelper.SET_END,
OStringSerializerHelper.COLLECTION_SEPARATOR);
return coll;
} else if (iValue.charAt(0) == OStringSerializerHelper.MAP_BEGIN
&& iValue.charAt(iValue.length() - 1) == OStringSerializerHelper.MAP_END) {
// MAP
return OStringSerializerHelper.getMap(iValue);
}
if (iValue.charAt(0) == ORID.PREFIX)
// RID
return new ORecordId(iValue);
boolean integer = true;
char c;
for (int index = 0; index < iValue.length(); ++index) {
c = iValue.charAt(index);
if (c < '0' || c > '9')
if ((index == 0 && (c == '+' || c == '-')))
continue;
else if (c == DECIMAL_SEPARATOR)
integer = false;
else {
if (index > 0) {
if (!integer && c == 'E') {
// CHECK FOR SCIENTIFIC NOTATION
if (index < iValue.length())
index++;
if (iValue.charAt(index) == '-')
continue;
}
final String v = iValue.substring(0, index);
if (c == 'f')
return new Float(v);
else if (c == 'c')
return new BigDecimal(v);
else if (c == 'l')
return new Long(v);
else if (c == 'd')
return new Double(v);
else if (c == 'b')
return new Byte(v);
else if (c == 'a' || c == 't')
return new Date(Long.parseLong(v));
else if (c == 's')
return new Short(v);
}
return iValue;
}
}
if (integer) {
try {
return new Integer(iValue);
} catch (NumberFormatException e) {
return new Long(iValue);
}
} else
return new BigDecimal(iValue);
}
public static Object simpleValueFromStream(final Object iValue, final OType iType) {
switch (iType) {
case STRING:
if (iValue instanceof String) {
final String s = OStringSerializerHelper.getStringContent(iValue);
return OStringSerializerHelper.decode(s);
}
return iValue.toString();
case INTEGER:
if (iValue instanceof Integer)
return iValue;
return new Integer(iValue.toString());
case BOOLEAN:
if (iValue instanceof Boolean)
return iValue;
return new Boolean(iValue.toString());
case FLOAT:
if (iValue instanceof Float)
return iValue;
return convertValue((String) iValue, iType);
case DECIMAL:
if (iValue instanceof BigDecimal)
return iValue;
return convertValue((String) iValue, iType);
case LONG:
if (iValue instanceof Long)
return iValue;
return convertValue((String) iValue, iType);
case DOUBLE:
if (iValue instanceof Double)
return iValue;
return convertValue((String) iValue, iType);
case SHORT:
if (iValue instanceof Short)
return iValue;
return convertValue((String) iValue, iType);
case BYTE:
if (iValue instanceof Byte)
return iValue;
return convertValue((String) iValue, iType);
case BINARY:
return OStringSerializerHelper.getBinaryContent(iValue);
case DATE:
case DATETIME:
if (iValue instanceof Date)
return iValue;
return convertValue((String) iValue, iType);
case LINK:
if (iValue instanceof ORID)
return iValue.toString();
else if (iValue instanceof String)
return new ORecordId((String) iValue);
else
return ((ORecord<?>) iValue).getIdentity().toString();
}
throw new IllegalArgumentException("Type " + iType + " is not simple type.");
}
public static void simpleValueToStream(final StringBuilder iBuffer, final OType iType, final Object iValue) {
if (iValue == null || iType == null)
return;
switch (iType) {
case STRING:
iBuffer.append('"');
iBuffer.append(OStringSerializerHelper.encode(iValue.toString()));
iBuffer.append('"');
break;
case BOOLEAN:
iBuffer.append(String.valueOf(iValue));
break;
case INTEGER:
iBuffer.append(String.valueOf(iValue));
break;
case FLOAT:
iBuffer.append(String.valueOf(iValue));
iBuffer.append('f');
break;
case DECIMAL:
if (iValue instanceof BigDecimal)
iBuffer.append(((BigDecimal) iValue).toPlainString());
else
iBuffer.append(String.valueOf(iValue));
iBuffer.append('c');
break;
case LONG:
iBuffer.append(String.valueOf(iValue));
iBuffer.append('l');
break;
case DOUBLE:
iBuffer.append(String.valueOf(iValue));
iBuffer.append('d');
break;
case SHORT:
iBuffer.append(String.valueOf(iValue));
iBuffer.append('s');
break;
case BYTE:
if (iValue instanceof Character)
iBuffer.append((int) ((Character) iValue).charValue());
else if (iValue instanceof String)
iBuffer.append(String.valueOf((int) ((String) iValue).charAt(0)));
else
iBuffer.append(String.valueOf(iValue));
iBuffer.append('b');
break;
case BINARY:
iBuffer.append(OStringSerializerHelper.BINARY_BEGINEND);
if (iValue instanceof Byte)
iBuffer.append(OBase64Utils.encodeBytes(new byte[] { ((Byte) iValue).byteValue() }));
else
iBuffer.append(OBase64Utils.encodeBytes((byte[]) iValue));
iBuffer.append(OStringSerializerHelper.BINARY_BEGINEND);
break;
case DATE:
if (iValue instanceof Date) {
// RESET HOURS, MINUTES, SECONDS AND MILLISECONDS
Calendar calendar = Calendar.getInstance();
calendar.setTime((Date) iValue);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
iBuffer.append(calendar.getTimeInMillis());
} else
iBuffer.append(iValue);
iBuffer.append('a');
break;
case DATETIME:
if (iValue instanceof Date)
iBuffer.append(((Date) iValue).getTime());
else
iBuffer.append(iValue);
iBuffer.append('t');
break;
}
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_record_string_ORecordSerializerStringAbstract.java
|
231 |
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface OId {
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_annotation_OId.java
|
1,148 |
class ParentDocument {
final String parentId;
final String[] queryValues;
int indexCounter;
ParentDocument(String parentId, String[] queryValues) {
this.parentId = parentId;
this.queryValues = queryValues;
this.indexCounter = -1;
}
}
| 0true
|
src_test_java_org_elasticsearch_benchmark_search_child_ParentChildIndexGenerator.java
|
25 |
private class HAMClusterListener extends ClusterListener.Adapter
{
@Override
public void enteredCluster( ClusterConfiguration configuration )
{
Map<InstanceId, ClusterMember> newMembers = new HashMap<InstanceId, ClusterMember>();
for ( InstanceId memberClusterUri : configuration.getMembers().keySet() )
newMembers.put( memberClusterUri, new ClusterMember( memberClusterUri ) );
members.clear();
members.putAll( newMembers );
}
@Override
public void leftCluster()
{
members.clear();
}
@Override
public void joinedCluster( InstanceId member, URI memberUri )
{
members.put( member, new ClusterMember( member ) );
}
@Override
public void leftCluster( InstanceId member )
{
members.remove( member );
}
}
| 1no label
|
enterprise_ha_src_main_java_org_neo4j_kernel_ha_cluster_member_ClusterMembers.java
|
1,171 |
BaseTransportResponseHandler<BenchmarkMessageResponse> handler = new BaseTransportResponseHandler<BenchmarkMessageResponse>() {
@Override
public BenchmarkMessageResponse newInstance() {
return new BenchmarkMessageResponse();
}
@Override
public String executor() {
return executor;
}
@Override
public void handleResponse(BenchmarkMessageResponse response) {
if (response.id() != id) {
System.out.println("NO ID MATCH [" + response.id() + "] and [" + id + "]");
}
latch.countDown();
}
@Override
public void handleException(TransportException exp) {
exp.printStackTrace();
latch.countDown();
}
};
| 0true
|
src_test_java_org_elasticsearch_benchmark_transport_TransportBenchmark.java
|
965 |
public abstract class TransportNodesOperationAction<Request extends NodesOperationRequest, Response extends NodesOperationResponse, NodeRequest extends NodeOperationRequest, NodeResponse extends NodeOperationResponse> extends TransportAction<Request, Response> {
protected final ClusterName clusterName;
protected final ClusterService clusterService;
protected final TransportService transportService;
final String transportAction;
final String transportNodeAction;
final String executor;
@Inject
public TransportNodesOperationAction(Settings settings, ClusterName clusterName, ThreadPool threadPool,
ClusterService clusterService, TransportService transportService) {
super(settings, threadPool);
this.clusterName = clusterName;
this.clusterService = clusterService;
this.transportService = transportService;
this.transportAction = transportAction();
this.transportNodeAction = transportAction() + "/n";
this.executor = executor();
transportService.registerHandler(transportAction, new TransportHandler());
transportService.registerHandler(transportNodeAction, new NodeTransportHandler());
}
@Override
protected void doExecute(Request request, ActionListener<Response> listener) {
new AsyncAction(request, listener).start();
}
protected abstract String transportAction();
protected boolean transportCompress() {
return false;
}
protected abstract String executor();
protected abstract Request newRequest();
protected abstract Response newResponse(Request request, AtomicReferenceArray nodesResponses);
protected abstract NodeRequest newNodeRequest();
protected abstract NodeRequest newNodeRequest(String nodeId, Request request);
protected abstract NodeResponse newNodeResponse();
protected abstract NodeResponse nodeOperation(NodeRequest request) throws ElasticsearchException;
protected abstract boolean accumulateExceptions();
protected String[] filterNodeIds(DiscoveryNodes nodes, String[] nodesIds) {
return nodesIds;
}
private class AsyncAction {
private final Request request;
private final String[] nodesIds;
private final ActionListener<Response> listener;
private final ClusterState clusterState;
private final AtomicReferenceArray<Object> responses;
private final AtomicInteger counter = new AtomicInteger();
private AsyncAction(Request request, ActionListener<Response> listener) {
this.request = request;
this.listener = listener;
clusterState = clusterService.state();
String[] nodesIds = clusterState.nodes().resolveNodesIds(request.nodesIds());
this.nodesIds = filterNodeIds(clusterState.nodes(), nodesIds);
this.responses = new AtomicReferenceArray<Object>(this.nodesIds.length);
}
private void start() {
if (nodesIds.length == 0) {
// nothing to notify
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
listener.onResponse(newResponse(request, responses));
}
});
return;
}
TransportRequestOptions transportRequestOptions = TransportRequestOptions.options();
if (request.timeout() != null) {
transportRequestOptions.withTimeout(request.timeout());
}
transportRequestOptions.withCompress(transportCompress());
for (int i = 0; i < nodesIds.length; i++) {
final String nodeId = nodesIds[i];
final int idx = i;
final DiscoveryNode node = clusterState.nodes().nodes().get(nodeId);
try {
if (nodeId.equals("_local") || nodeId.equals(clusterState.nodes().localNodeId())) {
threadPool.executor(executor()).execute(new Runnable() {
@Override
public void run() {
try {
onOperation(idx, nodeOperation(newNodeRequest(clusterState.nodes().localNodeId(), request)));
} catch (Throwable e) {
onFailure(idx, clusterState.nodes().localNodeId(), e);
}
}
});
} else if (nodeId.equals("_master")) {
threadPool.executor(executor()).execute(new Runnable() {
@Override
public void run() {
try {
onOperation(idx, nodeOperation(newNodeRequest(clusterState.nodes().masterNodeId(), request)));
} catch (Throwable e) {
onFailure(idx, clusterState.nodes().masterNodeId(), e);
}
}
});
} else {
if (node == null) {
onFailure(idx, nodeId, new NoSuchNodeException(nodeId));
} else {
NodeRequest nodeRequest = newNodeRequest(nodeId, request);
transportService.sendRequest(node, transportNodeAction, nodeRequest, transportRequestOptions, new BaseTransportResponseHandler<NodeResponse>() {
@Override
public NodeResponse newInstance() {
return newNodeResponse();
}
@Override
public void handleResponse(NodeResponse response) {
onOperation(idx, response);
}
@Override
public void handleException(TransportException exp) {
onFailure(idx, node.id(), exp);
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
});
}
}
} catch (Throwable t) {
onFailure(idx, nodeId, t);
}
}
}
private void onOperation(int idx, NodeResponse nodeResponse) {
responses.set(idx, nodeResponse);
if (counter.incrementAndGet() == responses.length()) {
finishHim();
}
}
private void onFailure(int idx, String nodeId, Throwable t) {
if (logger.isDebugEnabled()) {
logger.debug("failed to execute on node [{}]", t, nodeId);
}
if (accumulateExceptions()) {
responses.set(idx, new FailedNodeException(nodeId, "Failed node [" + nodeId + "]", t));
}
if (counter.incrementAndGet() == responses.length()) {
finishHim();
}
}
private void finishHim() {
Response finalResponse;
try {
finalResponse = newResponse(request, responses);
} catch (Throwable t) {
logger.debug("failed to combine responses from nodes", t);
listener.onFailure(t);
return;
}
listener.onResponse(finalResponse);
}
}
private class TransportHandler extends BaseTransportRequestHandler<Request> {
@Override
public Request newInstance() {
return newRequest();
}
@Override
public void messageReceived(final Request request, final TransportChannel channel) throws Exception {
request.listenerThreaded(false);
execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response response) {
TransportResponseOptions options = TransportResponseOptions.options().withCompress(transportCompress());
try {
channel.sendResponse(response, options);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send response", e);
}
}
});
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public String toString() {
return transportAction;
}
}
private class NodeTransportHandler extends BaseTransportRequestHandler<NodeRequest> {
@Override
public NodeRequest newInstance() {
return newNodeRequest();
}
@Override
public void messageReceived(final NodeRequest request, final TransportChannel channel) throws Exception {
channel.sendResponse(nodeOperation(request));
}
@Override
public String toString() {
return transportNodeAction;
}
@Override
public String executor() {
return executor;
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_nodes_TransportNodesOperationAction.java
|
483 |
public interface ResponseStream {
Object read() throws Exception;
void end() throws IOException;
}
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_spi_ResponseStream.java
|
879 |
public class TransportSearchScanAction extends TransportSearchTypeAction {
@Inject
public TransportSearchScanAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController) {
super(settings, threadPool, clusterService, searchService, searchPhaseController);
}
@Override
protected void doExecute(SearchRequest searchRequest, ActionListener<SearchResponse> listener) {
new AsyncAction(searchRequest, listener).start();
}
private class AsyncAction extends BaseAsyncAction<QuerySearchResult> {
private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) {
super(request, listener);
}
@Override
protected String firstPhaseName() {
return "init_scan";
}
@Override
protected void sendExecuteFirstPhase(DiscoveryNode node, ShardSearchRequest request, SearchServiceListener<QuerySearchResult> listener) {
searchService.sendExecuteScan(node, request, listener);
}
@Override
protected void moveToSecondPhase() throws Exception {
final InternalSearchResponse internalResponse = searchPhaseController.merge(SearchPhaseController.EMPTY_DOCS, firstResults, (AtomicArray<? extends FetchSearchResultProvider>) AtomicArray.empty());
String scrollId = null;
if (request.scroll() != null) {
scrollId = buildScrollId(request.searchType(), firstResults, ImmutableMap.of("total_hits", Long.toString(internalResponse.hits().totalHits())));
}
listener.onResponse(new SearchResponse(internalResponse, scrollId, expectedSuccessfulOps, successulOps.get(), buildTookInMillis(), buildShardFailures()));
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_search_type_TransportSearchScanAction.java
|
794 |
public class PercolateRequestBuilder extends BroadcastOperationRequestBuilder<PercolateRequest, PercolateResponse, PercolateRequestBuilder> {
private PercolateSourceBuilder sourceBuilder;
public PercolateRequestBuilder(Client client) {
super((InternalClient) client, new PercolateRequest());
}
/**
* Sets the type of the document to percolate.
*/
public PercolateRequestBuilder setDocumentType(String type) {
request.documentType(type);
return this;
}
/**
* A comma separated list of routing values to control the shards the search will be executed on.
*/
public PercolateRequestBuilder setRouting(String routing) {
request.routing(routing);
return this;
}
/**
* List of routing values to control the shards the search will be executed on.
*/
public PercolateRequestBuilder setRouting(String... routings) {
request.routing(Strings.arrayToCommaDelimitedString(routings));
return this;
}
/**
* Sets the preference to execute the search. Defaults to randomize across shards. Can be set to
* <tt>_local</tt> to prefer local shards, <tt>_primary</tt> to execute only on primary shards, or
* a custom value, which guarantees that the same order will be used across different requests.
*/
public PercolateRequestBuilder setPreference(String preference) {
request.preference(preference);
return this;
}
/**
* Enables percolating an existing document. Instead of specifying the source of the document to percolate, define
* a get request that will fetch a document and use its source.
*/
public PercolateRequestBuilder setGetRequest(GetRequest getRequest) {
request.getRequest(getRequest);
return this;
}
/**
* Whether only to return total count and don't keep track of the matches (Count percolation).
*/
public PercolateRequestBuilder setOnlyCount(boolean onlyCount) {
request.onlyCount(onlyCount);
return this;
}
/**
* Limits the maximum number of percolate query matches to be returned.
*/
public PercolateRequestBuilder setSize(int size) {
sourceBuilder().setSize(size);
return this;
}
/**
* Similar as {@link #setScore(boolean)}, but whether to sort by the score descending.
*/
public PercolateRequestBuilder setSortByScore(boolean sort) {
sourceBuilder().setSort(sort);
return this;
}
/**
* Adds
*/
public PercolateRequestBuilder addSort(SortBuilder sort) {
sourceBuilder().addSort(sort);
return this;
}
/**
* Whether to compute a score for each match and include it in the response. The score is based on
* {@link #setPercolateQuery(QueryBuilder)}}.
*/
public PercolateRequestBuilder setScore(boolean score) {
sourceBuilder().setTrackScores(score);
return this;
}
/**
* Sets a query to reduce the number of percolate queries to be evaluated and score the queries that match based
* on this query.
*/
public PercolateRequestBuilder setPercolateDoc(PercolateSourceBuilder.DocBuilder docBuilder) {
sourceBuilder().setDoc(docBuilder);
return this;
}
/**
* Sets a query to reduce the number of percolate queries to be evaluated and score the queries that match based
* on this query.
*/
public PercolateRequestBuilder setPercolateQuery(QueryBuilder queryBuilder) {
sourceBuilder().setQueryBuilder(queryBuilder);
return this;
}
/**
* Sets a filter to reduce the number of percolate queries to be evaluated.
*/
public PercolateRequestBuilder setPercolateFilter(FilterBuilder filterBuilder) {
sourceBuilder().setFilterBuilder(filterBuilder);
return this;
}
/**
* Enables highlighting for the percolate document. Per matched percolate query highlight the percolate document.
*/
public PercolateRequestBuilder setHighlightBuilder(HighlightBuilder highlightBuilder) {
sourceBuilder().setHighlightBuilder(highlightBuilder);
return this;
}
/**
* Add a facet definition.
*/
public PercolateRequestBuilder addFacet(FacetBuilder facetBuilder) {
sourceBuilder().addFacet(facetBuilder);
return this;
}
/**
* Add a aggregation definition.
*/
public PercolateRequestBuilder addAggregation(AggregationBuilder aggregationBuilder) {
sourceBuilder().addAggregation(aggregationBuilder);
return this;
}
/**
* Sets the raw percolate request body.
*/
public PercolateRequestBuilder setSource(PercolateSourceBuilder source) {
sourceBuilder = source;
return this;
}
public PercolateRequestBuilder setSource(Map<String, Object> source) {
request.source(source);
return this;
}
public PercolateRequestBuilder setSource(Map<String, Object> source, XContentType contentType) {
request.source(source, contentType);
return this;
}
public PercolateRequestBuilder setSource(String source) {
request.source(source);
return this;
}
public PercolateRequestBuilder setSource(XContentBuilder sourceBuilder) {
request.source(sourceBuilder);
return this;
}
public PercolateRequestBuilder setSource(BytesReference source) {
request.source(source, false);
return this;
}
public PercolateRequestBuilder setSource(BytesReference source, boolean unsafe) {
request.source(source, unsafe);
return this;
}
public PercolateRequestBuilder setSource(byte[] source) {
request.source(source);
return this;
}
public PercolateRequestBuilder setSource(byte[] source, int offset, int length) {
request.source(source, offset, length);
return this;
}
public PercolateRequestBuilder setSource(byte[] source, int offset, int length, boolean unsafe) {
request.source(source, offset, length, unsafe);
return this;
}
private PercolateSourceBuilder sourceBuilder() {
if (sourceBuilder == null) {
sourceBuilder = new PercolateSourceBuilder();
}
return sourceBuilder;
}
@Override
public PercolateRequest request() {
if (sourceBuilder != null) {
request.source(sourceBuilder);
}
return request;
}
@Override
protected void doExecute(ActionListener<PercolateResponse> listener) {
if (sourceBuilder != null) {
request.source(sourceBuilder);
}
((Client) client).percolate(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_percolate_PercolateRequestBuilder.java
|
47 |
public static class Builder
{
private final File root;
private final Provider provider = clusterOfSize( 3 );
private final Map<String, String> commonConfig = emptyMap();
private final Map<Integer, Map<String,String>> instanceConfig = new HashMap<>();
private HighlyAvailableGraphDatabaseFactory factory = new HighlyAvailableGraphDatabaseFactory();
private StoreDirInitializer initializer;
public Builder( File root )
{
this.root = root;
}
public Builder withSeedDir( final File seedDir )
{
return withStoreDirInitializer( new StoreDirInitializer()
{
@Override
public void initializeStoreDir( int serverId, File storeDir ) throws IOException
{
copyRecursively( seedDir, storeDir );
}
} );
}
public Builder withStoreDirInitializer( StoreDirInitializer initializer )
{
this.initializer = initializer;
return this;
}
public Builder withDbFactory( HighlyAvailableGraphDatabaseFactory dbFactory )
{
this.factory = dbFactory;
return this;
}
public ClusterManager build()
{
return new ClusterManager( this );
}
}
| 1no label
|
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterManager.java
|
1,474 |
public class CyclicPathFilterMap {
public static final String CLASS = Tokens.makeNamespace(CyclicPathFilterMap.class) + ".class";
public enum Counters {
PATHS_FILTERED
}
public static Configuration createConfiguration(final Class<? extends Element> klass) {
final Configuration configuration = new EmptyConfiguration();
configuration.setClass(CLASS, klass, Element.class);
configuration.setBoolean(Tokens.TITAN_HADOOP_PIPELINE_TRACK_PATHS, true);
return configuration;
}
public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> {
private boolean isVertex;
private HashSet set = new HashSet();
@Override
public void setup(final Mapper.Context context) throws IOException, InterruptedException {
this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class);
}
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException {
long pathsFiltered = 0l;
if (this.isVertex) {
if (value.hasPaths()) {
final Iterator<List<FaunusPathElement.MicroElement>> itty = value.getPaths().iterator();
while (itty.hasNext()) {
final List<FaunusPathElement.MicroElement> path = itty.next();
this.set.clear();
this.set.addAll(path);
if (path.size() != this.set.size()) {
itty.remove();
pathsFiltered++;
}
}
}
} else {
for (final Edge e : value.getEdges(Direction.BOTH)) {
final StandardFaunusEdge edge = (StandardFaunusEdge) e;
if (edge.hasPaths()) {
final Iterator<List<FaunusPathElement.MicroElement>> itty = edge.getPaths().iterator();
while (itty.hasNext()) {
final List<FaunusPathElement.MicroElement> path = itty.next();
this.set.clear();
this.set.addAll(path);
if (path.size() != this.set.size()) {
itty.remove();
pathsFiltered++;
}
}
}
}
}
DEFAULT_COMPAT.incrementContextCounter(context, Counters.PATHS_FILTERED, pathsFiltered);
context.write(NullWritable.get(), value);
}
}
}
| 1no label
|
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_filter_CyclicPathFilterMap.java
|
1,555 |
public class VertexMap {
public static final String IDS = Tokens.makeNamespace(VertexMap.class) + ".ids";
public enum Counters {
VERTICES_PROCESSED
}
public static Configuration createConfiguration(final long... ids) {
final String[] idStrings = new String[ids.length];
for (int i = 0; i < ids.length; i++) {
idStrings[i] = String.valueOf(ids[i]);
}
final Configuration configuration = new EmptyConfiguration();
configuration.setStrings(IDS, idStrings);
return configuration;
}
public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> {
private Collection<Long> ids;
@Override
public void setup(final Mapper.Context context) throws IOException, InterruptedException {
//todo: make as list and double up repeats
this.ids = VertexMap.Map.getLongCollection(context.getConfiguration(), IDS, new HashSet<Long>());
}
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException {
if (this.ids.contains(value.getLongId())) {
value.startPath();
DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_PROCESSED, 1L);
} else {
value.clearPaths();
}
context.write(NullWritable.get(), value);
}
private static Collection<Long> getLongCollection(final Configuration conf, final String key, final Collection<Long> collection) {
for (final String value : conf.getStrings(key)) {
collection.add(Long.valueOf(value));
}
return collection;
}
}
}
| 1no label
|
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_transform_VertexMap.java
|
32 |
public class Values extends AbstractCollection<V> {
@Override
public Iterator<V> iterator() {
return new ValueIterator(getFirstEntry());
}
public Iterator<V> inverseIterator() {
return new ValueInverseIterator(getLastEntry());
}
@Override
public int size() {
return OMVRBTree.this.size();
}
@Override
public boolean contains(final Object o) {
return OMVRBTree.this.containsValue(o);
}
@Override
public boolean remove(final Object o) {
for (OMVRBTreeEntry<K, V> e = getFirstEntry(); e != null; e = next(e)) {
if (valEquals(e.getValue(), o)) {
deleteEntry(e);
return true;
}
}
return false;
}
@Override
public void clear() {
OMVRBTree.this.clear();
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
|
452 |
@ClusterScope(scope = ElasticsearchIntegrationTest.Scope.TEST, numNodes = 0)
public class ClusterStatsTests extends ElasticsearchIntegrationTest {
private void assertCounts(ClusterStatsNodes.Counts counts, int total, int masterOnly, int dataOnly, int masterData, int client) {
assertThat(counts.getTotal(), Matchers.equalTo(total));
assertThat(counts.getMasterOnly(), Matchers.equalTo(masterOnly));
assertThat(counts.getDataOnly(), Matchers.equalTo(dataOnly));
assertThat(counts.getMasterData(), Matchers.equalTo(masterData));
assertThat(counts.getClient(), Matchers.equalTo(client));
}
@Test
public void testNodeCounts() {
cluster().startNode();
ClusterStatsResponse response = client().admin().cluster().prepareClusterStats().get();
assertCounts(response.getNodesStats().getCounts(), 1, 0, 0, 1, 0);
cluster().startNode(ImmutableSettings.builder().put("node.data", false));
response = client().admin().cluster().prepareClusterStats().get();
assertCounts(response.getNodesStats().getCounts(), 2, 1, 0, 1, 0);
cluster().startNode(ImmutableSettings.builder().put("node.master", false));
response = client().admin().cluster().prepareClusterStats().get();
assertCounts(response.getNodesStats().getCounts(), 3, 1, 1, 1, 0);
cluster().startNode(ImmutableSettings.builder().put("node.client", true));
response = client().admin().cluster().prepareClusterStats().get();
assertCounts(response.getNodesStats().getCounts(), 4, 1, 1, 1, 1);
}
private void assertShardStats(ClusterStatsIndices.ShardStats stats, int indices, int total, int primaries, double replicationFactor) {
assertThat(stats.getIndices(), Matchers.equalTo(indices));
assertThat(stats.getTotal(), Matchers.equalTo(total));
assertThat(stats.getPrimaries(), Matchers.equalTo(primaries));
assertThat(stats.getReplication(), Matchers.equalTo(replicationFactor));
}
@Test
public void testIndicesShardStats() {
cluster().startNode();
ClusterStatsResponse response = client().admin().cluster().prepareClusterStats().get();
assertThat(response.getStatus(), Matchers.equalTo(ClusterHealthStatus.GREEN));
prepareCreate("test1").setSettings("number_of_shards", 2, "number_of_replicas", 1).get();
ensureYellow();
response = client().admin().cluster().prepareClusterStats().get();
assertThat(response.getStatus(), Matchers.equalTo(ClusterHealthStatus.YELLOW));
assertThat(response.indicesStats.getDocs().getCount(), Matchers.equalTo(0l));
assertThat(response.indicesStats.getIndexCount(), Matchers.equalTo(1));
assertShardStats(response.getIndicesStats().getShards(), 1, 2, 2, 0.0);
// add another node, replicas should get assigned
cluster().startNode();
ensureGreen();
index("test1", "type", "1", "f", "f");
refresh(); // make the doc visible
response = client().admin().cluster().prepareClusterStats().get();
assertThat(response.getStatus(), Matchers.equalTo(ClusterHealthStatus.GREEN));
assertThat(response.indicesStats.getDocs().getCount(), Matchers.equalTo(1l));
assertShardStats(response.getIndicesStats().getShards(), 1, 4, 2, 1.0);
prepareCreate("test2").setSettings("number_of_shards", 3, "number_of_replicas", 0).get();
ensureGreen();
response = client().admin().cluster().prepareClusterStats().get();
assertThat(response.getStatus(), Matchers.equalTo(ClusterHealthStatus.GREEN));
assertThat(response.indicesStats.getIndexCount(), Matchers.equalTo(2));
assertShardStats(response.getIndicesStats().getShards(), 2, 7, 5, 2.0 / 5);
assertThat(response.getIndicesStats().getShards().getAvgIndexPrimaryShards(), Matchers.equalTo(2.5));
assertThat(response.getIndicesStats().getShards().getMinIndexPrimaryShards(), Matchers.equalTo(2));
assertThat(response.getIndicesStats().getShards().getMaxIndexPrimaryShards(), Matchers.equalTo(3));
assertThat(response.getIndicesStats().getShards().getAvgIndexShards(), Matchers.equalTo(3.5));
assertThat(response.getIndicesStats().getShards().getMinIndexShards(), Matchers.equalTo(3));
assertThat(response.getIndicesStats().getShards().getMaxIndexShards(), Matchers.equalTo(4));
assertThat(response.getIndicesStats().getShards().getAvgIndexReplication(), Matchers.equalTo(0.5));
assertThat(response.getIndicesStats().getShards().getMinIndexReplication(), Matchers.equalTo(0.0));
assertThat(response.getIndicesStats().getShards().getMaxIndexReplication(), Matchers.equalTo(1.0));
}
@Test
public void testValuesSmokeScreen() {
cluster().ensureAtMostNumNodes(5);
cluster().ensureAtLeastNumNodes(1);
SigarService sigarService = cluster().getInstance(SigarService.class);
index("test1", "type", "1", "f", "f");
ClusterStatsResponse response = client().admin().cluster().prepareClusterStats().get();
assertThat(response.getTimestamp(), Matchers.greaterThan(946681200000l)); // 1 Jan 2000
assertThat(response.indicesStats.getStore().getSizeInBytes(), Matchers.greaterThan(0l));
assertThat(response.nodesStats.getFs().getTotal().bytes(), Matchers.greaterThan(0l));
assertThat(response.nodesStats.getJvm().getVersions().size(), Matchers.greaterThan(0));
if (sigarService.sigarAvailable()) {
// We only get those if we have sigar
assertThat(response.nodesStats.getOs().getAvailableProcessors(), Matchers.greaterThan(0));
assertThat(response.nodesStats.getOs().getAvailableMemory().bytes(), Matchers.greaterThan(0l));
assertThat(response.nodesStats.getOs().getCpus().size(), Matchers.greaterThan(0));
}
assertThat(response.nodesStats.getVersions().size(), Matchers.greaterThan(0));
assertThat(response.nodesStats.getVersions().contains(Version.CURRENT), Matchers.equalTo(true));
assertThat(response.nodesStats.getPlugins().size(), Matchers.greaterThanOrEqualTo(0));
assertThat(response.nodesStats.getProcess().count, Matchers.greaterThan(0));
// 0 happens when not supported on platform
assertThat(response.nodesStats.getProcess().getAvgOpenFileDescriptors(), Matchers.greaterThanOrEqualTo(0L));
// these can be -1 if not supported on platform
assertThat(response.nodesStats.getProcess().getMinOpenFileDescriptors(), Matchers.greaterThanOrEqualTo(-1L));
assertThat(response.nodesStats.getProcess().getMaxOpenFileDescriptors(), Matchers.greaterThanOrEqualTo(-1L));
}
}
| 0true
|
src_test_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsTests.java
|
292 |
public class PrimaryMissingActionException extends ElasticsearchException {
public PrimaryMissingActionException(String message) {
super(message);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_PrimaryMissingActionException.java
|
245 |
private static class AnalyzingComparator implements Comparator<BytesRef> {
private final boolean hasPayloads;
public AnalyzingComparator(boolean hasPayloads) {
this.hasPayloads = hasPayloads;
}
private final ByteArrayDataInput readerA = new ByteArrayDataInput();
private final ByteArrayDataInput readerB = new ByteArrayDataInput();
private final BytesRef scratchA = new BytesRef();
private final BytesRef scratchB = new BytesRef();
@Override
public int compare(BytesRef a, BytesRef b) {
// First by analyzed form:
readerA.reset(a.bytes, a.offset, a.length);
scratchA.length = readerA.readShort();
scratchA.bytes = a.bytes;
scratchA.offset = readerA.getPosition();
readerB.reset(b.bytes, b.offset, b.length);
scratchB.bytes = b.bytes;
scratchB.length = readerB.readShort();
scratchB.offset = readerB.getPosition();
int cmp = scratchA.compareTo(scratchB);
if (cmp != 0) {
return cmp;
}
readerA.skipBytes(scratchA.length);
readerB.skipBytes(scratchB.length);
// Next by cost:
long aCost = readerA.readInt();
long bCost = readerB.readInt();
if (aCost < bCost) {
return -1;
} else if (aCost > bCost) {
return 1;
}
// Finally by surface form:
if (hasPayloads) {
scratchA.length = readerA.readShort();
scratchA.offset = readerA.getPosition();
scratchB.length = readerB.readShort();
scratchB.offset = readerB.getPosition();
} else {
scratchA.offset = readerA.getPosition();
scratchA.length = a.length - scratchA.offset;
scratchB.offset = readerB.getPosition();
scratchB.length = b.length - scratchB.offset;
}
return scratchA.compareTo(scratchB);
}
}
| 0true
|
src_main_java_org_apache_lucene_search_suggest_analyzing_XAnalyzingSuggester.java
|
1,452 |
public class DiscoveryNode implements Streamable, Serializable {
public static boolean localNode(Settings settings) {
if (settings.get("node.local") != null) {
return settings.getAsBoolean("node.local", false);
}
if (settings.get("node.mode") != null) {
String nodeMode = settings.get("node.mode");
if ("local".equals(nodeMode)) {
return true;
} else if ("network".equals(nodeMode)) {
return false;
} else {
throw new ElasticsearchIllegalArgumentException("unsupported node.mode [" + nodeMode + "]");
}
}
return false;
}
public static boolean nodeRequiresLocalStorage(Settings settings) {
return !(settings.getAsBoolean("node.client", false) || (!settings.getAsBoolean("node.data", true) && !settings.getAsBoolean("node.master", true)));
}
public static boolean clientNode(Settings settings) {
String client = settings.get("node.client");
return client != null && client.equals("true");
}
public static boolean masterNode(Settings settings) {
String master = settings.get("node.master");
if (master == null) {
return !clientNode(settings);
}
return master.equals("true");
}
public static boolean dataNode(Settings settings) {
String data = settings.get("node.data");
if (data == null) {
return !clientNode(settings);
}
return data.equals("true");
}
public static final ImmutableList<DiscoveryNode> EMPTY_LIST = ImmutableList.of();
private String nodeName = "";
private String nodeId;
private String hostName;
private String hostAddress;
private TransportAddress address;
private ImmutableMap<String, String> attributes;
private Version version = Version.CURRENT;
DiscoveryNode() {
}
public DiscoveryNode(String nodeId, TransportAddress address, Version version) {
this("", nodeId, address, ImmutableMap.<String, String>of(), version);
}
public DiscoveryNode(String nodeName, String nodeId, TransportAddress address, Map<String, String> attributes, Version version) {
this(nodeName, nodeId, NetworkUtils.getLocalHostName(""), NetworkUtils.getLocalHostAddress(""), address, attributes, version);
}
public DiscoveryNode(String nodeName, String nodeId, String hostName, String hostAddress, TransportAddress address, Map<String, String> attributes, Version version) {
if (nodeName != null) {
this.nodeName = nodeName.intern();
}
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (Map.Entry<String, String> entry : attributes.entrySet()) {
builder.put(entry.getKey().intern(), entry.getValue().intern());
}
this.attributes = builder.build();
this.nodeId = nodeId.intern();
this.hostName = hostName.intern();
this.hostAddress = hostAddress.intern();
this.address = address;
this.version = version;
}
/**
* Should this node form a connection to the provided node.
*/
public boolean shouldConnectTo(DiscoveryNode otherNode) {
if (clientNode() && otherNode.clientNode()) {
return false;
}
return true;
}
/**
* The address that the node can be communicated with.
*/
public TransportAddress address() {
return address;
}
/**
* The address that the node can be communicated with.
*/
public TransportAddress getAddress() {
return address();
}
/**
* The unique id of the node.
*/
public String id() {
return nodeId;
}
/**
* The unique id of the node.
*/
public String getId() {
return id();
}
/**
* The name of the node.
*/
public String name() {
return this.nodeName;
}
/**
* The name of the node.
*/
public String getName() {
return name();
}
/**
* The node attributes.
*/
public ImmutableMap<String, String> attributes() {
return this.attributes;
}
/**
* The node attributes.
*/
public ImmutableMap<String, String> getAttributes() {
return attributes();
}
/**
* Should this node hold data (shards) or not.
*/
public boolean dataNode() {
String data = attributes.get("data");
if (data == null) {
return !clientNode();
}
return data.equals("true");
}
/**
* Should this node hold data (shards) or not.
*/
public boolean isDataNode() {
return dataNode();
}
/**
* Is the node a client node or not.
*/
public boolean clientNode() {
String client = attributes.get("client");
return client != null && client.equals("true");
}
public boolean isClientNode() {
return clientNode();
}
/**
* Can this node become master or not.
*/
public boolean masterNode() {
String master = attributes.get("master");
if (master == null) {
return !clientNode();
}
return master.equals("true");
}
/**
* Can this node become master or not.
*/
public boolean isMasterNode() {
return masterNode();
}
public Version version() {
return this.version;
}
public String getHostName() {
return this.hostName;
}
public String getHostAddress() {
return this.hostAddress;
}
public Version getVersion() {
return this.version;
}
public static DiscoveryNode readNode(StreamInput in) throws IOException {
DiscoveryNode node = new DiscoveryNode();
node.readFrom(in);
return node;
}
@Override
public void readFrom(StreamInput in) throws IOException {
nodeName = in.readString().intern();
nodeId = in.readString().intern();
hostName = in.readString().intern();
hostAddress = in.readString().intern();
address = TransportAddressSerializers.addressFromStream(in);
int size = in.readVInt();
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (int i = 0; i < size; i++) {
builder.put(in.readString().intern(), in.readString().intern());
}
attributes = builder.build();
version = Version.readVersion(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(nodeName);
out.writeString(nodeId);
out.writeString(hostName);
out.writeString(hostAddress);
addressToStream(out, address);
out.writeVInt(attributes.size());
for (Map.Entry<String, String> entry : attributes.entrySet()) {
out.writeString(entry.getKey());
out.writeString(entry.getValue());
}
Version.writeVersion(version, out);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof DiscoveryNode))
return false;
DiscoveryNode other = (DiscoveryNode) obj;
return this.nodeId.equals(other.nodeId);
}
@Override
public int hashCode() {
return nodeId.hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (nodeName.length() > 0) {
sb.append('[').append(nodeName).append(']');
}
if (nodeId != null) {
sb.append('[').append(nodeId).append(']');
}
if (Strings.hasLength(hostName)) {
sb.append('[').append(hostName).append(']');
}
if (address != null) {
sb.append('[').append(address).append(']');
}
if (!attributes.isEmpty()) {
sb.append(attributes);
}
return sb.toString();
}
}
| 0true
|
src_main_java_org_elasticsearch_cluster_node_DiscoveryNode.java
|
130 |
static final class CreateAdder
implements ConcurrentHashMapV8.Fun<Object, LongAdder> {
public LongAdder apply(Object unused) { return new LongAdder(); }
}
| 0true
|
src_main_java_jsr166e_LongAdderTable.java
|
751 |
public class TxnSetAddRequest extends TxnCollectionRequest {
public TxnSetAddRequest() {
}
public TxnSetAddRequest(String name, Data value) {
super(name, value);
}
@Override
public Object innerCall() throws Exception {
return getEndpoint().getTransactionContext(txnId).getSet(name).add(value);
}
@Override
public String getServiceName() {
return SetService.SERVICE_NAME;
}
@Override
public int getClassId() {
return CollectionPortableHook.TXN_SET_ADD;
}
@Override
public Permission getRequiredPermission() {
return new SetPermission(name, ActionConstants.ACTION_ADD);
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_client_TxnSetAddRequest.java
|
525 |
client.executeTransaction(new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
try {
final TransactionalMap<String, Integer> txMap = context.getMap(mapName);
txMap.getForUpdate(key);
getKeyForUpdateLatch.countDown();
afterTryPutResult.await(30, TimeUnit.SECONDS);
} catch (Exception e) {
}
return true;
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_txn_ClientTxnMapTest.java
|
753 |
public class CopyFileRefactoringParticipant extends CopyParticipant {
private IFile file;
@Override
protected boolean initialize(Object element) {
file = (IFile) element;
return getProcessor() instanceof CopyProcessor &&
getProjectTypeChecker(file.getProject())!=null &&
file.getFileExtension()!=null &&
file.getFileExtension().equals("ceylon");
}
@Override
public String getName() {
return "Copy file participant for Ceylon source";
}
@Override
public RefactoringStatus checkConditions(IProgressMonitor pm,
CheckConditionsContext context) throws OperationCanceledException {
return new RefactoringStatus();
}
public Change createChange(IProgressMonitor pm) throws CoreException {
try {
IFolder dest = (IFolder) getArguments().getDestination();
final String newName = dest.getProjectRelativePath()
.removeFirstSegments(1).toPortableString()
.replace('/', '.');
IFile newFile = dest.getFile(file.getName());
String relFilePath = file.getProjectRelativePath()
.removeFirstSegments(1).toPortableString();
String relPath = file.getProjectRelativePath()
.removeFirstSegments(1).removeLastSegments(1)
.toPortableString();
final String oldName = relPath.replace('/', '.');
final IProject project = file.getProject();
TypeChecker tc = getProjectTypeChecker(project);
if (tc==null) return null;
PhasedUnit phasedUnit = tc.getPhasedUnitFromRelativePath(relFilePath);
if (phasedUnit==null) return null;
final List<ReplaceEdit> edits = new ArrayList<ReplaceEdit>();
final List<Declaration> declarations = phasedUnit.getDeclarations();
final Map<Declaration,String> imports = new HashMap<Declaration,String>();
phasedUnit.getCompilationUnit().visit(new Visitor() {
@Override
public void visit(ImportMemberOrType that) {
super.visit(that);
visitIt(that.getIdentifier(), that.getDeclarationModel());
}
@Override
public void visit(BaseMemberOrTypeExpression that) {
super.visit(that);
visitIt(that.getIdentifier(), that.getDeclaration());
}
@Override
public void visit(BaseType that) {
super.visit(that);
visitIt(that.getIdentifier(), that.getDeclarationModel());
}
@Override
public void visit(ModuleDescriptor that) {
super.visit(that);
visitIt(that.getImportPath());
}
@Override
public void visit(PackageDescriptor that) {
super.visit(that);
visitIt(that.getImportPath());
}
private void visitIt(Tree.ImportPath importPath) {
if (formatPath(importPath.getIdentifiers()).equals(oldName)) {
edits.add(new ReplaceEdit(importPath.getStartIndex(),
oldName.length(), newName));
}
}
private void visitIt(Tree.Identifier id, Declaration dec) {
if (dec!=null && !declarations.contains(dec)) {
String pn = dec.getUnit().getPackage().getNameAsString();
if (pn.equals(oldName) && !pn.isEmpty() &&
!pn.equals(Module.LANGUAGE_MODULE_NAME)) {
imports.put(dec, id.getText());
}
}
}
});
try {
TextFileChange change = new TextFileChange(file.getName(), newFile);
Tree.CompilationUnit cu = phasedUnit.getCompilationUnit();
change.setEdit(new MultiTextEdit());
for (ReplaceEdit edit: edits) {
change.addEdit(edit);
}
if (!imports.isEmpty()) {
List<InsertEdit> list = importEdits(cu,
imports.keySet(), imports.values(),
null, EditorUtil.getDocument(change));
for (TextEdit edit: list) {
change.addEdit(edit);
}
}
Tree.Import toDelete = findImportNode(cu, newName);
if (toDelete!=null) {
change.addEdit(new DeleteEdit(toDelete.getStartIndex(),
toDelete.getStopIndex()-toDelete.getStartIndex()+1));
}
if (change.getEdit().hasChildren()) {
return change;
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| 1no label
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_refactor_CopyFileRefactoringParticipant.java
|
231 |
PostingsHighlighter highlighter = new PostingsHighlighter() {
@Override
protected char getMultiValuedSeparator(String field) {
assert field.equals("body");
return '\u2029';
}
};
| 0true
|
src_test_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighterTests.java
|
6,023 |
public static class CandidateSet {
public Candidate[] candidates;
public final Candidate originalTerm;
public CandidateSet(Candidate[] candidates, Candidate originalTerm) {
this.candidates = candidates;
this.originalTerm = originalTerm;
}
public void addCandidates(List<Candidate> candidates) {
final Set<Candidate> set = new HashSet<DirectCandidateGenerator.Candidate>(candidates);
for (int i = 0; i < this.candidates.length; i++) {
set.add(this.candidates[i]);
}
this.candidates = set.toArray(new Candidate[set.size()]);
}
public void addOneCandidate(Candidate candidate) {
Candidate[] candidates = new Candidate[this.candidates.length + 1];
System.arraycopy(this.candidates, 0, candidates, 0, this.candidates.length);
candidates[candidates.length-1] = candidate;
this.candidates = candidates;
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_suggest_phrase_DirectCandidateGenerator.java
|
443 |
class NotSerializableDocument extends ODocument {
private static final long serialVersionUID = 1L;
private void writeObject(ObjectOutputStream oos) throws IOException {
throw new NotSerializableException();
}
}
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedSetTest.java
|
3,855 |
public static class Parser implements FilterParser {
@Inject
public Parser() {
}
@Override
public String[] names() {
return new String[]{NAME, Strings.toCamelCase(NAME)};
}
@Override
public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
String fieldName = null;
String geohash = null;
int levels = -1;
boolean neighbors = false;
XContentParser.Token token;
if ((token = parser.currentToken()) != Token.START_OBJECT) {
throw new ElasticsearchParseException(NAME + " must be an object");
}
while ((token = parser.nextToken()) != Token.END_OBJECT) {
if (token == Token.FIELD_NAME) {
String field = parser.text();
if (PRECISION.equals(field)) {
token = parser.nextToken();
if(token == Token.VALUE_NUMBER) {
levels = parser.intValue();
} else if(token == Token.VALUE_STRING) {
double meters = DistanceUnit.parse(parser.text(), DistanceUnit.DEFAULT, DistanceUnit.METERS);
levels = GeoUtils.geoHashLevelsForPrecision(meters);
}
} else if (NEIGHBORS.equals(field)) {
parser.nextToken();
neighbors = parser.booleanValue();
} else {
fieldName = field;
token = parser.nextToken();
if(token == Token.VALUE_STRING) {
// A string indicates either a gehash or a lat/lon string
String location = parser.text();
if(location.indexOf(",")>0) {
geohash = GeoPoint.parse(parser).geohash();
} else {
geohash = location;
}
} else {
geohash = GeoPoint.parse(parser).geohash();
}
}
} else {
throw new ElasticsearchParseException("unexpected token [" + token + "]");
}
}
if (geohash == null) {
throw new QueryParsingException(parseContext.index(), "no geohash value provided to geohash_cell filter");
}
MapperService.SmartNameFieldMappers smartMappers = parseContext.smartFieldMappers(fieldName);
if (smartMappers == null || !smartMappers.hasMapper()) {
throw new QueryParsingException(parseContext.index(), "failed to find geo_point field [" + fieldName + "]");
}
FieldMapper<?> mapper = smartMappers.mapper();
if (!(mapper instanceof GeoPointFieldMapper)) {
throw new QueryParsingException(parseContext.index(), "field [" + fieldName + "] is not a geo_point field");
}
GeoPointFieldMapper geoMapper = ((GeoPointFieldMapper) mapper);
if (!geoMapper.isEnableGeohashPrefix()) {
throw new QueryParsingException(parseContext.index(), "can't execute geohash_cell on field [" + fieldName + "], geohash_prefix is not enabled");
}
if(levels > 0) {
int len = Math.min(levels, geohash.length());
geohash = geohash.substring(0, len);
}
if (neighbors) {
return create(parseContext, geoMapper, geohash, GeoHashUtils.neighbors(geohash));
} else {
return create(parseContext, geoMapper, geohash, null);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_query_GeohashCellFilter.java
|
225 |
public class RuntimeEnvironmentPropertiesManagerTest extends BaseTest {
@Resource(name = "blConfigurationManager")
RuntimeEnvironmentPropertiesManager configurationManager;
@Test
public void testPropertyOnly() throws Exception {
String s = configurationManager.getProperty("detect.sequence.generator.inconsistencies");
if(s.indexOf("$")>=0) {
Assert.fail("RuntimeEnvironmentPropertiesManager bean not defined");
}
}
@Test(dependsOnMethods={"testPropertyOnly"})
public void testPrefix() throws Exception {
configurationManager.setPrefix("detect");
String s = configurationManager.getProperty("sequence.generator.inconsistencies");
if(s.indexOf("$")>=0) {
Assert.fail("RuntimeEnvironmentPropertiesManager bean not defined");
}
}
@Test(dependsOnMethods={"testPrefix"})
public void testSuffix() throws Exception {
String s = configurationManager.getProperty("sequence.generator","inconsistencies");
if(s.indexOf("$")>=0) {
Assert.fail("RuntimeEnvironmentPropertiesManager bean not defined");
}
}
@Test(dependsOnMethods={"testSuffix"})
public void testNullSuffix() throws Exception {
configurationManager.setPrefix("detect");
String s = configurationManager.getProperty("sequence.generator.inconsistencies", "SOMETHING");
Assert.assertNotNull(s);
}
@Test
public void testNULL() throws Exception {
String s = configurationManager.getProperty(null, "SOMETHING");
Assert.assertEquals(s, null);
}
}
| 0true
|
integration_src_test_java_org_broadleafcommerce_common_config_RuntimeEnvironmentPropertiesManagerTest.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.