Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
3,382
public class PagedBytesAtomicFieldData implements AtomicFieldData.WithOrdinals<ScriptDocValues.Strings> { public static PagedBytesAtomicFieldData empty(int numDocs) { return new Empty(numDocs); } // 0 ordinal in values means no value (its null) private final PagedBytes.Reader bytes; private final MonotonicAppendingLongBuffer termOrdToBytesOffset; protected final Ordinals ordinals; private volatile IntArray hashes; private long size = -1; private final long readerBytesSize; public PagedBytesAtomicFieldData(PagedBytes.Reader bytes, long readerBytesSize, MonotonicAppendingLongBuffer termOrdToBytesOffset, Ordinals ordinals) { this.bytes = bytes; this.termOrdToBytesOffset = termOrdToBytesOffset; this.ordinals = ordinals; this.readerBytesSize = readerBytesSize; } @Override public void close() { } @Override public boolean isMultiValued() { return ordinals.isMultiValued(); } @Override public int getNumDocs() { return ordinals.getNumDocs(); } @Override public long getNumberUniqueValues() { return ordinals.getNumOrds(); } @Override public boolean isValuesOrdered() { return true; } @Override public long getMemorySizeInBytes() { if (size == -1) { long size = ordinals.getMemorySizeInBytes(); // PackedBytes size += readerBytesSize; // PackedInts size += termOrdToBytesOffset.ramBytesUsed(); this.size = size; } return size; } private final IntArray getHashes() { if (hashes == null) { long numberOfValues = termOrdToBytesOffset.size(); IntArray hashes = BigArrays.newIntArray(numberOfValues); BytesRef scratch = new BytesRef(); for (long i = 0; i < numberOfValues; i++) { bytes.fill(scratch, termOrdToBytesOffset.get(i)); hashes.set(i, scratch.hashCode()); } this.hashes = hashes; } return hashes; } @Override public BytesValues.WithOrdinals getBytesValues(boolean needsHashes) { if (needsHashes) { final IntArray hashes = getHashes(); return new BytesValues.HashedBytesValues(hashes, bytes, termOrdToBytesOffset, ordinals.ordinals()); } else { return new BytesValues(bytes, termOrdToBytesOffset, ordinals.ordinals()); } } @Override public ScriptDocValues.Strings getScriptValues() { return new ScriptDocValues.Strings(getBytesValues(false)); } static class BytesValues extends org.elasticsearch.index.fielddata.BytesValues.WithOrdinals { protected final PagedBytes.Reader bytes; protected final MonotonicAppendingLongBuffer termOrdToBytesOffset; protected final Ordinals.Docs ordinals; BytesValues(PagedBytes.Reader bytes, MonotonicAppendingLongBuffer termOrdToBytesOffset, Ordinals.Docs ordinals) { super(ordinals); this.bytes = bytes; this.termOrdToBytesOffset = termOrdToBytesOffset; this.ordinals = ordinals; } @Override public BytesRef copyShared() { // when we fill from the pages bytes, we just reference an existing buffer slice, its enough // to create a shallow copy of the bytes to be safe for "reads". return new BytesRef(scratch.bytes, scratch.offset, scratch.length); } @Override public final Ordinals.Docs ordinals() { return this.ordinals; } @Override public final BytesRef getValueByOrd(long ord) { assert ord != Ordinals.MISSING_ORDINAL; bytes.fill(scratch, termOrdToBytesOffset.get(ord)); return scratch; } @Override public final BytesRef nextValue() { bytes.fill(scratch, termOrdToBytesOffset.get(ordinals.nextOrd())); return scratch; } static final class HashedBytesValues extends BytesValues { private final IntArray hashes; HashedBytesValues(IntArray hashes, Reader bytes, MonotonicAppendingLongBuffer termOrdToBytesOffset, Docs ordinals) { super(bytes, termOrdToBytesOffset, ordinals); this.hashes = hashes; } @Override public int currentValueHash() { assert ordinals.currentOrd() >= 0; return hashes.get(ordinals.currentOrd()); } } } private final static class Empty extends PagedBytesAtomicFieldData { Empty(int numDocs) { super(emptyBytes(), 0, new MonotonicAppendingLongBuffer(), new EmptyOrdinals(numDocs)); } static PagedBytes.Reader emptyBytes() { PagedBytes bytes = new PagedBytes(1); bytes.copyUsingLengthPrefix(new BytesRef()); return bytes.freeze(true); } @Override public boolean isMultiValued() { return false; } @Override public int getNumDocs() { return ordinals.getNumDocs(); } @Override public long getNumberUniqueValues() { return 0; } @Override public boolean isValuesOrdered() { return true; } @Override public BytesValues.WithOrdinals getBytesValues(boolean needsHashes) { return new EmptyByteValuesWithOrdinals(ordinals.ordinals()); } @Override public ScriptDocValues.Strings getScriptValues() { return ScriptDocValues.EMPTY_STRINGS; } } }
0true
src_main_java_org_elasticsearch_index_fielddata_plain_PagedBytesAtomicFieldData.java
1,184
Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { node.close(); } });
0true
src_main_java_org_elasticsearch_bootstrap_Bootstrap.java
184
ItemListener listener = new ItemListener() { public void itemAdded(ItemEvent itemEvent) { latch.countDown(); } public void itemRemoved(ItemEvent item) { } };
0true
hazelcast-client_src_test_java_com_hazelcast_client_collections_ClientListTest.java
1,095
public class QueueConfigReadOnly extends QueueConfig { QueueConfigReadOnly(QueueConfig config) { super(config); } public List<ItemListenerConfig> getItemListenerConfigs() { final List<ItemListenerConfig> itemListenerConfigs = super.getItemListenerConfigs(); final List<ItemListenerConfig> readOnlyItemListenerConfigs = new ArrayList<ItemListenerConfig>(itemListenerConfigs.size()); for (ItemListenerConfig itemListenerConfig : itemListenerConfigs) { readOnlyItemListenerConfigs.add(itemListenerConfig.getAsReadOnly()); } return Collections.unmodifiableList(readOnlyItemListenerConfigs); } public QueueStoreConfig getQueueStoreConfig() { final QueueStoreConfig queueStoreConfig = super.getQueueStoreConfig(); if (queueStoreConfig == null ){ return null; } return queueStoreConfig.getAsReadOnly(); } public QueueConfig setEmptyQueueTtl(int emptyQueueTtl) { throw new UnsupportedOperationException("This config is read-only queue: " + getName()); } public QueueConfig setMaxSize(int maxSize) { throw new UnsupportedOperationException("This config is read-only queue: " + getName()); } public QueueConfig setBackupCount(int backupCount) { throw new UnsupportedOperationException("This config is read-only queue: " + getName()); } public QueueConfig setAsyncBackupCount(int asyncBackupCount) { throw new UnsupportedOperationException("This config is read-only queue: " + getName()); } public QueueConfig setQueueStoreConfig(QueueStoreConfig queueStoreConfig) { throw new UnsupportedOperationException("This config is read-only queue: " + getName()); } public QueueConfig setStatisticsEnabled(boolean statisticsEnabled) { throw new UnsupportedOperationException("This config is read-only queue: " + getName()); } public QueueConfig addItemListenerConfig(ItemListenerConfig listenerConfig) { throw new UnsupportedOperationException("This config is read-only queue: " + getName()); } public QueueConfig setItemListenerConfigs(List<ItemListenerConfig> listenerConfigs) { throw new UnsupportedOperationException("This config is read-only queue: " + getName()); } }
0true
hazelcast_src_main_java_com_hazelcast_config_QueueConfigReadOnly.java
41
public class ClusterLeaveReelectionListener extends ClusterListener.Adapter { private final Election election; private final StringLogger logger; public ClusterLeaveReelectionListener( Election election, StringLogger logger ) { this.election = election; this.logger = logger; } @Override public void leftCluster( InstanceId member ) { logger.warn( "Demoting member " + member + " because it left the cluster" ); // Suggest reelection for all roles of this node election.demote( member ); } }
1no label
enterprise_cluster_src_main_java_org_neo4j_cluster_protocol_election_ClusterLeaveReelectionListener.java
317
new Thread() { public void run() { map.lock(key); lockedLatch.countDown(); } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapLockTest.java
3,344
public abstract class GeoPointCompressedAtomicFieldData extends AtomicGeoPointFieldData<ScriptDocValues> { private final int numDocs; protected long size = -1; public GeoPointCompressedAtomicFieldData(int numDocs) { this.numDocs = numDocs; } @Override public void close() { } @Override public int getNumDocs() { return numDocs; } @Override public ScriptDocValues getScriptValues() { return new ScriptDocValues.GeoPoints(getGeoPointValues()); } static class WithOrdinals extends GeoPointCompressedAtomicFieldData { private final GeoPointFieldMapper.Encoding encoding; private final PagedMutable lon, lat; private final Ordinals ordinals; public WithOrdinals(GeoPointFieldMapper.Encoding encoding, PagedMutable lon, PagedMutable lat, int numDocs, Ordinals ordinals) { super(numDocs); this.encoding = encoding; this.lon = lon; this.lat = lat; this.ordinals = ordinals; } @Override public boolean isMultiValued() { return ordinals.isMultiValued(); } @Override public boolean isValuesOrdered() { return true; } @Override public long getNumberUniqueValues() { return ordinals.getNumOrds(); } @Override public long getMemorySizeInBytes() { if (size == -1) { size = RamUsageEstimator.NUM_BYTES_INT/*size*/ + RamUsageEstimator.NUM_BYTES_INT/*numDocs*/ + lon.ramBytesUsed() + lat.ramBytesUsed(); } return size; } @Override public GeoPointValues getGeoPointValues() { return new GeoPointValuesWithOrdinals(encoding, lon, lat, ordinals.ordinals()); } public static class GeoPointValuesWithOrdinals extends GeoPointValues { private final GeoPointFieldMapper.Encoding encoding; private final PagedMutable lon, lat; private final Ordinals.Docs ordinals; private final GeoPoint scratch = new GeoPoint(); GeoPointValuesWithOrdinals(GeoPointFieldMapper.Encoding encoding, PagedMutable lon, PagedMutable lat, Ordinals.Docs ordinals) { super(ordinals.isMultiValued()); this.encoding = encoding; this.lon = lon; this.lat = lat; this.ordinals = ordinals; } @Override public GeoPoint nextValue() { final long ord = ordinals.nextOrd(); assert ord > 0; return encoding.decode(lat.get(ord), lon.get(ord), scratch); } @Override public int setDocument(int docId) { this.docId = docId; return ordinals.setDocument(docId); } } } /** * Assumes unset values are marked in bitset, and docId is used as the index to the value array. */ public static class SingleFixedSet extends GeoPointCompressedAtomicFieldData { private final GeoPointFieldMapper.Encoding encoding; private final PagedMutable lon, lat; private final FixedBitSet set; private final long numOrds; public SingleFixedSet(GeoPointFieldMapper.Encoding encoding, PagedMutable lon, PagedMutable lat, int numDocs, FixedBitSet set, long numOrds) { super(numDocs); this.encoding = encoding; this.lon = lon; this.lat = lat; this.set = set; this.numOrds = numOrds; } @Override public boolean isMultiValued() { return false; } @Override public boolean isValuesOrdered() { return false; } @Override public long getNumberUniqueValues() { return numOrds; } @Override public long getMemorySizeInBytes() { if (size == -1) { size = RamUsageEstimator.NUM_BYTES_INT/*size*/ + RamUsageEstimator.NUM_BYTES_INT/*numDocs*/ + lon.ramBytesUsed() + lat.ramBytesUsed() + RamUsageEstimator.sizeOf(set.getBits()); } return size; } @Override public GeoPointValues getGeoPointValues() { return new GeoPointValuesSingleFixedSet(encoding, lon, lat, set); } static class GeoPointValuesSingleFixedSet extends GeoPointValues { private final GeoPointFieldMapper.Encoding encoding; private final PagedMutable lat, lon; private final FixedBitSet set; private final GeoPoint scratch = new GeoPoint(); GeoPointValuesSingleFixedSet(GeoPointFieldMapper.Encoding encoding, PagedMutable lon, PagedMutable lat, FixedBitSet set) { super(false); this.encoding = encoding; this.lon = lon; this.lat = lat; this.set = set; } @Override public int setDocument(int docId) { this.docId = docId; return set.get(docId) ? 1 : 0; } @Override public GeoPoint nextValue() { return encoding.decode(lat.get(docId), lon.get(docId), scratch); } } } /** * Assumes all the values are "set", and docId is used as the index to the value array. */ public static class Single extends GeoPointCompressedAtomicFieldData { private final GeoPointFieldMapper.Encoding encoding; private final PagedMutable lon, lat; private final long numOrds; public Single(GeoPointFieldMapper.Encoding encoding, PagedMutable lon, PagedMutable lat, int numDocs, long numOrds) { super(numDocs); this.encoding = encoding; this.lon = lon; this.lat = lat; this.numOrds = numOrds; } @Override public boolean isMultiValued() { return false; } @Override public boolean isValuesOrdered() { return false; } @Override public long getNumberUniqueValues() { return numOrds; } @Override public long getMemorySizeInBytes() { if (size == -1) { size = RamUsageEstimator.NUM_BYTES_INT/*size*/ + RamUsageEstimator.NUM_BYTES_INT/*numDocs*/ + (lon.ramBytesUsed() + lat.ramBytesUsed()); } return size; } @Override public GeoPointValues getGeoPointValues() { return new GeoPointValuesSingle(encoding, lon, lat); } static class GeoPointValuesSingle extends GeoPointValues { private final GeoPointFieldMapper.Encoding encoding; private final PagedMutable lon, lat; private final GeoPoint scratch = new GeoPoint(); GeoPointValuesSingle(GeoPointFieldMapper.Encoding encoding, PagedMutable lon, PagedMutable lat) { super(false); this.encoding = encoding; this.lon = lon; this.lat = lat; } @Override public int setDocument(int docId) { this.docId = docId; return 1; } @Override public GeoPoint nextValue() { return encoding.decode(lat.get(docId), lon.get(docId), scratch); } } } }
0true
src_main_java_org_elasticsearch_index_fielddata_plain_GeoPointCompressedAtomicFieldData.java
2,069
new ModuleWriter(binder()) { @Override public <T> Void visit(Binding<T> binding) { overriddenKeys.add(binding.getKey()); return super.visit(binding); } @Override public Void visit(ScopeBinding scopeBinding) { overridesScopeAnnotations.add(scopeBinding.getAnnotationType()); return super.visit(scopeBinding); } @Override public Void visit(PrivateElements privateElements) { overriddenKeys.addAll(privateElements.getExposedKeys()); return super.visit(privateElements); } }.writeAll(overrideElements);
0true
src_main_java_org_elasticsearch_common_inject_util_Modules.java
1,417
public class DummyProperty { private long id; private int version; private String key; private DummyEntity entity; public DummyProperty() { } public DummyProperty(String key) { super(); this.key = key; } public DummyProperty(String key, DummyEntity entity) { super(); this.key = key; this.entity = entity; } public DummyProperty(long id, String key, DummyEntity entity) { super(); this.id = id; this.key = key; this.entity = entity; } public long getId() { return id; } public void setId(long id) { this.id = id; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public DummyEntity getEntity() { return entity; } public void setEntity(DummyEntity entity) { this.entity = entity; } }
0true
hazelcast-hibernate_hazelcast-hibernate3_src_test_java_com_hazelcast_hibernate_entity_DummyProperty.java
1,694
runnable = new Runnable() { public void run() { map.replace("key", null, "newValue"); } };
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
627
c4.addListenerConfig(new ListenerConfig(new LifecycleListener() { public void stateChanged(final LifecycleEvent event) { if (event.getState() == LifecycleState.MERGED) { latch.countDown(); } } }));
0true
hazelcast_src_test_java_com_hazelcast_cluster_SplitBrainHandlerTest.java
1,619
class UpdateTask extends PrioritizedRunnable { public final String source; public final ClusterStateUpdateTask updateTask; public final long addedAt = System.currentTimeMillis(); UpdateTask(String source, Priority priority, ClusterStateUpdateTask updateTask) { super(priority); this.source = source; this.updateTask = updateTask; } @Override public void run() { if (!lifecycle.started()) { logger.debug("processing [{}]: ignoring, cluster_service not started", source); return; } logger.debug("processing [{}]: execute", source); ClusterState previousClusterState = clusterState; ClusterState newClusterState; try { newClusterState = updateTask.execute(previousClusterState); } catch (Throwable e) { if (logger.isTraceEnabled()) { StringBuilder sb = new StringBuilder("failed to execute cluster state update, state:\nversion [").append(previousClusterState.version()).append("], source [").append(source).append("]\n"); sb.append(previousClusterState.nodes().prettyPrint()); sb.append(previousClusterState.routingTable().prettyPrint()); sb.append(previousClusterState.readOnlyRoutingNodes().prettyPrint()); logger.trace(sb.toString(), e); } updateTask.onFailure(source, e); return; } if (previousClusterState == newClusterState) { logger.debug("processing [{}]: no change in cluster_state", source); if (updateTask instanceof AckedClusterStateUpdateTask) { //no need to wait for ack if nothing changed, the update can be counted as acknowledged ((AckedClusterStateUpdateTask) updateTask).onAllNodesAcked(null); } if (updateTask instanceof ProcessedClusterStateUpdateTask) { ((ProcessedClusterStateUpdateTask) updateTask).clusterStateProcessed(source, previousClusterState, newClusterState); } return; } try { Discovery.AckListener ackListener = new NoOpAckListener(); if (newClusterState.nodes().localNodeMaster()) { // only the master controls the version numbers Builder builder = ClusterState.builder(newClusterState).version(newClusterState.version() + 1); if (previousClusterState.routingTable() != newClusterState.routingTable()) { builder.routingTable(RoutingTable.builder(newClusterState.routingTable()).version(newClusterState.routingTable().version() + 1)); } if (previousClusterState.metaData() != newClusterState.metaData()) { builder.metaData(MetaData.builder(newClusterState.metaData()).version(newClusterState.metaData().version() + 1)); } newClusterState = builder.build(); if (updateTask instanceof AckedClusterStateUpdateTask) { final AckedClusterStateUpdateTask ackedUpdateTask = (AckedClusterStateUpdateTask) updateTask; if (ackedUpdateTask.ackTimeout() == null || ackedUpdateTask.ackTimeout().millis() == 0) { ackedUpdateTask.onAckTimeout(); } else { try { ackListener = new AckCountDownListener(ackedUpdateTask, newClusterState.version(), newClusterState.nodes(), threadPool); } catch (EsRejectedExecutionException ex) { if (logger.isDebugEnabled()) { logger.debug("Couldn't schedule timeout thread - node might be shutting down", ex); } //timeout straightaway, otherwise we could wait forever as the timeout thread has not started ackedUpdateTask.onAckTimeout(); } } } } else { if (previousClusterState.blocks().hasGlobalBlock(Discovery.NO_MASTER_BLOCK) && !newClusterState.blocks().hasGlobalBlock(Discovery.NO_MASTER_BLOCK)) { // force an update, its a fresh update from the master as we transition from a start of not having a master to having one // have a fresh instances of routing and metadata to remove the chance that version might be the same Builder builder = ClusterState.builder(newClusterState); builder.routingTable(RoutingTable.builder(newClusterState.routingTable())); builder.metaData(MetaData.builder(newClusterState.metaData())); newClusterState = builder.build(); logger.debug("got first state from fresh master [{}]", newClusterState.nodes().masterNodeId()); } else if (newClusterState.version() < previousClusterState.version()) { // we got this cluster state from the master, filter out based on versions (don't call listeners) logger.debug("got old cluster state [" + newClusterState.version() + "<" + previousClusterState.version() + "] from source [" + source + "], ignoring"); return; } } if (logger.isTraceEnabled()) { StringBuilder sb = new StringBuilder("cluster state updated:\nversion [").append(newClusterState.version()).append("], source [").append(source).append("]\n"); sb.append(newClusterState.nodes().prettyPrint()); sb.append(newClusterState.routingTable().prettyPrint()); sb.append(newClusterState.readOnlyRoutingNodes().prettyPrint()); logger.trace(sb.toString()); } else if (logger.isDebugEnabled()) { logger.debug("cluster state updated, version [{}], source [{}]", newClusterState.version(), source); } ClusterChangedEvent clusterChangedEvent = new ClusterChangedEvent(source, newClusterState, previousClusterState); // new cluster state, notify all listeners final DiscoveryNodes.Delta nodesDelta = clusterChangedEvent.nodesDelta(); if (nodesDelta.hasChanges() && logger.isInfoEnabled()) { String summary = nodesDelta.shortSummary(); if (summary.length() > 0) { logger.info("{}, reason: {}", summary, source); } } // TODO, do this in parallel (and wait) for (DiscoveryNode node : nodesDelta.addedNodes()) { if (!nodeRequiresConnection(node)) { continue; } try { transportService.connectToNode(node); } catch (Throwable e) { // the fault detection will detect it as failed as well logger.warn("failed to connect to node [" + node + "]", e); } } // if we are the master, publish the new state to all nodes // we publish here before we send a notification to all the listeners, since if it fails // we don't want to notify if (newClusterState.nodes().localNodeMaster()) { logger.debug("publishing cluster state version {}", newClusterState.version()); discoveryService.publish(newClusterState, ackListener); } // update the current cluster state clusterState = newClusterState; logger.debug("set local cluster state to version {}", newClusterState.version()); for (ClusterStateListener listener : priorityClusterStateListeners) { listener.clusterChanged(clusterChangedEvent); } for (ClusterStateListener listener : clusterStateListeners) { listener.clusterChanged(clusterChangedEvent); } for (ClusterStateListener listener : lastClusterStateListeners) { listener.clusterChanged(clusterChangedEvent); } if (!nodesDelta.removedNodes().isEmpty()) { threadPool.generic().execute(new Runnable() { @Override public void run() { for (DiscoveryNode node : nodesDelta.removedNodes()) { transportService.disconnectFromNode(node); } } }); } //manual ack only from the master at the end of the publish if (newClusterState.nodes().localNodeMaster()) { try { ackListener.onNodeAck(localNode(), null); } catch (Throwable t) { logger.debug("error while processing ack for master node [{}]", t, newClusterState.nodes().localNode()); } } if (updateTask instanceof ProcessedClusterStateUpdateTask) { ((ProcessedClusterStateUpdateTask) updateTask).clusterStateProcessed(source, previousClusterState, newClusterState); } logger.debug("processing [{}]: done applying updated cluster_state (version: {})", source, newClusterState.version()); } catch (Throwable t) { StringBuilder sb = new StringBuilder("failed to apply updated cluster state:\nversion [").append(newClusterState.version()).append("], source [").append(source).append("]\n"); sb.append(newClusterState.nodes().prettyPrint()); sb.append(newClusterState.routingTable().prettyPrint()); sb.append(newClusterState.readOnlyRoutingNodes().prettyPrint()); logger.warn(sb.toString(), t); // TODO: do we want to call updateTask.onFailure here? } } }
1no label
src_main_java_org_elasticsearch_cluster_service_InternalClusterService.java
2,086
static class InterceptorInfo implements DataSerializable { String mapName; final List<Map.Entry<String, MapInterceptor>> interceptors = new LinkedList<Map.Entry<String, MapInterceptor>>(); InterceptorInfo(String mapName) { this.mapName = mapName; } InterceptorInfo() { } void addInterceptor(String id, MapInterceptor interceptor) { interceptors.add(new AbstractMap.SimpleImmutableEntry<String, MapInterceptor>(id, interceptor)); } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(mapName); out.writeInt(interceptors.size()); for (Map.Entry<String, MapInterceptor> entry : interceptors) { out.writeUTF(entry.getKey()); out.writeObject(entry.getValue()); } } @Override public void readData(ObjectDataInput in) throws IOException { mapName = in.readUTF(); int size = in.readInt(); for (int i = 0; i < size; i++) { String id = in.readUTF(); MapInterceptor interceptor = in.readObject(); interceptors.add(new AbstractMap.SimpleImmutableEntry<String, MapInterceptor>(id, interceptor)); } } }
0true
hazelcast_src_main_java_com_hazelcast_map_operation_PostJoinMapOperation.java
3,313
static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues { private final BigDoubleArrayList values; private final FixedBitSet set; DoubleValues(BigDoubleArrayList values, FixedBitSet set) { super(false); this.values = values; this.set = set; } @Override public int setDocument(int docId) { this.docId = docId; return set.get(docId) ? 1 : 0; } @Override public double nextValue() { return values.get(docId); } }
0true
src_main_java_org_elasticsearch_index_fielddata_plain_DoubleArrayAtomicFieldData.java
891
public class CountDownLatchBackupOperation extends BaseCountDownLatchOperation implements BackupOperation, IdentifiedDataSerializable { private int count; public CountDownLatchBackupOperation() { } public CountDownLatchBackupOperation(String name, int count) { super(name); this.count = count; } public void run() throws Exception { CountDownLatchService service = getService(); service.setCountDirect(name, count); } @Override public Object getResponse() { return Boolean.TRUE; } @Override public boolean returnsResponse() { return true; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeInt(count); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); count = in.readInt(); } @Override public int getFactoryId() { return CountDownLatchDataSerializerHook.F_ID; } @Override public int getId() { return CountDownLatchDataSerializerHook.COUNT_DOWN_LATCH_BACKUP_OPERATION; } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_countdownlatch_operations_CountDownLatchBackupOperation.java
1,473
public class RestoreSource implements Streamable, ToXContent { private SnapshotId snapshotId; private String index; RestoreSource() { } public RestoreSource(SnapshotId snapshotId, String index) { this.snapshotId = snapshotId; this.index = index; } public SnapshotId snapshotId() { return snapshotId; } public String index() { return index; } public static RestoreSource readRestoreSource(StreamInput in) throws IOException { RestoreSource restoreSource = new RestoreSource(); restoreSource.readFrom(in); return restoreSource; } public static RestoreSource readOptionalRestoreSource(StreamInput in) throws IOException { return in.readOptionalStreamable(new RestoreSource()); } @Override public void readFrom(StreamInput in) throws IOException { snapshotId = SnapshotId.readSnapshotId(in); index = in.readString(); } @Override public void writeTo(StreamOutput out) throws IOException { snapshotId.writeTo(out); out.writeString(index); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder.startObject() .field("repository", snapshotId.getRepository()) .field("snapshot", snapshotId.getSnapshot()) .field("index", index) .endObject(); } @Override public String toString() { return snapshotId.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RestoreSource that = (RestoreSource) o; if (!index.equals(that.index)) return false; if (!snapshotId.equals(that.snapshotId)) return false; return true; } @Override public int hashCode() { int result = snapshotId.hashCode(); result = 31 * result + index.hashCode(); return result; } }
0true
src_main_java_org_elasticsearch_cluster_routing_RestoreSource.java
506
public class StressThread extends TestThread { @Override public void doRun() throws Exception { while (!isStopped()) { int key = random.nextInt(REFERENCE_COUNT); IAtomicLong reference = references[key]; long value = reference.get(); assertEquals(format("The value for atomic reference: %s was not consistent", reference), key, value); } } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_stress_AtomicLongStableReadStressTest.java
956
@Service("blOrderDaoExtensionManager") public class OrderDaoExtensionManager extends ExtensionManager<OrderDaoExtensionHandler> { public OrderDaoExtensionManager() { super(OrderDaoExtensionHandler.class); } /** * By default, this manager will allow other handlers to process the method when a handler returns * HANDLED. */ @Override public boolean continueOnHandled() { return true; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_dao_OrderDaoExtensionManager.java
1,240
public final class CeylonClasspathUtil { private CeylonClasspathUtil() { // utility class } /** * Get the Ivy classpath container from the selection in the Java package view * * @param selection * the selection * @return * @throws JavaModelException */ public static CeylonProjectModulesContainer getCeylonClasspathContainer(IStructuredSelection selection) { if (selection == null) { return null; } for (@SuppressWarnings("rawtypes") Iterator it = selection.iterator(); it.hasNext();) { Object element = it.next(); CeylonProjectModulesContainer cp = (CeylonProjectModulesContainer) CeylonPlugin.adapt(element, CeylonProjectModulesContainer.class); if (cp != null) { return cp; } if (element instanceof ClassPathContainer) { // FIXME: we shouldn't check against internal JDT API but there are not adaptable to // useful class return jdt2CeylonCPC((ClassPathContainer) element); } } return null; } /** * Work around the non adaptability of ClassPathContainer * * @param cpc * the container to transform into an CeylonApplicationModulesContainer * @return the CeylonApplicationModulesContainer is such, null, if not */ public static CeylonProjectModulesContainer jdt2CeylonCPC(ClassPathContainer cpc) { IClasspathEntry entry = cpc.getClasspathEntry(); try { IClasspathContainer icp = JavaCore.getClasspathContainer(entry.getPath(), cpc .getJavaProject()); if (icp instanceof CeylonProjectModulesContainer) { return (CeylonProjectModulesContainer) icp; } } catch (JavaModelException e) { // unless there are issues with the JDT, this should never happen e.printStackTrace(); } return null; } public static boolean isCeylonClasspathContainer(IPath containerPath) { return isLanguageModuleClasspathContainer(containerPath) || isProjectModulesClasspathContainer(containerPath); } public static boolean isLanguageModuleClasspathContainer(IPath containerPath) { int size = containerPath.segmentCount(); if (size > 0) { return (containerPath.segment(0).equals(CeylonLanguageModuleContainer.CONTAINER_ID)); } return false; } public static boolean isProjectModulesClasspathContainer(IPath containerPath) { int size = containerPath.segmentCount(); if (size > 0) { return (containerPath.segment(0).equals(CeylonProjectModulesContainer.CONTAINER_ID)); } return false; } /** * Search the Ceylon classpath containers within the specified Java project * * @param javaProject * the project to search into * @return the Ceylon classpath container if found */ public static List <IClasspathContainer> getCeylonClasspathContainers( IJavaProject javaProject) { List<IClasspathContainer> containers = new ArrayList<IClasspathContainer>(); if (FakeProjectManager.isFake(javaProject) || !javaProject.exists()) { return containers; } try { IClasspathEntry[] entries = javaProject.getRawClasspath(); for (int i = 0; i < entries.length; i++) { IClasspathEntry entry = entries[i]; if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { IPath path = entry.getPath(); if (isCeylonClasspathContainer(path)) { IClasspathContainer cp = JavaCore.getClasspathContainer(path, javaProject); if (cp instanceof CeylonProjectModulesContainer || cp instanceof CeylonLanguageModuleContainer) { containers.add(cp); } } } } } catch (JavaModelException e) { // unless there are issues with the JDT, this should never happen e.printStackTrace(); } return containers; } public static CeylonProjectModulesContainer getCeylonProjectModulesClasspathContainer( IJavaProject javaProject) { try { IClasspathEntry[] entries = javaProject.getRawClasspath(); for (int i = 0; i < entries.length; i++) { IClasspathEntry entry = entries[i]; if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { IPath path = entry.getPath(); if (isProjectModulesClasspathContainer(path)) { IClasspathContainer cp = JavaCore.getClasspathContainer(path, javaProject); if (cp instanceof CeylonProjectModulesContainer) { return (CeylonProjectModulesContainer) cp; } } } } } catch (JavaModelException e) { // unless there are issues with the JDT, this should never happen e.printStackTrace(); } return null; } public static List<String> split(String str) { String[] terms = str.split(","); List<String> ret = new ArrayList<String>(); for (int i = 0; i < terms.length; i++) { String t = terms[i].trim(); if (t.length() > 0) { ret.add(t); } } return ret; } public static String concat(Collection<String> list) { if (list == null) { return ""; } StringBuffer b = new StringBuffer(); Iterator<String> it = list.iterator(); while (it.hasNext()) { b.append(it.next()); if (it.hasNext()) { b.append(","); } } return b.toString(); } /** * Just a verbatim copy of the internal Eclipse function: * org.eclipse.jdt.internal.corext.javadoc * .JavaDocLocations#getLibraryJavadocLocation(IClasspathEntry) * * @param entry * @return */ public static URL getLibraryJavadocLocation(IClasspathEntry entry) { if (entry == null) { throw new IllegalArgumentException("Entry must not be null"); //$NON-NLS-1$ } int kind = entry.getEntryKind(); if (kind != IClasspathEntry.CPE_LIBRARY && kind != IClasspathEntry.CPE_VARIABLE) { throw new IllegalArgumentException( "Entry must be of kind CPE_LIBRARY or " + "CPE_VARIABLE"); //$NON-NLS-1$ } IClasspathAttribute[] extraAttributes = entry.getExtraAttributes(); for (int i = 0; i < extraAttributes.length; i++) { IClasspathAttribute attrib = extraAttributes[i]; if (IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME.equals(attrib.getName())) { try { return new URL(attrib.getValue()); } catch (MalformedURLException e) { return null; } } } return null; } /** * Search the Ivy classpath entry within the specified Java project with the specific path * * @param containerPath * the path of the container * @param javaProject * the project to search into * @return the Ivy classpath container if found, otherwise return <code>null</code> */ public static IClasspathEntry getCeylonClasspathEntry(IPath containerPath, IJavaProject javaProject) { if (FakeProjectManager.isFake(javaProject) || !javaProject.exists()) { return null; } try { IClasspathEntry[] entries = javaProject.getRawClasspath(); for (int i = 0; i < entries.length; i++) { IClasspathEntry entry = entries[i]; if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { if (containerPath.equals(entry.getPath())) { return entry; } } } } catch (JavaModelException e) { // unless there are issues with the JDT, this should never happen e.printStackTrace(); } return null; } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_classpath_CeylonClasspathUtil.java
1,419
@XmlRootElement(name = "skuAttribute") @XmlAccessorType(value = XmlAccessType.FIELD) public class SkuAttributeWrapper extends BaseWrapper implements APIWrapper<SkuAttribute>{ @XmlElement protected Long id; @XmlElement protected Long skuId; @XmlElement protected String attributeName; @XmlElement protected String attributeValue; @Override public void wrapDetails(SkuAttribute model, HttpServletRequest request) { this.id = model.getId(); this.skuId = model.getSku().getId(); this.attributeName = model.getName(); this.attributeValue = model.getValue(); } @Override public void wrapSummary(SkuAttribute model, HttpServletRequest request) { wrapDetails(model, request); } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_wrapper_SkuAttributeWrapper.java
1,587
public class ODistributedServerLog { public enum DIRECTION { NONE, IN, OUT, BOTH } public static boolean isDebugEnabled() { return OLogManager.instance().isDebugEnabled(); } public static void debug(final Object iRequester, final String iLocalNode, final String iRemoteNode, final DIRECTION iDirection, final String iMessage, final Object... iAdditionalArgs) { OLogManager.instance().log(iRequester, Level.FINE, formatMessage(iRequester, iLocalNode, iRemoteNode, iDirection, iMessage), null, iAdditionalArgs); } public static void debug(final Object iRequester, final String iLocalNode, final String iRemoteNode, final DIRECTION iDirection, final String iMessage, final Throwable iException, final Object... iAdditionalArgs) { OLogManager.instance().log(iRequester, Level.FINE, formatMessage(iRequester, iLocalNode, iRemoteNode, iDirection, iMessage), iException, iAdditionalArgs); } public static void info(final Object iRequester, final String iLocalNode, final String iRemoteNode, final DIRECTION iDirection, final String iMessage, final Object... iAdditionalArgs) { OLogManager.instance().log(iRequester, Level.INFO, formatMessage(iRequester, iLocalNode, iRemoteNode, iDirection, iMessage), null, iAdditionalArgs); } public static void info(final Object iRequester, final String iLocalNode, final String iRemoteNode, final DIRECTION iDirection, final String iMessage, final Throwable iException, final Object... iAdditionalArgs) { OLogManager.instance().log(iRequester, Level.INFO, formatMessage(iRequester, iLocalNode, iRemoteNode, iDirection, iMessage), iException, iAdditionalArgs); } public static void warn(final Object iRequester, final String iLocalNode, final String iRemoteNode, final DIRECTION iDirection, final String iMessage, final Object... iAdditionalArgs) { OLogManager.instance().log(iRequester, Level.WARNING, formatMessage(iRequester, iLocalNode, iRemoteNode, iDirection, iMessage), null, iAdditionalArgs); } public static void warn(final Object iRequester, final String iLocalNode, final String iRemoteNode, final DIRECTION iDirection, final String iMessage, final Throwable iException, final Object... iAdditionalArgs) { OLogManager.instance().log(iRequester, Level.WARNING, formatMessage(iRequester, iLocalNode, iRemoteNode, iDirection, iMessage), iException, iAdditionalArgs); } public static void error(final Object iRequester, final String iLocalNode, final String iRemoteNode, final DIRECTION iDirection, final String iMessage, final Object... iAdditionalArgs) { OLogManager.instance().log(iRequester, Level.SEVERE, formatMessage(iRequester, iLocalNode, iRemoteNode, iDirection, iMessage), null, iAdditionalArgs); } public static void error(final Object iRequester, final String iLocalNode, final String iRemoteNode, final DIRECTION iDirection, final String iMessage, final Throwable iException, final Object... iAdditionalArgs) { OLogManager.instance().log(iRequester, Level.SEVERE, formatMessage(iRequester, iLocalNode, iRemoteNode, iDirection, iMessage), iException, iAdditionalArgs); } protected static String formatMessage(final Object iRequester, final String iLocalNode, final String iRemoteNode, final DIRECTION iDirection, final String iMessage) { final StringBuilder message = new StringBuilder(); if (iLocalNode != null) { message.append('['); message.append(iLocalNode); message.append(']'); } if (iRemoteNode != null && !iRemoteNode.equals(iLocalNode)) { switch (iDirection) { case IN: message.append("<-"); break; case OUT: message.append("->"); break; case BOTH: message.append("<>"); break; case NONE: message.append("--"); break; } message.append('['); message.append(iRemoteNode); message.append(']'); } message.append(' '); message.append(iMessage); return message.toString(); } }
0true
server_src_main_java_com_orientechnologies_orient_server_distributed_ODistributedServerLog.java
1,133
public class OSQLMethodAsDate extends OAbstractSQLMethod { public static final String NAME = "asdate"; public OSQLMethodAsDate() { super(NAME); } @Override public Object execute(OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iMethodParams) throws ParseException { if (ioResult != null) { if (ioResult instanceof Number) { ioResult = new Date(((Number) ioResult).longValue()); } else if (!(ioResult instanceof Date)) { ioResult = ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getConfiguration().getDateFormatInstance() .parse(ioResult.toString()); } } return ioResult; } }
0true
core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodAsDate.java
1,635
Orient.instance().getTimer().schedule(new TimerTask() { @Override public void run() { resynch(); } }, resyncEvery, resyncEvery);
0true
distributed_src_main_java_com_orientechnologies_orient_server_hazelcast_OHazelcastDistributedDatabase.java
567
public class BindOperation extends AbstractClusterOperation implements JoinOperation { private Address localAddress; private Address targetAddress; private boolean reply; public BindOperation() { } public BindOperation(Address localAddress, final Address targetAddress, final boolean reply) { this.localAddress = localAddress; this.targetAddress = targetAddress; this.reply = reply; } @Override public void run() { NodeEngineImpl ns = (NodeEngineImpl) getNodeEngine(); TcpIpConnectionManager connectionManager = (TcpIpConnectionManager) ns.getNode().getConnectionManager(); TcpIpConnection connection = (TcpIpConnection) getConnection(); connectionManager.bind(connection, localAddress, targetAddress, reply); } @Override protected void readInternal(final ObjectDataInput in) throws IOException { localAddress = new Address(); localAddress.readData(in); boolean hasTarget = in.readBoolean(); if (hasTarget) { targetAddress = new Address(); targetAddress.readData(in); } reply = in.readBoolean(); } @Override protected void writeInternal(final ObjectDataOutput out) throws IOException { localAddress.writeData(out); boolean hasTarget = targetAddress != null; out.writeBoolean(hasTarget); if (hasTarget) { targetAddress.writeData(out); } out.writeBoolean(reply); } @Override public String toString() { return "Bind " + localAddress; } }
0true
hazelcast_src_main_java_com_hazelcast_cluster_BindOperation.java
339
public class TransportNodesRestartAction extends TransportNodesOperationAction<NodesRestartRequest, NodesRestartResponse, TransportNodesRestartAction.NodeRestartRequest, NodesRestartResponse.NodeRestartResponse> { private final Node node; private final boolean disabled; private AtomicBoolean restartRequested = new AtomicBoolean(); @Inject public TransportNodesRestartAction(Settings settings, ClusterName clusterName, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, Node node) { super(settings, clusterName, threadPool, clusterService, transportService); this.node = node; disabled = componentSettings.getAsBoolean("disabled", false); } @Override protected void doExecute(NodesRestartRequest nodesRestartRequest, ActionListener<NodesRestartResponse> listener) { listener.onFailure(new ElasticsearchIllegalStateException("restart is disabled (for now) ....")); } @Override protected String executor() { return ThreadPool.Names.GENERIC; } @Override protected String transportAction() { return NodesRestartAction.NAME; } @Override protected NodesRestartResponse newResponse(NodesRestartRequest nodesShutdownRequest, AtomicReferenceArray responses) { final List<NodesRestartResponse.NodeRestartResponse> nodeRestartResponses = newArrayList(); for (int i = 0; i < responses.length(); i++) { Object resp = responses.get(i); if (resp instanceof NodesRestartResponse.NodeRestartResponse) { nodeRestartResponses.add((NodesRestartResponse.NodeRestartResponse) resp); } } return new NodesRestartResponse(clusterName, nodeRestartResponses.toArray(new NodesRestartResponse.NodeRestartResponse[nodeRestartResponses.size()])); } @Override protected NodesRestartRequest newRequest() { return new NodesRestartRequest(); } @Override protected NodeRestartRequest newNodeRequest() { return new NodeRestartRequest(); } @Override protected NodeRestartRequest newNodeRequest(String nodeId, NodesRestartRequest request) { return new NodeRestartRequest(nodeId, request); } @Override protected NodesRestartResponse.NodeRestartResponse newNodeResponse() { return new NodesRestartResponse.NodeRestartResponse(); } @Override protected NodesRestartResponse.NodeRestartResponse nodeOperation(NodeRestartRequest request) throws ElasticsearchException { if (disabled) { throw new ElasticsearchIllegalStateException("Restart is disabled"); } if (!restartRequested.compareAndSet(false, true)) { return new NodesRestartResponse.NodeRestartResponse(clusterService.localNode()); } logger.info("Restarting in [{}]", request.delay); threadPool.schedule(request.delay, ThreadPool.Names.GENERIC, new Runnable() { @Override public void run() { boolean restartWithWrapper = false; if (System.getProperty("elasticsearch-service") != null) { try { Class wrapperManager = settings.getClassLoader().loadClass("org.tanukisoftware.wrapper.WrapperManager"); logger.info("Initiating requested restart (using service)"); wrapperManager.getMethod("restartAndReturn").invoke(null); restartWithWrapper = true; } catch (Throwable e) { logger.error("failed to initial restart on service wrapper", e); } } if (!restartWithWrapper) { logger.info("Initiating requested restart"); try { node.stop(); node.start(); } catch (Exception e) { logger.warn("Failed to restart", e); } finally { restartRequested.set(false); } } } }); return new NodesRestartResponse.NodeRestartResponse(clusterService.localNode()); } @Override protected boolean accumulateExceptions() { return false; } protected static class NodeRestartRequest extends NodeOperationRequest { TimeValue delay; private NodeRestartRequest() { } private NodeRestartRequest(String nodeId, NodesRestartRequest request) { super(request, nodeId); this.delay = request.delay; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); delay = readTimeValue(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); delay.writeTo(out); } } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_restart_TransportNodesRestartAction.java
703
createIndexAction.execute(new CreateIndexRequest(index).cause("auto(bulk api)"), new ActionListener<CreateIndexResponse>() { @Override public void onResponse(CreateIndexResponse result) { if (counter.decrementAndGet() == 0) { executeBulk(bulkRequest, startTime, listener); } } @Override public void onFailure(Throwable e) { if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) { // we have the index, do it if (counter.decrementAndGet() == 0) { executeBulk(bulkRequest, startTime, listener); } } else if (failed.compareAndSet(false, true)) { listener.onFailure(e); } } });
1no label
src_main_java_org_elasticsearch_action_bulk_TransportBulkAction.java
800
public class AlterAndGetRequest extends AbstractAlterRequest { public AlterAndGetRequest() { } public AlterAndGetRequest(String name, Data function) { super(name, function); } @Override protected Operation prepareOperation() { return new AlterAndGetOperation(name, getFunction()); } @Override public int getClassId() { return AtomicLongPortableHook.ALTER_AND_GET; } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_client_AlterAndGetRequest.java
1,219
public class PaymentActivity extends BaseActivity<WorkflowPaymentContext> { public static final String ROLLBACK_PAYMENTCONTEXT = "rollback_paymentcontext"; public static final String ROLLBACK_RESPONSEITEM = "rollback_responseitem"; public static final String ROLLBACK_ACTIONTYPE = "rollback_actiontype"; protected PaymentService paymentService; protected String userName; protected boolean automaticallyRegisterRollbackHandlerForPayment = true; /* (non-Javadoc) * @see org.broadleafcommerce.core.workflow.Activity#execute(org.broadleafcommerce.core.workflow.ProcessContext) */ @Override public WorkflowPaymentContext execute(WorkflowPaymentContext context) throws Exception { CombinedPaymentContextSeed seed = context.getSeedData(); Map<PaymentInfo, Referenced> infos = seed.getInfos(); // If seed has a specified total, use that; otherwise use order total. Money transactionTotal, remainingTotal; if (seed.getTransactionAmount() != null) { transactionTotal = seed.getTransactionAmount(); remainingTotal = seed.getTransactionAmount(); } else { transactionTotal = seed.getOrderTotal(); remainingTotal = seed.getOrderTotal(); } Map<PaymentInfo, Referenced> replaceItems = new HashMap<PaymentInfo, Referenced>(); try { Iterator<PaymentInfo> itr = infos.keySet().iterator(); while(itr.hasNext()) { PaymentInfo info = itr.next(); if (paymentService.isValidCandidate(info.getType())) { Referenced referenced = infos.get(info); itr.remove(); infos.remove(info); PaymentContextImpl paymentContext = new PaymentContextImpl(transactionTotal, remainingTotal, info, referenced, userName); PaymentResponseItem paymentResponseItem; if (seed.getActionType().equals(PaymentActionType.AUTHORIZE)) { try { paymentResponseItem = paymentService.authorize(paymentContext); } finally { referenced.setReferenceNumber(info.getReferenceNumber()); replaceItems.put(info, referenced); } } else if (seed.getActionType().equals(PaymentActionType.AUTHORIZEANDDEBIT)) { try { paymentResponseItem = paymentService.authorizeAndDebit(paymentContext); } finally { referenced.setReferenceNumber(info.getReferenceNumber()); replaceItems.put(info, referenced); } } else if (seed.getActionType().equals(PaymentActionType.BALANCE)) { try { paymentResponseItem = paymentService.balance(paymentContext); } finally { referenced.setReferenceNumber(info.getReferenceNumber()); replaceItems.put(info, referenced); } } else if (seed.getActionType().equals(PaymentActionType.CREDIT)) { try { paymentResponseItem = paymentService.credit(paymentContext); } finally { referenced.setReferenceNumber(info.getReferenceNumber()); replaceItems.put(info, referenced); } } else if (seed.getActionType().equals(PaymentActionType.DEBIT)) { try { paymentResponseItem = paymentService.debit(paymentContext); } finally { referenced.setReferenceNumber(info.getReferenceNumber()); replaceItems.put(info, referenced); } } else if (seed.getActionType().equals(PaymentActionType.VOID)) { try { paymentResponseItem = paymentService.voidPayment(paymentContext); } finally { referenced.setReferenceNumber(info.getReferenceNumber()); replaceItems.put(info, referenced); } } else if (seed.getActionType().equals(PaymentActionType.REVERSEAUTHORIZE)) { try { paymentResponseItem = paymentService.reverseAuthorize(paymentContext); } finally { referenced.setReferenceNumber(info.getReferenceNumber()); replaceItems.put(info, referenced); } } else if (seed.getActionType().equals(PaymentActionType.PARTIALPAYMENT)) { try { paymentResponseItem = paymentService.partialPayment(paymentContext); } finally { referenced.setReferenceNumber(info.getReferenceNumber()); replaceItems.put(info, referenced); } } else { referenced.setReferenceNumber(info.getReferenceNumber()); replaceItems.put(info, referenced); throw new PaymentException("Module ("+paymentService.getClass().getName()+") does not support payment type of: " + seed.getActionType().toString()); } if (getRollbackHandler() != null && automaticallyRegisterRollbackHandlerForPayment) { Map<String, Object> myState = new HashMap<String, Object>(); if (getStateConfiguration() != null && !getStateConfiguration().isEmpty()) { myState.putAll(getStateConfiguration()); } myState.put(ROLLBACK_ACTIONTYPE, seed.getActionType()); myState.put(ROLLBACK_PAYMENTCONTEXT, paymentContext); myState.put(ROLLBACK_RESPONSEITEM, paymentResponseItem); ActivityStateManagerImpl.getStateManager().registerState(this, context, getRollbackHandler(), myState); } if (paymentResponseItem != null) { //validate payment response item if (paymentResponseItem.getTransactionAmount() == null || paymentResponseItem.getTransactionTimestamp() == null || paymentResponseItem.getTransactionSuccess() == null) { throw new PaymentException("The PaymentResponseItem instance did not contain one or more of the following: transactionAmount, transactionTimestamp or transactionSuccess"); } seed.getPaymentResponse().addPaymentResponseItem(info, paymentResponseItem); if (paymentResponseItem.getTransactionSuccess()) { remainingTotal = remainingTotal.subtract(paymentResponseItem.getTransactionAmount()); } else { if (paymentResponseItem.getTransactionAmount().lessThan(transactionTotal.getAmount())) { throw new InsufficientFundsException(String.format("Transaction amount was [%s] but paid amount was [%s]", transactionTotal.getAmount(), paymentResponseItem.getTransactionAmount())); } } } } } } finally { infos.putAll(replaceItems); } return context; } public PaymentService getPaymentService() { return paymentService; } public void setPaymentService(PaymentService paymentService) { this.paymentService = paymentService; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public boolean getAutomaticallyRegisterRollbackHandlerForPayment() { return automaticallyRegisterRollbackHandlerForPayment; } public void setAutomaticallyRegisterRollbackHandlerForPayment(boolean automaticallyRegisterRollbackHandlerForPayment) { this.automaticallyRegisterRollbackHandlerForPayment = automaticallyRegisterRollbackHandlerForPayment; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_service_workflow_PaymentActivity.java
649
private final class EntriesIterator implements Iterator<Map.Entry<Object, V>> { private int size = 0; private int nextEntriesIndex; private OHashIndexBucket.Entry<Object, V>[] entries; private EntriesIterator() { OHashIndexBucket.Entry<Object, V> firstEntry = hashTable.firstEntry(); if (firstEntry == null) entries = new OHashIndexBucket.Entry[0]; else entries = hashTable.ceilingEntries(firstEntry.key); size += entries.length; } @Override public boolean hasNext() { return entries.length > 0; } @Override public Map.Entry<Object, V> next() { if (entries.length == 0) throw new NoSuchElementException(); final OHashIndexBucket.Entry<Object, V> bucketEntry = entries[nextEntriesIndex]; nextEntriesIndex++; if (nextEntriesIndex >= entries.length) { entries = hashTable.higherEntries(entries[entries.length - 1].key); size += entries.length; nextEntriesIndex = 0; } return new Map.Entry<Object, V>() { @Override public Object getKey() { return bucketEntry.key; } @Override public V getValue() { return bucketEntry.value; } @Override public V setValue(V value) { throw new UnsupportedOperationException("setValue"); } }; } @Override public void remove() { throw new UnsupportedOperationException("remove"); } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_engine_OLocalHashTableIndexEngine.java
209
private class FindQuickAccessAction extends QuickMenuAction { public FindQuickAccessAction() { super(FIND_MENU_ID); } protected void fillMenu(IMenuManager menu) { IContributionItem[] cis = new FindMenuItems().getContributionItems(); for (IContributionItem ci: cis) { menu.add(ci); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonEditor.java
1,928
public class MapAddIndexRequest extends AllPartitionsClientRequest implements Portable, SecureRequest { private String name; private String attribute; private boolean ordered; public MapAddIndexRequest() { } public MapAddIndexRequest(String name, String attribute, boolean ordered) { this.name = name; this.attribute = attribute; this.ordered = ordered; } public String getServiceName() { return MapService.SERVICE_NAME; } @Override public int getFactoryId() { return MapPortableHook.F_ID; } public int getClassId() { return MapPortableHook.ADD_INDEX; } public void write(PortableWriter writer) throws IOException { writer.writeUTF("n", name); writer.writeUTF("a", attribute); writer.writeBoolean("o", ordered); } public void read(PortableReader reader) throws IOException { name = reader.readUTF("n"); attribute = reader.readUTF("a"); ordered = reader.readBoolean("o"); } protected OperationFactory createOperationFactory() { return new AddIndexOperationFactory(name, attribute, ordered); } protected Object reduce(Map<Integer, Object> map) { return null; } public Permission getRequiredPermission() { return new MapPermission(name, ActionConstants.ACTION_INDEX); } }
0true
hazelcast_src_main_java_com_hazelcast_map_client_MapAddIndexRequest.java
72
@SuppressWarnings("serial") static final class MapReduceEntriesToLongTask<K,V> extends BulkTask<K,V,Long> { final ObjectToLong<Map.Entry<K,V>> transformer; final LongByLongToLong reducer; final long basis; long result; MapReduceEntriesToLongTask<K,V> rights, nextRight; MapReduceEntriesToLongTask (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t, MapReduceEntriesToLongTask<K,V> nextRight, ObjectToLong<Map.Entry<K,V>> transformer, long basis, LongByLongToLong reducer) { super(p, b, i, f, t); this.nextRight = nextRight; this.transformer = transformer; this.basis = basis; this.reducer = reducer; } public final Long getRawResult() { return result; } public final void compute() { final ObjectToLong<Map.Entry<K,V>> transformer; final LongByLongToLong reducer; if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) { long r = this.basis; for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { addToPendingCount(1); (rights = new MapReduceEntriesToLongTask<K,V> (this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork(); } for (Node<K,V> p; (p = advance()) != null; ) r = reducer.apply(r, transformer.apply(p)); result = r; CountedCompleter<?> c; for (c = firstComplete(); c != null; c = c.nextComplete()) { @SuppressWarnings("unchecked") MapReduceEntriesToLongTask<K,V> t = (MapReduceEntriesToLongTask<K,V>)c, s = t.rights; while (s != null) { t.result = reducer.apply(t.result, s.result); s = t.rights = s.nextRight; } } } } }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
1,544
public interface Activity<T extends ProcessContext> extends BeanNameAware, Ordered { /** * Called by the encompassing processor to activate * the execution of the Activity * * @param context - process context for this workflow * @return resulting process context * @throws Exception */ public T execute(T context) throws Exception; /** * Determines if an activity should execute based on the current values in the {@link ProcessContext}. For example, a * context might have both an {@link Order} as well as a String 'status' of what the order should be changed to. It is * possible that an activity in a workflow could only deal with a particular status change, and thus could return false * from this method. * * @param context * @return */ public boolean shouldExecute(T context); /** * Get the fine-grained error handler wired up for this Activity * @return */ public ErrorHandler getErrorHandler(); public void setErrorHandler(final ErrorHandler errorHandler); public String getBeanName(); /** * Retrieve the RollbackHandler instance that should be called by the ActivityStateManager in the * event of a workflow execution problem. This RollbackHandler will presumably perform some * compensating operation to revert state for the activity. * * @return the handler responsible for reverting state for the activity */ public RollbackHandler getRollbackHandler(); /** * Set the RollbackHandler instance that should be called by the ActivityStateManager in the * event of a workflow execution problem. This RollbackHandler will presumably perform some * compensating operation to revert state for the activity. * * @param rollbackHandler the handler responsible for reverting state for the activity */ public void setRollbackHandler(RollbackHandler rollbackHandler); /** * Retrieve the optional region label for the RollbackHandler. Setting a region allows * partitioning of groups of RollbackHandlers for more fine grained control of rollback behavior. * Explicit calls to the ActivityStateManager API in an ErrorHandler instance allows explicit rollback * of specific rollback handler regions. Note, to disable automatic rollback behavior and enable explicit * rollbacks via the API, the workflow.auto.rollback.on.error property should be set to false in your implementation's * runtime property configuration. * * @return the rollback region label for the RollbackHandler instance */ public String getRollbackRegion(); /** * Set the optional region label for the RollbackHandler. Setting a region allows * partitioning of groups of RollbackHandlers for more fine grained control of rollback behavior. * Explicit calls to the ActivityStateManager API in an ErrorHandler instance allows explicit rollback * of specific rollback handler regions. Note, to disable automatic rollback behavior and enable explicit * rollbacks via the API, the workflow.auto.rollback.on.error property should be set to false in your implementation's * runtime property configuration. * * @param rollbackRegion the rollback region label for the RollbackHandler instance */ public void setRollbackRegion(String rollbackRegion); /** * Retrieve any user-defined state that should accompany the RollbackHandler. This configuration will be passed to * the RollbackHandler implementation at runtime. * * @return any user-defined state configuratio necessary for the execution of the RollbackHandler */ public Map<String, Object> getStateConfiguration(); /** * Set any user-defined state that should accompany the RollbackHandler. This configuration will be passed to * the RollbackHandler implementation at runtime. * * @param stateConfiguration any user-defined state configuration necessary for the execution of the RollbackHandler */ public void setStateConfiguration(Map<String, Object> stateConfiguration); /** * Whether or not this activity should automatically register a configured RollbackHandler with the ActivityStateManager. * It is useful to adjust this value if you plan on using the ActivityStateManager API to register RollbackHandlers * explicitly in your code. The default value is false. * * @return Whether or not to automatically register a RollbackHandler with the ActivityStateManager */ public boolean getAutomaticallyRegisterRollbackHandler(); /** * Whether or not this activity should automatically register a configured RollbackHandler with the ActivityStateManager. * It is useful to adjust this value if you plan on using the ActivityStateManager API to register RollbackHandlers * explicitly in your code. The default value is false. * * @param automaticallyRegisterRollbackHandler Whether or not to automatically register a RollbackHandler with the ActivityStateManager */ public void setAutomaticallyRegisterRollbackHandler(boolean automaticallyRegisterRollbackHandler); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_workflow_Activity.java
3,428
private class SnapshotRunnable implements Runnable { @Override public synchronized void run() { try { snapshot("scheduled"); } catch (Throwable e) { if (indexShard.state() == IndexShardState.CLOSED) { return; } logger.warn("failed to snapshot (scheduled)", e); } // schedule it again if (indexShard.state() != IndexShardState.CLOSED) { snapshotScheduleFuture = threadPool.schedule(snapshotInterval, ThreadPool.Names.SNAPSHOT, this); } } }
0true
src_main_java_org_elasticsearch_index_gateway_IndexShardGatewayService.java
1,079
public class MultiMapConfigReadOnly extends MultiMapConfig { public MultiMapConfigReadOnly(MultiMapConfig defConfig) { super(defConfig); } public List<EntryListenerConfig> getEntryListenerConfigs() { final List<EntryListenerConfig> listenerConfigs = super.getEntryListenerConfigs(); final List<EntryListenerConfig> readOnlyListenerConfigs = new ArrayList<EntryListenerConfig>(listenerConfigs.size()); for (EntryListenerConfig listenerConfig : listenerConfigs) { readOnlyListenerConfigs.add(listenerConfig.getAsReadOnly()); } return Collections.unmodifiableList(readOnlyListenerConfigs); } public MultiMapConfig setName(String name) { throw new UnsupportedOperationException("This config is read-only multimap: " + getName()); } public MultiMapConfig setValueCollectionType(String valueCollectionType) { throw new UnsupportedOperationException("This config is read-only multimap: " + getName()); } public MultiMapConfig setValueCollectionType(ValueCollectionType valueCollectionType) { throw new UnsupportedOperationException("This config is read-only multimap: " + getName()); } public MultiMapConfig addEntryListenerConfig(EntryListenerConfig listenerConfig) { throw new UnsupportedOperationException("This config is read-only multimap: " + getName()); } public MultiMapConfig setEntryListenerConfigs(List<EntryListenerConfig> listenerConfigs) { throw new UnsupportedOperationException("This config is read-only multimap: " + getName()); } public MultiMapConfig setBinary(boolean binary) { throw new UnsupportedOperationException("This config is read-only multimap: " + getName()); } public MultiMapConfig setSyncBackupCount(int syncBackupCount) { throw new UnsupportedOperationException("This config is read-only multimap: " + getName()); } public MultiMapConfig setBackupCount(int backupCount) { throw new UnsupportedOperationException("This config is read-only multimap: " + getName()); } public MultiMapConfig setAsyncBackupCount(int asyncBackupCount) { throw new UnsupportedOperationException("This config is read-only multimap: " + getName()); } public MultiMapConfig setStatisticsEnabled(boolean statisticsEnabled) { throw new UnsupportedOperationException("This config is read-only multimap: " + getName()); } }
0true
hazelcast_src_main_java_com_hazelcast_config_MultiMapConfigReadOnly.java
2,270
public static final Decoder NO_DECODER = new Decoder() { @Override public String decode(String value) { return value; } };
0true
src_main_java_org_elasticsearch_common_path_PathTrie.java
405
public interface OTrackedMultiValue<K, V> { /** * Add change listener. * * @param changeListener * Change listener instance. */ public void addChangeListener(OMultiValueChangeListener<K, V> changeListener); /** * Remove change listener. * * @param changeListener * Change listener instance. */ public void removeRecordChangeListener(OMultiValueChangeListener<K, V> changeListener); /** * * Reverts all operations that were performed on collection and return original collection state. * * @param changeEvents * List of operations that were performed on collection. * * @return Original collection state. */ public Object returnOriginalState(List<OMultiValueChangeEvent<K, V>> changeEvents); public Class<?> getGenericClass(); }
0true
core_src_main_java_com_orientechnologies_orient_core_db_record_OTrackedMultiValue.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
1,658
public class SandBoxActionType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, SandBoxActionType> TYPES = new LinkedHashMap<String, SandBoxActionType>(); public static final SandBoxActionType EDIT = new SandBoxActionType("EDIT", "Edit"); public static final SandBoxActionType PROMOTE = new SandBoxActionType("PROMOTE", "Promote"); public static final SandBoxActionType REJECT = new SandBoxActionType("REJECT", "Reject"); public static final SandBoxActionType REVERT = new SandBoxActionType("REVERT", "Revert"); public static SandBoxActionType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public SandBoxActionType() { //do nothing } public SandBoxActionType(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; SandBoxActionType other = (SandBoxActionType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_domain_SandBoxActionType.java
593
public class EmailStatusHandler implements StatusHandler { @Resource(name="blEmailService") protected EmailService emailService; protected EmailInfo emailInfo; protected EmailTarget emailTarget; public void handleStatus(String serviceName, ServiceStatusType status) { String message = serviceName + " is reporting a status of " + status.getType(); EmailInfo copy = emailInfo.clone(); copy.setMessageBody(message); copy.setSubject(message); emailService.sendBasicEmail(copy, emailTarget, null); } public EmailInfo getEmailInfo() { return emailInfo; } public void setEmailInfo(EmailInfo emailInfo) { this.emailInfo = emailInfo; } public EmailTarget getEmailTarget() { return emailTarget; } public void setEmailTarget(EmailTarget emailTarget) { this.emailTarget = emailTarget; } }
0true
common_src_main_java_org_broadleafcommerce_common_vendor_service_monitor_handler_EmailStatusHandler.java
1,590
public class SafeReducerOutputs { private final MultipleOutputs outputs; private final Reducer.Context context; private final boolean testing; public SafeReducerOutputs(final Reducer.Context context) { this.context = context; this.outputs = new MultipleOutputs(this.context); this.testing = this.context.getConfiguration().getBoolean(HadoopCompiler.TESTING, false); } public void write(final String type, final Writable key, final Writable value) throws IOException, InterruptedException { if (this.testing) { if (type.equals(Tokens.SIDEEFFECT)) this.context.write(key, value); } else this.outputs.write(type, key, value); } public void close() throws IOException, InterruptedException { this.outputs.close(); } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_util_SafeReducerOutputs.java
2,535
new HashMap<String, Object>() {{ put("n_field", "value"); put("n_field2", "value2"); }});
0true
src_test_java_org_elasticsearch_common_xcontent_support_XContentMapValuesTests.java
1,517
@Component("blNamedOrderProcessor") public class NamedOrderProcessor extends AbstractModelVariableModifierProcessor { @Resource(name = "blOrderService") protected OrderService orderService; /** * Sets the name of this processor to be used in Thymeleaf template * * NOTE: thymeleaf normalizes the attribute names by converting all to lower-case * we will use the underscore instead of camel case to avoid confusion * */ public NamedOrderProcessor() { super("named_order"); } @Override public int getPrecedence() { return 10000; } @Override protected void modifyModelAttributes(Arguments arguments, Element element) { Customer customer = CustomerState.getCustomer(); String orderVar = element.getAttributeValue("orderVar"); String orderName = element.getAttributeValue("orderName"); Order order = orderService.findNamedOrderForCustomer(orderName, customer); if (order != null) { addToModel(arguments, orderVar, order); } else { addToModel(arguments, orderVar, new NullOrderImpl()); } } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_processor_NamedOrderProcessor.java
360
public class HBaseCompat0_98 implements HBaseCompat { @Override public void setCompression(HColumnDescriptor cd, String algo) { cd.setCompressionType(Compression.Algorithm.valueOf(algo)); } @Override public HTableDescriptor newTableDescriptor(String tableName) { TableName tn = TableName.valueOf(tableName); return new HTableDescriptor(tn); } }
0true
titan-hbase-parent_titan-hbase-098_src_main_java_com_thinkaurelius_titan_diskstorage_hbase_HBaseCompat0_98.java
591
public class IndexShardSegments implements Iterable<ShardSegments> { private final ShardId shardId; private final ShardSegments[] shards; IndexShardSegments(ShardId shardId, ShardSegments[] shards) { this.shardId = shardId; this.shards = shards; } public ShardId getShardId() { return this.shardId; } public ShardSegments getAt(int i) { return shards[i]; } public ShardSegments[] getShards() { return this.shards; } @Override public Iterator<ShardSegments> iterator() { return Iterators.forArray(shards); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_segments_IndexShardSegments.java
1,377
public final class CacheEnvironment { private CacheEnvironment(){} public static final String CONFIG_FILE_PATH_LEGACY = Environment.CACHE_PROVIDER_CONFIG; public static final String CONFIG_FILE_PATH = "hibernate.cache.hazelcast.configuration_file_path"; public static final String USE_NATIVE_CLIENT = "hibernate.cache.hazelcast.use_native_client"; public static final String NATIVE_CLIENT_ADDRESS = "hibernate.cache.hazelcast.native_client_address"; public static final String NATIVE_CLIENT_GROUP = "hibernate.cache.hazelcast.native_client_group"; public static final String NATIVE_CLIENT_PASSWORD = "hibernate.cache.hazelcast.native_client_password"; public static final String SHUTDOWN_ON_STOP = "hibernate.cache.hazelcast.shutdown_on_session_factory_close"; public static final String LOCK_TIMEOUT = "hibernate.cache.hazelcast.lock_timeout"; public static final String HAZELCAST_INSTANCE_NAME = "hibernate.cache.hazelcast.instance_name"; private static final int MAXIMUM_LOCK_TIMEOUT = 10000; // milliseconds private final static int DEFAULT_CACHE_TIMEOUT = (3600 * 1000); // one hour in milliseconds public static final String EXPLICIT_VERSION_CHECK = "hibernate.cache.hazelcast.explicit_version_check"; public static String getConfigFilePath(Properties props) { String configResourcePath = PropertiesHelper.getString(CacheEnvironment.CONFIG_FILE_PATH_LEGACY, props, null); if (StringHelper.isEmpty(configResourcePath)) { configResourcePath = PropertiesHelper.getString(CacheEnvironment.CONFIG_FILE_PATH, props, null); } return configResourcePath; } public static String getInstanceName(Properties props) { return PropertiesHelper.getString(HAZELCAST_INSTANCE_NAME, props, null); } public static boolean isNativeClient(Properties props) { return PropertiesHelper.getBoolean(CacheEnvironment.USE_NATIVE_CLIENT, props, false); } public static int getDefaultCacheTimeoutInMillis() { return DEFAULT_CACHE_TIMEOUT; } public static int getLockTimeoutInMillis(Properties props) { int timeout = -1; try { timeout = PropertiesHelper.getInt(LOCK_TIMEOUT, props, -1); } catch (Exception ignored) { } if (timeout < 0) { timeout = MAXIMUM_LOCK_TIMEOUT; } return timeout; } public static boolean shutdownOnStop(Properties props, boolean defaultValue) { return PropertiesHelper.getBoolean(CacheEnvironment.SHUTDOWN_ON_STOP, props, defaultValue); } public static boolean isExplicitVersionCheckEnabled(Properties props) { return PropertiesHelper.getBoolean(CacheEnvironment.EXPLICIT_VERSION_CHECK, props, false); } }
0true
hazelcast-hibernate_hazelcast-hibernate3_src_main_java_com_hazelcast_hibernate_CacheEnvironment.java
1,780
assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertTrue(map.size() < size); } });
0true
hazelcast_src_test_java_com_hazelcast_map_EvictionTest.java
3,367
public final class BasicOperationScheduler { public static final int TERMINATION_TIMEOUT_SECONDS = 3; private final ILogger logger; private final Node node; private final ExecutionService executionService; private final BasicOperationProcessor processor; //the generic workqueues are shared between all generic operation threads, so that work can be stolen //and a task gets processed as quickly as possible. private final BlockingQueue genericWorkQueue = new LinkedBlockingQueue(); private final ConcurrentLinkedQueue genericPriorityWorkQueue = new ConcurrentLinkedQueue(); //all operations for specific partitions will be executed on these threads, .e.g map.put(key,value). final OperationThread[] partitionOperationThreads; //all operations that are not specific for a partition will be executed here, e.g heartbeat or map.size final OperationThread[] genericOperationThreads; //The genericOperationRandom is used when a generic operation is scheduled, and a generic OperationThread //needs to be selected. //todo: //We could have a look at the ThreadLocalRandom, but it requires java 7. So some kind of reflection //could to the trick to use something less painful. private final Random genericOperationRandom = new Random(); private final ResponseThread responseThread; private volatile boolean shutdown; //The trigger is used when a priority message is send and offered to the operation-thread priority queue. //To wakeup the thread, a priorityTaskTrigger is send to the regular blocking queue to wake up the operation //thread. private final Runnable priorityTaskTrigger = new Runnable() { @Override public void run() { } @Override public String toString() { return "TriggerTask"; } }; public BasicOperationScheduler(Node node, ExecutionService executionService, BasicOperationProcessor processor) { this.executionService = executionService; this.logger = node.getLogger(BasicOperationScheduler.class); this.node = node; this.processor = processor; this.genericOperationThreads = new OperationThread[getGenericOperationThreadCount()]; initOperationThreads(genericOperationThreads, new GenericOperationThreadFactory()); this.partitionOperationThreads = new OperationThread[getPartitionOperationThreadCount()]; initOperationThreads(partitionOperationThreads, new PartitionOperationThreadFactory()); this.responseThread = new ResponseThread(); responseThread.start(); logger.info("Starting with " + genericOperationThreads.length + " generic operation threads and " + partitionOperationThreads.length + " partition operation threads."); } private static void initOperationThreads(OperationThread[] operationThreads, ThreadFactory threadFactory) { for (int threadId = 0; threadId < operationThreads.length; threadId++) { OperationThread operationThread = (OperationThread) threadFactory.newThread(null); operationThreads[threadId] = operationThread; operationThread.start(); } } private int getGenericOperationThreadCount() { int threadCount = node.getGroupProperties().GENERIC_OPERATION_THREAD_COUNT.getInteger(); if (threadCount <= 0) { int coreSize = Runtime.getRuntime().availableProcessors(); threadCount = coreSize * 2; } return threadCount; } private int getPartitionOperationThreadCount() { int threadCount = node.getGroupProperties().PARTITION_OPERATION_THREAD_COUNT.getInteger(); if (threadCount <= 0) { int coreSize = Runtime.getRuntime().availableProcessors(); threadCount = coreSize * 2; } return threadCount; } int getPartitionIdForExecution(Operation op) { return op instanceof PartitionAwareOperation ? op.getPartitionId() : -1; } boolean isAllowedToRunInCurrentThread(Operation op) { return isAllowedToRunInCurrentThread(getPartitionIdForExecution(op)); } boolean isInvocationAllowedFromCurrentThread(Operation op) { return isInvocationAllowedFromCurrentThread(getPartitionIdForExecution(op)); } boolean isAllowedToRunInCurrentThread(int partitionId) { //todo: do we want to allow non partition specific tasks to be run on a partitionSpecific operation thread? if (partitionId < 0) { return true; } Thread currentThread = Thread.currentThread(); //we are only allowed to execute partition aware actions on an OperationThread. if (!(currentThread instanceof OperationThread)) { return false; } OperationThread operationThread = (OperationThread) currentThread; //if the operationThread is a not a partition specific operation thread, then we are not allowed to execute //partition specific operations on it. if (!operationThread.isPartitionSpecific) { return false; } //so it is an partition operation thread, now we need to make sure that this operation thread is allowed //to execute operations for this particular partitionId. int threadId = operationThread.threadId; return toPartitionThreadIndex(partitionId) == threadId; } boolean isInvocationAllowedFromCurrentThread(int partitionId) { Thread currentThread = Thread.currentThread(); if (currentThread instanceof OperationThread) { if (partitionId > -1) { //todo: we need to check for isPartitionSpecific int threadId = ((OperationThread) currentThread).threadId; return toPartitionThreadIndex(partitionId) == threadId; } return true; } return true; } public int getOperationExecutorQueueSize() { int size = 0; for (OperationThread t : partitionOperationThreads) { size += t.workQueue.size(); } size += genericWorkQueue.size(); return size; } public int getPriorityOperationExecutorQueueSize() { int size = 0; for (OperationThread t : partitionOperationThreads) { size += t.priorityWorkQueue.size(); } size += genericPriorityWorkQueue.size(); return size; } public int getResponseQueueSize() { return responseThread.workQueue.size(); } public void execute(Operation op) { String executorName = op.getExecutorName(); if (executorName == null) { int partitionId = getPartitionIdForExecution(op); boolean hasPriority = op.isUrgent(); execute(op, partitionId, hasPriority); } else { executeOnExternalExecutor(op, executorName); } } private void executeOnExternalExecutor(Operation op, String executorName) { ExecutorService executor = executionService.getExecutor(executorName); if (executor == null) { throw new IllegalStateException("Could not found executor with name: " + executorName); } if (op instanceof PartitionAware) { throw new IllegalStateException("PartitionAwareOperation " + op + " can't be executed on a " + "custom executor with name: " + executorName); } if (op instanceof UrgentSystemOperation) { throw new IllegalStateException("UrgentSystemOperation " + op + " can't be executed on a custom " + "executor with name: " + executorName); } executor.execute(new LocalOperationProcessor(op)); } public void execute(Packet packet) { try { if (packet.isHeaderSet(Packet.HEADER_RESPONSE)) { //it is an response packet. responseThread.workQueue.add(packet); } else { //it is an must be an operation packet int partitionId = packet.getPartitionId(); boolean hasPriority = packet.isUrgent(); execute(packet, partitionId, hasPriority); } } catch (RejectedExecutionException e) { if (node.nodeEngine.isActive()) { throw e; } } } private void execute(Object task, int partitionId, boolean priority) { if (task == null) { throw new NullPointerException(); } BlockingQueue workQueue; Queue priorityWorkQueue; if (partitionId < 0) { workQueue = genericWorkQueue; priorityWorkQueue = genericPriorityWorkQueue; } else { OperationThread partitionOperationThread = partitionOperationThreads[toPartitionThreadIndex(partitionId)]; workQueue = partitionOperationThread.workQueue; priorityWorkQueue = partitionOperationThread.priorityWorkQueue; } if (priority) { offerWork(priorityWorkQueue, task); offerWork(workQueue, priorityTaskTrigger); } else { offerWork(workQueue, task); } } private void offerWork(Queue queue, Object task) { //in 3.3 we are going to apply backpressure on overload and then we are going to do something //with the return values of the offer methods. //Currently the queues are all unbound, so this can't happen anyway. boolean offer = queue.offer(task); if (!offer) { logger.severe("Failed to offer " + task + " to BasicOperationScheduler due to overload"); } } private int toPartitionThreadIndex(int partitionId) { return partitionId % partitionOperationThreads.length; } public void shutdown() { shutdown = true; interruptAll(partitionOperationThreads); interruptAll(genericOperationThreads); awaitTermination(partitionOperationThreads); awaitTermination(genericOperationThreads); } private static void interruptAll(OperationThread[] operationThreads) { for (OperationThread thread : operationThreads) { thread.interrupt(); } } private static void awaitTermination(OperationThread[] operationThreads) { for (OperationThread thread : operationThreads) { try { thread.awaitTermination(TERMINATION_TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } } } @Override public String toString() { return "BasicOperationScheduler{" + "node=" + node.getThisAddress() + '}'; } private class GenericOperationThreadFactory implements ThreadFactory { private int threadId; @Override public OperationThread newThread(Runnable ignore) { String threadName = node.getThreadPoolNamePrefix("generic-operation") + threadId; OperationThread thread = new OperationThread(threadName, false, threadId, genericWorkQueue, genericPriorityWorkQueue); threadId++; return thread; } } private class PartitionOperationThreadFactory implements ThreadFactory { private int threadId; @Override public Thread newThread(Runnable ignore) { String threadName = node.getThreadPoolNamePrefix("partition-operation") + threadId; //each partition operation thread, has its own workqueues because operations are partition specific and can't //be executed by other threads. LinkedBlockingQueue workQueue = new LinkedBlockingQueue(); ConcurrentLinkedQueue priorityWorkQueue = new ConcurrentLinkedQueue(); OperationThread thread = new OperationThread(threadName, true, threadId, workQueue, priorityWorkQueue); threadId++; return thread; } } final class OperationThread extends Thread { private final int threadId; private final boolean isPartitionSpecific; private final BlockingQueue workQueue; private final Queue priorityWorkQueue; public OperationThread(String name, boolean isPartitionSpecific, int threadId, BlockingQueue workQueue, Queue priorityWorkQueue) { super(node.threadGroup, name); setContextClassLoader(node.getConfigClassLoader()); this.isPartitionSpecific = isPartitionSpecific; this.workQueue = workQueue; this.priorityWorkQueue = priorityWorkQueue; this.threadId = threadId; } @Override public void run() { try { doRun(); } catch (OutOfMemoryError e) { onOutOfMemory(e); } catch (Throwable t) { logger.severe(t); } } private void doRun() { for (; ; ) { Object task; try { task = workQueue.take(); } catch (InterruptedException e) { if (shutdown) { return; } continue; } if (shutdown) { return; } processPriorityMessages(); process(task); } } private void process(Object task) { try { processor.process(task); } catch (Exception e) { logger.severe("Failed to process task: " + task + " on partitionThread:" + getName()); } } private void processPriorityMessages() { for (; ; ) { Object task = priorityWorkQueue.poll(); if (task == null) { return; } process(task); } } public void awaitTermination(int timeout, TimeUnit unit) throws InterruptedException { join(unit.toMillis(timeout)); } } private class ResponseThread extends Thread { private final BlockingQueue<Packet> workQueue = new LinkedBlockingQueue<Packet>(); public ResponseThread() { super(node.threadGroup, node.getThreadNamePrefix("response")); setContextClassLoader(node.getConfigClassLoader()); } public void run() { try { doRun(); } catch (OutOfMemoryError e) { onOutOfMemory(e); } catch (Throwable t) { logger.severe(t); } } private void doRun() { for (; ; ) { Object task; try { task = workQueue.take(); } catch (InterruptedException e) { if (shutdown) { return; } continue; } if (shutdown) { return; } process(task); } } private void process(Object task) { try { processor.process(task); } catch (Exception e) { logger.severe("Failed to process task: " + task + " on partitionThread:" + getName()); } } } /** * Process the operation that has been send locally to this OperationService. */ private class LocalOperationProcessor implements Runnable { private final Operation op; private LocalOperationProcessor(Operation op) { this.op = op; } @Override public void run() { processor.process(op); } } }
1no label
hazelcast_src_main_java_com_hazelcast_spi_impl_BasicOperationScheduler.java
2,807
private static class ExtendedProcessor extends AnalysisBinderProcessor { @Override public void processCharFilters(CharFiltersBindings charFiltersBindings) { charFiltersBindings.processCharFilter("mapping", MappingCharFilterFactory.class); } @Override public void processTokenFilters(TokenFiltersBindings tokenFiltersBindings) { tokenFiltersBindings.processTokenFilter("snowball", SnowballTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("stemmer", StemmerTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("word_delimiter", WordDelimiterTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("delimited_payload_filter", DelimitedPayloadTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("synonym", SynonymTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("elision", ElisionTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("keep", KeepWordFilterFactory.class); tokenFiltersBindings.processTokenFilter("pattern_capture", PatternCaptureGroupTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("pattern_replace", PatternReplaceTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("dictionary_decompounder", DictionaryCompoundWordTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("hyphenation_decompounder", HyphenationCompoundWordTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("arabic_stem", ArabicStemTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("brazilian_stem", BrazilianStemTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("czech_stem", CzechStemTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("dutch_stem", DutchStemTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("french_stem", FrenchStemTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("german_stem", GermanStemTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("russian_stem", RussianStemTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("keyword_marker", KeywordMarkerTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("stemmer_override", StemmerOverrideTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("arabic_normalization", ArabicNormalizationFilterFactory.class); tokenFiltersBindings.processTokenFilter("persian_normalization", PersianNormalizationFilterFactory.class); tokenFiltersBindings.processTokenFilter("hunspell", HunspellTokenFilterFactory.class); tokenFiltersBindings.processTokenFilter("cjk_bigram", CJKBigramFilterFactory.class); tokenFiltersBindings.processTokenFilter("cjk_width", CJKWidthFilterFactory.class); } @Override public void processTokenizers(TokenizersBindings tokenizersBindings) { tokenizersBindings.processTokenizer("pattern", PatternTokenizerFactory.class); } @Override public void processAnalyzers(AnalyzersBindings analyzersBindings) { analyzersBindings.processAnalyzer("pattern", PatternAnalyzerProvider.class); analyzersBindings.processAnalyzer("snowball", SnowballAnalyzerProvider.class); analyzersBindings.processAnalyzer("arabic", ArabicAnalyzerProvider.class); analyzersBindings.processAnalyzer("armenian", ArmenianAnalyzerProvider.class); analyzersBindings.processAnalyzer("basque", BasqueAnalyzerProvider.class); analyzersBindings.processAnalyzer("brazilian", BrazilianAnalyzerProvider.class); analyzersBindings.processAnalyzer("bulgarian", BulgarianAnalyzerProvider.class); analyzersBindings.processAnalyzer("catalan", CatalanAnalyzerProvider.class); analyzersBindings.processAnalyzer("chinese", ChineseAnalyzerProvider.class); analyzersBindings.processAnalyzer("cjk", CjkAnalyzerProvider.class); analyzersBindings.processAnalyzer("czech", CzechAnalyzerProvider.class); analyzersBindings.processAnalyzer("danish", DanishAnalyzerProvider.class); analyzersBindings.processAnalyzer("dutch", DutchAnalyzerProvider.class); analyzersBindings.processAnalyzer("english", EnglishAnalyzerProvider.class); analyzersBindings.processAnalyzer("finnish", FinnishAnalyzerProvider.class); analyzersBindings.processAnalyzer("french", FrenchAnalyzerProvider.class); analyzersBindings.processAnalyzer("galician", GalicianAnalyzerProvider.class); analyzersBindings.processAnalyzer("german", GermanAnalyzerProvider.class); analyzersBindings.processAnalyzer("greek", GreekAnalyzerProvider.class); analyzersBindings.processAnalyzer("hindi", HindiAnalyzerProvider.class); analyzersBindings.processAnalyzer("hungarian", HungarianAnalyzerProvider.class); analyzersBindings.processAnalyzer("indonesian", IndonesianAnalyzerProvider.class); analyzersBindings.processAnalyzer("italian", ItalianAnalyzerProvider.class); analyzersBindings.processAnalyzer("latvian", LatvianAnalyzerProvider.class); analyzersBindings.processAnalyzer("norwegian", NorwegianAnalyzerProvider.class); analyzersBindings.processAnalyzer("persian", PersianAnalyzerProvider.class); analyzersBindings.processAnalyzer("portuguese", PortugueseAnalyzerProvider.class); analyzersBindings.processAnalyzer("romanian", RomanianAnalyzerProvider.class); analyzersBindings.processAnalyzer("russian", RussianAnalyzerProvider.class); analyzersBindings.processAnalyzer("spanish", SpanishAnalyzerProvider.class); analyzersBindings.processAnalyzer("swedish", SwedishAnalyzerProvider.class); analyzersBindings.processAnalyzer("turkish", TurkishAnalyzerProvider.class); analyzersBindings.processAnalyzer("thai", ThaiAnalyzerProvider.class); } }
0true
src_main_java_org_elasticsearch_index_analysis_AnalysisModule.java
1,844
public class MapRecordKey { final String mapName; final Data key; public MapRecordKey(String mapName, Data key) { this.mapName = mapName; this.key = key; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MapRecordKey that = (MapRecordKey) o; if (key != null ? !key.equals(that.key) : that.key != null) return false; if (mapName != null ? !mapName.equals(that.mapName) : that.mapName != null) return false; return true; } @Override public int hashCode() { int result = mapName != null ? mapName.hashCode() : 0; result = 31 * result + (key != null ? key.hashCode() : 0); return result; } }
0true
hazelcast_src_main_java_com_hazelcast_map_MapRecordKey.java
1,368
public final class MemberCallableTaskOperation extends BaseCallableTaskOperation implements IdentifiedDataSerializable { public MemberCallableTaskOperation() { } public MemberCallableTaskOperation(String name, String uuid, Callable callable) { super(name, uuid, callable); } @Override public ExceptionAction onException(Throwable throwable) { if (throwable instanceof MemberLeftException || throwable instanceof TargetNotMemberException) { return ExceptionAction.THROW_EXCEPTION; } return super.onException(throwable); } @Override public int getFactoryId() { return ExecutorDataSerializerHook.F_ID; } @Override public int getId() { return ExecutorDataSerializerHook.MEMBER_CALLABLE_TASK; } }
0true
hazelcast_src_main_java_com_hazelcast_executor_MemberCallableTaskOperation.java
286
public abstract class ActionResponse extends TransportResponse { @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); } }
0true
src_main_java_org_elasticsearch_action_ActionResponse.java
1,589
public class NodeVersionAllocationDecider extends AllocationDecider { @Inject public NodeVersionAllocationDecider(Settings settings) { super(settings); } @Override public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { String sourceNodeId = shardRouting.currentNodeId(); /* if sourceNodeId is not null we do a relocation and just check the version of the node * that we are currently allocate on. If not we are initializing and recover from primary.*/ if (sourceNodeId == null) { // we allocate - check primary if (shardRouting.primary()) { // we are the primary we can allocate wherever return allocation.decision(Decision.YES, "primary shard can be allocated anywhere"); } final MutableShardRouting primary = allocation.routingNodes().activePrimary(shardRouting); if (primary == null) { // we have a primary - it's a start ;) return allocation.decision(Decision.YES, "no active primary shard yet"); } sourceNodeId = primary.currentNodeId(); } return isVersionCompatible(allocation.routingNodes(), sourceNodeId, node, allocation); } private Decision isVersionCompatible(final RoutingNodes routingNodes, final String sourceNodeId, final RoutingNode target, RoutingAllocation allocation) { final RoutingNode source = routingNodes.node(sourceNodeId); if (target.node().version().onOrAfter(source.node().version())) { /* we can allocate if we can recover from a node that is younger or on the same version * if the primary is already running on a newer version that won't work due to possible * differences in the lucene index format etc.*/ return allocation.decision(Decision.YES, "target node version [%s] is same or newer than source node version [%s]", target.node().version(), source.node().version()); } else { return allocation.decision(Decision.NO, "target node version [%s] is older than source node version [%s]", target.node().version(), source.node().version()); } } }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_decider_NodeVersionAllocationDecider.java
260
ex.schedule(new Runnable() { @Override public void run() { hzs.get(1).getLifecycleService().terminate(); } }, 1000, TimeUnit.MILLISECONDS);
0true
hazelcast-client_src_test_java_com_hazelcast_client_executor_ExecutionDelayTest.java
1,644
public class CodecTests extends ElasticsearchIntegrationTest { @Test public void testFieldsWithCustomPostingsFormat() throws Exception { try { client().admin().indices().prepareDelete("test").execute().actionGet(); } catch (Exception e) { // ignore } client().admin().indices().prepareCreate("test") .addMapping("type1", jsonBuilder().startObject().startObject("type1").startObject("properties").startObject("field1") .field("postings_format", "test1").field("index_options", "docs").field("type", "string").endObject().endObject().endObject().endObject()) .setSettings(ImmutableSettings.settingsBuilder() .put("index.number_of_shards", 1) .put("index.number_of_replicas", 0) .put("index.codec.postings_format.test1.type", "pulsing") ).execute().actionGet(); client().prepareIndex("test", "type1", "1").setSource("field1", "quick brown fox", "field2", "quick brown fox").execute().actionGet(); client().prepareIndex("test", "type1", "2").setSource("field1", "quick lazy huge brown fox", "field2", "quick lazy huge brown fox").setRefresh(true).execute().actionGet(); SearchResponse searchResponse = client().prepareSearch().setQuery(QueryBuilders.matchQuery("field2", "quick brown").type(MatchQueryBuilder.Type.PHRASE).slop(0)).execute().actionGet(); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); try { client().prepareSearch().setQuery(QueryBuilders.matchQuery("field1", "quick brown").type(MatchQueryBuilder.Type.PHRASE).slop(0)).execute().actionGet(); } catch (SearchPhaseExecutionException e) { assertThat(e.getMessage(), endsWith("IllegalStateException[field \"field1\" was indexed without position data; cannot run PhraseQuery (term=quick)]; }")); } } @Test public void testIndexingWithSimpleTextCodec() throws Exception { try { client().admin().indices().prepareDelete("test").execute().actionGet(); } catch (Exception e) { // ignore } client().admin().indices().prepareCreate("test") .setSettings(ImmutableSettings.settingsBuilder() .put("index.number_of_shards", 1) .put("index.number_of_replicas", 0) .put("index.codec", "SimpleText") ).execute().actionGet(); client().prepareIndex("test", "type1", "1").setSource("field1", "quick brown fox", "field2", "quick brown fox").execute().actionGet(); client().prepareIndex("test", "type1", "2").setSource("field1", "quick lazy huge brown fox", "field2", "quick lazy huge brown fox").setRefresh(true).execute().actionGet(); SearchResponse searchResponse = client().prepareSearch().setQuery(QueryBuilders.matchQuery("field2", "quick brown").type(MatchQueryBuilder.Type.PHRASE).slop(0)).execute().actionGet(); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); try { client().prepareSearch().setQuery(QueryBuilders.matchQuery("field1", "quick brown").type(MatchQueryBuilder.Type.PHRASE).slop(0)).execute().actionGet(); } catch (SearchPhaseExecutionException e) { assertThat(e.getMessage(), endsWith("IllegalStateException[field \"field1\" was indexed without position data; cannot run PhraseQuery (term=quick)]; }")); } } @Test public void testCustomDocValuesFormat() throws IOException { try { client().admin().indices().prepareDelete("test").execute().actionGet(); } catch (Exception e) { // ignore } client().admin().indices().prepareCreate("test") .addMapping("test", jsonBuilder().startObject().startObject("test") .startObject("_version").field("doc_values_format", "disk").endObject() .startObject("properties").startObject("field").field("type", "long").field("doc_values_format", "dvf").endObject().endObject() .endObject().endObject()) .setSettings(ImmutableSettings.settingsBuilder() .put("index.codec.doc_values_format.dvf.type", "disk") .build()); for (int i = 10; i >= 0; --i) { client().prepareIndex("test", "test", Integer.toString(i)).setSource("field", randomLong()).setRefresh(i == 0 || rarely()).execute().actionGet(); } SearchResponse searchResponse = client().prepareSearch().setQuery(QueryBuilders.matchAllQuery()).addSort(new FieldSortBuilder("field")).execute().actionGet(); assertThat(searchResponse.getFailedShards(), equalTo(0)); } }
0true
src_test_java_org_elasticsearch_codecs_CodecTests.java
1,905
class TypeConverterBindingProcessor extends AbstractProcessor { TypeConverterBindingProcessor(Errors errors) { super(errors); } /** * Installs default converters for primitives, enums, and class literals. */ public void prepareBuiltInConverters(InjectorImpl injector) { this.injector = injector; try { // Configure type converters. convertToPrimitiveType(int.class, Integer.class); convertToPrimitiveType(long.class, Long.class); convertToPrimitiveType(boolean.class, Boolean.class); convertToPrimitiveType(byte.class, Byte.class); convertToPrimitiveType(short.class, Short.class); convertToPrimitiveType(float.class, Float.class); convertToPrimitiveType(double.class, Double.class); convertToClass(Character.class, new TypeConverter() { public Object convert(String value, TypeLiteral<?> toType) { value = value.trim(); if (value.length() != 1) { throw new RuntimeException("Length != 1."); } return value.charAt(0); } @Override public String toString() { return "TypeConverter<Character>"; } }); convertToClasses(Matchers.subclassesOf(Enum.class), new TypeConverter() { @SuppressWarnings("unchecked") public Object convert(String value, TypeLiteral<?> toType) { return Enum.valueOf((Class) toType.getRawType(), value); } @Override public String toString() { return "TypeConverter<E extends Enum<E>>"; } }); internalConvertToTypes( new AbstractMatcher<TypeLiteral<?>>() { public boolean matches(TypeLiteral<?> typeLiteral) { return typeLiteral.getRawType() == Class.class; } @Override public String toString() { return "Class<?>"; } }, new TypeConverter() { @SuppressWarnings("unchecked") public Object convert(String value, TypeLiteral<?> toType) { try { return Class.forName(value); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage()); } } @Override public String toString() { return "TypeConverter<Class<?>>"; } } ); } finally { this.injector = null; } } private <T> void convertToPrimitiveType(Class<T> primitiveType, final Class<T> wrapperType) { try { final Method parser = wrapperType.getMethod( "parse" + Strings.capitalize(primitiveType.getName()), String.class); TypeConverter typeConverter = new TypeConverter() { @SuppressWarnings("unchecked") public Object convert(String value, TypeLiteral<?> toType) { try { return parser.invoke(null, value); } catch (IllegalAccessException e) { throw new AssertionError(e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getTargetException().getMessage()); } } @Override public String toString() { return "TypeConverter<" + wrapperType.getSimpleName() + ">"; } }; convertToClass(wrapperType, typeConverter); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } private <T> void convertToClass(Class<T> type, TypeConverter converter) { convertToClasses(Matchers.identicalTo(type), converter); } private void convertToClasses(final Matcher<? super Class<?>> typeMatcher, TypeConverter converter) { internalConvertToTypes(new AbstractMatcher<TypeLiteral<?>>() { public boolean matches(TypeLiteral<?> typeLiteral) { Type type = typeLiteral.getType(); if (!(type instanceof Class)) { return false; } Class<?> clazz = (Class<?>) type; return typeMatcher.matches(clazz); } @Override public String toString() { return typeMatcher.toString(); } }, converter); } private void internalConvertToTypes(Matcher<? super TypeLiteral<?>> typeMatcher, TypeConverter converter) { injector.state.addConverter( new MatcherAndConverter(typeMatcher, converter, SourceProvider.UNKNOWN_SOURCE)); } @Override public Boolean visit(TypeConverterBinding command) { injector.state.addConverter(new MatcherAndConverter( command.getTypeMatcher(), command.getTypeConverter(), command.getSource())); return true; } }
0true
src_main_java_org_elasticsearch_common_inject_TypeConverterBindingProcessor.java
855
public abstract class ReadRequest extends PartitionClientRequest implements Portable, SecureRequest { protected String name; public ReadRequest() { } public ReadRequest(String name) { this.name = name; } @Override protected int getPartition() { ClientEngine clientEngine = getClientEngine(); Data key = clientEngine.getSerializationService().toData(name); return clientEngine.getPartitionService().getPartitionId(key); } @Override public String getServiceName() { return AtomicReferenceService.SERVICE_NAME; } @Override public int getFactoryId() { return AtomicReferencePortableHook.F_ID; } @Override public void write(PortableWriter writer) throws IOException { writer.writeUTF("n", name); } @Override public void read(PortableReader reader) throws IOException { name = reader.readUTF("n"); } @Override public Permission getRequiredPermission() { return new AtomicReferencePermission(name, ActionConstants.ACTION_READ); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_ReadRequest.java
2,318
static class TimeIntervalTimeZoneRounding extends TimeZoneRounding { final static byte ID = 5; private long interval; private DateTimeZone preTz; private DateTimeZone postTz; TimeIntervalTimeZoneRounding() { // for serialization } TimeIntervalTimeZoneRounding(long interval, DateTimeZone preTz, DateTimeZone postTz) { this.interval = interval; this.preTz = preTz; this.postTz = postTz; } @Override public byte id() { return ID; } @Override public long roundKey(long utcMillis) { long time = utcMillis + preTz.getOffset(utcMillis); return Rounding.Interval.roundKey(time, interval); } @Override public long valueForKey(long key) { long time = Rounding.Interval.roundValue(key, interval); // now, time is still in local, move it to UTC time = time - preTz.getOffset(time); // now apply post Tz time = time + postTz.getOffset(time); return time; } @Override public long nextRoundingValue(long value) { return value + interval; } @Override public void readFrom(StreamInput in) throws IOException { interval = in.readVLong(); preTz = DateTimeZone.forID(in.readSharedString()); postTz = DateTimeZone.forID(in.readSharedString()); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVLong(interval); out.writeSharedString(preTz.getID()); out.writeSharedString(postTz.getID()); } }
0true
src_main_java_org_elasticsearch_common_rounding_TimeZoneRounding.java
130
public class OBinaryConverterFactory { private static final boolean unsafeWasDetected; static { boolean unsafeDetected = false; try { Class<?> sunClass = Class.forName("sun.misc.Unsafe"); unsafeDetected = sunClass != null; } catch (ClassNotFoundException cnfe) { // Ignore } unsafeWasDetected = unsafeDetected; } public static OBinaryConverter getConverter() { boolean useUnsafe = Boolean.valueOf(System.getProperty("memory.useUnsafe")); if (useUnsafe && unsafeWasDetected) return OUnsafeBinaryConverter.INSTANCE; return OSafeBinaryConverter.INSTANCE; } }
0true
commons_src_main_java_com_orientechnologies_common_serialization_OBinaryConverterFactory.java
3,647
public class LatLonAndGeohashMappingGeoPointTests extends ElasticsearchTestCase { @Test public void testLatLonValues() throws Exception { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("point").field("type", "geo_point").field("lat_lon", true).field("geohash", true).endObject().endObject() .endObject().endObject().string(); DocumentMapper defaultMapper = MapperTestUtils.newParser().parse(mapping); ParsedDocument doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder() .startObject() .startObject("point").field("lat", 1.2).field("lon", 1.3).endObject() .endObject() .bytes()); assertThat(doc.rootDoc().getField("point.lat"), notNullValue()); assertThat(doc.rootDoc().getField("point.lon"), notNullValue()); assertThat(doc.rootDoc().get("point.geohash"), equalTo(GeoHashUtils.encode(1.2, 1.3))); } @Test public void testLatLonInOneValue() throws Exception { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("point").field("type", "geo_point").field("lat_lon", true).field("geohash", true).endObject().endObject() .endObject().endObject().string(); DocumentMapper defaultMapper = MapperTestUtils.newParser().parse(mapping); ParsedDocument doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder() .startObject() .field("point", "1.2,1.3") .endObject() .bytes()); assertThat(doc.rootDoc().getField("point.lat"), notNullValue()); assertThat(doc.rootDoc().getField("point.lon"), notNullValue()); assertThat(doc.rootDoc().get("point.geohash"), equalTo(GeoHashUtils.encode(1.2, 1.3))); } @Test public void testGeoHashValue() throws Exception { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("point").field("type", "geo_point").field("lat_lon", true).field("geohash", true).endObject().endObject() .endObject().endObject().string(); DocumentMapper defaultMapper = MapperTestUtils.newParser().parse(mapping); ParsedDocument doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder() .startObject() .field("point", GeoHashUtils.encode(1.2, 1.3)) .endObject() .bytes()); assertThat(doc.rootDoc().getField("point.lat"), notNullValue()); assertThat(doc.rootDoc().getField("point.lon"), notNullValue()); assertThat(doc.rootDoc().get("point.geohash"), equalTo(GeoHashUtils.encode(1.2, 1.3))); } }
0true
src_test_java_org_elasticsearch_index_mapper_geo_LatLonAndGeohashMappingGeoPointTests.java
532
@Deprecated public class GatewaySnapshotRequest extends BroadcastOperationRequest<GatewaySnapshotRequest> { GatewaySnapshotRequest() { } /** * Constructs a new gateway snapshot against one or more indices. No indices means the gateway snapshot * will be executed against all indices. */ public GatewaySnapshotRequest(String... indices) { this.indices = indices; } }
0true
src_main_java_org_elasticsearch_action_admin_indices_gateway_snapshot_GatewaySnapshotRequest.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
2,585
public class SocketAcceptor implements Runnable { private final ServerSocketChannel serverSocketChannel; private final TcpIpConnectionManager connectionManager; private final ILogger logger; public SocketAcceptor(ServerSocketChannel serverSocketChannel, TcpIpConnectionManager connectionManager) { this.serverSocketChannel = serverSocketChannel; this.connectionManager = connectionManager; this.logger = connectionManager.ioService.getLogger(this.getClass().getName()); } public void run() { Selector selector = null; try { if (logger.isFinestEnabled()) { log(Level.FINEST, "Starting SocketAcceptor on " + serverSocketChannel); } selector = Selector.open(); serverSocketChannel.configureBlocking(false); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while (connectionManager.isLive()) { // block until new connection or interruption. final int keyCount = selector.select(); if (Thread.currentThread().isInterrupted()) { break; } if (keyCount == 0) { continue; } final Set<SelectionKey> setSelectedKeys = selector.selectedKeys(); final Iterator<SelectionKey> it = setSelectedKeys.iterator(); while (it.hasNext()) { final SelectionKey sk = it.next(); it.remove(); // of course it is acceptable! if (sk.isValid() && sk.isAcceptable()) { acceptSocket(); } } } } catch (OutOfMemoryError e) { OutOfMemoryErrorDispatcher.onOutOfMemory(e); } catch (IOException e) { log(Level.SEVERE, e.getClass().getName() + ": " + e.getMessage(), e); } finally { closeSelector(selector); } } private void closeSelector(Selector selector) { if (selector != null) { try { if (logger.isFinestEnabled()) { logger.finest("Closing selector " + Thread.currentThread().getName()); } selector.close(); } catch (final Exception ignored) { } } } private void acceptSocket() { if (!connectionManager.isLive()) { return; } SocketChannelWrapper socketChannelWrapper = null; try { final SocketChannel socketChannel = serverSocketChannel.accept(); if (socketChannel != null) { socketChannelWrapper = connectionManager.wrapSocketChannel(socketChannel, false); } } catch (Exception e) { if (e instanceof ClosedChannelException && !connectionManager.isLive()) { // ClosedChannelException // or AsynchronousCloseException // or ClosedByInterruptException logger.finest("Terminating socket acceptor thread...", e); } else { String error = "Unexpected error while accepting connection! " + e.getClass().getName() + ": " + e.getMessage(); log(Level.WARNING, error); try { serverSocketChannel.close(); } catch (Exception ignore) { } connectionManager.ioService.onFatalError(e); } } if (socketChannelWrapper != null) { final SocketChannelWrapper socketChannel = socketChannelWrapper; log(Level.INFO, "Accepting socket connection from " + socketChannel.socket().getRemoteSocketAddress()); final MemberSocketInterceptor memberSocketInterceptor = connectionManager.getMemberSocketInterceptor(); if (memberSocketInterceptor == null) { configureAndAssignSocket(socketChannel, null); } else { connectionManager.ioService.executeAsync(new Runnable() { public void run() { configureAndAssignSocket(socketChannel, memberSocketInterceptor); } }); } } } private void configureAndAssignSocket(SocketChannelWrapper socketChannel, MemberSocketInterceptor memberSocketInterceptor) { try { connectionManager.initSocket(socketChannel.socket()); if (memberSocketInterceptor != null) { log(Level.FINEST, "Calling member socket interceptor: " + memberSocketInterceptor + " for " + socketChannel); memberSocketInterceptor.onAccept(socketChannel.socket()); } socketChannel.configureBlocking(false); connectionManager.assignSocketChannel(socketChannel); } catch (Exception e) { log(Level.WARNING, e.getClass().getName() + ": " + e.getMessage(), e); IOUtil.closeResource(socketChannel); } } private void log(Level level, String message) { log(level, message, null); } private void log(Level level, String message, Exception e) { logger.log(level, message, e); connectionManager.ioService.getSystemLogService().logConnection(message); } }
1no label
hazelcast_src_main_java_com_hazelcast_nio_SocketAcceptor.java
2,581
private class MasterNodeFailureListener implements MasterFaultDetection.Listener { @Override public void onMasterFailure(DiscoveryNode masterNode, String reason) { handleMasterGone(masterNode, reason); } @Override public void onDisconnectedFromMaster() { // got disconnected from the master, send a join request DiscoveryNode masterNode = latestDiscoNodes.masterNode(); try { membership.sendJoinRequest(masterNode, localNode); } catch (Exception e) { logger.warn("failed to send join request on disconnection from master [{}]", masterNode); } } }
0true
src_main_java_org_elasticsearch_discovery_zen_ZenDiscovery.java
792
public interface CandidateFulfillmentGroupOffer extends Serializable { public Money getDiscountedPrice(); public void setDiscountedPrice(Money discountedPrice); public FulfillmentGroup getFulfillmentGroup(); public void setFulfillmentGroup(FulfillmentGroup fulfillmentGroup); public void setOffer(Offer offer); public Offer getOffer(); public int getPriority(); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_CandidateFulfillmentGroupOffer.java
856
Transformer adjustmentToOfferTransformer = new Transformer() { @Override public Object transform(Object input) { return ((Adjustment)input).getOffer(); } };
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_OfferServiceImpl.java
1,200
public class OQueryOperatorPlus extends OQueryOperator { public OQueryOperatorPlus() { super("+", 9, false); } @Override public Object evaluateRecord(final OIdentifiable iRecord, ODocument iCurrentResult, final OSQLFilterCondition iCondition, Object iLeft, Object iRight, OCommandContext iContext) { if (iRight == null) return iLeft; if (iLeft == null) return iRight; if (iLeft instanceof Date) iLeft = ((Date) iLeft).getTime(); if (iRight instanceof Date) iRight = ((Date) iRight).getTime(); if (iLeft instanceof String) return (String) iLeft + iRight.toString(); else if (iRight instanceof String) return iLeft.toString() + (String) iRight; else if (iLeft instanceof Number && iRight instanceof Number) { final Number l = (Number) iLeft; final Number r = (Number) iRight; if (l instanceof Integer) return l.intValue() + r.intValue(); else if (l instanceof Long) return l.longValue() + r.longValue(); else if (l instanceof Short) return l.shortValue() + r.shortValue(); else if (l instanceof Float) return l.floatValue() + r.floatValue(); else if (l instanceof Double) return l.doubleValue() + r.doubleValue(); else if (l instanceof BigDecimal) { if (r instanceof BigDecimal) return ((BigDecimal) l).add((BigDecimal) r); else if (r instanceof Float) return ((BigDecimal) l).add(new BigDecimal(r.floatValue())); else if (r instanceof Double) return ((BigDecimal) l).add(new BigDecimal(r.doubleValue())); else if (r instanceof Long) return ((BigDecimal) l).add(new BigDecimal(r.longValue())); else if (r instanceof Integer) return ((BigDecimal) l).add(new BigDecimal(r.intValue())); else if (r instanceof Short) return ((BigDecimal) l).add(new BigDecimal(r.shortValue())); } } return null; } @Override public OIndexReuseType getIndexReuseType(Object iLeft, Object iRight) { return OIndexReuseType.NO_INDEX; } @Override public ORID getBeginRidRange(Object iLeft, Object iRight) { return null; } @Override public ORID getEndRidRange(Object iLeft, Object iRight) { return null; } }
0true
core_src_main_java_com_orientechnologies_orient_core_sql_operator_math_OQueryOperatorPlus.java
1,610
public class OCreateRecordTask extends OAbstractRecordReplicatedTask { private static final long serialVersionUID = 1L; protected byte[] content; protected byte recordType; public OCreateRecordTask() { } public OCreateRecordTask(final ORecordId iRid, final byte[] iContent, final ORecordVersion iVersion, final byte iRecordType) { super(iRid, iVersion); content = iContent; recordType = iRecordType; } @Override public Object execute(final OServer iServer, ODistributedServerManager iManager, final ODatabaseDocumentTx database) throws Exception { ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, "creating record %s/%s v.%s...", database.getName(), rid.toString(), version.toString()); final ORecordInternal<?> record = Orient.instance().getRecordFactoryManager().newInstance(recordType); record.fill(rid, version, content, true); if (rid.getClusterId() != -1) record.save(database.getClusterNameById(rid.getClusterId()), true); else record.save(); rid = (ORecordId) record.getIdentity(); ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, "+-> assigned new rid %s/%s v.%d", database.getName(), rid.toString(), record.getVersion()); return new OPhysicalPosition(rid.getClusterPosition(), record.getRecordVersion()); } @Override public QUORUM_TYPE getQuorumType() { return QUORUM_TYPE.WRITE; } @Override public OFixCreateRecordTask getFixTask(final ODistributedRequest iRequest, final ODistributedResponse iBadResponse, final ODistributedResponse iGoodResponse) { OPhysicalPosition badResult = (OPhysicalPosition) iBadResponse.getPayload(); OPhysicalPosition goodResult = (OPhysicalPosition) iGoodResponse.getPayload(); return new OFixCreateRecordTask(new ORecordId(rid.getClusterId(), badResult.clusterPosition), content, version, recordType, new ORecordId(rid.getClusterId(), goodResult.clusterPosition)); } @Override public void writeExternal(final ObjectOutput out) throws IOException { out.writeUTF(rid.toString()); if (content == null) out.writeInt(0); else { out.writeInt(content.length); out.write(content); } if (version == null) version = OVersionFactory.instance().createUntrackedVersion(); version.getSerializer().writeTo(out, version); out.write(recordType); } @Override public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { rid = new ORecordId(in.readUTF()); final int contentSize = in.readInt(); if (contentSize == 0) content = null; else { content = new byte[contentSize]; in.readFully(content); } if (version == null) version = OVersionFactory.instance().createUntrackedVersion(); version.getSerializer().readFrom(in, version); recordType = in.readByte(); } @Override public String getName() { return "record_create"; } }
0true
server_src_main_java_com_orientechnologies_orient_server_distributed_task_OCreateRecordTask.java
167
public interface SecureRequest { Permission getRequiredPermission(); }
0true
hazelcast_src_main_java_com_hazelcast_client_SecureRequest.java
330
Comparator<Object> nameCompare = new Comparator<Object>() { public int compare(Object arg0, Object arg1) { return ((Node) arg0).getNodeName().compareTo(((Node) arg1).getNodeName()); } };
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_handlers_AttributePreserveInsert.java
2,453
pool.execute(new Runnable() { public void run() { latch.countDown(); try { barrier.await(); barrier.await(); } catch (Throwable e) { barrier.reset(e); } } });
0true
src_test_java_org_elasticsearch_common_util_concurrent_EsExecutorsTests.java
6,304
public class MockFSDirectoryService extends FsDirectoryService { private final MockDirectoryHelper helper; private FsDirectoryService delegateService; @Inject public MockFSDirectoryService(ShardId shardId, @IndexSettings Settings indexSettings, IndexStore indexStore) { super(shardId, indexSettings, indexStore); helper = new MockDirectoryHelper(shardId, indexSettings, logger); delegateService = helper.randomDirectorService(indexStore); } @Override public Directory[] build() throws IOException { return helper.wrapAllInplace(delegateService.build()); } @Override protected synchronized FSDirectory newFSDirectory(File location, LockFactory lockFactory) throws IOException { throw new UnsupportedOperationException(); } }
1no label
src_test_java_org_elasticsearch_test_store_MockFSDirectoryService.java
752
public class MultiGetItemResponse implements Streamable { private GetResponse response; private MultiGetResponse.Failure failure; MultiGetItemResponse() { } public MultiGetItemResponse(GetResponse response, MultiGetResponse.Failure failure) { this.response = response; this.failure = failure; } /** * The index name of the document. */ public String getIndex() { if (failure != null) { return failure.getIndex(); } return response.getIndex(); } /** * The type of the document. */ public String getType() { if (failure != null) { return failure.getType(); } return response.getType(); } /** * The id of the document. */ public String getId() { if (failure != null) { return failure.getId(); } return response.getId(); } /** * Is this a failed execution? */ public boolean isFailed() { return failure != null; } /** * The actual get response, <tt>null</tt> if its a failure. */ public GetResponse getResponse() { return this.response; } /** * The failure if relevant. */ public MultiGetResponse.Failure getFailure() { return this.failure; } public static MultiGetItemResponse readItemResponse(StreamInput in) throws IOException { MultiGetItemResponse response = new MultiGetItemResponse(); response.readFrom(in); return response; } @Override public void readFrom(StreamInput in) throws IOException { if (in.readBoolean()) { failure = MultiGetResponse.Failure.readFailure(in); } else { response = new GetResponse(); response.readFrom(in); } } @Override public void writeTo(StreamOutput out) throws IOException { if (failure != null) { out.writeBoolean(true); failure.writeTo(out); } else { out.writeBoolean(false); response.writeTo(out); } } }
0true
src_main_java_org_elasticsearch_action_get_MultiGetItemResponse.java
240
highlighter = new XPostingsHighlighter() { @Override protected Passage[] getEmptyHighlight(String fieldName, BreakIterator bi, int maxPassages) { return new Passage[0]; } };
0true
src_test_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighterTests.java
262
@Inherited @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @TestGroup(enabled = true, sysProperty = SYSPROP_INTEGRATION) public @interface IntegrationTests { }
0true
src_test_java_org_apache_lucene_util_AbstractRandomizedTest.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
236
.registerHookValue(profilerPrefix + "current", "Number of entries in cache", METRIC_TYPE.SIZE, new OProfilerHookValue() { public Object getValue() { return getSize(); } }, profilerMetadataPrefix + "current");
0true
core_src_main_java_com_orientechnologies_orient_core_cache_OAbstractRecordCache.java
408
runConflictingTx(new TxJob() { @Override public void run(IndexTransaction tx) { tx.delete(defStore, defDoc, TEXT, ImmutableMap.of(), true); } }, new TxJob() {
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexProviderTest.java
818
public class ClearScrollResponse extends ActionResponse { private boolean succeeded; public ClearScrollResponse(boolean succeeded) { this.succeeded = succeeded; } ClearScrollResponse() { } public boolean isSucceeded() { return succeeded; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); succeeded = in.readBoolean(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeBoolean(succeeded); } }
1no label
src_main_java_org_elasticsearch_action_search_ClearScrollResponse.java
345
return new IShowInTargetList() { public String[] getShowInTargetIds() { return new String[] { JavaPlugin.ID_RES_NAV }; } };
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_explorer_PackageExplorerPart.java
978
public interface DiscreteOrderItemFeePrice extends Serializable { public abstract Long getId(); public abstract void setId(Long id); public DiscreteOrderItem getDiscreteOrderItem(); public void setDiscreteOrderItem(DiscreteOrderItem discreteOrderItem); public abstract Money getAmount(); public abstract void setAmount(Money amount); public abstract String getName(); public abstract void setName(String name); public abstract String getReportingCode(); public abstract void setReportingCode(String reportingCode); public DiscreteOrderItemFeePrice clone(); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_DiscreteOrderItemFeePrice.java
3,274
Collections.sort(ordsAndIds, new Comparator<OrdAndId>() { @Override public int compare(OrdAndId o1, OrdAndId o2) { if (o1.ord < o2.ord) { return -1; } if (o1.ord == o2.ord) { if (o1.id < o2.id) { return -1; } if (o1.id > o2.id) { return 1; } return 0; } return 1; } });
0true
src_test_java_org_elasticsearch_index_fielddata_ordinals_MultiOrdinalsTests.java
3,209
FLOAT(32, true, SortField.Type.FLOAT, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) { @Override public double toDouble(BytesRef indexForm) { return NumericUtils.sortableIntToFloat(NumericUtils.prefixCodedToInt(indexForm)); } @Override public void toIndexForm(Number number, BytesRef bytes) { NumericUtils.intToPrefixCodedBytes(NumericUtils.floatToSortableInt(number.floatValue()), 0, bytes); } @Override public Number toNumber(BytesRef indexForm) { return NumericUtils.sortableIntToFloat(NumericUtils.prefixCodedToInt(indexForm)); } },
0true
src_main_java_org_elasticsearch_index_fielddata_IndexNumericFieldData.java
311
private abstract class NodeStoreScan<RESULT, FAILURE extends Exception> implements StoreScan<FAILURE> { private volatile boolean continueScanning; protected abstract RESULT read( NodeRecord node ); protected abstract void process( RESULT result ) throws FAILURE; @Override public void run() throws FAILURE { PrimitiveLongIterator nodeIds = new StoreIdIterator( nodeStore ); continueScanning = true; while ( continueScanning && nodeIds.hasNext() ) { long id = nodeIds.next(); RESULT result = null; try ( Lock ignored = locks.acquireNodeLock( id, LockService.LockType.READ_LOCK ) ) { NodeRecord record = nodeStore.forceGetRecord( id ); if ( record.inUse() ) { result = read( record ); } } if ( result != null ) { process( result ); } } } @Override public void stop() { continueScanning = false; } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreIndexStoreView.java
400
static enum EvictionPolicy { NONE, LRU, LFU }
0true
hazelcast-client_src_main_java_com_hazelcast_client_nearcache_ClientNearCache.java
225
XPostingsHighlighter highlighter = new XPostingsHighlighter() { @Override protected BreakIterator getBreakIterator(String field) { return new WholeBreakIterator(); } @Override protected char getMultiValuedSeparator(String field) { //U+2029 PARAGRAPH SEPARATOR (PS): each value holds a discrete passage for highlighting return 8233; } };
0true
src_test_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighterTests.java
1,057
public static enum Flag { // Do not change the order of these flags we use // the ordinal for encoding! Only append to the end! Positions, Offsets, Payloads, FieldStatistics, TermStatistics; }
0true
src_main_java_org_elasticsearch_action_termvector_TermVectorRequest.java
349
SafeRunner.run(new ISafeRunnable() { public void run() throws Exception { fWorkingSetModel= new WorkingSetModel(fMemento); } public void handleException(Throwable exception) { fWorkingSetModel= new WorkingSetModel(null); } });
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_explorer_PackageExplorerPart.java
2,731
public static class NodeLocalGatewayMetaState extends NodeOperationResponse { private MetaData metaData; NodeLocalGatewayMetaState() { } public NodeLocalGatewayMetaState(DiscoveryNode node, MetaData metaData) { super(node); this.metaData = metaData; } public MetaData metaData() { return metaData; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); if (in.readBoolean()) { metaData = MetaData.Builder.readFrom(in); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); if (metaData == null) { out.writeBoolean(false); } else { out.writeBoolean(true); MetaData.Builder.writeTo(metaData, out); } } }
0true
src_main_java_org_elasticsearch_gateway_local_state_meta_TransportNodesListGatewayMetaState.java
1,333
public interface SolrHelperService { /** * Swaps the primary and reindex cores. * If the reindex core is null, we are operating in single core mode. In this scenario, no swap occurs. * * @throws ServiceException */ public void swapActiveCores() throws ServiceException; /** * Determines the current namespace we are operating on. For example, if you have multiple sites set up, * you may want to filter that here. * * <ul> * <li>Note: This method should ALWAYS return a non-empty string.</li> * </ul> * * @return the global namespace */ public String getCurrentNamespace(); /** * This property is needed to be non-null to allow filtering by multiple facets at one time and have the results * be an AND of the facets. Apart from being non-empty, the actual value does not matter. * * @return the non-empty global facet tag field */ public String getGlobalFacetTagField(); /** * Returns the property name for the given field, field type, and prefix * * @param field * @param searchableFieldType * @param prefix * @return the property name for the field and fieldtype */ public String getPropertyNameForFieldSearchable(Field field, FieldType searchableFieldType, String prefix); /** * Returns the property name for the given field, its configured facet field type, and the given prefix * * @param field * @param prefix * @return the property name for the facet type of this field */ public String getPropertyNameForFieldFacet(Field field, String prefix); /** * Returns the searchable field types for the given field. If there were none configured, will return * a list with TEXT FieldType. * * @param field * @return the searchable field types for the given field */ public List<FieldType> getSearchableFieldTypes(Field field); /** * Returns the property name for the given field and field type. This will apply the global prefix to the field, * and it will also apply either the locale prefix or the pricelist prefix, depending on whether or not the field * type was set to FieldType.PRICE * * @param field * @param searchableFieldType * @return the property name for the field and fieldtype */ public String getPropertyNameForFieldSearchable(Field field, FieldType searchableFieldType); /** * Returns the property name for the given field and its configured facet field type. This will apply the global prefix * to the field, and it will also apply either the locale prefix or the pricelist prefix, depending on whether or not * the field type was set to FieldType.PRICE * * @param field * @return the property name for the facet type of this field */ public String getPropertyNameForFieldFacet(Field field); /** * @param product * @return the Solr id of this product */ public String getSolrDocumentId(SolrInputDocument document, Product product); /** * @return the name of the field that keeps track what namespace this document belongs to */ public String getNamespaceFieldName(); /** * @return the id field name, with the global prefix as appropriate */ public String getIdFieldName(); /** * @return the productId field name */ public String getProductIdFieldName(); /** * @return the category field name, with the global prefix as appropriate */ public String getCategoryFieldName(); /** * @return the explicit category field name, with the global prefix as appropriate */ public String getExplicitCategoryFieldName(); /** * @param category * @return the default sort field name for this category */ public String getCategorySortFieldName(Category category); /** * Determines if there is a locale prefix that needs to be applied to the given field for this particular request. * By default, a locale prefix is not applicable for category, explicitCategory, or fields that have type Price. * Also, it is not applicable for non-translatable fields * * <ul> * <li>Note: This method should NOT return null. There must be a default locale configured.</li> * </ul> * * @return the global prefix if there is one, "" if there isn't */ public String getLocalePrefix(); /** * @return the default locale's prefix */ public String getDefaultLocalePrefix(); /** * Returns the default locale. Will cache the result for subsequent use. * * Note: There is no currently configured cache invalidation strategy for the the default locale. * Override this method to provide for one if you need it. * * @return the default locale */ public Locale getDefaultLocale(); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_service_solr_SolrHelperService.java
430
trackedMap.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { firedEvents.add(event); } });
0true
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedMapTest.java
1,125
public class OrderItemSplitContainer { protected OrderItem key; protected List<PromotableOrderItem> splitItems = new ArrayList<PromotableOrderItem>(); public OrderItem getKey() { return key; } public void setKey(OrderItem key) { this.key = key; } public List<PromotableOrderItem> getSplitItems() { return splitItems; } public void setSplitItems(List<PromotableOrderItem> splitItems) { this.splitItems = splitItems; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_manipulation_OrderItemSplitContainer.java
1,948
public class MapPutIfAbsentRequest extends MapPutRequest { public MapPutIfAbsentRequest() { } public MapPutIfAbsentRequest(String name, Data key, Data value, long threadId) { super(name, key, value, threadId); } public MapPutIfAbsentRequest(String name, Data key, Data value, long threadId, long ttl) { super(name, key, value, threadId, ttl); } public int getClassId() { return MapPortableHook.PUT_IF_ABSENT; } protected Operation prepareOperation() { PutIfAbsentOperation op = new PutIfAbsentOperation(name, key, value, ttl); op.setThreadId(threadId); return op; } }
0true
hazelcast_src_main_java_com_hazelcast_map_client_MapPutIfAbsentRequest.java
1,280
public class OPhysicalPositionSerializer implements OBinarySerializer<OPhysicalPosition> { public static final OPhysicalPositionSerializer INSTANCE = new OPhysicalPositionSerializer(); public static final byte ID = 50; @Override public int getObjectSize(OPhysicalPosition object, Object... hints) { return getFixedLength(); } @Override public int getObjectSize(byte[] stream, int startPosition) { return getFixedLength(); } @Override public void serialize(OPhysicalPosition object, byte[] stream, int startPosition, Object... hints) { int position = startPosition; OClusterPositionSerializer.INSTANCE.serialize(object.clusterPosition, stream, position); position += OClusterPositionSerializer.INSTANCE.getFixedLength(); object.recordVersion.getSerializer().writeTo(stream, position, object.recordVersion); position += OVersionFactory.instance().getVersionSize(); OIntegerSerializer.INSTANCE.serialize(object.dataSegmentId, stream, position); position += OIntegerSerializer.INT_SIZE; OIntegerSerializer.INSTANCE.serialize(object.recordSize, stream, position); position += OIntegerSerializer.INT_SIZE; OLongSerializer.INSTANCE.serialize(object.dataSegmentPos, stream, position); position += OLongSerializer.LONG_SIZE; OByteSerializer.INSTANCE.serialize(object.recordType, stream, position); } @Override public OPhysicalPosition deserialize(byte[] stream, int startPosition) { final OPhysicalPosition physicalPosition = new OPhysicalPosition(); int position = startPosition; physicalPosition.clusterPosition = OClusterPositionSerializer.INSTANCE.deserialize(stream, position); position += OClusterPositionSerializer.INSTANCE.getFixedLength(); final ORecordVersion version = OVersionFactory.instance().createVersion(); version.getSerializer().readFrom(stream, position, version); position += OVersionFactory.instance().getVersionSize(); physicalPosition.dataSegmentId = OIntegerSerializer.INSTANCE.deserialize(stream, position); position += OIntegerSerializer.INT_SIZE; physicalPosition.recordSize = OIntegerSerializer.INSTANCE.deserialize(stream, position); position += OIntegerSerializer.INT_SIZE; physicalPosition.dataSegmentPos = OLongSerializer.INSTANCE.deserialize(stream, position); position += OLongSerializer.LONG_SIZE; physicalPosition.recordType = OByteSerializer.INSTANCE.deserialize(stream, position); return physicalPosition; } @Override public byte getId() { return ID; } @Override public boolean isFixedLength() { return true; } @Override public int getFixedLength() { final int clusterPositionSize = OClusterPositionSerializer.INSTANCE.getFixedLength(); final int versionSize = OVersionFactory.instance().getVersionSize(); return clusterPositionSize + versionSize + 2 * OIntegerSerializer.INT_SIZE + OLongSerializer.LONG_SIZE + OByteSerializer.BYTE_SIZE; } @Override public void serializeNative(OPhysicalPosition object, byte[] stream, int startPosition, Object... hints) { int position = startPosition; OClusterPositionSerializer.INSTANCE.serializeNative(object.clusterPosition, stream, position); position += OClusterPositionSerializer.INSTANCE.getFixedLength(); object.recordVersion.getSerializer().fastWriteTo(stream, position, object.recordVersion); position += OVersionFactory.instance().getVersionSize(); OIntegerSerializer.INSTANCE.serializeNative(object.dataSegmentId, stream, position); position += OIntegerSerializer.INT_SIZE; OIntegerSerializer.INSTANCE.serializeNative(object.recordSize, stream, position); position += OIntegerSerializer.INT_SIZE; OLongSerializer.INSTANCE.serializeNative(object.dataSegmentPos, stream, position); position += OLongSerializer.LONG_SIZE; OByteSerializer.INSTANCE.serializeNative(object.recordType, stream, position); } @Override public OPhysicalPosition deserializeNative(byte[] stream, int startPosition) { final OPhysicalPosition physicalPosition = new OPhysicalPosition(); int position = startPosition; physicalPosition.clusterPosition = OClusterPositionSerializer.INSTANCE.deserializeNative(stream, position); position += OClusterPositionSerializer.INSTANCE.getFixedLength(); final ORecordVersion version = OVersionFactory.instance().createVersion(); version.getSerializer().fastReadFrom(stream, position, version); position += OVersionFactory.instance().getVersionSize(); physicalPosition.dataSegmentId = OIntegerSerializer.INSTANCE.deserializeNative(stream, position); position += OIntegerSerializer.INT_SIZE; physicalPosition.recordSize = OIntegerSerializer.INSTANCE.deserializeNative(stream, position); position += OIntegerSerializer.INT_SIZE; physicalPosition.dataSegmentPos = OLongSerializer.INSTANCE.deserializeNative(stream, position); position += OLongSerializer.LONG_SIZE; physicalPosition.recordType = OByteSerializer.INSTANCE.deserializeNative(stream, position); return physicalPosition; } @Override public int getObjectSizeNative(byte[] stream, int startPosition) { return getFixedLength(); } @Override public void serializeInDirectMemory(OPhysicalPosition object, ODirectMemoryPointer pointer, long offset, Object... hints) { long currentOffset = offset; OClusterPositionSerializer.INSTANCE.serializeInDirectMemory(object.clusterPosition, pointer, currentOffset); currentOffset += OClusterPositionSerializer.INSTANCE.getFixedLength(); byte[] serializedVersion = new byte[OVersionFactory.instance().getVersionSize()]; object.recordVersion.getSerializer().fastWriteTo(serializedVersion, 0, object.recordVersion); pointer.set(currentOffset, serializedVersion, 0, serializedVersion.length); currentOffset += OVersionFactory.instance().getVersionSize(); OIntegerSerializer.INSTANCE.serializeInDirectMemory(object.dataSegmentId, pointer, currentOffset); currentOffset += OIntegerSerializer.INT_SIZE; OIntegerSerializer.INSTANCE.serializeInDirectMemory(object.recordSize, pointer, currentOffset); currentOffset += OIntegerSerializer.INT_SIZE; OLongSerializer.INSTANCE.serializeInDirectMemory(object.dataSegmentPos, pointer, currentOffset); currentOffset += OLongSerializer.LONG_SIZE; OByteSerializer.INSTANCE.serializeInDirectMemory(object.recordType, pointer, currentOffset); } @Override public OPhysicalPosition deserializeFromDirectMemory(ODirectMemoryPointer pointer, long offset) { final OPhysicalPosition physicalPosition = new OPhysicalPosition(); long currentPointer = offset; physicalPosition.clusterPosition = OClusterPositionSerializer.INSTANCE.deserializeFromDirectMemory(pointer, currentPointer); currentPointer += OClusterPositionSerializer.INSTANCE.getFixedLength(); final ORecordVersion version = OVersionFactory.instance().createVersion(); byte[] serializedVersion = pointer.get(currentPointer, OVersionFactory.instance().getVersionSize()); version.getSerializer().fastReadFrom(serializedVersion, 0, version); physicalPosition.recordVersion = version; currentPointer += OVersionFactory.instance().getVersionSize(); physicalPosition.dataSegmentId = OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(pointer, currentPointer); currentPointer += OIntegerSerializer.INT_SIZE; OIntegerSerializer.INSTANCE.deserializeFromDirectMemory(pointer, currentPointer); currentPointer += OIntegerSerializer.INT_SIZE; physicalPosition.dataSegmentPos = OLongSerializer.INSTANCE.deserializeFromDirectMemory(pointer, currentPointer); currentPointer += OLongSerializer.LONG_SIZE; physicalPosition.recordType = OByteSerializer.INSTANCE.deserializeFromDirectMemory(pointer, currentPointer); return physicalPosition; } @Override public int getObjectSizeInDirectMemory(ODirectMemoryPointer pointer, long offset) { return getFixedLength(); } @Override public OPhysicalPosition preprocess(OPhysicalPosition value, Object... hints) { return value; } }
0true
core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_eh_OPhysicalPositionSerializer.java
461
public class CeylonNavigatorContentProvider implements IPipelinedTreeContentProvider2, ICeylonModelListener { private org.eclipse.ui.navigator.IExtensionStateModel javaNavigatorStateModel; private boolean isFlatLayout() { return javaNavigatorStateModel.getBooleanProperty(Values.IS_LAYOUT_FLAT); } @SuppressWarnings({"rawtypes", "unchecked"}) @Override public void getPipelinedChildren(Object aParent, Set theCurrentChildren) { if (aParent instanceof IJavaProject) { aParent = ((IJavaProject) aParent).getProject(); } if (aParent instanceof IProject) { IProject project = (IProject) aParent; Map<String, RepositoryNode> repositories = getProjectRepositoryNodes(project); List<Object> toRemove = new ArrayList<>(); for (Object child : theCurrentChildren) { if (child instanceof ClassPathContainer) { toRemove.add(child); ClassPathContainer cpContainer = (ClassPathContainer) child; for (IAdaptable entry : cpContainer.getChildren()) { if (entry instanceof IPackageFragmentRoot) { IPackageFragmentRoot pfr = (IPackageFragmentRoot) entry; for (RepositoryNode rn : repositories.values()) { for (ExternalModuleNode emn : rn.getModules()) { if (emn.getModule() != null && emn.getModule() .getPackageFragmentRoots() .contains(pfr)) { emn.getBinaryArchives().add(pfr); } } } } if (entry instanceof RequiredProjectWrapper) { System.out.print(""); } } } if (child instanceof LibraryContainer) { toRemove.add(child); } } theCurrentChildren.removeAll(toRemove); for (RepositoryNode repoNode : repositories.values()) { theCurrentChildren.add(repoNode); } } if (aParent instanceof IPackageFragmentRoot) { IPackageFragmentRoot root = (IPackageFragmentRoot) aParent; if (CeylonBuilder.isSourceFolder(root)) { Map<String, SourceModuleNode> moduleNodes = getSourceDirectoryModules(root); List<Object> toRemove = new ArrayList<Object>(); for (Object child : theCurrentChildren) { if (child instanceof IPackageFragment) { toRemove.add(child); } else { if (child instanceof IFile) { toRemove.add(child); } } } theCurrentChildren.removeAll(toRemove); try { for (IJavaElement pfElement : root.getChildren()) { IPackageFragment child = (IPackageFragment) pfElement; IFolder pkgFolder = (IFolder) ((IPackageFragment) child).getResource(); Package pkg = CeylonBuilder.getPackage(pkgFolder); if (pkg != null) { Module module = pkg.getModule(); String signature = module.getSignature(); SourceModuleNode moduleNode = moduleNodes.get(signature); if (moduleNode != null) { if (! isFlatLayout() && ! module.isDefault() && ! pkg.getNameAsString().equals(module.getNameAsString())) { continue; } moduleNode.getPackageFragments().add((IPackageFragment) child); } } } } catch (JavaModelException e) { e.printStackTrace(); } for (SourceModuleNode moduleNode : moduleNodes.values()) { theCurrentChildren.add(moduleNode); } } } if (aParent instanceof IPackageFragment) { if (!(aParent instanceof SourceModuleNode)) { IPackageFragment pkgFragment = (IPackageFragment) aParent; IPackageFragmentRoot root = (IPackageFragmentRoot) pkgFragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); if (root != null) { IFolder rootFolder = null; try { rootFolder = (IFolder) root.getCorrespondingResource(); } catch (JavaModelException e) { e.printStackTrace(); } if (rootFolder != null && RootFolderType.SOURCE.equals(CeylonBuilder.getRootFolderType(root))) { if (pkgFragment.isDefaultPackage()) { try { for (IResource r : rootFolder.members()) { if (r instanceof IFile && ! JavaCore.isJavaLikeFileName(r.getName())) { theCurrentChildren.add((IFile)r); } } } catch (CoreException e) { e.printStackTrace(); } } else { JDTModule fragmentModule = CeylonBuilder.getModule(pkgFragment); if (fragmentModule != null) { for (Iterator<Object> itr = theCurrentChildren.iterator(); itr.hasNext(); ) { Object child = itr.next(); if (child instanceof IPackageFragment) { IPackageFragment childPkg = (IPackageFragment) child; if (! fragmentModule.equals(CeylonBuilder.getModule(childPkg))) { itr.remove(); } } } } } } } } else { theCurrentChildren.clear(); theCurrentChildren.addAll(((SourceModuleNode)aParent).getPackageFragments()); } } } private synchronized Map<String, RepositoryNode> getProjectRepositoryNodes(IProject project) { RepositoryManager repoManager = CeylonBuilder.getProjectRepositoryManager(project); Map<String, RepositoryNode> repositories = new LinkedHashMap<>(); for (String displayString : repoManager.getRepositoriesDisplayString()) { repositories.put(displayString, new RepositoryNode(project, displayString)); } RepositoryNode unknownRepositoryNode = new RepositoryNode(project, NodeUtils.UNKNOWN_REPOSITORY); repositories.put(NodeUtils.UNKNOWN_REPOSITORY, unknownRepositoryNode); for (JDTModule externalModule : CeylonBuilder.getProjectExternalModules(project)) { if (! externalModule.isAvailable()) { continue; } String repoDisplayString = externalModule.getRepositoryDisplayString(); if (repositories.containsKey(repoDisplayString)) { repositories.get(repoDisplayString).addModule(externalModule); } else { unknownRepositoryNode.addModule(externalModule); } } return repositories; } private synchronized Map<String, SourceModuleNode> getSourceDirectoryModules(IPackageFragmentRoot sourceRoot) { Map<String, SourceModuleNode> sourceDirectoryModules = new LinkedHashMap<>(); for (Module m : CeylonBuilder.getProjectSourceModules(sourceRoot.getJavaProject().getProject())) { if (m instanceof JDTModule) { JDTModule module = (JDTModule) m; if (module.getPackageFragmentRoots().contains(sourceRoot)) { String signature = module.getSignature(); SourceModuleNode sourceModuleNode = sourceDirectoryModules.get(signature); if (sourceModuleNode == null) { sourceModuleNode = SourceModuleNode.createSourceModuleNode(sourceRoot, signature); sourceDirectoryModules.put(signature, sourceModuleNode); } } } } return sourceDirectoryModules; } @Override @SuppressWarnings("rawtypes") public void getPipelinedElements(Object anInput, Set theCurrentElements) {} @Override public Object getPipelinedParent(Object anObject, Object aSuggestedParent) { if (anObject instanceof IPackageFragmentRoot) { IPackageFragmentRoot pfr = (IPackageFragmentRoot) anObject; if (aSuggestedParent instanceof ClassPathContainer) { IProject project = pfr.getJavaProject().getProject(); Map<String, RepositoryNode> repositories = getProjectRepositoryNodes(project); for (RepositoryNode rn : repositories.values()) { for (ExternalModuleNode emn : rn.getModules()) { if (emn.getModule() .getPackageFragmentRoots() .contains(pfr)) { return rn; } } } return null; } } if (anObject instanceof IPackageFragment) { if ( !(anObject instanceof SourceModuleNode)) { IPackageFragment pkgFragment = (IPackageFragment) anObject; IPackageFragmentRoot root = (IPackageFragmentRoot) pkgFragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); Map<String, SourceModuleNode> moduleNodes = getSourceDirectoryModules(root); if (CeylonBuilder.isSourceFolder(root)) { if (aSuggestedParent instanceof IPackageFragmentRoot) { JDTModule module = CeylonBuilder.getModule(pkgFragment); if (module != null) { return moduleNodes.get(module.getSignature()); } } if (aSuggestedParent instanceof IPackageFragment) { JDTModule module = CeylonBuilder.getModule(pkgFragment); if (module != null) { JDTModule parentModule = CeylonBuilder.getModule((IPackageFragment)aSuggestedParent); if (! module.equals(parentModule)) { String signature = module.getSignature(); return moduleNodes.get(signature); } } } } } else { return ((SourceModuleNode)anObject).getSourceFolder(); } } if (anObject instanceof IFile && aSuggestedParent instanceof IPackageFragmentRoot) { IPackageFragmentRoot root = (IPackageFragmentRoot) aSuggestedParent; try { for (IJavaElement je : root.getChildren()) { if (((IPackageFragment)je).isDefaultPackage()) { return je; } } } catch (JavaModelException e) { e.printStackTrace(); } } return aSuggestedParent; } /* (non-Javadoc) * @see org.eclipse.ui.navigator.IPipelinedTreeContentProvider#interceptAdd(org.eclipse.ui.navigator.PipelinedShapeModification) */ @Override public PipelinedShapeModification interceptAdd( PipelinedShapeModification aShapeModification) { Object aParent = aShapeModification.getParent(); @SuppressWarnings("rawtypes") Set changedChildren = aShapeModification.getChildren(); /* * IProject - ClassPathContainer * => remove the modification and refresh project */ if (aParent instanceof IProject) { for (Object child : changedChildren) { if (child instanceof ClassPathContainer) { aShapeModification.getChildren().clear(); scheduleRefresh(aParent); return aShapeModification; } } } /* * ClassPathContainer - IPackageFragmentRoot * => * Calculate the parent module for each root. * - If only on parent module => add ExternalModuleNode - IPackageFragmentRoot (What happens if the module didn't exist before ??) * - Else refresh on project * */ if (aParent instanceof ClassPathContainer) { replaceParentOrScheduleRefresh(aShapeModification, aParent, changedChildren, ((ClassPathContainer)aParent).getJavaProject().getProject()); return aShapeModification; } /* IPackageFragmentRoot - IPackageFragment * => Calculate the parent source module for each fragment. - If only on parent module => add sourceModule - IPackageFragment * (What happens if the module didn't exist before ??) - Else refresh on the IPackageFragmentRoot IPackageFragmentRoot - IFile * => add defaultPackage - IFile (What happens if the default module wasn't displayed before ??) */ if (aParent instanceof IPackageFragmentRoot) { IPackageFragmentRoot root = (IPackageFragmentRoot) aParent; if (CeylonBuilder.isSourceFolder(root)) { replaceParentOrScheduleRefresh(aShapeModification, aParent, changedChildren, aParent); } return aShapeModification; } return aShapeModification; } @SuppressWarnings("rawtypes") private void replaceParentOrScheduleRefresh( PipelinedShapeModification shapeModification, Object parent, Set addedChildren, Object nodeToRefresh) { Object newParent = null; for (Object child : addedChildren) { Object currentParent = getPipelinedParent(child, parent); if (currentParent == null) { currentParent = getParent(child); } if (newParent == null) { newParent = currentParent; } else { if (! newParent.equals(currentParent)) { // Several new parents // Cancel the addition and refresh the project newParent = null; break; } } } if (newParent == null) { shapeModification.getChildren().clear(); scheduleRefresh(nodeToRefresh); } else { shapeModification.setParent(newParent); } } private void scheduleRefresh(final Object aParent) { if (viewer != null) { UIJob refreshJob = new UIJob("Refresh Viewer") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { viewer.refresh(aParent); return Status.OK_STATUS; } }; refreshJob.setSystem(true); refreshJob.schedule(); } } @Override public PipelinedShapeModification interceptRemove( PipelinedShapeModification aRemoveModification) { return aRemoveModification; } @Override @SuppressWarnings("unchecked") public boolean interceptRefresh( PipelinedViewerUpdate aRefreshSynchronization) { ClassPathContainer aClassPathContainer = null; for (Object target : aRefreshSynchronization.getRefreshTargets()) { if (target instanceof ClassPathContainer) { aClassPathContainer = (ClassPathContainer)target; break; } } if (aClassPathContainer != null) { aRefreshSynchronization.getRefreshTargets().clear(); aRefreshSynchronization.getRefreshTargets().addAll(getProjectRepositoryNodes(aClassPathContainer.getJavaProject().getProject()).values()); return true; } return false; } @Override public boolean interceptUpdate(PipelinedViewerUpdate anUpdateSynchronization) { return false; } @Override public void init(ICommonContentExtensionSite aConfig) { CeylonBuilder.addModelListener(this); INavigatorContentExtension javaNavigatorExtension = null; @SuppressWarnings("unchecked") Set<INavigatorContentExtension> set = aConfig.getService().findContentExtensionsByTriggerPoint(JavaCore.create(ResourcesPlugin.getWorkspace().getRoot())); for (INavigatorContentExtension extension : set) { if (extension.getDescriptor().equals(aConfig.getExtension().getDescriptor().getOverriddenDescriptor())) { javaNavigatorExtension = extension; break; } } ITreeContentProvider javaContentProvider = javaNavigatorExtension.getContentProvider(); if (javaContentProvider instanceof PackageExplorerContentProvider) { ((PackageExplorerContentProvider) javaContentProvider).setShowLibrariesNode(true); } javaNavigatorStateModel = javaNavigatorExtension.getStateModel(); final INavigatorFilterService filterService = aConfig.getService().getFilterService(); final List<String> filtersToActivate = new ArrayList<>(); for (ICommonFilterDescriptor descriptor : filterService.getVisibleFilterDescriptors()) { String filterId = descriptor.getId(); if (filterService.isActive(filterId)) { if (filterId.equals("org.eclipse.jdt.java.ui.filters.HideEmptyPackages")) { filtersToActivate.add("com.redhat.ceylon.eclipse.ui.navigator.filters.HideEmptyPackages"); } else if (filterId.equals("org.eclipse.jdt.java.ui.filters.HideEmptyInnerPackages")) { filtersToActivate.add("com.redhat.ceylon.eclipse.ui.navigator.filters.HideEmptyInnerPackages"); } else { filtersToActivate.add(filterId); } } } UIJob changeJDTEmptyFiltersJob = new UIJob("Change JDT Empty Filters") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { filterService.activateFilterIdsAndUpdateViewer(filtersToActivate.toArray(new String[0])); return Status.OK_STATUS; } }; changeJDTEmptyFiltersJob.setSystem(true); changeJDTEmptyFiltersJob.schedule(); } @Override public Object[] getElements(Object inputElement) { System.out.print(""); return new Object[0]; } @Override public Object[] getChildren(Object parentElement) { if (parentElement instanceof RepositoryNode) { return ((RepositoryNode)parentElement).getModules().toArray(); } if (parentElement instanceof ExternalModuleNode) { ExternalModuleNode moduleNode = (ExternalModuleNode) parentElement; ArrayList<Object> result = new ArrayList<Object>(moduleNode.getBinaryArchives().size() + (moduleNode.getSourceArchive() != null ? 1 : 0)); if (moduleNode.getSourceArchive() != null) { result.add(moduleNode.getSourceArchive()); } result.addAll(moduleNode.getBinaryArchives()); return result.toArray(); } if (parentElement instanceof SourceModuleNode) { return ((SourceModuleNode)parentElement).getPackageFragments().toArray(); } if (parentElement instanceof CeylonArchiveFileStore) { CeylonArchiveFileStore archiveFileStore = (CeylonArchiveFileStore)parentElement; List<Object> children = new ArrayList<Object>(); try { for (IFileStore child : archiveFileStore.childStores(EFS.NONE, null)) { CeylonArchiveFileStore childFileStore = (CeylonArchiveFileStore)child; children.add(childFileStore); } } catch (CoreException e) { e.printStackTrace(); } return children.toArray(); } return new Object[0]; } @Override public Object getParent(Object element) { if (element instanceof RepositoryNode) { return ((RepositoryNode)element).project; } if (element instanceof ExternalModuleNode) { return ((ExternalModuleNode)element).getRepositoryNode(); } if (element instanceof SourceModuleNode) { return ((SourceModuleNode)element).getSourceFolder(); } if (element instanceof CeylonArchiveFileStore) { CeylonArchiveFileStore archiveFileStore = (CeylonArchiveFileStore) element; if (archiveFileStore.getParent() == null) { // it's the archive root for (IProject project: CeylonBuilder.getProjects()) { for (RepositoryNode repoNode: getProjectRepositoryNodes(project).values()) { for (ExternalModuleNode moduleNode: repoNode.getModules()) { CeylonArchiveFileStore sourceArchive = moduleNode.getSourceArchive(); if (sourceArchive!=null && sourceArchive.equals(archiveFileStore)) { return moduleNode; } } } } } else { return ((CeylonArchiveFileStore) element).getParent(); } } return null; } @Override public boolean hasChildren(Object element) { if (element instanceof RepositoryNode) { return ! ((RepositoryNode)element).getModules().isEmpty(); } if (element instanceof ExternalModuleNode) { return ! ((ExternalModuleNode)element).getBinaryArchives().isEmpty() || ((ExternalModuleNode)element).getSourceArchive() != null; } if (element instanceof SourceModuleNode) { SourceModuleNode sourceModuleNode = (SourceModuleNode) element; return sourceModuleNode.getPackageFragments().size() > 0; } if (element instanceof CeylonArchiveFileStore) { try { return ((CeylonArchiveFileStore) element).childNames(EFS.NONE, null).length > 0; } catch (CoreException e) { e.printStackTrace(); } } return false; } @Override public void dispose() { CeylonBuilder.removeModelListener(this); } private StructuredViewer viewer = null; @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { this.viewer = (StructuredViewer) viewer; } @Override public void restoreState(IMemento aMemento) { } @Override public void saveState(IMemento aMemento) { } @Override public boolean hasPipelinedChildren(Object anInput, boolean currentHasChildren) { if (anInput instanceof SourceModuleNode) { SourceModuleNode sourceModuleNode = (SourceModuleNode) anInput; return sourceModuleNode.getPackageFragments().size() > 0; } if (anInput instanceof IPackageFragment) { IPackageFragment pkgFragment = (IPackageFragment) anInput; IPackageFragmentRoot root = (IPackageFragmentRoot) pkgFragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); if (pkgFragment.isDefaultPackage() && root != null) { IFolder rootFolder = null; try { rootFolder = (IFolder) root.getCorrespondingResource(); } catch (JavaModelException e) { e.printStackTrace(); } if (rootFolder != null && CeylonBuilder.isSourceFolder(root)) { try { for (IResource r : rootFolder.members()) { if (r instanceof IFile) { return true; } } } catch (JavaModelException e) { e.printStackTrace(); } catch (CoreException e) { e.printStackTrace(); } } } } return currentHasChildren; } @Override public void modelParsed(IProject project) { if (project != null) { try { for (IPackageFragmentRoot pfr : JavaCore.create(project).getAllPackageFragmentRoots()) { if (CeylonBuilder.isSourceFolder(pfr)) { scheduleRefresh(pfr); } } } catch (JavaModelException e) { e.printStackTrace(); } } } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_navigator_CeylonNavigatorContentProvider.java
2,355
public class JobSupervisor { private final ConcurrentMap<Object, Reducer> reducers = new ConcurrentHashMap<Object, Reducer>(); private final ConcurrentMap<Integer, Set<Address>> remoteReducers = new ConcurrentHashMap<Integer, Set<Address>>(); private final AtomicReference<DefaultContext> context = new AtomicReference<DefaultContext>(); private final ConcurrentMap<Object, Address> keyAssignments = new ConcurrentHashMap<Object, Address>(); private final Address jobOwner; private final boolean ownerNode; private final AbstractJobTracker jobTracker; private final JobTaskConfiguration configuration; private final MapReduceService mapReduceService; private final ExecutorService executorService; private final JobProcessInformationImpl jobProcessInformation; public JobSupervisor(JobTaskConfiguration configuration, AbstractJobTracker jobTracker, boolean ownerNode, MapReduceService mapReduceService) { this.jobTracker = jobTracker; this.ownerNode = ownerNode; this.configuration = configuration; this.mapReduceService = mapReduceService; this.jobOwner = configuration.getJobOwner(); this.executorService = mapReduceService.getExecutorService(configuration.getName()); // Calculate partition count this.jobProcessInformation = createJobProcessInformation(configuration, this); // Preregister reducer task to handle immediate reducing events String name = configuration.getName(); String jobId = configuration.getJobId(); jobTracker.registerReducerTask(new ReducerTask(name, jobId, this)); } public MapReduceService getMapReduceService() { return mapReduceService; } public JobTracker getJobTracker() { return jobTracker; } public void startTasks(MappingPhase mappingPhase) { // Start map-combiner tasks jobTracker.registerMapCombineTask(new MapCombineTask(configuration, this, mappingPhase)); } public void onNotification(MapReduceNotification notification) { if (notification instanceof IntermediateChunkNotification) { IntermediateChunkNotification icn = (IntermediateChunkNotification) notification; ReducerTask reducerTask = jobTracker.getReducerTask(icn.getJobId()); reducerTask.processChunk(icn.getChunk()); } else if (notification instanceof LastChunkNotification) { LastChunkNotification lcn = (LastChunkNotification) notification; ReducerTask reducerTask = jobTracker.getReducerTask(lcn.getJobId()); reducerTask.processChunk(lcn.getPartitionId(), lcn.getSender(), lcn.getChunk()); } else if (notification instanceof ReducingFinishedNotification) { ReducingFinishedNotification rfn = (ReducingFinishedNotification) notification; processReducerFinished(rfn); } } public void notifyRemoteException(Address remoteAddress, Throwable throwable) { // Cancel all partition states jobProcessInformation.cancelPartitionState(); // Notify all other nodes about cancellation Set<Address> addresses = collectRemoteAddresses(); // Now notify all involved members to cancel the job cancelRemoteOperations(addresses); // Cancel local job TrackableJobFuture future = cancel(); if (future != null) { // Might be already cancelled by another members exception ExceptionUtil.fixRemoteStackTrace(throwable, Thread.currentThread().getStackTrace(), "Operation failed on node: " + remoteAddress); future.setResult(throwable); } } public boolean cancelAndNotify(Exception exception) { // Cancel all partition states jobProcessInformation.cancelPartitionState(); // Notify all other nodes about cancellation Set<Address> addresses = collectRemoteAddresses(); // Now notify all involved members to cancel the job cancelRemoteOperations(addresses); // Cancel local job TrackableJobFuture future = cancel(); if (future != null) { // Might be already cancelled by another members exception future.setResult(exception); } return true; } // TODO Not yet fully supported public boolean cancelNotifyAndRestart() { // Cancel all partition states jobProcessInformation.cancelPartitionState(); // Notify all other nodes about cancellation Set<Address> addresses = collectRemoteAddresses(); // Now notify all involved members to cancel the job cancelRemoteOperations(addresses); // Kill local tasks String jobId = getConfiguration().getJobId(); MapCombineTask mapCombineTask = jobTracker.unregisterMapCombineTask(jobId); if (mapCombineTask != null) { mapCombineTask.cancel(); } ReducerTask reducerTask = jobTracker.unregisterReducerTask(jobId); if (reducerTask != null) { reducerTask.cancel(); } // Reset local data jobProcessInformation.resetPartitionState(); reducers.clear(); remoteReducers.clear(); context.set(null); keyAssignments.clear(); // Restart // TODO restart with a new KeyValueJob return true; } public TrackableJobFuture cancel() { String jobId = getConfiguration().getJobId(); TrackableJobFuture future = jobTracker.unregisterTrackableJob(jobId); MapCombineTask mapCombineTask = jobTracker.unregisterMapCombineTask(jobId); if (mapCombineTask != null) { mapCombineTask.cancel(); } ReducerTask reducerTask = jobTracker.unregisterReducerTask(jobId); if (reducerTask != null) { reducerTask.cancel(); } mapReduceService.destroyJobSupervisor(this); return future; } public Map<Object, Object> getJobResults() { Map<Object, Object> result; if (configuration.getReducerFactory() != null) { int mapsize = MapReduceUtil.mapSize(reducers.size()); result = new HashMap<Object, Object>(mapsize); for (Map.Entry<Object, Reducer> entry : reducers.entrySet()) { result.put(entry.getKey(), entry.getValue().finalizeReduce()); } } else { DefaultContext currentContext = context.get(); result = currentContext.finish(); } return result; } public <KeyIn, ValueIn, ValueOut> Reducer<KeyIn, ValueIn, ValueOut> getReducerByKey(Object key) { Reducer reducer = reducers.get(key); if (reducer == null && configuration.getReducerFactory() != null) { reducer = configuration.getReducerFactory().newReducer(key); Reducer oldReducer = reducers.putIfAbsent(key, reducer); if (oldReducer != null) { reducer = oldReducer; } else { reducer.beginReduce(key); } } return reducer; } public Address getReducerAddressByKey(Object key) { Address address = keyAssignments.get(key); if (address != null) { return address; } return null; } public Address assignKeyReducerAddress(Object key) { // Assign new key to a known member Address address = keyAssignments.get(key); if (address == null) { address = mapReduceService.getKeyMember(key); Address oldAddress = keyAssignments.putIfAbsent(key, address); if (oldAddress != null) { address = oldAddress; } } return address; } public boolean checkAssignedMembersAvailable() { return mapReduceService.checkAssignedMembersAvailable(keyAssignments.values()); } public boolean assignKeyReducerAddress(Object key, Address address) { Address oldAssignment = keyAssignments.putIfAbsent(key, address); return oldAssignment == null || oldAssignment.equals(address); } public void checkFullyProcessed(JobProcessInformation processInformation) { if (isOwnerNode()) { JobPartitionState[] partitionStates = processInformation.getPartitionStates(); for (JobPartitionState partitionState : partitionStates) { if (partitionState == null || partitionState.getState() != JobPartitionState.State.PROCESSED) { return; } } String name = configuration.getName(); String jobId = configuration.getJobId(); NodeEngine nodeEngine = configuration.getNodeEngine(); GetResultOperationFactory operationFactory = new GetResultOperationFactory(name, jobId); List<Map> results = MapReduceUtil.executeOperation(operationFactory, mapReduceService, nodeEngine, true); boolean reducedResult = configuration.getReducerFactory() != null; if (results != null) { Map<Object, Object> mergedResults = new HashMap<Object, Object>(); for (Map<?, ?> map : results) { for (Map.Entry entry : map.entrySet()) { collectResults(reducedResult, mergedResults, entry); } } // Get the initial future object to eventually set the result and cleanup TrackableJobFuture future = jobTracker.unregisterTrackableJob(jobId); jobTracker.unregisterMapCombineTask(jobId); jobTracker.unregisterReducerTask(jobId); mapReduceService.destroyJobSupervisor(this); future.setResult(mergedResults); } } } public <K, V> DefaultContext<K, V> getOrCreateContext(MapCombineTask mapCombineTask) { DefaultContext<K, V> newContext = new DefaultContext<K, V>(configuration.getCombinerFactory(), mapCombineTask); if (context.compareAndSet(null, newContext)) { return newContext; } return context.get(); } public void registerReducerEventInterests(int partitionId, Set<Address> remoteReducers) { Set<Address> addresses = this.remoteReducers.get(partitionId); if (addresses == null) { addresses = new CopyOnWriteArraySet<Address>(); Set<Address> oldSet = this.remoteReducers.putIfAbsent(partitionId, addresses); if (oldSet != null) { addresses = oldSet; } } addresses.addAll(remoteReducers); } public Collection<Address> getReducerEventInterests(int partitionId) { return this.remoteReducers.get(partitionId); } public JobProcessInformationImpl getJobProcessInformation() { return jobProcessInformation; } public Address getJobOwner() { return jobOwner; } public boolean isOwnerNode() { return ownerNode; } public JobTaskConfiguration getConfiguration() { return configuration; } private void collectResults(boolean reducedResult, Map<Object, Object> mergedResults, Map.Entry entry) { if (reducedResult) { mergedResults.put(entry.getKey(), entry.getValue()); } else { List<Object> list = (List) mergedResults.get(entry.getKey()); if (list == null) { list = new ArrayList<Object>(); mergedResults.put(entry.getKey(), list); } for (Object value : (List) entry.getValue()) { list.add(value); } } } private Set<Address> collectRemoteAddresses() { Set<Address> addresses = new HashSet<Address>(); for (Set<Address> remoteReducerAddresses : remoteReducers.values()) { addAllFilterJobOwner(addresses, remoteReducerAddresses); } for (JobPartitionState partitionState : jobProcessInformation.getPartitionStates()) { if (partitionState != null && partitionState.getOwner() != null) { if (!partitionState.getOwner().equals(jobOwner)) { addresses.add(partitionState.getOwner()); } } } return addresses; } private void cancelRemoteOperations(Set<Address> addresses) { String name = getConfiguration().getName(); String jobId = getConfiguration().getJobId(); for (Address address : addresses) { try { CancelJobSupervisorOperation operation = new CancelJobSupervisorOperation(name, jobId); mapReduceService.processRequest(address, operation, name); } catch (Exception ignore) { // We can ignore this exception since we just want to cancel the job // and the member may be crashed or unreachable in some way ILogger logger = mapReduceService.getNodeEngine().getLogger(JobSupervisor.class); logger.finest("Remote node may already be down", ignore); } } } private void processReducerFinished(final ReducingFinishedNotification notification) { // Just offload it to free the event queue executorService.submit(new Runnable() { @Override public void run() { processReducerFinished0(notification); } }); } private void addAllFilterJobOwner(Set<Address> target, Set<Address> source) { for (Address address : source) { if (jobOwner.equals(address)) { continue; } target.add(address); } } private void processReducerFinished0(ReducingFinishedNotification notification) { String name = configuration.getName(); String jobId = configuration.getJobId(); int partitionId = notification.getPartitionId(); Address reducerAddress = notification.getAddress(); if (checkPartitionReductionCompleted(partitionId, reducerAddress)) { try { RequestPartitionResult result = mapReduceService .processRequest(jobOwner, new RequestPartitionProcessed(name, jobId, partitionId, REDUCING), name); if (result.getResultState() != SUCCESSFUL) { throw new RuntimeException("Could not finalize processing for partitionId " + partitionId); } } catch (Throwable t) { MapReduceUtil.notifyRemoteException(this, t); if (t instanceof Error) { ExceptionUtil.sneakyThrow(t); } } } } private boolean checkPartitionReductionCompleted(int partitionId, Address reducerAddress) { Set<Address> remoteAddresses = remoteReducers.get(partitionId); if (remoteAddresses == null) { throw new RuntimeException("Reducer for partition " + partitionId + " not registered"); } remoteAddresses.remove(reducerAddress); if (remoteAddresses.size() == 0) { if (remoteReducers.remove(partitionId) != null) { return true; } } return false; } }
1no label
hazelcast_src_main_java_com_hazelcast_mapreduce_impl_task_JobSupervisor.java
903
public interface ORecordStringable { public String value(); public ORecordStringable value(String iValue); }
0true
core_src_main_java_com_orientechnologies_orient_core_record_ORecordStringable.java
83
public static class Order { public static final int File_Details = 2000; public static final int Advanced = 3000; }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_domain_StaticAssetImpl.java
1,599
public class OperationRoutingModule extends AbstractModule implements SpawnModules { private final Settings settings; public OperationRoutingModule(Settings settings) { this.settings = settings; } @Override public Iterable<? extends Module> spawnModules() { return ImmutableList.of(createModule(settings.getAsClass("cluster.routing.operation.type", PlainOperationRoutingModule.class, "org.elasticsearch.cluster.routing.operation.", "OperationRoutingModule"), settings)); } @Override protected void configure() { bind(HashFunction.class).to(settings.getAsClass("cluster.routing.operation.hash.type", DjbHashFunction.class, "org.elasticsearch.cluster.routing.operation.hash.", "HashFunction")).asEagerSingleton(); } }
0true
src_main_java_org_elasticsearch_cluster_routing_operation_OperationRoutingModule.java
242
private static class Comparison { private final Collection<Field> fields = new ArrayList<Field>(); Comparison( Class<?> type ) { for ( Field field : type.getDeclaredFields() ) { if ( field.getDeclaringClass() == type ) { field.setAccessible( true ); fields.add( field ); } } } boolean compare( Object expected, Object actual ) { try { for ( Field field : fields ) { if ( !equal( field.get( expected ), field.get( actual ) ) ) { return false; } } return true; } catch ( Exception failure ) { return false; } } private static boolean equal( Object a, Object b ) { return a == b || (a != null && (a.equals( b ) || (b != null && deepEquals( a, b )))); } private static boolean deepEquals( Object a, Object b ) { if (a.getClass() == b.getClass() && a.getClass().isArray()) { if ( a instanceof Object[] ) { return Arrays.deepEquals( (Object[]) a, (Object[]) b ); } if ( a instanceof byte[] ) { return Arrays.equals( (byte[]) a, (byte[]) b ); } if ( a instanceof char[] ) { return Arrays.equals( (char[]) a, (char[])b ); } } return false; } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_nioneo_xa_TransactionWriterTest.java