Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
3,759
static class IndexUpgraderMergeSpecification extends MergeSpecification { @Override public void add(OneMerge merge) { super.add(new IndexUpgraderOneMerge(merge.segments)); } @Override public String segString(Directory dir) { return "IndexUpgraderMergeSpec[" + super.segString(dir) + "]"; } }
0true
src_main_java_org_elasticsearch_index_merge_policy_IndexUpgraderMergePolicy.java
2,038
public abstract class BasePutOperation extends LockAwareOperation implements BackupAwareOperation { protected transient Data dataOldValue; protected transient EntryEventType eventType; public BasePutOperation(String name, Data dataKey, Data value) { super(name, dataKey, value, -1); } public BasePutOperation(String name, Data dataKey, Data value, long ttl) { super(name, dataKey, value, ttl); } public BasePutOperation() { } public void afterRun() { mapService.interceptAfterPut(name, dataValue); if (eventType == null) eventType = dataOldValue == null ? EntryEventType.ADDED : EntryEventType.UPDATED; mapService.publishEvent(getCallerAddress(), name, eventType, dataKey, dataOldValue, dataValue); invalidateNearCaches(); if (mapContainer.getWanReplicationPublisher() != null && mapContainer.getWanMergePolicy() != null) { Record record = recordStore.getRecord(dataKey); if (record == null) { return; } final SimpleEntryView entryView = mapService.createSimpleEntryView(dataKey, mapService.toData(dataValue), record); mapService.publishWanReplicationUpdate(name, entryView); } } public boolean shouldBackup() { return true; } public Operation getBackupOperation() { Record record = recordStore.getRecord(dataKey); RecordInfo replicationInfo = mapService.createRecordInfo(record); return new PutBackupOperation(name, dataKey, dataValue, replicationInfo); } public final int getAsyncBackupCount() { return mapContainer.getAsyncBackupCount(); } public final int getSyncBackupCount() { return mapContainer.getBackupCount(); } public void onWaitExpire() { final ResponseHandler responseHandler = getResponseHandler(); responseHandler.sendResponse(null); } @Override public String toString() { return "BasePutOperation{" + name + "}"; } }
1no label
hazelcast_src_main_java_com_hazelcast_map_operation_BasePutOperation.java
3,853
public class GeohashCellFilter { public static final String NAME = "geohash_cell"; public static final String NEIGHBORS = "neighbors"; public static final String PRECISION = "precision"; /** * Create a new geohash filter for a given set of geohashes. In general this method * returns a boolean filter combining the geohashes OR-wise. * * @param context Context of the filter * @param fieldMapper field mapper for geopoints * @param geohash mandatory geohash * @param geohashes optional array of additional geohashes * @return a new GeoBoundinboxfilter */ public static Filter create(QueryParseContext context, GeoPointFieldMapper fieldMapper, String geohash, @Nullable List<String> geohashes) { if (fieldMapper.geoHashStringMapper() == null) { throw new ElasticsearchIllegalArgumentException("geohash filter needs geohash_prefix to be enabled"); } StringFieldMapper geoHashMapper = fieldMapper.geoHashStringMapper(); if (geohashes == null || geohashes.size() == 0) { return geoHashMapper.termFilter(geohash, context); } else { geohashes.add(geohash); return geoHashMapper.termsFilter(geohashes, context); } } /** * Builder for a geohashfilter. It needs the fields <code>fieldname</code> and * <code>geohash</code> to be set. the default for a neighbor filteing is * <code>false</code>. */ public static class Builder extends BaseFilterBuilder { // we need to store the geohash rather than the corresponding point, // because a transformation from a geohash to a point an back to the // geohash will extend the accuracy of the hash to max precision // i.e. by filing up with z's. private String field; private String geohash; private int levels = -1; private boolean neighbors; public Builder(String field) { this(field, null, false); } public Builder(String field, GeoPoint point) { this(field, point.geohash(), false); } public Builder(String field, String geohash) { this(field, geohash, false); } public Builder(String field, String geohash, boolean neighbors) { super(); this.field = field; this.geohash = geohash; this.neighbors = neighbors; } public Builder point(GeoPoint point) { this.geohash = point.getGeohash(); return this; } public Builder point(double lat, double lon) { this.geohash = GeoHashUtils.encode(lat, lon); return this; } public Builder geohash(String geohash) { this.geohash = geohash; return this; } public Builder precision(int levels) { this.levels = levels; return this; } public Builder precision(String precision) { double meters = DistanceUnit.parse(precision, DistanceUnit.DEFAULT, DistanceUnit.METERS); return precision(GeoUtils.geoHashLevelsForPrecision(meters)); } public Builder neighbors(boolean neighbors) { this.neighbors = neighbors; return this; } public Builder field(String field) { this.field = field; return this; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(NAME); if (neighbors) { builder.field(NEIGHBORS, neighbors); } if(levels > 0) { builder.field(PRECISION, levels); } builder.field(field, geohash); builder.endObject(); } } public static class Parser implements FilterParser { @Inject public Parser() { } @Override public String[] names() { return new String[]{NAME, Strings.toCamelCase(NAME)}; } @Override public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); String fieldName = null; String geohash = null; int levels = -1; boolean neighbors = false; XContentParser.Token token; if ((token = parser.currentToken()) != Token.START_OBJECT) { throw new ElasticsearchParseException(NAME + " must be an object"); } while ((token = parser.nextToken()) != Token.END_OBJECT) { if (token == Token.FIELD_NAME) { String field = parser.text(); if (PRECISION.equals(field)) { token = parser.nextToken(); if(token == Token.VALUE_NUMBER) { levels = parser.intValue(); } else if(token == Token.VALUE_STRING) { double meters = DistanceUnit.parse(parser.text(), DistanceUnit.DEFAULT, DistanceUnit.METERS); levels = GeoUtils.geoHashLevelsForPrecision(meters); } } else if (NEIGHBORS.equals(field)) { parser.nextToken(); neighbors = parser.booleanValue(); } else { fieldName = field; token = parser.nextToken(); if(token == Token.VALUE_STRING) { // A string indicates either a gehash or a lat/lon string String location = parser.text(); if(location.indexOf(",")>0) { geohash = GeoPoint.parse(parser).geohash(); } else { geohash = location; } } else { geohash = GeoPoint.parse(parser).geohash(); } } } else { throw new ElasticsearchParseException("unexpected token [" + token + "]"); } } if (geohash == null) { throw new QueryParsingException(parseContext.index(), "no geohash value provided to geohash_cell filter"); } MapperService.SmartNameFieldMappers smartMappers = parseContext.smartFieldMappers(fieldName); if (smartMappers == null || !smartMappers.hasMapper()) { throw new QueryParsingException(parseContext.index(), "failed to find geo_point field [" + fieldName + "]"); } FieldMapper<?> mapper = smartMappers.mapper(); if (!(mapper instanceof GeoPointFieldMapper)) { throw new QueryParsingException(parseContext.index(), "field [" + fieldName + "] is not a geo_point field"); } GeoPointFieldMapper geoMapper = ((GeoPointFieldMapper) mapper); if (!geoMapper.isEnableGeohashPrefix()) { throw new QueryParsingException(parseContext.index(), "can't execute geohash_cell on field [" + fieldName + "], geohash_prefix is not enabled"); } if(levels > 0) { int len = Math.min(levels, geohash.length()); geohash = geohash.substring(0, len); } if (neighbors) { return create(parseContext, geoMapper, geohash, GeoHashUtils.neighbors(geohash)); } else { return create(parseContext, geoMapper, geohash, null); } } } }
1no label
src_main_java_org_elasticsearch_index_query_GeohashCellFilter.java
82
public class ChangeRefiningTypeProposal { static void addChangeRefiningTypeProposal(IFile file, Tree.CompilationUnit cu, Collection<ICompletionProposal> proposals, Node node) { Tree.Declaration decNode = findDeclaration(cu, node); if (decNode instanceof Tree.TypedDeclaration) { TypedDeclaration dec = ((Tree.TypedDeclaration) decNode).getDeclarationModel(); Declaration rd = dec.getRefinedDeclaration(); if (rd instanceof TypedDeclaration) { TypeDeclaration decContainer = (TypeDeclaration) dec.getContainer(); TypeDeclaration rdContainer = (TypeDeclaration) rd.getContainer(); ProducedType supertype = decContainer.getType().getSupertype(rdContainer); ProducedReference pr = rd.getProducedReference(supertype, Collections.<ProducedType>emptyList()); ProducedType t = pr.getType(); String type = t.getProducedTypeName(decNode.getUnit()); TextFileChange change = new TextFileChange("Change Type", file); int offset = node.getStartIndex(); int length = node.getStopIndex()-offset+1; change.setEdit(new ReplaceEdit(offset, length, type)); proposals.add(new CorrectionProposal("Change type to '" + type + "'", change, new Region(offset, length))); } } } static void addChangeRefiningParametersProposal(IFile file, CompilationUnit cu, Collection<ICompletionProposal> proposals, Node node) { Tree.Declaration decNode = (Tree.Declaration) Nodes.findStatement(cu, node); Tree.ParameterList list; if (decNode instanceof Tree.AnyMethod) { list = ((Tree.AnyMethod) decNode).getParameterLists().get(0); } else if (decNode instanceof Tree.AnyClass) { list = ((Tree.AnyClass) decNode).getParameterList(); } else { return; } Declaration dec = decNode.getDeclarationModel(); Declaration rd = dec.getRefinedDeclaration(); if (rd instanceof Functional && dec instanceof Functional) { List<ParameterList> rdPls = ((Functional) rd).getParameterLists(); List<ParameterList> decPls = ((Functional) dec).getParameterLists(); if (rdPls.isEmpty() || decPls.isEmpty()) { return; } List<Parameter> rdpl = rdPls.get(0).getParameters(); List<Parameter> dpl = decPls.get(0).getParameters(); TypeDeclaration decContainer = (TypeDeclaration) dec.getContainer(); TypeDeclaration rdContainer = (TypeDeclaration) rd.getContainer(); ProducedType supertype = decContainer.getType().getSupertype(rdContainer); ProducedReference pr = rd.getProducedReference(supertype, Collections.<ProducedType>emptyList()); List<Tree.Parameter> params = list.getParameters(); TextFileChange change = new TextFileChange("Fix Refining Parameter List", file); change.setEdit(new MultiTextEdit()); Unit unit = decNode.getUnit(); for (int i=0; i<params.size(); i++) { Tree.Parameter p = params.get(i); if (rdpl.size()<=i) { Integer start = i==0 ? list.getStartIndex()+1 : params.get(i-1).getStopIndex()+1; Integer stop = params.get(params.size()-1).getStopIndex()+1; change.addEdit(new DeleteEdit(start, stop-start)); break; } else { Parameter rdp = rdpl.get(i); ProducedType pt = pr.getTypedParameter(rdp).getFullType(); ProducedType dt = dpl.get(i).getModel() .getTypedReference().getFullType(); if (!dt.isExactly(pt)) { change.addEdit(new ReplaceEdit(p.getStartIndex(), p.getStopIndex()-p.getStartIndex()+1, //TODO: better handling for callable parameters pt.getProducedTypeName(unit) + " " + rdp.getName())); } } } if (rdpl.size()>params.size()) { StringBuilder buf = new StringBuilder(); for (int i=params.size(); i<rdpl.size(); i++) { Parameter p = rdpl.get(i); if (i>0) { buf.append(", "); } appendParameterText(buf, pr, p, unit); } Integer offset = params.isEmpty() ? list.getStartIndex()+1 : params.get(params.size()-1).getStopIndex()+1; change.addEdit(new InsertEdit(offset, buf.toString())); } if (change.getEdit().hasChildren()) { proposals.add(new CorrectionProposal("Fix refining parameter list", change, new Region(list.getStartIndex()+1, 0))); } } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ChangeRefiningTypeProposal.java
3,224
public class NoOrdinalsStringFieldDataTests extends PagedBytesStringFieldDataTests { @SuppressWarnings("unchecked") @Override public IndexFieldData<AtomicFieldData<ScriptDocValues>> getForField(String fieldName) { final IndexFieldData<?> in = super.getForField(fieldName); return new IndexFieldData<AtomicFieldData<ScriptDocValues>>() { @Override public Index index() { return in.index(); } @Override public Names getFieldNames() { return in.getFieldNames(); } @Override public boolean valuesOrdered() { return in.valuesOrdered(); } @Override public AtomicFieldData<ScriptDocValues> load(AtomicReaderContext context) { return in.load(context); } @Override public AtomicFieldData<ScriptDocValues> loadDirect(AtomicReaderContext context) throws Exception { return in.loadDirect(context); } @Override public XFieldComparatorSource comparatorSource(Object missingValue, SortMode sortMode) { return new BytesRefFieldComparatorSource(this, missingValue, sortMode); } @Override public void clear() { in.clear(); } @Override public void clear(IndexReader reader) { in.clear(reader); } }; } }
0true
src_test_java_org_elasticsearch_index_fielddata_NoOrdinalsStringFieldDataTests.java
946
new Thread(new Runnable() { public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } instance.shutdown(); } }).start();
0true
hazelcast_src_test_java_com_hazelcast_concurrent_lock_LockTest.java
294
public abstract class AbstractStoreTransaction implements StoreTransaction { private final BaseTransactionConfig config; public AbstractStoreTransaction(BaseTransactionConfig config) { Preconditions.checkNotNull(config); this.config = config; } @Override public void commit() throws BackendException { } @Override public void rollback() throws BackendException { } @Override public BaseTransactionConfig getConfiguration() { return config; } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_common_AbstractStoreTransaction.java
1,081
public static class Result { private final Streamable action; private final Operation operation; private final Map<String, Object> updatedSourceAsMap; private final XContentType updateSourceContentType; public Result(Streamable action, Operation operation, Map<String, Object> updatedSourceAsMap, XContentType updateSourceContentType) { this.action = action; this.operation = operation; this.updatedSourceAsMap = updatedSourceAsMap; this.updateSourceContentType = updateSourceContentType; } @SuppressWarnings("unchecked") public <T extends Streamable> T action() { return (T) action; } public Operation operation() { return operation; } public Map<String, Object> updatedSourceAsMap() { return updatedSourceAsMap; } public XContentType updateSourceContentType() { return updateSourceContentType; } }
0true
src_main_java_org_elasticsearch_action_update_UpdateHelper.java
74
@SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask<K,V> extends BulkTask<K,V,Double> { final ObjectToDouble<? super K> transformer; final DoubleByDoubleToDouble reducer; final double basis; double result; MapReduceKeysToDoubleTask<K,V> rights, nextRight; MapReduceKeysToDoubleTask (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t, MapReduceKeysToDoubleTask<K,V> nextRight, ObjectToDouble<? super K> transformer, double basis, DoubleByDoubleToDouble reducer) { super(p, b, i, f, t); this.nextRight = nextRight; this.transformer = transformer; this.basis = basis; this.reducer = reducer; } public final Double getRawResult() { return result; } public final void compute() { final ObjectToDouble<? super K> transformer; final DoubleByDoubleToDouble reducer; if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) { double r = this.basis; for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { addToPendingCount(1); (rights = new MapReduceKeysToDoubleTask<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.key)); result = r; CountedCompleter<?> c; for (c = firstComplete(); c != null; c = c.nextComplete()) { @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask<K,V> t = (MapReduceKeysToDoubleTask<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
3,227
public final class RamAccountingTermsEnum extends FilteredTermsEnum { // Flush every 1mb private static final long FLUSH_BUFFER_SIZE = 1024 * 1024; private final MemoryCircuitBreaker breaker; private final TermsEnum termsEnum; private final AbstractIndexFieldData.PerValueEstimator estimator; private long totalBytes; private long flushBuffer; public RamAccountingTermsEnum(TermsEnum termsEnum, MemoryCircuitBreaker breaker, AbstractIndexFieldData.PerValueEstimator estimator) { super(termsEnum); this.breaker = breaker; this.termsEnum = termsEnum; this.estimator = estimator; this.totalBytes = 0; this.flushBuffer = 0; } /** * Always accept the term. */ @Override protected AcceptStatus accept(BytesRef term) throws IOException { return AcceptStatus.YES; } /** * Flush the {@code flushBuffer} to the breaker, incrementing the total * bytes and resetting the buffer. */ public void flush() { breaker.addEstimateBytesAndMaybeBreak(this.flushBuffer); this.totalBytes += this.flushBuffer; this.flushBuffer = 0; } /** * Proxy to the original next() call, but estimates the overhead of * loading the next term. */ @Override public BytesRef next() throws IOException { BytesRef term = termsEnum.next(); if (term == null && this.flushBuffer != 0) { // We have reached the end of the termsEnum, flush the buffer flush(); } else { this.flushBuffer += estimator.bytesPerValue(term); if (this.flushBuffer >= FLUSH_BUFFER_SIZE) { flush(); } } return term; } /** * @return the total number of bytes that have been aggregated */ public long getTotalBytes() { return this.totalBytes; } }
0true
src_main_java_org_elasticsearch_index_fielddata_RamAccountingTermsEnum.java
1,565
@ManagedDescription("HazelcastInstance.Node") public class NodeMBean extends HazelcastMBean<Node> { public NodeMBean(HazelcastInstance hazelcastInstance, Node node, ManagementService service) { super(node, service); Hashtable<String, String> properties = new Hashtable<String, String>(3); properties.put("type", quote("HazelcastInstance.Node")); properties.put("name", quote("node" + node.address)); properties.put("instance", quote(hazelcastInstance.getName())); setObjectName(properties); } @ManagedAnnotation("address") @ManagedDescription("Address of the node") public String getName() { return managedObject.address.toString(); } @ManagedAnnotation("masterAddress") @ManagedDescription("The master address of the cluster") public String getMasterAddress() { Address a = managedObject.getMasterAddress(); return a == null ? null : a.toString(); } }
0true
hazelcast_src_main_java_com_hazelcast_jmx_NodeMBean.java
1,175
public class NettyEchoBenchmark { public static void main(String[] args) { final int payloadSize = 100; int CYCLE_SIZE = 50000; final long NUMBER_OF_ITERATIONS = 500000; ChannelBuffer message = ChannelBuffers.buffer(100); for (int i = 0; i < message.capacity(); i++) { message.writeByte((byte) i); } // Configure the server. ServerBootstrap serverBootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // Set up the pipeline factory. serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new EchoServerHandler()); } }); // Bind and start to accept incoming connections. serverBootstrap.bind(new InetSocketAddress(9000)); ClientBootstrap clientBootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); // ClientBootstrap clientBootstrap = new ClientBootstrap( // new OioClientSocketChannelFactory(Executors.newCachedThreadPool())); // Set up the pipeline factory. final EchoClientHandler clientHandler = new EchoClientHandler(); clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(clientHandler); } }); // Start the connection attempt. ChannelFuture future = clientBootstrap.connect(new InetSocketAddress("localhost", 9000)); future.awaitUninterruptibly(); Channel clientChannel = future.getChannel(); System.out.println("Warming up..."); for (long i = 0; i < 10000; i++) { clientHandler.latch = new CountDownLatch(1); clientChannel.write(message); try { clientHandler.latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Warmed up"); long start = System.currentTimeMillis(); long cycleStart = System.currentTimeMillis(); for (long i = 1; i < NUMBER_OF_ITERATIONS; i++) { clientHandler.latch = new CountDownLatch(1); clientChannel.write(message); try { clientHandler.latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } if ((i % CYCLE_SIZE) == 0) { long cycleEnd = System.currentTimeMillis(); System.out.println("Ran 50000, TPS " + (CYCLE_SIZE / ((double) (cycleEnd - cycleStart) / 1000))); cycleStart = cycleEnd; } } long end = System.currentTimeMillis(); long seconds = (end - start) / 1000; System.out.println("Ran [" + NUMBER_OF_ITERATIONS + "] iterations, payload [" + payloadSize + "]: took [" + seconds + "], TPS: " + ((double) NUMBER_OF_ITERATIONS) / seconds); clientChannel.close().awaitUninterruptibly(); clientBootstrap.releaseExternalResources(); serverBootstrap.releaseExternalResources(); } public static class EchoClientHandler extends SimpleChannelUpstreamHandler { public volatile CountDownLatch latch; public EchoClientHandler() { } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { latch.countDown(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { e.getCause().printStackTrace(); e.getChannel().close(); } } public static class EchoServerHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { e.getChannel().write(e.getMessage()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { // Close the connection when an exception is raised. e.getCause().printStackTrace(); e.getChannel().close(); } } }
0true
src_test_java_org_elasticsearch_benchmark_transport_netty_NettyEchoBenchmark.java
2,603
static class NotMasterException extends ElasticsearchIllegalStateException { @Override public Throwable fillInStackTrace() { return null; } }
1no label
src_main_java_org_elasticsearch_discovery_zen_fd_MasterFaultDetection.java
406
@Embeddable public class ArchiveStatus implements Serializable { @Column(name = "ARCHIVED") @AdminPresentation(friendlyName = "archived", visibility = VisibilityEnum.HIDDEN_ALL, group = "ArchiveStatus") protected Character archived = 'N'; public Character getArchived() { return archived; } public void setArchived(Character archived) { this.archived = archived; } }
1no label
common_src_main_java_org_broadleafcommerce_common_persistence_ArchiveStatus.java
1,217
public final class ORecordMetadata { private final ORID recordId; private final ORecordVersion recordVersion; public ORecordMetadata(ORID recordId, ORecordVersion recordVersion) { this.recordId = recordId; this.recordVersion = recordVersion; } public ORID getRecordId() { return recordId; } public ORecordVersion getRecordVersion() { return recordVersion; } }
0true
core_src_main_java_com_orientechnologies_orient_core_storage_ORecordMetadata.java
395
return new KeyInformation.IndexRetriever() { @Override public KeyInformation get(String store, String key) { //Same for all stores return mappings.get(key); } @Override public KeyInformation.StoreRetriever get(String store) { return new KeyInformation.StoreRetriever() { @Override public KeyInformation get(String key) { return mappings.get(key); } }; } };
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexProviderTest.java
25
final class FunctionCompletionProposal extends CompletionProposal { private final CeylonParseController cpc; private final Declaration dec; private FunctionCompletionProposal(int offset, String prefix, String desc, String text, Declaration dec, CeylonParseController cpc) { super(offset, prefix, getDecoratedImage(dec.isShared() ? CEYLON_FUN : CEYLON_LOCAL_FUN, getDecorationAttributes(dec), false), desc, text); this.cpc = cpc; this.dec = dec; } private DocumentChange createChange(IDocument document) throws BadLocationException { DocumentChange change = new DocumentChange("Complete Invocation", document); change.setEdit(new MultiTextEdit()); HashSet<Declaration> decs = new HashSet<Declaration>(); Tree.CompilationUnit cu = cpc.getRootNode(); importDeclaration(decs, dec, cu); int il=applyImports(change, decs, cu, document); change.addEdit(createEdit(document)); offset+=il; return change; } @Override public boolean isAutoInsertable() { return false; } @Override public void apply(IDocument document) { try { createChange(document).perform(new NullProgressMonitor()); } catch (Exception e) { e.printStackTrace(); } } protected static void addFunctionProposal(int offset, final CeylonParseController cpc, Tree.Primary primary, List<ICompletionProposal> result, final Declaration dec, IDocument doc) { Tree.Term arg = primary; while (arg instanceof Tree.Expression) { arg = ((Tree.Expression) arg).getTerm(); } final int start = arg.getStartIndex(); final int stop = arg.getStopIndex(); int origin = primary.getStartIndex(); String argText; String prefix; try { //the argument argText = doc.get(start, stop-start+1); //the text to replace prefix = doc.get(origin, offset-origin); } catch (BadLocationException e) { return; } String text = dec.getName(arg.getUnit()) + "(" + argText + ")"; if (((Functional)dec).isDeclaredVoid()) { text += ";"; } Unit unit = cpc.getRootNode().getUnit(); result.add(new FunctionCompletionProposal(offset, prefix, getDescriptionFor(dec, unit) + "(...)", text, dec, cpc)); } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_FunctionCompletionProposal.java
824
public class GetAndSetOperation extends AtomicLongBackupAwareOperation { private long newValue; private long returnValue; public GetAndSetOperation() { } public GetAndSetOperation(String name, long newValue) { super(name); this.newValue = newValue; } @Override public void run() throws Exception { LongWrapper number = getNumber(); returnValue = number.getAndSet(newValue); } @Override public Object getResponse() { return returnValue; } @Override public int getId() { return AtomicLongDataSerializerHook.GET_AND_SET; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeLong(newValue); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); newValue = in.readLong(); } @Override public Operation getBackupOperation() { return new SetBackupOperation(name, newValue); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_operations_GetAndSetOperation.java
546
private static class TransactionalObjectKey { private final String serviceName; private final String name; TransactionalObjectKey(String serviceName, String name) { this.serviceName = serviceName; this.name = name; } public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TransactionalObjectKey)) { return false; } TransactionalObjectKey that = (TransactionalObjectKey) o; if (!name.equals(that.name)) { return false; } if (!serviceName.equals(that.serviceName)) { return false; } return true; } public int hashCode() { int result = serviceName.hashCode(); result = 31 * result + name.hashCode(); return result; } }
0true
hazelcast-client_src_main_java_com_hazelcast_client_txn_TransactionContextProxy.java
1,531
public interface HeadProcessorExtensionListener { public void processAttributeValues(Arguments arguments, Element element); }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_processor_extension_HeadProcessorExtensionListener.java
35
public class LinkedModeCompletionProposal implements ICompletionProposal, ICompletionProposalExtension2 { private static final class NullProposal implements ICompletionProposal, ICompletionProposalExtension2 { private List<ICompletionProposal> proposals; private NullProposal(List<ICompletionProposal> proposals) { this.proposals = proposals; } @Override public void apply(IDocument document) {} @Override public Point getSelection(IDocument document) { return null; } @Override public String getAdditionalProposalInfo() { return null; } @Override public String getDisplayString() { return ""; } @Override public Image getImage() { return null; } @Override public IContextInformation getContextInformation() { return null; } @Override public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {} @Override public void selected(ITextViewer viewer, boolean smartToggle) {} @Override public void unselected(ITextViewer viewer) {} @Override public boolean validate(IDocument document, int offset, DocumentEvent event) { for (ICompletionProposal p: proposals) { if (p instanceof ICompletionProposalExtension2) { ICompletionProposalExtension2 ext = (ICompletionProposalExtension2) p; if (ext.validate(document, offset, event)) { return true; } } else { return true; } } return false; } } private final String text; private final Image image; private final int offset; private int position; private LinkedModeCompletionProposal(int offset, String text, int position) { this(offset, text, position, null); } private LinkedModeCompletionProposal(int offset, String text, int position, Image image) { this.text=text; this.position = position; this.image = image; this.offset = offset; } @Override public Image getImage() { return image; } @Override public Point getSelection(IDocument document) { return new Point(offset + text.length(), 0); } public void apply(IDocument document) { try { IRegion region = getCurrentRegion(document); document.replace(region.getOffset(), region.getLength(), text); } catch (BadLocationException e) { e.printStackTrace(); } } protected IRegion getCurrentRegion(IDocument document) throws BadLocationException { int start = offset; int length = 0; int count = 0; for (int i=offset; i<document.getLength(); i++) { char ch = document.getChar(i); if (Character.isWhitespace(ch) || ch=='(') { if (count++==position) { break; } else { start = i+1; length = -1; } } length++; } return new Region(start, length); } public String getDisplayString() { return text; } public String getAdditionalProposalInfo() { return null; } @Override public IContextInformation getContextInformation() { return null; } @Override public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { apply(viewer.getDocument()); } @Override public void selected(ITextViewer viewer, boolean smartToggle) {} @Override public void unselected(ITextViewer viewer) {} @Override public boolean validate(IDocument document, int offset, DocumentEvent event) { try { IRegion region = getCurrentRegion(document); String prefix = document.get(region.getOffset(), offset-region.getOffset()); return text.startsWith(prefix); } catch (BadLocationException e) { return false; } } public static ICompletionProposal[] getNameProposals(int offset, int seq, String[] names) { return getNameProposals(offset, seq, names, null); } public static ICompletionProposal[] getNameProposals(int offset, int seq, String[] names, String defaultName) { List<ICompletionProposal> nameProposals = new ArrayList<ICompletionProposal>(); Set<String> proposedNames = new HashSet<String>(); if (defaultName!=null) { LinkedModeCompletionProposal nameProposal = new LinkedModeCompletionProposal(offset, defaultName, seq); nameProposals.add(nameProposal); proposedNames.add(defaultName); } for (String name: names) { if (proposedNames.add(name)) { if (defaultName==null || !defaultName.equals(name)) { LinkedModeCompletionProposal nameProposal = new LinkedModeCompletionProposal(offset, name, seq); nameProposals.add(nameProposal); } } } ICompletionProposal[] proposals = new ICompletionProposal[nameProposals.size() + 1]; int i=0; proposals[i++] = new NullProposal(nameProposals); for (ICompletionProposal tp: nameProposals) { proposals[i++] = tp; } return proposals; } public static ICompletionProposal[] getSupertypeProposals(int offset, Unit unit, ProducedType type, boolean includeValue, String kind) { if (type==null) { return new ICompletionProposal[0]; } TypeDeclaration td = type.getDeclaration(); List<TypeDeclaration> supertypes = isTypeUnknown(type) ? Collections.<TypeDeclaration>emptyList() : td.getSupertypeDeclarations(); int size = supertypes.size(); if (includeValue) size++; if (td instanceof UnionType || td instanceof IntersectionType) { size++; } ICompletionProposal[] typeProposals = new ICompletionProposal[size]; int i=0; if (includeValue) { typeProposals[i++] = new LinkedModeCompletionProposal(offset, kind, 0, getDecoratedImage(CEYLON_LITERAL, 0, false)); } if (td instanceof UnionType || td instanceof IntersectionType) { String typeName = type.getProducedTypeName(unit); typeProposals[i++] = new LinkedModeCompletionProposal(offset, typeName, 0, getImageForDeclaration(td)); } for (int j=supertypes.size()-1; j>=0; j--) { ProducedType supertype = type.getSupertype(supertypes.get(j)); String typeName = supertype.getProducedTypeName(unit); typeProposals[i++] = new LinkedModeCompletionProposal(offset, typeName, 0, getImageForDeclaration(supertype.getDeclaration())); } return typeProposals; } public static ICompletionProposal[] getCaseTypeProposals(int offset, Unit unit, ProducedType type) { if (type==null) { return new ICompletionProposal[0]; } List<ProducedType> caseTypes = type.getCaseTypes(); if (caseTypes==null) { return new ICompletionProposal[0]; } ICompletionProposal[] typeProposals = new ICompletionProposal[caseTypes.size()]; for (int i=0; i<caseTypes.size(); i++) { ProducedType ct = caseTypes.get(i); String typeName = ct.getProducedTypeName(unit); typeProposals[i] = new LinkedModeCompletionProposal(offset, typeName, 0, getImageForDeclaration(ct.getDeclaration())); } return typeProposals; } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_LinkedModeCompletionProposal.java
1,091
public class PageCartRuleProcessor extends AbstractPageRuleProcessor { private OrderDao orderDao; /** * Expects to find a valid "Customer" in the valueMap. * Uses the customer to locate the cart and then loops through the items in the current * cart and checks to see if the cart items rules are met. * * @param sc * @return */ @Override public boolean checkForMatch(PageDTO page, Map<String, Object> valueMap) { List<ItemCriteriaDTO> itemCriterias = page.getItemCriteriaDTOList(); if (itemCriterias != null && itemCriterias.size() > 0) { Order order = lookupOrderForCustomer((Customer) valueMap.get("customer")); if (order == null || order.getOrderItems() == null || order.getOrderItems().size() < 1) { return false; } for(ItemCriteriaDTO itemCriteria : itemCriterias) { if (! checkItemCriteria(itemCriteria, order.getOrderItems())) { // Item criteria check failed. return false; } } } return true; } private Order lookupOrderForCustomer(Customer c) { Order o = null; if (c != null) { o = orderDao.readCartForCustomer(c); } return o; } private boolean checkItemCriteria(ItemCriteriaDTO itemCriteria, List<OrderItem> orderItems) { Map<String,Object> vars = new HashMap<String, Object>(); int foundCount = 0; Iterator<OrderItem> items = orderItems.iterator(); while (foundCount < itemCriteria.getQty() && items.hasNext()) { OrderItem currentItem = items.next(); vars.put("discreteOrderItem", currentItem); vars.put("orderItem", currentItem); boolean match = executeExpression(itemCriteria.getMatchRule(), vars); if (match) { foundCount = foundCount + currentItem.getQuantity(); } } return (foundCount >= itemCriteria.getQty().intValue()); } public void setOrderDao(OrderDao orderDao) { this.orderDao = orderDao; } public OrderDao getOrderDao() { return orderDao; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_PageCartRuleProcessor.java
777
public class InventoryType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, InventoryType> TYPES = new LinkedHashMap<String, InventoryType>(); public static final InventoryType NONE = new InventoryType("NONE", "None"); public static final InventoryType BASIC = new InventoryType("BASIC", "Basic"); public static InventoryType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public InventoryType() { //do nothing } public InventoryType(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; InventoryType other = (InventoryType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_inventory_service_type_InventoryType.java
371
public interface OObjectLazyMultivalueElement<T> { public void detach(boolean nonProxiedInstance); public void detachAll(boolean nonProxiedInstance); public T getNonOrientInstance(); public Object getUnderlying(); }
0true
core_src_main_java_com_orientechnologies_orient_core_db_object_OObjectLazyMultivalueElement.java
1,391
public class EditedPhasedUnit extends IdePhasedUnit { WeakReference<ProjectPhasedUnit> savedPhasedUnitRef; public EditedPhasedUnit(VirtualFile unitFile, VirtualFile srcDir, CompilationUnit cu, Package p, ModuleManager moduleManager, TypeChecker typeChecker, List<CommonToken> tokenStream, ProjectPhasedUnit savedPhasedUnit) { super(unitFile, srcDir, cu, p, moduleManager, typeChecker, tokenStream); savedPhasedUnitRef = new WeakReference<ProjectPhasedUnit>(savedPhasedUnit); if (savedPhasedUnit!=null) { savedPhasedUnit.addWorkingCopy(this); } } public EditedPhasedUnit(PhasedUnit other) { super(other); } @Override public Unit newUnit() { return new EditedSourceFile(this); } @Override public EditedSourceFile getUnit() { return (EditedSourceFile) super.getUnit(); } public ProjectPhasedUnit getOriginalPhasedUnit() { return savedPhasedUnitRef.get(); } public IFile getSourceFileResource() { return getOriginalPhasedUnit() == null ? null : getOriginalPhasedUnit().getSourceFileResource(); } public IFolder getSourceFolderResource() { return getOriginalPhasedUnit() == null ? null : getOriginalPhasedUnit().getSourceFolderResource(); } public IProject getProjectResource() { return getOriginalPhasedUnit() == null ? null : getOriginalPhasedUnit().getProjectResource(); } @Override protected boolean reuseExistingDescriptorModels() { return true; } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_typechecker_EditedPhasedUnit.java
2,155
public class AndDocIdSet extends DocIdSet { private final DocIdSet[] sets; public AndDocIdSet(DocIdSet[] sets) { this.sets = sets; } @Override public boolean isCacheable() { for (DocIdSet set : sets) { if (!set.isCacheable()) { return false; } } return true; } @Override public Bits bits() throws IOException { Bits[] bits = new Bits[sets.length]; for (int i = 0; i < sets.length; i++) { bits[i] = sets[i].bits(); if (bits[i] == null) { return null; } } return new AndBits(bits); } @Override public DocIdSetIterator iterator() throws IOException { // we try and be smart here, if we can iterate through docsets quickly, prefer to iterate // over them as much as possible, before actually going to "bits" based ones to check List<DocIdSet> iterators = new ArrayList<DocIdSet>(sets.length); List<Bits> bits = new ArrayList<Bits>(sets.length); for (DocIdSet set : sets) { if (DocIdSets.isFastIterator(set)) { iterators.add(set); } else { Bits bit = set.bits(); if (bit != null) { bits.add(bit); } else { iterators.add(set); } } } if (bits.isEmpty()) { return new IteratorBasedIterator(iterators.toArray(new DocIdSet[iterators.size()])); } if (iterators.isEmpty()) { return new BitsDocIdSetIterator(new AndBits(bits.toArray(new Bits[bits.size()]))); } // combination of both..., first iterating over the "fast" ones, and then checking on the more // expensive ones return new BitsDocIdSetIterator.FilteredIterator( new IteratorBasedIterator(iterators.toArray(new DocIdSet[iterators.size()])), new AndBits(bits.toArray(new Bits[bits.size()])) ); } static class AndBits implements Bits { private final Bits[] bits; AndBits(Bits[] bits) { this.bits = bits; } @Override public boolean get(int index) { for (Bits bit : bits) { if (!bit.get(index)) { return false; } } return true; } @Override public int length() { return bits[0].length(); } } static class IteratorBasedIterator extends DocIdSetIterator { int lastReturn = -1; private DocIdSetIterator[] iterators = null; private final long cost; IteratorBasedIterator(DocIdSet[] sets) throws IOException { iterators = new DocIdSetIterator[sets.length]; int j = 0; long cost = Integer.MAX_VALUE; for (DocIdSet set : sets) { if (set == null) { lastReturn = DocIdSetIterator.NO_MORE_DOCS; // non matching break; } else { DocIdSetIterator dcit = set.iterator(); if (dcit == null) { lastReturn = DocIdSetIterator.NO_MORE_DOCS; // non matching break; } iterators[j++] = dcit; cost = Math.min(cost, dcit.cost()); } } this.cost = cost; if (lastReturn != DocIdSetIterator.NO_MORE_DOCS) { lastReturn = (iterators.length > 0 ? -1 : DocIdSetIterator.NO_MORE_DOCS); } } @Override public final int docID() { return lastReturn; } @Override public final int nextDoc() throws IOException { if (lastReturn == DocIdSetIterator.NO_MORE_DOCS) return DocIdSetIterator.NO_MORE_DOCS; DocIdSetIterator dcit = iterators[0]; int target = dcit.nextDoc(); int size = iterators.length; int skip = 0; int i = 1; while (i < size) { if (i != skip) { dcit = iterators[i]; int docid = dcit.advance(target); if (docid > target) { target = docid; if (i != 0) { skip = i; i = 0; continue; } else skip = 0; } } i++; } return (lastReturn = target); } @Override public final int advance(int target) throws IOException { if (lastReturn == DocIdSetIterator.NO_MORE_DOCS) return DocIdSetIterator.NO_MORE_DOCS; DocIdSetIterator dcit = iterators[0]; target = dcit.advance(target); int size = iterators.length; int skip = 0; int i = 1; while (i < size) { if (i != skip) { dcit = iterators[i]; int docid = dcit.advance(target); if (docid > target) { target = docid; if (i != 0) { skip = i; i = 0; continue; } else { skip = 0; } } } i++; } return (lastReturn = target); } @Override public long cost() { return cost; } } }
1no label
src_main_java_org_elasticsearch_common_lucene_docset_AndDocIdSet.java
1,910
public interface RecordStore { String getName(); Object put(Data dataKey, Object dataValue, long ttl); void put(Map.Entry<Data, Object> entry); Object putIfAbsent(Data dataKey, Object value, long ttl); Record putBackup(Data key, Object value); Record putBackup(Data key, Object value, long ttl); boolean tryPut(Data dataKey, Object value, long ttl); boolean set(Data dataKey, Object value, long ttl); Object remove(Data dataKey); boolean remove(Data dataKey, Object testValue); /** * Similar to {@link com.hazelcast.map.RecordStore#remove(com.hazelcast.nio.serialization.Data)} * except removeBackup doesn't touch mapstore since it does not return previous value. */ void removeBackup(Data dataKey); Object get(Data dataKey); MapEntrySet getAll(Set<Data> keySet); boolean containsKey(Data dataKey); Object replace(Data dataKey, Object value); boolean replace(Data dataKey, Object oldValue, Object newValue); void putTransient(Data dataKey, Object value, long ttl); void putFromLoad(Data dataKey, Object value, long ttl); boolean merge(Data dataKey, EntryView mergingEntryView, MapMergePolicy mergePolicy); Record getRecord(Data key); void putForReplication(Data key, Record record); void deleteRecord(Data key); Map<Data, Record> getReadonlyRecordMap(); Set<Data> keySet(); int size(); boolean lock(Data key, String caller, long threadId, long ttl); boolean txnLock(Data key, String caller, long threadId, long ttl); boolean extendLock(Data key, String caller, long threadId, long ttl); boolean unlock(Data key, String caller, long threadId); boolean isLocked(Data key); boolean canAcquireLock(Data key, String caller, long threadId); String getLockOwnerInfo(Data key); boolean containsValue(Object testValue); Object evict(Data key); Collection<Data> valuesData(); MapContainer getMapContainer(); Set<Map.Entry<Data, Data>> entrySetData(); Map.Entry<Data, Object> getMapEntry(Data dataKey); Map.Entry<Data, Object> getMapEntryForBackup(Data dataKey); void flush(); void clearPartition(); void reset(); boolean forceUnlock(Data dataKey); long getHeapCost(); SizeEstimator getSizeEstimator(); boolean isLoaded(); void checkIfLoaded(); void setLoaded(boolean loaded); void clear(); boolean isEmpty(); WriteBehindQueue<DelayedEntry> getWriteBehindQueue(); List findUnlockedExpiredRecords(); void removeFromWriteBehindWaitingDeletions(Data key); }
0true
hazelcast_src_main_java_com_hazelcast_map_RecordStore.java
74
{ @Override public void beforeCompletion() { throw firstException; } @Override public void afterCompletion( int status ) { } };
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestTransactionImpl.java
1,270
public class TotalActivity extends BaseActivity<PricingContext> { @Override public PricingContext execute(PricingContext context) throws Exception { Order order = context.getSeedData(); setTaxSums(order); Money total = BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, order.getCurrency()); total = total.add(order.getSubTotal()); total = total.subtract(order.getOrderAdjustmentsValue()); total = total.add(order.getTotalShipping()); // There may not be any taxes on the order if (order.getTotalTax() != null) { total = total.add(order.getTotalTax()); } Money fees = BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, order.getCurrency()); for (FulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) { Money fgTotal = BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, order.getCurrency()); fgTotal = fgTotal.add(fulfillmentGroup.getMerchandiseTotal()); fgTotal = fgTotal.add(fulfillmentGroup.getShippingPrice()); fgTotal = fgTotal.add(fulfillmentGroup.getTotalTax()); for (FulfillmentGroupFee fulfillmentGroupFee : fulfillmentGroup.getFulfillmentGroupFees()) { fgTotal = fgTotal.add(fulfillmentGroupFee.getAmount()); fees = fees.add(fulfillmentGroupFee.getAmount()); } fulfillmentGroup.setTotal(fgTotal); } total = total.add(fees); order.setTotal(total); context.setSeedData(order); return context; } protected void setTaxSums(Order order) { Money orderTotalTax = BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, order.getCurrency()); for (FulfillmentGroup fg : order.getFulfillmentGroups()) { Money fgTotalFgTax = BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, order.getCurrency()); Money fgTotalItemTax = BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, order.getCurrency()); Money fgTotalFeeTax = BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, order.getCurrency()); // Add in all FG specific taxes (such as shipping tax) if (fg.getTaxes() != null) { for (TaxDetail tax : fg.getTaxes()) { fgTotalFgTax = fgTotalFgTax.add(tax.getAmount()); } } for (FulfillmentGroupItem item : fg.getFulfillmentGroupItems()) { Money itemTotalTax = BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, order.getCurrency()); // Add in all taxes for this item if (item.getTaxes() != null) { for (TaxDetail tax : item.getTaxes()) { itemTotalTax = itemTotalTax.add(tax.getAmount()); } } item.setTotalTax(itemTotalTax); fgTotalItemTax = fgTotalItemTax.add(itemTotalTax); } for (FulfillmentGroupFee fee : fg.getFulfillmentGroupFees()) { Money feeTotalTax = BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, order.getCurrency()); // Add in all taxes for this fee if (fee.getTaxes() != null) { for (TaxDetail tax : fee.getTaxes()) { feeTotalTax = feeTotalTax.add(tax.getAmount()); } } fee.setTotalTax(feeTotalTax); fgTotalFeeTax = fgTotalFeeTax.add(feeTotalTax); } Money fgTotalTax = BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, order.getCurrency()).add(fgTotalFgTax).add(fgTotalItemTax).add(fgTotalFeeTax); // Set the fulfillment group tax sums fg.setTotalFulfillmentGroupTax(fgTotalFgTax); fg.setTotalItemTax(fgTotalItemTax); fg.setTotalFeeTax(fgTotalFeeTax); fg.setTotalTax(fgTotalTax); orderTotalTax = orderTotalTax.add(fgTotalTax); } order.setTotalTax(orderTotalTax); } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_service_workflow_TotalActivity.java
2,960
public class TrimTokenFilterFactory extends AbstractTokenFilterFactory { private final boolean updateOffsets; private static final String UPDATE_OFFSETS_KEY = "update_offsets"; @Inject public TrimTokenFilterFactory(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); if (version.onOrAfter(Version.LUCENE_44) && settings.get(UPDATE_OFFSETS_KEY) != null) { throw new ElasticsearchIllegalArgumentException(UPDATE_OFFSETS_KEY + " is not supported anymore. Please fix your analysis chain or use" + " an older compatibility version (<=4.3) but beware that it might cause highlighting bugs."); } this.updateOffsets = settings.getAsBoolean("update_offsets", false); } @Override public TokenStream create(TokenStream tokenStream) { if (version.onOrAfter(Version.LUCENE_44)) { return new TrimFilter(version, tokenStream); } return new TrimFilter(version, tokenStream, updateOffsets); } }
0true
src_main_java_org_elasticsearch_index_analysis_TrimTokenFilterFactory.java
217
public class ClientReadHandler extends ClientAbstractSelectionHandler { private final ByteBuffer buffer; private volatile long lastHandle; private ClientPacket packet; public ClientReadHandler(ClientConnection connection, IOSelector ioSelector, int bufferSize) { super(connection, ioSelector); buffer = ByteBuffer.allocate(bufferSize); } @Override public void run() { registerOp(SelectionKey.OP_READ); } @Override public void handle() { lastHandle = Clock.currentTimeMillis(); if (!connection.live()) { if (logger.isFinestEnabled()) { String message = "We are being asked to read, but connection is not live so we won't"; logger.finest(message); } return; } try { int readBytes = socketChannel.read(buffer); if (readBytes == -1) { throw new EOFException("Remote socket closed!"); } } catch (IOException e) { handleSocketException(e); return; } try { if (buffer.position() == 0) { return; } buffer.flip(); while (buffer.hasRemaining()) { if (packet == null) { packet = new ClientPacket(connection.getConnectionManager().getSerializationContext()); } boolean complete = packet.readFrom(buffer); if (complete) { packet.setConn(connection); connectionManager.handlePacket(packet); packet = null; } else { break; } } if (buffer.hasRemaining()) { buffer.compact(); } else { buffer.clear(); } } catch (Throwable t) { handleSocketException(t); } } long getLastHandle() { return lastHandle; } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientReadHandler.java
3,165
public class DisabledFieldDataFormatTests extends ElasticsearchIntegrationTest { public void test() throws Exception { createIndex("test"); ensureGreen(); for (int i = 0; i < 10; ++i) { client().prepareIndex("test", "type", Integer.toString(i)).setSource("s", "value" + i).execute().actionGet(); } refresh(); // disable field data updateFormat("disabled"); SearchResponse resp = null; // try to run something that relies on field data and make sure that it fails try { resp = client().prepareSearch("test").addAggregation(AggregationBuilders.terms("t").field("s")).execute().actionGet(); assertTrue(resp.toString(), resp.getFailedShards() > 0); } catch (SearchPhaseExecutionException e) { // expected } // enable it again updateFormat("paged_bytes"); // try to run something that relies on field data and make sure that it works resp = client().prepareSearch("test").addAggregation(AggregationBuilders.terms("t").field("s")).execute().actionGet(); assertNoFailures(resp); // disable it again updateFormat("disabled"); // this time, it should work because segments are already loaded resp = client().prepareSearch("test").addAggregation(AggregationBuilders.terms("t").field("s")).execute().actionGet(); assertNoFailures(resp); // but add more docs and the new segment won't be loaded client().prepareIndex("test", "type", "-1").setSource("s", "value").execute().actionGet(); refresh(); try { resp = client().prepareSearch("test").addAggregation(AggregationBuilders.terms("t").field("s")).execute().actionGet(); assertTrue(resp.toString(), resp.getFailedShards() > 0); } catch (SearchPhaseExecutionException e) { // expected } } private void updateFormat(String format) throws Exception { client().admin().indices().preparePutMapping("test").setType("type").setSource( XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties") .startObject("s") .field("type", "string") .startObject("fielddata") .field("format", format) .endObject() .endObject() .endObject() .endObject() .endObject()).execute().actionGet(); } }
0true
src_test_java_org_elasticsearch_index_fielddata_DisabledFieldDataFormatTests.java
218
public class ClientWriteHandler extends ClientAbstractSelectionHandler implements Runnable { private final Queue<SocketWritable> writeQueue = new ConcurrentLinkedQueue<SocketWritable>(); private final AtomicBoolean informSelector = new AtomicBoolean(true); private final ByteBuffer buffer; private boolean ready; private SocketWritable lastWritable; private volatile long lastHandle; // private boolean initialized = false; public ClientWriteHandler(ClientConnection connection, IOSelector ioSelector, int bufferSize) { super(connection, ioSelector); buffer = ByteBuffer.allocate(bufferSize); } @Override public void handle() { lastHandle = Clock.currentTimeMillis(); if (!connection.live()) { return; } // if (!initialized) { // initialized = true; // buffer.put(Protocols.CLIENT_BINARY.getBytes()); // buffer.put(ClientTypes.JAVA.getBytes()); // registerWrite(); // } if (lastWritable == null && (lastWritable = poll()) == null && buffer.position() == 0) { ready = true; return; } try { while (buffer.hasRemaining() && lastWritable != null) { boolean complete = lastWritable.writeTo(buffer); if (complete) { lastWritable = poll(); } else { break; } } if (buffer.position() > 0) { buffer.flip(); try { socketChannel.write(buffer); } catch (Exception e) { lastWritable = null; handleSocketException(e); return; } if (buffer.hasRemaining()) { buffer.compact(); } else { buffer.clear(); } } } catch (Throwable t) { logger.severe("Fatal Error at WriteHandler for endPoint: " + connection.getEndPoint(), t); } finally { ready = false; registerWrite(); } } public void enqueueSocketWritable(SocketWritable socketWritable) { writeQueue.offer(socketWritable); if (informSelector.compareAndSet(true, false)) { // we don't have to call wake up if this WriteHandler is // already in the task queue. // we can have a counter to check this later on. // for now, wake up regardless. ioSelector.addTask(this); ioSelector.wakeup(); } } private SocketWritable poll() { return writeQueue.poll(); } @Override public void run() { informSelector.set(true); if (ready) { handle(); } else { registerWrite(); } ready = false; } private void registerWrite() { registerOp(SelectionKey.OP_WRITE); } @Override public void shutdown() { writeQueue.clear(); while (poll() != null) { } } long getLastHandle() { return lastHandle; } }
0true
hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientWriteHandler.java
1,060
public class OCommandExecutorSQLTruncateRecord extends OCommandExecutorSQLAbstract implements OCommandDistributedReplicateRequest { public static final String KEYWORD_TRUNCATE = "TRUNCATE"; public static final String KEYWORD_RECORD = "RECORD"; private Set<String> records = new HashSet<String>(); @SuppressWarnings("unchecked") public OCommandExecutorSQLTruncateRecord parse(final OCommandRequest iRequest) { init((OCommandRequestText) iRequest); StringBuilder word = new StringBuilder(); int oldPos = 0; int pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true); if (pos == -1 || !word.toString().equals(KEYWORD_TRUNCATE)) throw new OCommandSQLParsingException("Keyword " + KEYWORD_TRUNCATE + " not found. Use " + getSyntax(), parserText, oldPos); oldPos = pos; pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true); if (pos == -1 || !word.toString().equals(KEYWORD_RECORD)) throw new OCommandSQLParsingException("Keyword " + KEYWORD_RECORD + " not found. Use " + getSyntax(), parserText, oldPos); oldPos = pos; pos = nextWord(parserText, parserText, oldPos, word, true); if (pos == -1) throw new OCommandSQLParsingException("Expected one or more records. Use " + getSyntax(), parserText, oldPos); if (word.charAt(0) == '[') // COLLECTION OStringSerializerHelper.getCollection(parserText, oldPos, records); else { records.add(word.toString()); } if (records.isEmpty()) throw new OCommandSQLParsingException("Missed record(s). Use " + getSyntax(), parserText, oldPos); return this; } /** * Execute the command. */ public Object execute(final Map<Object, Object> iArgs) { if (records.isEmpty()) throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet"); final ODatabaseRecord database = getDatabase(); for (String rec : records) { try { final ORecordId rid = new ORecordId(rec); database.getStorage().deleteRecord(rid, OVersionFactory.instance().createUntrackedVersion(), 0, null); database.getLevel1Cache().deleteRecord(rid); } catch (Throwable e) { throw new OCommandExecutionException("Error on executing command", e); } } return records.size(); } @Override public String getSyntax() { return "TRUNCATE RECORD <rid>*"; } }
0true
core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLTruncateRecord.java
243
private static class KeySkipPredicate implements Predicate<Row<ByteBuffer, ByteBuffer>> { private final ByteBuffer skip; public KeySkipPredicate(ByteBuffer skip) { this.skip = skip; } @Override public boolean apply(@Nullable Row<ByteBuffer, ByteBuffer> row) { return (row != null) && !row.getKey().equals(skip); } }
0true
titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_astyanax_AstyanaxKeyColumnValueStore.java
748
CreditCardPaymentInfo cc = new CreditCardPaymentInfo() { private static final long serialVersionUID = 1L; private String referenceNumber = "1234"; @Override public String getCvvCode() { return "123"; } @Override public Integer getExpirationMonth() { return 11; } @Override public Integer getExpirationYear() { return 2011; } @Override public Long getId() { return null; } @Override public String getPan() { return "1111111111111111"; } @Override public void setCvvCode(String cvvCode) { //do nothing } @Override public void setExpirationMonth(Integer expirationMonth) { //do nothing } @Override public void setExpirationYear(Integer expirationYear) { //do nothing } @Override public void setId(Long id) { //do nothing } @Override public void setPan(String pan) { //do nothing } @Override public EncryptionModule getEncryptionModule() { return encryptionModule; } @Override public String getReferenceNumber() { return referenceNumber; } @Override public void setEncryptionModule(EncryptionModule encryptionModule) { //do nothing } @Override public void setReferenceNumber(String referenceNumber) { this.referenceNumber = referenceNumber; } @Override public String getNameOnCard() { return "Cardholder Name"; } @Override public void setNameOnCard(String nameOnCard) { // do nothing } };
0true
integration_src_test_java_org_broadleafcommerce_core_checkout_service_CheckoutTest.java
349
public class GenericEvent implements Serializable { final String value; public GenericEvent(String value) { this.value = value; } public String getValue() { return value; } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_GenericEvent.java
890
searchService.sendExecuteQuery(node, internalScrollSearchRequest(searchId, request), new SearchServiceListener<QuerySearchResult>() { @Override public void onResult(QuerySearchResult result) { queryResults.set(shardIndex, result); if (counter.decrementAndGet() == 0) { executeFetchPhase(); } } @Override public void onFailure(Throwable t) { onQueryPhaseFailure(shardIndex, counter, searchId, t); } });
0true
src_main_java_org_elasticsearch_action_search_type_TransportSearchScrollQueryThenFetchAction.java
1,203
public class PaymentProcessorException extends PaymentException { private static final long serialVersionUID = 1L; protected PaymentResponseItem paymentResponseItem; public PaymentProcessorException(PaymentResponseItem paymentResponseItem) { super(); this.paymentResponseItem = paymentResponseItem; } public PaymentProcessorException(String message, Throwable cause, PaymentResponseItem paymentResponseItem) { super(message, cause); this.paymentResponseItem = paymentResponseItem; } public PaymentProcessorException(String message, PaymentResponseItem paymentResponseItem) { super(message); this.paymentResponseItem = paymentResponseItem; } public PaymentProcessorException(Throwable cause, PaymentResponseItem paymentResponseItem) { super(cause); this.paymentResponseItem = paymentResponseItem; } public PaymentResponseItem getPaymentResponseItem() { return paymentResponseItem; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_service_exception_PaymentProcessorException.java
1,761
public static class SloppyArcFixedSourceDistance extends FixedSourceDistanceBase { public SloppyArcFixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) { super(sourceLatitude, sourceLongitude, unit); } @Override public double calculate(double targetLatitude, double targetLongitude) { return SLOPPY_ARC.calculate(sourceLatitude, sourceLongitude, targetLatitude, targetLongitude, unit); } }
0true
src_main_java_org_elasticsearch_common_geo_GeoDistance.java
19
Collections.sort(results, new Comparator<DeclarationWithProximity>() { public int compare(DeclarationWithProximity x, DeclarationWithProximity y) { if (x.getProximity()<y.getProximity()) return -1; if (x.getProximity()>y.getProximity()) return 1; int c = x.getDeclaration().getName().compareTo(y.getDeclaration().getName()); if (c!=0) return c; return x.getDeclaration().getQualifiedNameString() .compareTo(y.getDeclaration().getQualifiedNameString()); } });
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_CompletionUtil.java
2,618
public final class UnsafeHelper { public static final Unsafe UNSAFE; public static final boolean UNSAFE_AVAILABLE; public static final long BYTE_ARRAY_BASE_OFFSET; public static final long SHORT_ARRAY_BASE_OFFSET; public static final long CHAR_ARRAY_BASE_OFFSET; public static final long INT_ARRAY_BASE_OFFSET; public static final long FLOAT_ARRAY_BASE_OFFSET; public static final long LONG_ARRAY_BASE_OFFSET; public static final long DOUBLE_ARRAY_BASE_OFFSET; public static final int BYTE_ARRAY_INDEX_SCALE; public static final int SHORT_ARRAY_INDEX_SCALE; public static final int CHAR_ARRAY_INDEX_SCALE; public static final int INT_ARRAY_INDEX_SCALE; public static final int FLOAT_ARRAY_INDEX_SCALE; public static final int LONG_ARRAY_INDEX_SCALE; public static final int DOUBLE_ARRAY_INDEX_SCALE; static { try { Unsafe unsafe = findUnsafe(); BYTE_ARRAY_BASE_OFFSET = unsafe.arrayBaseOffset(byte[].class); SHORT_ARRAY_BASE_OFFSET = unsafe.arrayBaseOffset(short[].class); CHAR_ARRAY_BASE_OFFSET = unsafe.arrayBaseOffset(char[].class); INT_ARRAY_BASE_OFFSET = unsafe.arrayBaseOffset(int[].class); FLOAT_ARRAY_BASE_OFFSET = unsafe.arrayBaseOffset(float[].class); LONG_ARRAY_BASE_OFFSET = unsafe.arrayBaseOffset(long[].class); DOUBLE_ARRAY_BASE_OFFSET = unsafe.arrayBaseOffset(double[].class); BYTE_ARRAY_INDEX_SCALE = unsafe.arrayIndexScale(byte[].class); SHORT_ARRAY_INDEX_SCALE = unsafe.arrayIndexScale(short[].class); CHAR_ARRAY_INDEX_SCALE = unsafe.arrayIndexScale(char[].class); INT_ARRAY_INDEX_SCALE = unsafe.arrayIndexScale(int[].class); FLOAT_ARRAY_INDEX_SCALE = unsafe.arrayIndexScale(float[].class); LONG_ARRAY_INDEX_SCALE = unsafe.arrayIndexScale(long[].class); DOUBLE_ARRAY_INDEX_SCALE = unsafe.arrayIndexScale(double[].class); // test if unsafe has required methods... byte[] buffer = new byte[8]; unsafe.putChar(buffer, BYTE_ARRAY_BASE_OFFSET, '0'); unsafe.putShort(buffer, BYTE_ARRAY_BASE_OFFSET, (short) 1); unsafe.putInt(buffer, BYTE_ARRAY_BASE_OFFSET, 2); unsafe.putFloat(buffer, BYTE_ARRAY_BASE_OFFSET, 3f); unsafe.putLong(buffer, BYTE_ARRAY_BASE_OFFSET, 4L); unsafe.putDouble(buffer, BYTE_ARRAY_BASE_OFFSET, 5d); unsafe.copyMemory(new byte[8], BYTE_ARRAY_BASE_OFFSET, buffer, BYTE_ARRAY_BASE_OFFSET, buffer.length); UNSAFE = unsafe; UNSAFE_AVAILABLE = UNSAFE != null; } catch (Throwable e) { throw new HazelcastException(e); } } private UnsafeHelper() { } private static Unsafe findUnsafe() { try { return Unsafe.getUnsafe(); } catch (SecurityException se) { return AccessController.doPrivileged(new PrivilegedAction<Unsafe>() { @Override public Unsafe run() { try { Class<Unsafe> type = Unsafe.class; try { Field field = type.getDeclaredField("theUnsafe"); field.setAccessible(true); return type.cast(field.get(type)); } catch (Exception e) { for (Field field : type.getDeclaredFields()) { if (type.isAssignableFrom(field.getType())) { field.setAccessible(true); return type.cast(field.get(type)); } } } } catch (Exception e) { throw new RuntimeException("Unsafe unavailable", e); } throw new RuntimeException("Unsafe unavailable"); } }); } } }
1no label
hazelcast_src_main_java_com_hazelcast_nio_UnsafeHelper.java
1,275
nodesService.execute(new TransportClientNodesService.NodeListenerCallback<Response>() { @Override public void doWithNode(DiscoveryNode node, ActionListener<Response> listener) throws ElasticsearchException { proxy.execute(node, request, listener); } }, listener);
0true
src_main_java_org_elasticsearch_client_transport_support_InternalTransportIndicesAdminClient.java
2,331
public class SettingsFilter extends AbstractComponent { public static interface Filter { void filter(ImmutableSettings.Builder settings); } private final CopyOnWriteArrayList<Filter> filters = new CopyOnWriteArrayList<Filter>(); @Inject public SettingsFilter(Settings settings) { super(settings); } public void addFilter(Filter filter) { filters.add(filter); } public void removeFilter(Filter filter) { filters.remove(filter); } public Settings filterSettings(Settings settings) { ImmutableSettings.Builder builder = ImmutableSettings.settingsBuilder().put(settings); for (Filter filter : filters) { filter.filter(builder); } return builder.build(); } }
0true
src_main_java_org_elasticsearch_common_settings_SettingsFilter.java
3,374
final class BasicOperationService implements InternalOperationService { private final AtomicLong executedOperationsCount = new AtomicLong(); private final NodeEngineImpl nodeEngine; private final Node node; private final ILogger logger; private final AtomicLong callIdGen = new AtomicLong(1); private final Map<RemoteCallKey, RemoteCallKey> executingCalls; final ConcurrentMap<Long, BasicInvocation> invocations; private final long defaultCallTimeout; private final ExecutionService executionService; final BasicOperationScheduler scheduler; BasicOperationService(NodeEngineImpl nodeEngine) { this.nodeEngine = nodeEngine; this.node = nodeEngine.getNode(); this.logger = node.getLogger(OperationService.class); this.defaultCallTimeout = node.getGroupProperties().OPERATION_CALL_TIMEOUT_MILLIS.getLong(); this.executionService = nodeEngine.getExecutionService(); int coreSize = Runtime.getRuntime().availableProcessors(); boolean reallyMultiCore = coreSize >= 8; int concurrencyLevel = reallyMultiCore ? coreSize * 4 : 16; this.executingCalls = new ConcurrentHashMap<RemoteCallKey, RemoteCallKey>(1000, 0.75f, concurrencyLevel); this.invocations = new ConcurrentHashMap<Long, BasicInvocation>(1000, 0.75f, concurrencyLevel); this.scheduler = new BasicOperationScheduler(node, executionService, new BasicOperationProcessorImpl()); } @Override public int getPartitionOperationThreadCount() { return scheduler.partitionOperationThreads.length; } @Override public int getGenericOperationThreadCount() { return scheduler.genericOperationThreads.length; } @Override public int getRunningOperationsCount() { return executingCalls.size(); } @Override public long getExecutedOperationCount() { return executedOperationsCount.get(); } @Override public int getRemoteOperationsCount() { return invocations.size(); } @Override public int getResponseQueueSize() { return scheduler.getResponseQueueSize(); } @Override public int getOperationExecutorQueueSize() { return scheduler.getOperationExecutorQueueSize(); } @Override public int getPriorityOperationExecutorQueueSize() { return scheduler.getPriorityOperationExecutorQueueSize(); } @Override public InvocationBuilder createInvocationBuilder(String serviceName, Operation op, int partitionId) { if (partitionId < 0) { throw new IllegalArgumentException("Partition id cannot be negative!"); } return new BasicInvocationBuilder(nodeEngine, serviceName, op, partitionId); } @Override public InvocationBuilder createInvocationBuilder(String serviceName, Operation op, Address target) { if (target == null) { throw new IllegalArgumentException("Target cannot be null!"); } return new BasicInvocationBuilder(nodeEngine, serviceName, op, target); } @PrivateApi @Override public void receive(final Packet packet) { scheduler.execute(packet); } /** * Runs operation in calling thread. * * @param op */ @Override //todo: move to BasicOperationScheduler public void runOperationOnCallingThread(Operation op) { if (scheduler.isAllowedToRunInCurrentThread(op)) { processOperation(op); } else { throw new IllegalThreadStateException("Operation: " + op + " cannot be run in current thread! -> " + Thread.currentThread()); } } /** * Executes operation in operation executor pool. * * @param op */ @Override public void executeOperation(final Operation op) { scheduler.execute(op); } @Override @SuppressWarnings("unchecked") public <E> InternalCompletableFuture<E> invokeOnPartition(String serviceName, Operation op, int partitionId) { return new BasicPartitionInvocation(nodeEngine, serviceName, op, partitionId, InvocationBuilder.DEFAULT_REPLICA_INDEX, InvocationBuilder.DEFAULT_TRY_COUNT, InvocationBuilder.DEFAULT_TRY_PAUSE_MILLIS, InvocationBuilder.DEFAULT_CALL_TIMEOUT, null, null, InvocationBuilder.DEFAULT_DESERIALIZE_RESULT).invoke(); } @Override @SuppressWarnings("unchecked") public <E> InternalCompletableFuture<E> invokeOnTarget(String serviceName, Operation op, Address target) { return new BasicTargetInvocation(nodeEngine, serviceName, op, target, InvocationBuilder.DEFAULT_TRY_COUNT, InvocationBuilder.DEFAULT_TRY_PAUSE_MILLIS, InvocationBuilder.DEFAULT_CALL_TIMEOUT, null, null, InvocationBuilder.DEFAULT_DESERIALIZE_RESULT).invoke(); } // =============================== processing response =============================== private void processResponsePacket(Packet packet) { try { final Data data = packet.getData(); final Response response = (Response) nodeEngine.toObject(data); if (response instanceof NormalResponse) { notifyRemoteCall((NormalResponse) response); } else if (response instanceof BackupResponse) { notifyBackupCall(response.getCallId()); } else { throw new IllegalStateException("Unrecognized response type: " + response); } } catch (Throwable e) { logger.severe("While processing response...", e); } } // TODO: @mm - operations those do not return response can cause memory leaks! Call->Invocation->Operation->Data private void notifyRemoteCall(NormalResponse response) { BasicInvocation invocation = invocations.get(response.getCallId()); if (invocation == null) { throw new HazelcastException("No invocation for response:" + response); } invocation.notify(response); } @Override public void notifyBackupCall(long callId) { try { final BasicInvocation invocation = invocations.get(callId); if (invocation != null) { invocation.signalOneBackupComplete(); } } catch (Exception e) { ReplicaErrorLogger.log(e, logger); } } // =============================== processing operation =============================== private void processOperationPacket(Packet packet) { final Connection conn = packet.getConn(); try { final Address caller = conn.getEndPoint(); final Data data = packet.getData(); final Object object = nodeEngine.toObject(data); final Operation op = (Operation) object; op.setNodeEngine(nodeEngine); OperationAccessor.setCallerAddress(op, caller); OperationAccessor.setConnection(op, conn); ResponseHandlerFactory.setRemoteResponseHandler(nodeEngine, op); if (!isJoinOperation(op) && node.clusterService.getMember(op.getCallerAddress()) == null) { final Exception error = new CallerNotMemberException(op.getCallerAddress(), op.getPartitionId(), op.getClass().getName(), op.getServiceName()); handleOperationError(op, error); } else { String executorName = op.getExecutorName(); if (executorName == null) { processOperation(op); } else { ExecutorService executor = executionService.getExecutor(executorName); if (executor == null) { throw new IllegalStateException("Could not found executor with name: " + executorName); } executor.execute(new LocalOperationProcessor(op)); } } } catch (Throwable e) { logger.severe(e); } } /** * Runs operation in calling thread. */ private void processOperation(final Operation op) { executedOperationsCount.incrementAndGet(); RemoteCallKey callKey = null; try { if (isCallTimedOut(op)) { Object response = new CallTimeoutException(op.getClass().getName(), op.getInvocationTime(), op.getCallTimeout()); op.getResponseHandler().sendResponse(response); return; } callKey = beforeCallExecution(op); final int partitionId = op.getPartitionId(); if (op instanceof PartitionAwareOperation) { if (partitionId < 0) { throw new IllegalArgumentException("Partition id cannot be negative! -> " + partitionId); } final InternalPartition internalPartition = nodeEngine.getPartitionService().getPartition(partitionId); if (retryDuringMigration(op) && internalPartition.isMigrating()) { throw new PartitionMigratingException(node.getThisAddress(), partitionId, op.getClass().getName(), op.getServiceName()); } final Address owner = internalPartition.getReplicaAddress(op.getReplicaIndex()); if (op.validatesTarget() && !node.getThisAddress().equals(owner)) { throw new WrongTargetException(node.getThisAddress(), owner, partitionId, op.getReplicaIndex(), op.getClass().getName(), op.getServiceName()); } } OperationAccessor.setStartTime(op, Clock.currentTimeMillis()); op.beforeRun(); if (op instanceof WaitSupport) { WaitSupport waitSupport = (WaitSupport) op; if (waitSupport.shouldWait()) { nodeEngine.waitNotifyService.await(waitSupport); return; } } op.run(); final boolean returnsResponse = op.returnsResponse(); Object response = null; if (op instanceof BackupAwareOperation) { final BackupAwareOperation backupAwareOp = (BackupAwareOperation) op; int syncBackupCount = 0; if (backupAwareOp.shouldBackup()) { syncBackupCount = sendBackups(backupAwareOp); } if (returnsResponse) { response = new NormalResponse(op.getResponse(), op.getCallId(), syncBackupCount, op.isUrgent()); } } if (returnsResponse) { if (response == null) { response = op.getResponse(); } final ResponseHandler responseHandler = op.getResponseHandler(); if (responseHandler == null) { throw new IllegalStateException("ResponseHandler should not be null!"); } responseHandler.sendResponse(response); } try { op.afterRun(); if (op instanceof Notifier) { final Notifier notifier = (Notifier) op; if (notifier.shouldNotify()) { nodeEngine.waitNotifyService.notify(notifier); } } } catch (Throwable e) { // passed the response phase // `afterRun` and `notifier` errors cannot be sent to the caller anymore // just log the error logOperationError(op, e); } } catch (Throwable e) { handleOperationError(op, e); } finally { afterCallExecution(op, callKey); } } private static boolean retryDuringMigration(Operation op) { return !(op instanceof ReadonlyOperation || OperationAccessor.isMigrationOperation(op)); } @PrivateApi public boolean isCallTimedOut(Operation op) { if (op.returnsResponse() && op.getCallId() != 0) { final long callTimeout = op.getCallTimeout(); final long invocationTime = op.getInvocationTime(); final long expireTime = invocationTime + callTimeout; if (expireTime > 0 && expireTime < Long.MAX_VALUE) { final long now = nodeEngine.getClusterTime(); if (expireTime < now) { return true; } } } return false; } private RemoteCallKey beforeCallExecution(Operation op) { RemoteCallKey callKey = null; if (op.getCallId() != 0 && op.returnsResponse()) { callKey = new RemoteCallKey(op); RemoteCallKey current; if ((current = executingCalls.put(callKey, callKey)) != null) { logger.warning("Duplicate Call record! -> " + callKey + " / " + current + " == " + op.getClass().getName()); } } return callKey; } private void afterCallExecution(Operation op, RemoteCallKey callKey) { if (callKey != null && op.getCallId() != 0 && op.returnsResponse()) { if (executingCalls.remove(callKey) == null) { logger.severe("No Call record has been found: -> " + callKey + " == " + op.getClass().getName()); } } } private int sendBackups(BackupAwareOperation backupAwareOp) throws Exception { Operation op = (Operation) backupAwareOp; boolean returnsResponse = op.returnsResponse(); InternalPartitionService partitionService = nodeEngine.getPartitionService(); int maxBackupCount = InternalPartition.MAX_BACKUP_COUNT; int maxPossibleBackupCount = Math.min(partitionService.getMemberGroupsSize() - 1, maxBackupCount); int requestedSyncBackupCount = backupAwareOp.getSyncBackupCount() > 0 ? Math.min(maxBackupCount, backupAwareOp.getSyncBackupCount()) : 0; int requestedAsyncBackupCount = backupAwareOp.getAsyncBackupCount() > 0 ? Math.min(maxBackupCount - requestedSyncBackupCount, backupAwareOp.getAsyncBackupCount()) : 0; int totalRequestedBackupCount = requestedSyncBackupCount + requestedAsyncBackupCount; if (totalRequestedBackupCount == 0) { return 0; } int partitionId = op.getPartitionId(); long[] replicaVersions = partitionService.incrementPartitionReplicaVersions(partitionId, totalRequestedBackupCount); int syncBackupCount = Math.min(maxPossibleBackupCount, requestedSyncBackupCount); int asyncBackupCount = Math.min(maxPossibleBackupCount - syncBackupCount, requestedAsyncBackupCount); if (!returnsResponse) { asyncBackupCount += syncBackupCount; syncBackupCount = 0; } int totalBackupCount = syncBackupCount + asyncBackupCount; if (totalBackupCount == 0) { return 0; } int sentSyncBackupCount = 0; String serviceName = op.getServiceName(); InternalPartition partition = partitionService.getPartition(partitionId); for (int replicaIndex = 1; replicaIndex <= totalBackupCount; replicaIndex++) { Address target = partition.getReplicaAddress(replicaIndex); if (target != null) { if (target.equals(node.getThisAddress())) { throw new IllegalStateException("Normally shouldn't happen! Owner node and backup node " + "are the same! " + partition); } else { Operation backupOp = backupAwareOp.getBackupOperation(); if (backupOp == null) { throw new IllegalArgumentException("Backup operation should not be null!"); } backupOp.setPartitionId(partitionId).setReplicaIndex(replicaIndex).setServiceName(serviceName); Data backupOpData = nodeEngine.getSerializationService().toData(backupOp); boolean isSyncBackup = replicaIndex <= syncBackupCount; Backup backup = new Backup(backupOpData, op.getCallerAddress(), replicaVersions, isSyncBackup); backup.setPartitionId(partitionId).setReplicaIndex(replicaIndex).setServiceName(serviceName) .setCallerUuid(nodeEngine.getLocalMember().getUuid()); OperationAccessor.setCallId(backup, op.getCallId()); send(backup, target); if (isSyncBackup) { sentSyncBackupCount++; } } } } return sentSyncBackupCount; } private void handleOperationError(Operation op, Throwable e) { if (e instanceof OutOfMemoryError) { OutOfMemoryErrorDispatcher.onOutOfMemory((OutOfMemoryError) e); } op.logError(e); ResponseHandler responseHandler = op.getResponseHandler(); if (op.returnsResponse() && responseHandler != null) { try { if (node.isActive()) { responseHandler.sendResponse(e); } else if (responseHandler.isLocal()) { responseHandler.sendResponse(new HazelcastInstanceNotActiveException()); } } catch (Throwable t) { logger.warning("While sending op error... op: " + op + ", error: " + e, t); } } } private void logOperationError(Operation op, Throwable e) { if (e instanceof OutOfMemoryError) { OutOfMemoryErrorDispatcher.onOutOfMemory((OutOfMemoryError) e); } op.logError(e); } @Override public Map<Integer, Object> invokeOnAllPartitions(String serviceName, OperationFactory operationFactory) throws Exception { Map<Address, List<Integer>> memberPartitions = nodeEngine.getPartitionService().getMemberPartitionsMap(); return invokeOnPartitions(serviceName, operationFactory, memberPartitions); } @Override public Map<Integer, Object> invokeOnPartitions(String serviceName, OperationFactory operationFactory, Collection<Integer> partitions) throws Exception { final Map<Address, List<Integer>> memberPartitions = new HashMap<Address, List<Integer>>(3); for (int partition : partitions) { Address owner = nodeEngine.getPartitionService().getPartitionOwner(partition); if (!memberPartitions.containsKey(owner)) { memberPartitions.put(owner, new ArrayList<Integer>()); } memberPartitions.get(owner).add(partition); } return invokeOnPartitions(serviceName, operationFactory, memberPartitions); } private Map<Integer, Object> invokeOnPartitions(String serviceName, OperationFactory operationFactory, Map<Address, List<Integer>> memberPartitions) throws Exception { final Thread currentThread = Thread.currentThread(); if (currentThread instanceof BasicOperationScheduler.OperationThread) { throw new IllegalThreadStateException(currentThread + " cannot make invocation on multiple partitions!"); } final Map<Address, Future> responses = new HashMap<Address, Future>(memberPartitions.size()); for (Map.Entry<Address, List<Integer>> mp : memberPartitions.entrySet()) { final Address address = mp.getKey(); final List<Integer> partitions = mp.getValue(); final PartitionIteratingOperation pi = new PartitionIteratingOperation(partitions, operationFactory); Future future = createInvocationBuilder(serviceName, pi, address).setTryCount(10).setTryPauseMillis(300).invoke(); responses.put(address, future); } Map<Integer, Object> partitionResults = new HashMap<Integer, Object>( nodeEngine.getPartitionService().getPartitionCount()); int x = 0; for (Map.Entry<Address, Future> response : responses.entrySet()) { try { Future future = response.getValue(); PartitionResponse result = (PartitionResponse) nodeEngine.toObject(future.get()); partitionResults.putAll(result.asMap()); } catch (Throwable t) { if (logger.isFinestEnabled()) { logger.finest(t); } else { logger.warning(t.getMessage()); } List<Integer> partitions = memberPartitions.get(response.getKey()); for (Integer partition : partitions) { partitionResults.put(partition, t); } } x++; } final List<Integer> failedPartitions = new LinkedList<Integer>(); for (Map.Entry<Integer, Object> partitionResult : partitionResults.entrySet()) { int partitionId = partitionResult.getKey(); Object result = partitionResult.getValue(); if (result instanceof Throwable) { failedPartitions.add(partitionId); } } for (Integer failedPartition : failedPartitions) { Future f = createInvocationBuilder(serviceName, operationFactory.createOperation(), failedPartition).invoke(); partitionResults.put(failedPartition, f); } for (Integer failedPartition : failedPartitions) { Future f = (Future) partitionResults.get(failedPartition); Object result = f.get(); partitionResults.put(failedPartition, result); } return partitionResults; } @Override public boolean send(final Operation op, final Address target) { if (target == null) { throw new IllegalArgumentException("Target is required!"); } if (nodeEngine.getThisAddress().equals(target)) { throw new IllegalArgumentException("Target is this node! -> " + target + ", op: " + op); } return send(op, node.getConnectionManager().getOrConnect(target)); } @Override public boolean send(Response response, Address target) { if (target == null) { throw new IllegalArgumentException("Target is required!"); } if (nodeEngine.getThisAddress().equals(target)) { throw new IllegalArgumentException("Target is this node! -> " + target + ", response: " + response); } Data data = nodeEngine.toData(response); Packet packet = new Packet(data, nodeEngine.getSerializationContext()); packet.setHeader(Packet.HEADER_OP); packet.setHeader(Packet.HEADER_RESPONSE); if (response.isUrgent()) { packet.setHeader(Packet.HEADER_URGENT); } return nodeEngine.send(packet, node.getConnectionManager().getOrConnect(target)); } private boolean send(final Operation op, final Connection connection) { Data data = nodeEngine.toData(op); //enable this line to get some logging of sizes of operations. //System.out.println(op.getClass()+" "+data.bufferSize()); final int partitionId = scheduler.getPartitionIdForExecution(op); Packet packet = new Packet(data, partitionId, nodeEngine.getSerializationContext()); packet.setHeader(Packet.HEADER_OP); if (op instanceof UrgentSystemOperation) { packet.setHeader(Packet.HEADER_URGENT); } return nodeEngine.send(packet, connection); } public long registerInvocation(BasicInvocation invocation) { long callId = callIdGen.getAndIncrement(); Operation op = invocation.op; if (op.getCallId() != 0) { invocations.remove(op.getCallId()); } invocations.put(callId, invocation); setCallId(invocation.op, callId); return callId; } public void deregisterInvocation(long id) { invocations.remove(id); } @PrivateApi long getDefaultCallTimeout() { return defaultCallTimeout; } @PrivateApi boolean isOperationExecuting(Address callerAddress, String callerUuid, long operationCallId) { return executingCalls.containsKey(new RemoteCallKey(callerAddress, callerUuid, operationCallId)); } @PrivateApi boolean isOperationExecuting(Address callerAddress, String callerUuid, String serviceName, Object identifier) { Object service = nodeEngine.getService(serviceName); if (service == null) { logger.severe("Not able to find operation execution info. Invalid service: " + serviceName); return false; } if (service instanceof ExecutionTracingService) { return ((ExecutionTracingService) service).isOperationExecuting(callerAddress, callerUuid, identifier); } logger.severe("Not able to find operation execution info. Invalid service: " + service); return false; } @Override public void onMemberLeft(final MemberImpl member) { // postpone notifying calls since real response may arrive in the mean time. nodeEngine.getExecutionService().schedule(new Runnable() { public void run() { final Iterator<BasicInvocation> iter = invocations.values().iterator(); while (iter.hasNext()) { final BasicInvocation invocation = iter.next(); if (invocation.isCallTarget(member)) { iter.remove(); invocation.notify(new MemberLeftException(member)); } } } }, 1111, TimeUnit.MILLISECONDS); } @Override public void shutdown() { logger.finest("Stopping operation threads..."); final Object response = new HazelcastInstanceNotActiveException(); for (BasicInvocation invocation : invocations.values()) { invocation.notify(response); } invocations.clear(); scheduler.shutdown(); } public class BasicOperationProcessorImpl implements BasicOperationProcessor { @Override public void process(Object o) { if (o == null) { throw new IllegalArgumentException(); } else if (o instanceof Operation) { processOperation((Operation) o); } else if (o instanceof Packet) { Packet packet = (Packet) o; if (packet.isHeaderSet(Packet.HEADER_RESPONSE)) { processResponsePacket(packet); } else { processOperationPacket(packet); } } else if (o instanceof Runnable) { ((Runnable) o).run(); } else { throw new IllegalArgumentException("Unrecognized task:" + o); } } } /** * 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() { processOperation(op); } } private static class RemoteCallKey { private final long time = Clock.currentTimeMillis(); private final Address callerAddress; // human readable caller private final String callerUuid; private final long callId; private RemoteCallKey(Address callerAddress, String callerUuid, long callId) { if (callerUuid == null) { throw new IllegalArgumentException("Caller UUID is required!"); } this.callerAddress = callerAddress; if (callerAddress == null) { throw new IllegalArgumentException("Caller address is required!"); } this.callerUuid = callerUuid; this.callId = callId; } private RemoteCallKey(final Operation op) { callerUuid = op.getCallerUuid(); if (callerUuid == null) { throw new IllegalArgumentException("Caller UUID is required! -> " + op); } callerAddress = op.getCallerAddress(); if (callerAddress == null) { throw new IllegalArgumentException("Caller address is required! -> " + op); } callId = op.getCallId(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RemoteCallKey callKey = (RemoteCallKey) o; if (callId != callKey.callId) return false; if (!callerUuid.equals(callKey.callerUuid)) return false; return true; } @Override public int hashCode() { int result = callerUuid.hashCode(); result = 31 * result + (int) (callId ^ (callId >>> 32)); return result; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("RemoteCallKey"); sb.append("{callerAddress=").append(callerAddress); sb.append(", callerUuid=").append(callerUuid); sb.append(", callId=").append(callId); sb.append(", time=").append(time); sb.append('}'); return sb.toString(); } } }
1no label
hazelcast_src_main_java_com_hazelcast_spi_impl_BasicOperationService.java
1,021
applyTailIndexes(lastIndexResult, new IndexValuesResultListener() { @Override public boolean addResult(OIdentifiable value) { result.add(value); return true; } });
0true
core_src_main_java_com_orientechnologies_orient_core_sql_OChainedIndexProxy.java
731
public class CollectionAddRequest extends CollectionRequest { protected Data value; public CollectionAddRequest() { } public CollectionAddRequest(String name, Data value) { super(name); this.value = value; } @Override protected Operation prepareOperation() { return new CollectionAddOperation(name, value); } @Override public int getClassId() { return CollectionPortableHook.COLLECTION_ADD; } public void write(PortableWriter writer) throws IOException { super.write(writer); value.writeData(writer.getRawDataOutput()); } public void read(PortableReader reader) throws IOException { super.read(reader); value = new Data(); value.readData(reader.getRawDataInput()); } @Override public String getRequiredAction() { return ActionConstants.ACTION_ADD; } }
0true
hazelcast_src_main_java_com_hazelcast_collection_client_CollectionAddRequest.java
2,145
public class AllEntries extends Reader { public static class Entry { private final String name; private final FastStringReader reader; private final int startOffset; private final float boost; public Entry(String name, FastStringReader reader, int startOffset, float boost) { this.name = name; this.reader = reader; this.startOffset = startOffset; this.boost = boost; } public int startOffset() { return startOffset; } public String name() { return this.name; } public float boost() { return this.boost; } public FastStringReader reader() { return this.reader; } } private final List<Entry> entries = Lists.newArrayList(); private Entry current; private Iterator<Entry> it; private boolean itsSeparatorTime = false; private boolean customBoost = false; public void addText(String name, String text, float boost) { if (boost != 1.0f) { customBoost = true; } final int lastStartOffset; if (entries.isEmpty()) { lastStartOffset = -1; } else { final Entry last = entries.get(entries.size() - 1); lastStartOffset = last.startOffset() + last.reader().length(); } final int startOffset = lastStartOffset + 1; // +1 because we insert a space between tokens Entry entry = new Entry(name, new FastStringReader(text), startOffset, boost); entries.add(entry); } public boolean customBoost() { return customBoost; } public void clear() { this.entries.clear(); this.current = null; this.it = null; itsSeparatorTime = false; } public void reset() { try { for (Entry entry : entries) { entry.reader().reset(); } } catch (IOException e) { throw new ElasticsearchIllegalStateException("should not happen"); } it = entries.iterator(); if (it.hasNext()) { current = it.next(); itsSeparatorTime = true; } } public String buildText() { reset(); FastCharArrayWriter writer = new FastCharArrayWriter(); for (Entry entry : entries) { writer.append(entry.reader()); writer.append(' '); } reset(); return writer.toString(); } public List<Entry> entries() { return this.entries; } public Set<String> fields() { Set<String> fields = newHashSet(); for (Entry entry : entries) { fields.add(entry.name()); } return fields; } // compute the boost for a token with the given startOffset public float boost(int startOffset) { if (!entries.isEmpty()) { int lo = 0, hi = entries.size() - 1; while (lo <= hi) { final int mid = (lo + hi) >>> 1; final int midOffset = entries.get(mid).startOffset(); if (startOffset < midOffset) { hi = mid - 1; } else { lo = mid + 1; } } final int index = Math.max(0, hi); // protection against broken token streams assert entries.get(index).startOffset() <= startOffset; assert index == entries.size() - 1 || entries.get(index + 1).startOffset() > startOffset; return entries.get(index).boost(); } return 1.0f; } @Override public int read(char[] cbuf, int off, int len) throws IOException { if (current == null) { return -1; } if (customBoost) { int result = current.reader().read(cbuf, off, len); if (result == -1) { if (itsSeparatorTime) { itsSeparatorTime = false; cbuf[off] = ' '; return 1; } itsSeparatorTime = true; // close(); No need to close, we work on in mem readers if (it.hasNext()) { current = it.next(); } else { current = null; } return read(cbuf, off, len); } return result; } else { int read = 0; while (len > 0) { int result = current.reader().read(cbuf, off, len); if (result == -1) { if (it.hasNext()) { current = it.next(); } else { current = null; if (read == 0) { return -1; } return read; } cbuf[off++] = ' '; read++; len--; } else { read += result; off += result; len -= result; } } return read; } } @Override public void close() { if (current != null) { // no need to close, these are readers on strings current = null; } } @Override public boolean ready() throws IOException { return (current != null) && current.reader().ready(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Entry entry : entries) { sb.append(entry.name()).append(','); } return sb.toString(); } }
0true
src_main_java_org_elasticsearch_common_lucene_all_AllEntries.java
1,864
class LookupProcessor extends AbstractProcessor { LookupProcessor(Errors errors) { super(errors); } @Override public <T> Boolean visit(MembersInjectorLookup<T> lookup) { try { MembersInjector<T> membersInjector = injector.membersInjectorStore.get(lookup.getType(), errors); lookup.initializeDelegate(membersInjector); } catch (ErrorsException e) { errors.merge(e.getErrors()); // TODO: source } return true; } @Override public <T> Boolean visit(ProviderLookup<T> lookup) { // ensure the provider can be created try { Provider<T> provider = injector.getProviderOrThrow(lookup.getKey(), errors); lookup.initializeDelegate(provider); } catch (ErrorsException e) { errors.merge(e.getErrors()); // TODO: source } return true; } }
0true
src_main_java_org_elasticsearch_common_inject_LookupProcessor.java
328
public class PackageExplorerActionGroup extends CompositeActionGroup { private static final String FRAME_ACTION_SEPARATOR_ID= "FRAME_ACTION_SEPARATOR_ID"; //$NON-NLS-1$ private static final String FRAME_ACTION_GROUP_ID= "FRAME_ACTION_GROUP_ID"; //$NON-NLS-1$ private PackageExplorerPart fPart; private FrameList fFrameList; private GoIntoAction fZoomInAction; private BackAction fBackAction; private ForwardAction fForwardAction; private UpAction fUpAction; private boolean fFrameActionsShown; private GotoTypeAction fGotoTypeAction; private GotoPackageAction fGotoPackageAction; private GotoResourceAction fGotoResourceAction; private CollapseAllAction fCollapseAllAction; private SelectAllAction fSelectAllAction; private ToggleLinkingAction fToggleLinkingAction; private RefactorActionGroup fRefactorActionGroup; private NavigateActionGroup fNavigateActionGroup; private ViewActionGroup fViewActionGroup; private CustomFiltersActionGroup fCustomFiltersActionGroup; private IAction fGotoRequiredProjectAction; private ProjectActionGroup fProjectActionGroup; public PackageExplorerActionGroup(PackageExplorerPart part) { super(); fPart= part; fFrameActionsShown= false; TreeViewer viewer= part.getTreeViewer(); IPropertyChangeListener workingSetListener= new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { doWorkingSetChanged(event); } }; IWorkbenchPartSite site = fPart.getSite(); setGroups(new ActionGroup[] { new NewWizardsActionGroup(site), fNavigateActionGroup= new NavigateActionGroup(fPart), new CCPActionGroup(fPart), new GenerateBuildPathActionGroup(fPart), new GenerateActionGroup(fPart), fRefactorActionGroup= new RefactorActionGroup(fPart), new ImportActionGroup(fPart), new BuildActionGroup(fPart), new JavaSearchActionGroup(fPart), fProjectActionGroup= new ProjectActionGroup(fPart), fViewActionGroup= new ViewActionGroup(fPart.getRootMode(), workingSetListener, site), fCustomFiltersActionGroup= new CustomFiltersActionGroup(fPart, viewer), new LayoutActionGroup(fPart) }); fViewActionGroup.fillFilters(viewer); PackagesFrameSource frameSource= new PackagesFrameSource(fPart); fFrameList= new FrameList(frameSource); frameSource.connectTo(fFrameList); fZoomInAction= new GoIntoAction(fFrameList); fPart.getSite().getSelectionProvider().addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { fZoomInAction.update(); } }); fBackAction= new BackAction(fFrameList); fForwardAction= new ForwardAction(fFrameList); fUpAction= new UpAction(fFrameList); fFrameList.addPropertyChangeListener(new IPropertyChangeListener() { // connect after the actions (order of property listener) public void propertyChange(PropertyChangeEvent event) { fPart.updateTitle(); fPart.updateToolbar(); } }); fGotoTypeAction= new GotoTypeAction(fPart); fGotoPackageAction= new GotoPackageAction(fPart); fGotoResourceAction= new GotoResourceAction(fPart); fCollapseAllAction= new CollapseAllAction(fPart.getTreeViewer()); fCollapseAllAction.setActionDefinitionId(CollapseAllHandler.COMMAND_ID); fToggleLinkingAction = new ToggleLinkingAction(fPart); fToggleLinkingAction.setActionDefinitionId(IWorkbenchCommandConstants.NAVIGATE_TOGGLE_LINK_WITH_EDITOR); fGotoRequiredProjectAction= new GotoRequiredProjectAction(fPart); fSelectAllAction= new SelectAllAction(fPart.getTreeViewer()); } @Override public void dispose() { super.dispose(); } //---- Persistent state ----------------------------------------------------------------------- /* package */ void restoreFilterAndSorterState(IMemento memento) { fViewActionGroup.restoreState(memento); fCustomFiltersActionGroup.restoreState(memento); } /* package */ void saveFilterAndSorterState(IMemento memento) { fViewActionGroup.saveState(memento); fCustomFiltersActionGroup.saveState(memento); } //---- Action Bars ---------------------------------------------------------------------------- @Override public void fillActionBars(IActionBars actionBars) { super.fillActionBars(actionBars); setGlobalActionHandlers(actionBars); fillToolBar(actionBars.getToolBarManager()); fillViewMenu(actionBars.getMenuManager()); } private void setGlobalActionHandlers(IActionBars actionBars) { // Navigate Go Into and Go To actions. actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, fZoomInAction); actionBars.setGlobalActionHandler(ActionFactory.BACK.getId(), fBackAction); actionBars.setGlobalActionHandler(ActionFactory.FORWARD.getId(), fForwardAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.UP, fUpAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_TO_RESOURCE, fGotoResourceAction); actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_TYPE, fGotoTypeAction); actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_PACKAGE, fGotoPackageAction); actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), fSelectAllAction); fRefactorActionGroup.retargetFileMenuActions(actionBars); IHandlerService handlerService= (IHandlerService) fPart.getViewSite().getService(IHandlerService.class); handlerService.activateHandler(IWorkbenchCommandConstants.NAVIGATE_TOGGLE_LINK_WITH_EDITOR, new ActionHandler(fToggleLinkingAction)); handlerService.activateHandler(CollapseAllHandler.COMMAND_ID, new ActionHandler(fCollapseAllAction)); } /* package */ void fillToolBar(IToolBarManager toolBar) { if (fBackAction.isEnabled() || fUpAction.isEnabled() || fForwardAction.isEnabled()) { toolBar.add(fBackAction); toolBar.add(fForwardAction); toolBar.add(fUpAction); toolBar.add(new Separator(FRAME_ACTION_SEPARATOR_ID)); fFrameActionsShown= true; } toolBar.add(new GroupMarker(FRAME_ACTION_GROUP_ID)); toolBar.add(fCollapseAllAction); toolBar.add(fToggleLinkingAction); toolBar.update(true); } public void updateToolBar(IToolBarManager toolBar) { boolean hasBeenFrameActionsShown= fFrameActionsShown; fFrameActionsShown= fBackAction.isEnabled() || fUpAction.isEnabled() || fForwardAction.isEnabled(); if (fFrameActionsShown != hasBeenFrameActionsShown) { if (hasBeenFrameActionsShown) { toolBar.remove(fBackAction.getId()); toolBar.remove(fForwardAction.getId()); toolBar.remove(fUpAction.getId()); toolBar.remove(FRAME_ACTION_SEPARATOR_ID); } else { toolBar.prependToGroup(FRAME_ACTION_GROUP_ID, new Separator(FRAME_ACTION_SEPARATOR_ID)); toolBar.prependToGroup(FRAME_ACTION_GROUP_ID, fUpAction); toolBar.prependToGroup(FRAME_ACTION_GROUP_ID, fForwardAction); toolBar.prependToGroup(FRAME_ACTION_GROUP_ID, fBackAction); } toolBar.update(true); } } /* package */ void fillViewMenu(IMenuManager menu) { menu.add(new Separator()); menu.add(fToggleLinkingAction); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$ } //---- Context menu ------------------------------------------------------------------------- @Override public void fillContextMenu(IMenuManager menu) { IStructuredSelection selection= (IStructuredSelection)getContext().getSelection(); int size= selection.size(); Object element= selection.getFirstElement(); if (element instanceof ClassPathContainer.RequiredProjectWrapper) menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fGotoRequiredProjectAction); addGotoMenu(menu, element, size); addOpenNewWindowAction(menu, element); super.fillContextMenu(menu); } private void addGotoMenu(IMenuManager menu, Object element, int size) { boolean enabled= size == 1 && fPart.getTreeViewer().isExpandable(element) && (isGoIntoTarget(element) || element instanceof IContainer); fZoomInAction.setEnabled(enabled); if (enabled) menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction); } private boolean isGoIntoTarget(Object element) { if (element == null) return false; if (element instanceof IJavaElement) { int type= ((IJavaElement)element).getElementType(); return type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT || type == IJavaElement.PACKAGE_FRAGMENT; } if (element instanceof IWorkingSet) { return true; } return false; } private void addOpenNewWindowAction(IMenuManager menu, Object element) { if (element instanceof IJavaElement) { element= ((IJavaElement)element).getResource(); } // fix for 64890 Package explorer out of sync when open/closing projects [package explorer] 64890 if (element instanceof IProject && !((IProject)element).isOpen()) return; if (!(element instanceof IContainer)) return; menu.appendToGroup( IContextMenuConstants.GROUP_OPEN, new OpenInNewWindowAction(fPart.getSite().getWorkbenchWindow(), (IContainer)element)); } //---- Key board and mouse handling ------------------------------------------------------------ /* package*/ void handleDoubleClick(DoubleClickEvent event) { TreeViewer viewer= fPart.getTreeViewer(); IStructuredSelection selection= (IStructuredSelection)event.getSelection(); Object element= selection.getFirstElement(); if (viewer.isExpandable(element)) { if (doubleClickGoesInto()) { // don't zoom into compilation units and class files if (element instanceof ICompilationUnit || element instanceof IClassFile) return; if (element instanceof IOpenable || element instanceof IContainer || element instanceof IWorkingSet) { fZoomInAction.run(); } } else { IAction openAction= fNavigateActionGroup.getOpenAction(); if (openAction != null && openAction.isEnabled() && OpenStrategy.getOpenMethod() == OpenStrategy.DOUBLE_CLICK) return; if (selection instanceof ITreeSelection) { TreePath[] paths= ((ITreeSelection)selection).getPathsFor(element); for (int i= 0; i < paths.length; i++) { viewer.setExpandedState(paths[i], !viewer.getExpandedState(paths[i])); } } else { viewer.setExpandedState(element, !viewer.getExpandedState(element)); } } } else if (element instanceof IProject && !((IProject) element).isOpen()) { OpenProjectAction openProjectAction= fProjectActionGroup.getOpenProjectAction(); if (openProjectAction.isEnabled()) { openProjectAction.run(); } } } /** * Called by Package Explorer. * * @param event the open event * @param activate <code>true</code> if the opened editor should be activated */ /* package */void handleOpen(ISelection event, boolean activate) { IAction openAction= fNavigateActionGroup.getOpenAction(); if (openAction != null && openAction.isEnabled()) { // XXX: should use the given arguments instead of using org.eclipse.jface.util.OpenStrategy.activateOnOpen() openAction.run(); return; } } /* package */ void handleKeyEvent(KeyEvent event) { if (event.stateMask != 0) return; if (event.keyCode == SWT.BS) { if (fUpAction != null && fUpAction.isEnabled()) { fUpAction.run(); event.doit= false; } } } private void doWorkingSetChanged(PropertyChangeEvent event) { if (ViewActionGroup.MODE_CHANGED.equals(event.getProperty())) { fPart.rootModeChanged(((Integer)event.getNewValue()).intValue()); Object oldInput= null; Object newInput= null; if (fPart.getRootMode() == PackageExplorerPart.PROJECTS_AS_ROOTS) { oldInput= fPart.getWorkingSetModel(); newInput= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); } else { oldInput= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); newInput= fPart.getWorkingSetModel(); } if (oldInput != null && newInput != null) { Frame frame; for (int i= 0; (frame= fFrameList.getFrame(i)) != null; i++) { if (frame instanceof TreeFrame) { TreeFrame treeFrame= (TreeFrame)frame; if (oldInput.equals(treeFrame.getInput())) treeFrame.setInput(newInput); } } } } else { IWorkingSet workingSet= (IWorkingSet) event.getNewValue(); String workingSetLabel= null; if (workingSet != null) workingSetLabel= BasicElementLabels.getWorkingSetLabel(workingSet); fPart.setWorkingSetLabel(workingSetLabel); fPart.updateTitle(); String property= event.getProperty(); if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) { TreeViewer viewer= fPart.getTreeViewer(); viewer.getControl().setRedraw(false); viewer.refresh(); viewer.getControl().setRedraw(true); } } } private boolean doubleClickGoesInto() { return PreferenceConstants.DOUBLE_CLICK_GOES_INTO.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.DOUBLE_CLICK)); } public FrameAction getUpAction() { return fUpAction; } public FrameAction getBackAction() { return fBackAction; } public FrameAction getForwardAction() { return fForwardAction; } public ViewActionGroup getWorkingSetActionGroup() { return fViewActionGroup; } public CustomFiltersActionGroup getCustomFilterActionGroup() { return fCustomFiltersActionGroup; } public FrameList getFrameList() { return fFrameList; } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_explorer_PackageExplorerActionGroup.java
1,450
public static enum State { INIT((byte) 0), STARTED((byte) 1), SUCCESS((byte) 2), FAILED((byte) 3), ABORTED((byte) 4), MISSING((byte) 5); private byte value; State(byte value) { this.value = value; } public byte value() { return value; } public boolean completed() { switch (this) { case INIT: return false; case STARTED: return false; case SUCCESS: return true; case FAILED: return true; case ABORTED: return false; case MISSING: return true; default: assert false; return true; } } public boolean failed() { switch (this) { case INIT: return false; case STARTED: return false; case SUCCESS: return false; case FAILED: return true; case ABORTED: return true; case MISSING: return true; default: assert false; return false; } } public static State fromValue(byte value) { switch (value) { case 0: return INIT; case 1: return STARTED; case 2: return SUCCESS; case 3: return FAILED; case 4: return ABORTED; case 5: return MISSING; default: throw new ElasticsearchIllegalArgumentException("No snapshot state for value [" + value + "]"); } } }
0true
src_main_java_org_elasticsearch_cluster_metadata_SnapshotMetaData.java
211
class HeartBeat implements Runnable { long begin; final int heartBeatTimeout = heartBeatInterval/2; @Override public void run() { if (!live) { return; } begin = Clock.currentTimeMillis(); final Map<ClientConnection, Future> futureMap = new HashMap<ClientConnection, Future>(); for (ClientConnection connection : connections.values()) { if (begin - connection.lastReadTime() > heartBeatTimeout) { final ClientPingRequest request = new ClientPingRequest(); final ICompletableFuture future = invocationService.send(request, connection); futureMap.put(connection, future); } else { connection.heartBeatingSucceed(); } } for (Map.Entry<ClientConnection, Future> entry : futureMap.entrySet()) { final Future future = entry.getValue(); final ClientConnection connection = entry.getKey(); try { future.get(getRemainingTimeout(), TimeUnit.MILLISECONDS); connection.heartBeatingSucceed(); } catch (Exception ignored) { connection.heartBeatingFailed(); } } } private long getRemainingTimeout() { long timeout = heartBeatTimeout - Clock.currentTimeMillis() + begin; return timeout < 0 ? 0 : timeout; } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientConnectionManagerImpl.java
4,902
public class RestThreadPoolAction extends AbstractCatAction { private final static String[] SUPPORTED_NAMES = new String[] { ThreadPool.Names.BULK, ThreadPool.Names.FLUSH, ThreadPool.Names.GENERIC, ThreadPool.Names.GET, ThreadPool.Names.INDEX, ThreadPool.Names.MANAGEMENT, ThreadPool.Names.MERGE, ThreadPool.Names.OPTIMIZE, ThreadPool.Names.PERCOLATE, ThreadPool.Names.REFRESH, ThreadPool.Names.SEARCH, ThreadPool.Names.SNAPSHOT, ThreadPool.Names.SUGGEST, ThreadPool.Names.WARMER }; private final static String[] SUPPORTED_ALIASES = new String[] { "b", "f", "ge", "g", "i", "ma", "m", "o", "p", "r", "s", "sn", "su", "w" }; private final static String[] DEFAULT_THREAD_POOLS = new String[] { ThreadPool.Names.BULK, ThreadPool.Names.INDEX, ThreadPool.Names.SEARCH, }; private final static Map<String, String> ALIAS_TO_THREAD_POOL; private final static Map<String, String> THREAD_POOL_TO_ALIAS; static { ALIAS_TO_THREAD_POOL = Maps.newHashMapWithExpectedSize(SUPPORTED_NAMES.length); for (String supportedThreadPool : SUPPORTED_NAMES) { ALIAS_TO_THREAD_POOL.put(supportedThreadPool.substring(0, 3), supportedThreadPool); } THREAD_POOL_TO_ALIAS = Maps.newHashMapWithExpectedSize(SUPPORTED_NAMES.length); for (int i = 0; i < SUPPORTED_NAMES.length; i++) { THREAD_POOL_TO_ALIAS.put(SUPPORTED_NAMES[i], SUPPORTED_ALIASES[i]); } } @Inject public RestThreadPoolAction(Settings settings, Client client, RestController controller) { super(settings, client); controller.registerHandler(GET, "/_cat/thread_pool", this); } @Override void documentation(StringBuilder sb) { sb.append("/_cat/thread_pool\n"); } @Override public void doRequest(final RestRequest request, final RestChannel channel) { final ClusterStateRequest clusterStateRequest = new ClusterStateRequest(); clusterStateRequest.clear().nodes(true); clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local())); clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout())); final String[] pools = fetchSortedPools(request, DEFAULT_THREAD_POOLS); client.admin().cluster().state(clusterStateRequest, new ActionListener<ClusterStateResponse>() { @Override public void onResponse(final ClusterStateResponse clusterStateResponse) { NodesInfoRequest nodesInfoRequest = new NodesInfoRequest(); nodesInfoRequest.clear().process(true); client.admin().cluster().nodesInfo(nodesInfoRequest, new ActionListener<NodesInfoResponse>() { @Override public void onResponse(final NodesInfoResponse nodesInfoResponse) { NodesStatsRequest nodesStatsRequest = new NodesStatsRequest(); nodesStatsRequest.clear().threadPool(true); client.admin().cluster().nodesStats(nodesStatsRequest, new ActionListener<NodesStatsResponse>() { @Override public void onResponse(NodesStatsResponse nodesStatsResponse) { try { channel.sendResponse(RestTable.buildResponse(buildTable(request, clusterStateResponse, nodesInfoResponse, nodesStatsResponse, pools), request, channel)); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } }); } @Override public void onFailure(Throwable e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } }); } @Override public void onFailure(Throwable e) { try { channel.sendResponse(new XContentThrowableRestResponse(request, e)); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } } }); } @Override Table getTableWithHeader(final RestRequest request) { Table table = new Table(); table.startHeaders(); table.addCell("id", "default:false;alias:id,nodeId;desc:unique node id"); table.addCell("pid", "default:false;alias:p;desc:process id"); table.addCell("host", "alias:h;desc:host name"); table.addCell("ip", "alias:i;desc:ip address"); table.addCell("port", "default:false;alias:po;desc:bound transport port"); final String[] requestedPools = fetchSortedPools(request, DEFAULT_THREAD_POOLS); for (String pool : SUPPORTED_NAMES) { String poolAlias = THREAD_POOL_TO_ALIAS.get(pool); boolean display = false; for (String requestedPool : requestedPools) { if (pool.equals(requestedPool)) { display = true; break; } } String defaultDisplayVal = Boolean.toString(display); table.addCell( pool + ".active", "alias:" + poolAlias + "a;default:" + defaultDisplayVal + ";text-align:right;desc:number of active " + pool + " threads" ); table.addCell( pool + ".size", "alias:" + poolAlias + "s;default:false;text-align:right;desc:number of active " + pool + " threads" ); table.addCell( pool + ".queue", "alias:" + poolAlias + "q;default:" + defaultDisplayVal + ";text-align:right;desc:number of " + pool + " threads in queue" ); table.addCell( pool + ".rejected", "alias:" + poolAlias + "r;default:" + defaultDisplayVal + ";text-align:right;desc:number of rejected " + pool + " threads" ); table.addCell( pool + ".largest", "alias:" + poolAlias + "l;default:false;text-align:right;desc:highest number of seen active " + pool + " threads" ); table.addCell( pool + ".completed", "alias:" + poolAlias + "c;default:false;text-align:right;desc:number of completed " + pool + " threads" ); } table.endHeaders(); return table; } private Table buildTable(RestRequest req, ClusterStateResponse state, NodesInfoResponse nodesInfo, NodesStatsResponse nodesStats, String[] pools) { boolean fullId = req.paramAsBoolean("full_id", false); DiscoveryNodes nodes = state.getState().nodes(); Table table = getTableWithHeader(req); for (DiscoveryNode node : nodes) { NodeInfo info = nodesInfo.getNodesMap().get(node.id()); NodeStats stats = nodesStats.getNodesMap().get(node.id()); table.startRow(); table.addCell(fullId ? node.id() : Strings.substring(node.getId(), 0, 4)); table.addCell(info == null ? null : info.getProcess().id()); table.addCell(node.getHostName()); table.addCell(node.getHostAddress()); if (node.address() instanceof InetSocketTransportAddress) { table.addCell(((InetSocketTransportAddress) node.address()).address().getPort()); } else { table.addCell("-"); } final Map<String, ThreadPoolStats.Stats> poolThreadStats; if (stats == null) { poolThreadStats = Collections.emptyMap(); } else { poolThreadStats = new HashMap<String, ThreadPoolStats.Stats>(14); ThreadPoolStats threadPoolStats = stats.getThreadPool(); for (ThreadPoolStats.Stats threadPoolStat : threadPoolStats) { poolThreadStats.put(threadPoolStat.getName(), threadPoolStat); } } for (String pool : SUPPORTED_NAMES) { ThreadPoolStats.Stats poolStats = poolThreadStats.get(pool); table.addCell(poolStats == null ? null : poolStats.getActive()); table.addCell(poolStats == null ? null : poolStats.getThreads()); table.addCell(poolStats == null ? null : poolStats.getQueue()); table.addCell(poolStats == null ? null : poolStats.getRejected()); table.addCell(poolStats == null ? null : poolStats.getLargest()); table.addCell(poolStats == null ? null : poolStats.getCompleted()); } table.endRow(); } return table; } // The thread pool columns should always be in the same order. private String[] fetchSortedPools(RestRequest request, String[] defaults) { String[] headers = request.paramAsStringArray("h", null); if (headers == null) { return defaults; } else { Set<String> requestedPools = new LinkedHashSet<String>(headers.length); for (String header : headers) { int dotIndex = header.indexOf('.'); if (dotIndex != -1) { String headerPrefix = header.substring(0, dotIndex); if (THREAD_POOL_TO_ALIAS.containsKey(headerPrefix)) { requestedPools.add(headerPrefix); } } else if (ALIAS_TO_THREAD_POOL.containsKey(header)) { requestedPools.add(ALIAS_TO_THREAD_POOL.get(header)); } } return requestedPools.toArray(new String[0]); } } }
1no label
src_main_java_org_elasticsearch_rest_action_cat_RestThreadPoolAction.java
300
public class OTraverseRecordProcess extends OTraverseAbstractProcess<ODocument> { private boolean skipDocument = false; /** * @param iCommand * @param iTarget */ public OTraverseRecordProcess(final OTraverse iCommand, final ODocument iTarget) { this(iCommand, iTarget, false); } public OTraverseRecordProcess(final OTraverse iCommand, final ODocument iTarget, final boolean iSkipDocument) { super(iCommand, iTarget); skipDocument = iSkipDocument; if (!skipDocument) command.getContext().incrementDepth(); } public OIdentifiable process() { if (target == null) return drop(); if (command.getContext().isAlreadyTraversed(target)) // ALREADY EVALUATED, DON'T GO IN DEEP return drop(); if (target.getInternalStatus() == ORecordElement.STATUS.NOT_LOADED) try { target.reload(); } catch (final ORecordNotFoundException e) { // INVALID RID return drop(); } if (command.getPredicate() != null) { final Object conditionResult = command.getPredicate().evaluate(target, null, command.getContext()); if (conditionResult != Boolean.TRUE) return drop(); } // UPDATE ALL TRAVERSED RECORD TO AVOID RECURSION command.getContext().addTraversed(target); // MATCH! final List<Object> fields = new ArrayList<Object>(); // TRAVERSE THE DOCUMENT ITSELF for (Object cfgFieldObject : command.getFields()) { String cfgField = cfgFieldObject.toString(); if ("*".equals(cfgField) || OSQLFilterItemFieldAll.FULL_NAME.equalsIgnoreCase(cfgField) || OSQLFilterItemFieldAny.FULL_NAME.equalsIgnoreCase(cfgField)) { // ADD ALL THE DOCUMENT FIELD for (String f : target.fieldNames()) fields.add(f); break; } else { // SINGLE FIELD final int pos = cfgField.indexOf('.'); if (pos > -1) { // FOUND <CLASS>.<FIELD> final OClass cls = target.getSchemaClass(); if (cls == null) // JUMP IT BECAUSE NO SCHEMA continue; final String className = cfgField.substring(0, pos); if (!cls.isSubClassOf(className)) // JUMP IT BECAUSE IT'S NOT A INSTANCEOF THE CLASS continue; cfgField = cfgField.substring(pos + 1); fields.add(cfgField); } else fields.add(cfgFieldObject); } } final OTraverseFieldProcess field = new OTraverseFieldProcess(command, fields.iterator()); if (skipDocument) { // GO DIRECTLY TO THE FIELD final OIdentifiable res = field.process(); if (res != null) return res; return drop(); } else // RETURN THE DOCUMENT ITSELF return target; } @Override public String getStatus() { return target != null ? target.getIdentity().toString() : null; } @Override public String toString() { return target != null ? target.getIdentity().toString() : "-"; } /* * (non-Javadoc) * * @see com.orientechnologies.orient.core.command.traverse.OTraverseAbstractProcess#drop() */ @Override public OIdentifiable drop() { if (!skipDocument) command.getContext().decrementDepth(); return super.drop(); } }
1no label
core_src_main_java_com_orientechnologies_orient_core_command_traverse_OTraverseRecordProcess.java
1,092
public interface OSQLFunction { /** * Process a record. * * @param iCurrentRecord * : current record * @param iCurrentResult * TODO * @param iFuncParams * : function parameters, number is ensured to be within minParams and maxParams. * @param iContext * : object calling this function * @return function result, can be null. Special cases : can be null if function aggregate results, can be null if function filter * results : this mean result is excluded */ public Object execute(OIdentifiable iCurrentRecord, Object iCurrentResult, Object[] iFuncParams, OCommandContext iContext); /** * Configure the function. * * @param configuredParameters */ public void config(Object[] configuredParameters); /** * A function can make calculation on several records before returning a result. * <p> * Example of such functions : sum, count, max, min ... * <p> * The final result of the aggregation is obtain by calling {@link #getResult() } * * @param configuredParameters * @return true if function aggregate results */ public boolean aggregateResults(); /** * A function can act both as transformation or filtering records. If the function may reduce the number final records than it * must return true. * <p> * Function should return null for the * {@linkplain #execute(com.orientechnologies.orient.core.db.record.OIdentifiable, Object, java.lang.Object[], OCommandContext) * execute} method if the record must be excluded. * * @return true if the function acts as a record filter. */ public boolean filterResult(); /** * Function name, the name is used by the sql parser to identify a call this function. * * @return String , function name, never null or empty. */ public String getName(); /** * Minimum number of parameter this function must have. * * @return minimum number of parameters */ public int getMinParams(); /** * Maximum number of parameter this function can handle. * * @return maximum number of parameters ??? -1 , negative or Integer.MAX_VALUE for unlimited ??? */ public int getMaxParams(); /** * Returns a convinient SQL String representation of the function. * <p> * Example : * * <pre> * myFunction( param1, param2, [optionalParam3]) * </pre> * * This text will be used in exception messages. * * @return String , never null. */ public String getSyntax(); /** * Only called when function aggregates results after all records have been passed to the function. * * @return Aggregation result */ public Object getResult(); /** * Called by OCommandExecutor, given parameter is the number of results. ??? strange ??? * * @param iResult */ public void setResult(Object iResult); /** * This methods correspond to distributed query execution * * @return {@code true} if results that comes from different nodes need to be merged to obtain valid one, {@code false} otherwise */ public boolean shouldMergeDistributedResult(); /** * This methods correspond to distributed query execution * * @param resultsToMerge * is the results that comes from different nodes * @return is the valid merged result */ public Object mergeDistributedResult(List<Object> resultsToMerge); }
0true
core_src_main_java_com_orientechnologies_orient_core_sql_functions_OSQLFunction.java
4,234
public final class RamDirectoryService extends AbstractIndexShardComponent implements DirectoryService { @Inject public RamDirectoryService(ShardId shardId, @IndexSettings Settings indexSettings) { super(shardId, indexSettings); } @Override public long throttleTimeInNanos() { return 0; } @Override public Directory[] build() { return new Directory[]{new CustomRAMDirectory()}; } @Override public void renameFile(Directory dir, String from, String to) throws IOException { CustomRAMDirectory leaf = DirectoryUtils.getLeaf(dir, CustomRAMDirectory.class); assert leaf != null; leaf.renameTo(from, to); } @Override public void fullDelete(Directory dir) { } static class CustomRAMDirectory extends RAMDirectory { public synchronized void renameTo(String from, String to) throws IOException { RAMFile fromFile = fileMap.get(from); if (fromFile == null) throw new FileNotFoundException(from); RAMFile toFile = fileMap.get(to); if (toFile != null) { sizeInBytes.addAndGet(-fileLength(from)); fileMap.remove(from); } fileMap.put(to, fromFile); } @Override public String toString() { return "ram"; } } }
1no label
src_main_java_org_elasticsearch_index_store_ram_RamDirectoryService.java
285
list.setFilters(new ViewerFilter[] {new ViewerFilter() { @Override public boolean select(Viewer viewer, Object parentElement, Object element) { return ((IFile) element).getName().toLowerCase() .startsWith(filterText.getText().toLowerCase()); } }});
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_RecentFilesPopup.java
1,883
T t = injector.callInContext(new ContextualCallable<T>() { public T call(InternalContext context) throws ErrorsException { Dependency dependency = context.getDependency(); return internalFactory.get(errors, context, dependency); } });
0true
src_main_java_org_elasticsearch_common_inject_ProviderToInternalFactoryAdapter.java
482
int indexesSizeOne = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<Integer>() { public Integer call() { return indexesOne.size(); } });
0true
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java
257
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class ClientExecutorServiceTest { static final int CLUSTER_SIZE = 3; static HazelcastInstance instance1; static HazelcastInstance instance2; static HazelcastInstance instance3; static HazelcastInstance client; @BeforeClass public static void init() { instance1 = Hazelcast.newHazelcastInstance(); instance2 = Hazelcast.newHazelcastInstance(); instance3 = Hazelcast.newHazelcastInstance(); client = HazelcastClient.newHazelcastClient(); } @AfterClass public static void destroy() { client.shutdown(); Hazelcast.shutdownAll(); } @Test(expected = UnsupportedOperationException.class) public void testGetLocalExecutorStats() throws Throwable, InterruptedException { IExecutorService service = client.getExecutorService(randomString()); service.getLocalExecutorStats(); } @Test public void testIsTerminated() throws InterruptedException, ExecutionException, TimeoutException { final IExecutorService service = client.getExecutorService(randomString()); assertFalse(service.isTerminated()); } @Test public void testIsShutdown() throws InterruptedException, ExecutionException, TimeoutException { final IExecutorService service = client.getExecutorService(randomString()); assertFalse(service.isShutdown()); } @Test public void testShutdownNow() throws InterruptedException, ExecutionException, TimeoutException { final IExecutorService service = client.getExecutorService(randomString()); service.shutdownNow(); assertTrueEventually(new AssertTask() { public void run() throws Exception { assertTrue(service.isShutdown()); } }); } @Test(expected = TimeoutException.class) public void testCancellationAwareTask_whenTimeOut() throws InterruptedException, ExecutionException, TimeoutException { IExecutorService service = client.getExecutorService(randomString()); CancellationAwareTask task = new CancellationAwareTask(5000); Future future = service.submit(task); future.get(1, TimeUnit.SECONDS); } @Test public void testFutureAfterCancellationAwareTaskTimeOut() throws InterruptedException, ExecutionException, TimeoutException { IExecutorService service = client.getExecutorService(randomString()); CancellationAwareTask task = new CancellationAwareTask(5000); Future future = service.submit(task); try { future.get(1, TimeUnit.SECONDS); } catch (TimeoutException e) { } assertFalse(future.isDone()); assertFalse(future.isCancelled()); } @Test public void testCancelFutureAfterCancellationAwareTaskTimeOut() throws InterruptedException, ExecutionException, TimeoutException { IExecutorService service = client.getExecutorService(randomString()); CancellationAwareTask task = new CancellationAwareTask(5000); Future future = service.submit(task); try { future.get(1, TimeUnit.SECONDS); } catch (TimeoutException e) { } assertTrue(future.cancel(true)); assertTrue(future.isCancelled()); assertTrue(future.isDone()); } @Test(expected = CancellationException.class) public void testGetFutureAfterCancel() throws InterruptedException, ExecutionException, TimeoutException { IExecutorService service = client.getExecutorService(randomString()); CancellationAwareTask task = new CancellationAwareTask(5000); Future future = service.submit(task); try { future.get(1, TimeUnit.SECONDS); } catch (TimeoutException e) { } future.cancel(true); future.get(); } @Test(expected = ExecutionException.class) public void testSubmitFailingCallableException() throws ExecutionException, InterruptedException { IExecutorService service = client.getExecutorService(randomString()); final Future<String> f = service.submit(new FailingCallable()); f.get(); } @Test(expected = IllegalStateException.class) public void testSubmitFailingCallableReasonExceptionCause() throws Throwable { IExecutorService service = client.getExecutorService(randomString()); final Future<String> f = service.submit(new FailingCallable()); try { f.get(); } catch (ExecutionException e) { throw e.getCause(); } } @Test(expected = IllegalStateException.class) public void testExecute_withNoMemberSelected() { final IExecutorService service = client.getExecutorService(randomString()); final String mapName = randomString(); final MemberSelector selector = new SelectNoMembers(); service.execute(new MapPutRunnable(mapName), selector); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceTest.java
1,165
new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 1; i++) { BenchmarkMessageRequest message = new BenchmarkMessageRequest(2, BytesRef.EMPTY_BYTES); long start = System.currentTimeMillis(); transportServiceClient.submitRequest(smallNode, "benchmark", message, options().withType(TransportRequestOptions.Type.STATE), new BaseTransportResponseHandler<BenchmarkMessageResponse>() { @Override public BenchmarkMessageResponse newInstance() { return new BenchmarkMessageResponse(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void handleResponse(BenchmarkMessageResponse response) { } @Override public void handleException(TransportException exp) { exp.printStackTrace(); } }).txGet(); long took = System.currentTimeMillis() - start; System.out.println("Took " + took + "ms"); } } }).start();
0true
src_test_java_org_elasticsearch_benchmark_transport_BenchmarkNettyLargeMessages.java
606
private static class LatchMembershipListener implements MembershipListener { private final CountDownLatch latch; private LatchMembershipListener(CountDownLatch latch) { this.latch = latch; } @Override public void memberAdded(MembershipEvent membershipEvent) { } @Override public void memberRemoved(MembershipEvent membershipEvent) { } @Override public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) { latch.countDown(); } }
0true
hazelcast_src_test_java_com_hazelcast_cluster_MemberAttributeTest.java
2,631
public class MulticastZenPing extends AbstractLifecycleComponent<ZenPing> implements ZenPing { private static final byte[] INTERNAL_HEADER = new byte[]{1, 9, 8, 4}; private final String address; private final int port; private final String group; private final int bufferSize; private final int ttl; private final ThreadPool threadPool; private final TransportService transportService; private final ClusterName clusterName; private final NetworkService networkService; private final Version version; private volatile DiscoveryNodesProvider nodesProvider; private final boolean pingEnabled; private volatile Receiver receiver; private volatile Thread receiverThread; private volatile MulticastSocket multicastSocket; private DatagramPacket datagramPacketSend; private DatagramPacket datagramPacketReceive; private final AtomicInteger pingIdGenerator = new AtomicInteger(); private final Map<Integer, ConcurrentMap<DiscoveryNode, PingResponse>> receivedResponses = newConcurrentMap(); private final Object sendMutex = new Object(); private final Object receiveMutex = new Object(); public MulticastZenPing(ThreadPool threadPool, TransportService transportService, ClusterName clusterName, Version version) { this(EMPTY_SETTINGS, threadPool, transportService, clusterName, new NetworkService(EMPTY_SETTINGS), version); } public MulticastZenPing(Settings settings, ThreadPool threadPool, TransportService transportService, ClusterName clusterName, NetworkService networkService, Version version) { super(settings); this.threadPool = threadPool; this.transportService = transportService; this.clusterName = clusterName; this.networkService = networkService; this.version = version; this.address = componentSettings.get("address"); this.port = componentSettings.getAsInt("port", 54328); this.group = componentSettings.get("group", "224.2.2.4"); this.bufferSize = componentSettings.getAsInt("buffer_size", 2048); this.ttl = componentSettings.getAsInt("ttl", 3); this.pingEnabled = componentSettings.getAsBoolean("ping.enabled", true); logger.debug("using group [{}], with port [{}], ttl [{}], and address [{}]", group, port, ttl, address); this.transportService.registerHandler(MulticastPingResponseRequestHandler.ACTION, new MulticastPingResponseRequestHandler()); } @Override public void setNodesProvider(DiscoveryNodesProvider nodesProvider) { if (lifecycle.started()) { throw new ElasticsearchIllegalStateException("Can't set nodes provider when started"); } this.nodesProvider = nodesProvider; } @Override protected void doStart() throws ElasticsearchException { try { this.datagramPacketReceive = new DatagramPacket(new byte[bufferSize], bufferSize); this.datagramPacketSend = new DatagramPacket(new byte[bufferSize], bufferSize, InetAddress.getByName(group), port); } catch (Exception e) { logger.warn("disabled, failed to setup multicast (datagram) discovery : {}", e.getMessage()); if (logger.isDebugEnabled()) { logger.debug("disabled, failed to setup multicast (datagram) discovery", e); } return; } InetAddress multicastInterface = null; try { MulticastSocket multicastSocket; // if (NetworkUtils.canBindToMcastAddress()) { // try { // multicastSocket = new MulticastSocket(new InetSocketAddress(group, port)); // } catch (Exception e) { // logger.debug("Failed to create multicast socket by binding to group address, binding to port", e); // multicastSocket = new MulticastSocket(port); // } // } else { multicastSocket = new MulticastSocket(port); // } multicastSocket.setTimeToLive(ttl); // set the send interface multicastInterface = networkService.resolvePublishHostAddress(address); multicastSocket.setInterface(multicastInterface); multicastSocket.joinGroup(InetAddress.getByName(group)); multicastSocket.setReceiveBufferSize(bufferSize); multicastSocket.setSendBufferSize(bufferSize); multicastSocket.setSoTimeout(60000); this.multicastSocket = multicastSocket; this.receiver = new Receiver(); this.receiverThread = daemonThreadFactory(settings, "discovery#multicast#receiver").newThread(receiver); this.receiverThread.start(); } catch (Exception e) { datagramPacketReceive = null; datagramPacketSend = null; if (multicastSocket != null) { multicastSocket.close(); multicastSocket = null; } logger.warn("disabled, failed to setup multicast discovery on port [{}], [{}]: {}", port, multicastInterface, e.getMessage()); if (logger.isDebugEnabled()) { logger.debug("disabled, failed to setup multicast discovery on {}", e, multicastInterface); } } } @Override protected void doStop() throws ElasticsearchException { if (receiver != null) { receiver.stop(); } if (receiverThread != null) { receiverThread.interrupt(); } if (multicastSocket != null) { multicastSocket.close(); multicastSocket = null; } } @Override protected void doClose() throws ElasticsearchException { } public PingResponse[] pingAndWait(TimeValue timeout) { final AtomicReference<PingResponse[]> response = new AtomicReference<PingResponse[]>(); final CountDownLatch latch = new CountDownLatch(1); try { ping(new PingListener() { @Override public void onPing(PingResponse[] pings) { response.set(pings); latch.countDown(); } }, timeout); } catch (EsRejectedExecutionException ex) { logger.debug("Ping execution rejected", ex); return PingResponse.EMPTY; } try { latch.await(); return response.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return PingResponse.EMPTY; } } @Override public void ping(final PingListener listener, final TimeValue timeout) { if (!pingEnabled) { threadPool.generic().execute(new Runnable() { @Override public void run() { listener.onPing(PingResponse.EMPTY); } }); return; } final int id = pingIdGenerator.incrementAndGet(); receivedResponses.put(id, ConcurrentCollections.<DiscoveryNode, PingResponse>newConcurrentMap()); sendPingRequest(id); // try and send another ping request halfway through (just in case someone woke up during it...) // this can be a good trade-off to nailing the initial lookup or un-delivered messages threadPool.schedule(TimeValue.timeValueMillis(timeout.millis() / 2), ThreadPool.Names.GENERIC, new Runnable() { @Override public void run() { try { sendPingRequest(id); } catch (Exception e) { logger.warn("[{}] failed to send second ping request", e, id); } } }); threadPool.schedule(timeout, ThreadPool.Names.GENERIC, new Runnable() { @Override public void run() { ConcurrentMap<DiscoveryNode, PingResponse> responses = receivedResponses.remove(id); listener.onPing(responses.values().toArray(new PingResponse[responses.size()])); } }); } private void sendPingRequest(int id) { if (multicastSocket == null) { return; } synchronized (sendMutex) { try { BytesStreamOutput bStream = new BytesStreamOutput(); StreamOutput out = new HandlesStreamOutput(bStream); out.writeBytes(INTERNAL_HEADER); Version.writeVersion(version, out); out.writeInt(id); clusterName.writeTo(out); nodesProvider.nodes().localNode().writeTo(out); out.close(); datagramPacketSend.setData(bStream.bytes().toBytes()); multicastSocket.send(datagramPacketSend); if (logger.isTraceEnabled()) { logger.trace("[{}] sending ping request", id); } } catch (Exception e) { if (lifecycle.stoppedOrClosed()) { return; } if (logger.isDebugEnabled()) { logger.debug("failed to send multicast ping request", e); } else { logger.warn("failed to send multicast ping request: {}", ExceptionsHelper.detailedMessage(e)); } } } } class MulticastPingResponseRequestHandler extends BaseTransportRequestHandler<MulticastPingResponse> { static final String ACTION = "discovery/zen/multicast"; @Override public MulticastPingResponse newInstance() { return new MulticastPingResponse(); } @Override public void messageReceived(MulticastPingResponse request, TransportChannel channel) throws Exception { if (logger.isTraceEnabled()) { logger.trace("[{}] received {}", request.id, request.pingResponse); } ConcurrentMap<DiscoveryNode, PingResponse> responses = receivedResponses.get(request.id); if (responses == null) { logger.warn("received ping response {} with no matching id [{}]", request.pingResponse, request.id); } else { responses.put(request.pingResponse.target(), request.pingResponse); } channel.sendResponse(TransportResponse.Empty.INSTANCE); } @Override public String executor() { return ThreadPool.Names.SAME; } } static class MulticastPingResponse extends TransportRequest { int id; PingResponse pingResponse; MulticastPingResponse() { } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); id = in.readInt(); pingResponse = PingResponse.readPingResponse(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeInt(id); pingResponse.writeTo(out); } } private class Receiver implements Runnable { private volatile boolean running = true; public void stop() { running = false; } @Override public void run() { while (running) { try { int id = -1; DiscoveryNode requestingNodeX = null; ClusterName clusterName = null; Map<String, Object> externalPingData = null; XContentType xContentType = null; synchronized (receiveMutex) { try { multicastSocket.receive(datagramPacketReceive); } catch (SocketTimeoutException ignore) { continue; } catch (Exception e) { if (running) { if (multicastSocket.isClosed()) { logger.warn("multicast socket closed while running, restarting..."); // for some reason, the socket got closed on us while we are still running // make a best effort in trying to start the multicast socket again... threadPool.generic().execute(new Runnable() { @Override public void run() { MulticastZenPing.this.stop(); MulticastZenPing.this.start(); } }); running = false; return; } else { logger.warn("failed to receive packet, throttling...", e); Thread.sleep(500); } } continue; } try { boolean internal = false; if (datagramPacketReceive.getLength() > 4) { int counter = 0; for (; counter < INTERNAL_HEADER.length; counter++) { if (datagramPacketReceive.getData()[datagramPacketReceive.getOffset() + counter] != INTERNAL_HEADER[counter]) { break; } } if (counter == INTERNAL_HEADER.length) { internal = true; } } if (internal) { StreamInput input = CachedStreamInput.cachedHandles(new BytesStreamInput(datagramPacketReceive.getData(), datagramPacketReceive.getOffset() + INTERNAL_HEADER.length, datagramPacketReceive.getLength(), true)); Version version = Version.readVersion(input); input.setVersion(version); id = input.readInt(); clusterName = ClusterName.readClusterName(input); requestingNodeX = readNode(input); } else { xContentType = XContentFactory.xContentType(datagramPacketReceive.getData(), datagramPacketReceive.getOffset(), datagramPacketReceive.getLength()); if (xContentType != null) { // an external ping externalPingData = XContentFactory.xContent(xContentType) .createParser(datagramPacketReceive.getData(), datagramPacketReceive.getOffset(), datagramPacketReceive.getLength()) .mapAndClose(); } else { throw new ElasticsearchIllegalStateException("failed multicast message, probably message from previous version"); } } } catch (Exception e) { logger.warn("failed to read requesting data from {}", e, datagramPacketReceive.getSocketAddress()); continue; } } if (externalPingData != null) { handleExternalPingRequest(externalPingData, xContentType, datagramPacketReceive.getSocketAddress()); } else { handleNodePingRequest(id, requestingNodeX, clusterName); } } catch (Exception e) { if (running) { logger.warn("unexpected exception in multicast receiver", e); } } } } @SuppressWarnings("unchecked") private void handleExternalPingRequest(Map<String, Object> externalPingData, XContentType contentType, SocketAddress remoteAddress) { if (externalPingData.containsKey("response")) { // ignoring responses sent over the multicast channel logger.trace("got an external ping response (ignoring) from {}, content {}", remoteAddress, externalPingData); return; } if (multicastSocket == null) { logger.debug("can't send ping response, no socket, from {}, content {}", remoteAddress, externalPingData); return; } Map<String, Object> request = (Map<String, Object>) externalPingData.get("request"); if (request == null) { logger.warn("malformed external ping request, no 'request' element from {}, content {}", remoteAddress, externalPingData); return; } String clusterName = request.containsKey("cluster_name") ? request.get("cluster_name").toString() : request.containsKey("clusterName") ? request.get("clusterName").toString() : null; if (clusterName == null) { logger.warn("malformed external ping request, missing 'cluster_name' element within request, from {}, content {}", remoteAddress, externalPingData); return; } if (!clusterName.equals(MulticastZenPing.this.clusterName.value())) { logger.trace("got request for cluster_name {}, but our cluster_name is {}, from {}, content {}", clusterName, MulticastZenPing.this.clusterName.value(), remoteAddress, externalPingData); return; } if (logger.isTraceEnabled()) { logger.trace("got external ping request from {}, content {}", remoteAddress, externalPingData); } try { DiscoveryNode localNode = nodesProvider.nodes().localNode(); XContentBuilder builder = XContentFactory.contentBuilder(contentType); builder.startObject().startObject("response"); builder.field("cluster_name", MulticastZenPing.this.clusterName.value()); builder.startObject("version").field("number", version.number()).field("snapshot_build", version.snapshot).endObject(); builder.field("transport_address", localNode.address().toString()); if (nodesProvider.nodeService() != null) { for (Map.Entry<String, String> attr : nodesProvider.nodeService().attributes().entrySet()) { builder.field(attr.getKey(), attr.getValue()); } } builder.startObject("attributes"); for (Map.Entry<String, String> attr : localNode.attributes().entrySet()) { builder.field(attr.getKey(), attr.getValue()); } builder.endObject(); builder.endObject().endObject(); synchronized (sendMutex) { BytesReference bytes = builder.bytes(); datagramPacketSend.setData(bytes.array(), bytes.arrayOffset(), bytes.length()); multicastSocket.send(datagramPacketSend); if (logger.isTraceEnabled()) { logger.trace("sending external ping response {}", builder.string()); } } } catch (Exception e) { logger.warn("failed to send external multicast response", e); } } private void handleNodePingRequest(int id, DiscoveryNode requestingNodeX, ClusterName clusterName) { if (!pingEnabled) { return; } DiscoveryNodes discoveryNodes = nodesProvider.nodes(); final DiscoveryNode requestingNode = requestingNodeX; if (requestingNode.id().equals(discoveryNodes.localNodeId())) { // that's me, ignore return; } if (!clusterName.equals(MulticastZenPing.this.clusterName)) { if (logger.isTraceEnabled()) { logger.trace("[{}] received ping_request from [{}], but wrong cluster_name [{}], expected [{}], ignoring", id, requestingNode, clusterName, MulticastZenPing.this.clusterName); } return; } // don't connect between two client nodes, no need for that... if (!discoveryNodes.localNode().shouldConnectTo(requestingNode)) { if (logger.isTraceEnabled()) { logger.trace("[{}] received ping_request from [{}], both are client nodes, ignoring", id, requestingNode, clusterName); } return; } final MulticastPingResponse multicastPingResponse = new MulticastPingResponse(); multicastPingResponse.id = id; multicastPingResponse.pingResponse = new PingResponse(discoveryNodes.localNode(), discoveryNodes.masterNode(), clusterName); if (logger.isTraceEnabled()) { logger.trace("[{}] received ping_request from [{}], sending {}", id, requestingNode, multicastPingResponse.pingResponse); } if (!transportService.nodeConnected(requestingNode)) { // do the connect and send on a thread pool threadPool.generic().execute(new Runnable() { @Override public void run() { // connect to the node if possible try { transportService.connectToNode(requestingNode); transportService.sendRequest(requestingNode, MulticastPingResponseRequestHandler.ACTION, multicastPingResponse, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleException(TransportException exp) { logger.warn("failed to receive confirmation on sent ping response to [{}]", exp, requestingNode); } }); } catch (Exception e) { logger.warn("failed to connect to requesting node {}", e, requestingNode); } } }); } else { transportService.sendRequest(requestingNode, MulticastPingResponseRequestHandler.ACTION, multicastPingResponse, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleException(TransportException exp) { logger.warn("failed to receive confirmation on sent ping response to [{}]", exp, requestingNode); } }); } } } }
0true
src_main_java_org_elasticsearch_discovery_zen_ping_multicast_MulticastZenPing.java
2,473
static class CallableJob extends PrioritizedCallable<Integer> { private final int result; private final List<Integer> results; private final CountDownLatch latch; CallableJob(int result, Priority priority, List<Integer> results, CountDownLatch latch) { super(priority); this.result = result; this.results = results; this.latch = latch; } @Override public Integer call() throws Exception { results.add(result); latch.countDown(); return result; } }
0true
src_test_java_org_elasticsearch_common_util_concurrent_PrioritizedExecutorsTests.java
1,828
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class MapInstanceSharingTest extends HazelcastTestSupport { private static HazelcastInstance[] instances; private static HazelcastInstance local; private static HazelcastInstance remote; @BeforeClass public static void setUp() { instances = new TestHazelcastInstanceFactory(2).newInstances(); warmUpPartitions(instances); local = instances[0]; remote = instances[1]; } @Test public void invocationToLocalMember() throws ExecutionException, InterruptedException { String localKey = generateKeyOwnedBy(local); IMap<String, DummyObject> map = local.getMap(UUID.randomUUID().toString()); DummyObject inserted = new DummyObject(); map.put(localKey,inserted); DummyObject get1 = map.get(localKey); DummyObject get2 = map.get(localKey); assertNotNull(get1); assertNotNull(get2); assertNotSame(get1, get2); assertNotSame(get1, inserted); assertNotSame(get2, inserted); } public static class DummyObject implements Serializable { } @Test public void invocationToRemoteMember() throws ExecutionException, InterruptedException { String remoteKey = generateKeyOwnedBy(remote); IMap<String, DummyObject> map = local.getMap(UUID.randomUUID().toString()); DummyObject inserted = new DummyObject(); map.put(remoteKey, inserted); DummyObject get1 = map.get(remoteKey); DummyObject get2 = map.get(remoteKey); assertNotNull(get1); assertNotNull(get2); assertNotSame(get1, get2); assertNotSame(get1, inserted); assertNotSame(get2, inserted); } }
0true
hazelcast_src_test_java_com_hazelcast_map_MapInstanceSharingTest.java
930
new ODbRelatedCall<Iterator<Entry<Object, Object>>>() { public Iterator<Entry<Object, Object>> call() { return myMap.entrySet().iterator(); } });
0true
core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocumentHelper.java
1,279
Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { log("Shutting down " + nodes.size()); while (nodes.size() > 0) { removeNode(); } } });
0true
hazelcast_src_main_java_com_hazelcast_examples_LongRunningTest.java
1,667
runnable = new Runnable() { public void run() { map.containsValue(null); } };
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
978
public enum ReplicationType { /** * Sync replication, wait till all replicas have performed the operation. */ SYNC((byte) 0), /** * Async replication. Will send the request to replicas, but will not wait for it */ ASYNC((byte) 1), /** * Use the default replication type configured for this node. */ DEFAULT((byte) 2); private byte id; ReplicationType(byte id) { this.id = id; } /** * The internal representation of the operation type. */ public byte id() { return id; } /** * Constructs the operation type from its internal representation. */ public static ReplicationType fromId(byte id) { if (id == 0) { return SYNC; } else if (id == 1) { return ASYNC; } else if (id == 2) { return DEFAULT; } else { throw new ElasticsearchIllegalArgumentException("No type match for [" + id + "]"); } } /** * Parse the replication type from string. */ public static ReplicationType fromString(String type) { if ("async".equals(type)) { return ASYNC; } else if ("sync".equals(type)) { return SYNC; } else if ("default".equals(type)) { return DEFAULT; } throw new ElasticsearchIllegalArgumentException("No replication type match for [" + type + "], should be either `async`, or `sync`"); } }
0true
src_main_java_org_elasticsearch_action_support_replication_ReplicationType.java
602
public class BroadleafGWTModuleURLMappingResourceHttpRequestHandler extends ResourceHttpRequestHandler { @Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String, String> urlPatternDispatchMap = (Map<String, String>) getApplicationContext().getBean("blResourceUrlPatternRequestDispatchMap"); for (Map.Entry<String, String> entry : urlPatternDispatchMap.entrySet()) { RequestMatcher matcher = new AntPathRequestMatcher(entry.getKey()); if (matcher.matches(request)){ request.getRequestDispatcher(entry.getValue()).forward(request, response); return; } } super.handleRequest(request, response); } }
0true
common_src_main_java_org_broadleafcommerce_common_web_BroadleafGWTModuleURLMappingResourceHttpRequestHandler.java
480
public class AnalyzeAction extends IndicesAction<AnalyzeRequest, AnalyzeResponse, AnalyzeRequestBuilder> { public static final AnalyzeAction INSTANCE = new AnalyzeAction(); public static final String NAME = "indices/analyze"; private AnalyzeAction() { super(NAME); } @Override public AnalyzeResponse newResponse() { return new AnalyzeResponse(); } @Override public AnalyzeRequestBuilder newRequestBuilder(IndicesAdminClient client) { return new AnalyzeRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_analyze_AnalyzeAction.java
248
public class AstyanaxMultiWriteStoreTest extends MultiWriteKeyColumnValueStoreTest { @BeforeClass public static void startCassandra() { CassandraStorageSetup.startCleanEmbedded(); } @Override public KeyColumnValueStoreManager openStorageManager() throws BackendException { return new AstyanaxStoreManager(CassandraStorageSetup.getAstyanaxConfiguration(getClass().getSimpleName())); } }
0true
titan-cassandra_src_test_java_com_thinkaurelius_titan_diskstorage_cassandra_astyanax_AstyanaxMultiWriteStoreTest.java
1,029
public interface OrderItem extends Serializable, Cloneable { /** * The unique identifier of this OrderItem * @return */ Long getId(); /** * Sets the unique id of the OrderItem. Typically left null for new items and Broadleaf will * set using the next sequence number. * @param id */ void setId(Long id); /** * Reference back to the containing order. * @return */ Order getOrder(); /** * Sets the order for this orderItem. * @param order */ void setOrder(Order order); /** * The retail price of the item that was added to the {@link Order} at the time that this was added. This is preferable * to use as opposed to checking the price of the item that was added from the catalog domain (like in * {@link DiscreteOrderItem}, using {@link DiscreteOrderItem#getSku()}'s retail price) since the price in the catalog * domain could have changed since the item was added to the {@link Order}. * * @return */ Money getRetailPrice(); /** * Calling this method will manually set the retailPrice. To avoid the pricing engine * resetting this price, you should also make a call to * {@link #setRetailPriceOverride(true)} * * Consider also calling {@link #setDiscountingAllowed(boolean)} with a value of false to restrict * discounts after manually setting the retail price. * * @param retailPrice */ void setRetailPrice(Money retailPrice); /** * Indicates that the retail price was manually set. A typical usage might be for a * CSR who has override privileges to control setting the price. This will automatically be set * by calling {@link #setRetailPrice(Money)} */ void setRetailPriceOverride(boolean override); /** * Returns true if the retail price was manually set. If the retail price is manually set, * calls to updatePrices() will not do anything. * @return */ boolean isRetailPriceOverride(); /** * Returns the salePrice for this item. Note this method will return the lower of the retailPrice * or salePrice. It will return the retailPrice instead of null. * * For SKU based pricing, a call to {@link #updateSaleAndRetailPrices()} will ensure that the * retailPrice being used is current. * * @return */ Money getSalePrice(); /** * Calling this method will manually set the salePrice. It will also make a call to * {@link #setSalePriceSetManually(true)} * * To avoid the pricing engine resetting this price, you should also make a call to * {@link #setSalePriceOverride(true)} * * Typically for {@link DiscreteOrderItem}s, the prices will be set with a call to {@link #updateSaleAndRetailPrices()} * which will use the Broadleaf dynamic pricing engine or the values directly tied to the SKU. * * @param salePrice */ void setSalePrice(Money salePrice); /** * Indicates that the sale price was manually set. A typical usage might be for a * CSR who has override privileges to control setting the price. * * Consider also calling {@link #setDiscountingAllowed(boolean)} with a value of false to restrict * discounts after manually setting the retail price. * * If the salePrice is not lower than the retailPrice, the system will return the retailPrice when * a call to {@link #getSalePrice()} is made. */ void setSalePriceOverride(boolean override); /** * Returns true if the sale price was manually set. If the retail price is manually set, * calls to updatePrices() will not do anything. * @return */ boolean isSalePriceOverride(); /** * @deprecated * Delegates to {@link #getAverageAdjustmentValue()} instead but this method is of little * or no value in most practical applications unless only simple promotions are being used. * * @return */ @Deprecated Money getAdjustmentValue(); /** * @deprecated * Delegates to {@link #getAveragePrice()} * * @return */ @Deprecated Money getPrice(); /** * @deprecated * Calling this method is the same as calling the following: * * {@link #setRetailPrice(Money)} * {@link #setSalePrice(Money)} * {@link #setRetailPriceOverride(true)} * {@link #setSalePriceOverride(true)} * {@link #setDiscountingAllowed(false)} * * This has the effect of setting the price in a way that no discounts or adjustments can be made. * * @param price */ @Deprecated void setPrice(Money price); /** * The quantity of this {@link OrderItem}. * * @return */ int getQuantity(); /** * Sets the quantity of this item */ void setQuantity(int quantity); /** * Collection of priceDetails for this orderItem. * * Without discounts, an orderItem would have exactly 1 ItemPriceDetail. When orderItem discounting or * tax-calculations result in an orderItem having multiple prices like in a buy-one-get-one free example, * the orderItem will get an additional ItemPriceDetail. * * Generally, an OrderItem will have 1 ItemPriceDetail record for each uniquely priced version of the item. */ List<OrderItemPriceDetail> getOrderItemPriceDetails(); /** * Returns the list of orderItem price details. * @see {@link #getOrderItemPriceDetails()} * @param orderItemPriceDetails */ void setOrderItemPriceDetails(List<OrderItemPriceDetail> orderItemPriceDetails); Category getCategory(); void setCategory(Category category); List<CandidateItemOffer> getCandidateItemOffers(); void setCandidateItemOffers(List<CandidateItemOffer> candidateItemOffers); /** * Returns item level adjustment for versions of Broadleaf Commerce prior to 2.3.0 which replaced * this concept with OrderItemPriceDetail adjustments. * @return a List of OrderItemAdjustment */ @Deprecated List<OrderItemAdjustment> getOrderItemAdjustments(); /** * @deprecated * Item level adjustments are now stored at the OrderItemPriceDetail level instead to * prevent unnecessary item splitting of OrderItems when evaluating promotions * in the pricing engine. */ @Deprecated void setOrderItemAdjustments(List<OrderItemAdjustment> orderItemAdjustments); /** * If any quantity of this item was used to qualify for an offer, then this returned list * will indicate the offer and the relevant quantity. * * As an example, a BuyOneGetOneFree offer would have 1 qualifier and 1 adjustment. * * @return a List of OrderItemAdjustment */ List<OrderItemQualifier> getOrderItemQualifiers(); /** * Sets the list of OrderItemQualifiers * */ void setOrderItemQualifiers(List<OrderItemQualifier> orderItemQualifiers); PersonalMessage getPersonalMessage(); void setPersonalMessage(PersonalMessage personalMessage); boolean isInCategory(String categoryName); GiftWrapOrderItem getGiftWrapOrderItem(); void setGiftWrapOrderItem(GiftWrapOrderItem giftWrapOrderItem); OrderItemType getOrderItemType(); void setOrderItemType(OrderItemType orderItemType); /** * @deprecated * If the item is taxable, returns {@link #getAveragePrice()} * * It is recommended instead that tax calculation engines use the {@link #getTotalTaxableAmount()} which provides the taxable * total for all quantities of this item. This method suffers from penny rounding errors in some * situations. * * @return */ @Deprecated Money getTaxablePrice(); /** * Default implementation uses {@link #getSalePrice()} &lt; {@link #getRetailPrice()} * * @return */ boolean getIsOnSale(); /** * If true, this item can be discounted.. */ boolean isDiscountingAllowed(); /** * Turns off discount processing for this line item. * @param disableDiscounts */ void setDiscountingAllowed(boolean discountingAllowed); /** * Returns true if this item received a discount. * @return */ boolean getIsDiscounted(); /** * Generally copied from the Sku.getName() * @return */ String getName(); /** * Used to reset the base price of the item that the pricing engine uses. * * Generally, this will update the retailPrice and salePrice based on the * corresponding value in the SKU. * * If the retail or sale price was manually set, this method will not change * those prices. * * For non-manually set prices, prices can change based on system activities such as * locale changes and customer authentication, this method is used to * ensure that all cart items reflect the current base price before * executing other pricing / adjustment operations. * * Other known scenarios that can effect the base prices include the automatic bundling * or loading a stale cart from the database. * * See notes in subclasses for specific behavior of this method. * * @return true if the base prices changed as a result of this call */ boolean updateSaleAndRetailPrices(); /** * Called by the pricing engine after prices have been computed. Allows the * system to set the averagePrice that is stored for the item. */ void finalizePrice(); /** * Sets the name of this order item. * @param name */ void setName(String name); OrderItem clone(); /** * Used to set the final price of the item and corresponding details. * @param useSalePrice */ void assignFinalPrice(); /** * Returns the unit price of this item. If the parameter allowSalesPrice is true, will * return the sale price if one exists. * * @param allowSalesPrice * @return */ Money getPriceBeforeAdjustments(boolean allowSalesPrice); /** * Used by the promotion engine to add offers that might apply to this orderItem. * @param candidateItemOffer */ void addCandidateItemOffer(CandidateItemOffer candidateItemOffer); /** * Removes all candidate offers. Used by the promotion engine which subsequently adds * the candidate offers that might apply back to this item. */ void removeAllCandidateItemOffers(); /** * Removes all adjustment for this order item and reset the adjustment price. */ int removeAllAdjustments(); /** * A list of arbitrary attributes added to this item. */ Map<String, OrderItemAttribute> getOrderItemAttributes(); /** * Sets the map of order item attributes. * * @param orderItemAttributes */ void setOrderItemAttributes(Map<String, OrderItemAttribute> orderItemAttributes); /** * Returns the average unit display price for the item. * * Some implementations may choose to show this on a view cart screen. Due to fractional discounts, * it the display could represent a unit price that is off. * * For example, if this OrderItem had 3 items at $1 each and also received a $1 discount. The net * effect under the default rounding scenario would be an average price of $0.666666 * * Most systems would represent this as $0.67 as the discounted unit price; however, this amount times 3 ($2.01) * would not equal the getTotalPrice() which would be $2.00. For this reason, it is not recommended * that implementations utilize this field. Instead, they may choose not to show the unit price or show * multiple prices by looping through the OrderItemPriceDetails. * * @return */ Money getAveragePrice(); /** * Returns the average unit item adjustments. * * For example, if this item has a quantity of 2 at a base-price of $10 and a 10% discount applies to both * then this method would return $1. * * Some implementations may choose to show this on a view cart screen. Due to fractional discounts, * the display could represent a unit adjustment value that is off due to rounding. See {@link #getAveragePrice()} * for an example of this. * * Implementations wishing to show unit prices may choose instead to show the individual OrderItemPriceDetails * instead of this value to avoid the rounding problem. This would result in multiple cart item * display rows for each OrderItem. * * Alternatively, the cart display should use {@link #getTotalAdjustmentValue()}. * * @return */ Money getAverageAdjustmentValue(); /** * Returns the total for all item level adjustments. * * For example, if the item has a 2 items priced at $10 a piece and a 10% discount applies to both * quantities. This method would return $2. * * @return */ Money getTotalAdjustmentValue(); /** * Returns the total price to be paid for this order item including item-level adjustments. * * It does not include the effect of order level adjustments. Calculated by looping through * the orderItemPriceDetails * * @return */ Money getTotalPrice(); /** * Returns whether or not this item is taxable. If this flag is not set, it returns true by default * * @return the taxable flag. If null, returns true */ Boolean isTaxable(); /** * Sets whether or not this item is taxable. Generally, this has been copied from the * setting of the relevant SKU at the time it was added. * * @param taxable */ void setTaxable(Boolean taxable); /** * Returns the total price to be paid before adjustments. * * @return */ Money getTotalPriceBeforeAdjustments(boolean allowSalesPrice); /** * Returns a boolean indicating whether this sku is active. This is used to determine whether a user * the sku can add the sku to their cart. */ public boolean isSkuActive(); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_OrderItem.java
1,354
private static final class ConcurrentWriter implements Callable<Void> { private final CountDownLatch startLatch; private final OWriteAheadLog writeAheadLog; private final NavigableMap<OLogSequenceNumber, WriteAheadLogTest.TestRecord> recordConcurrentMap; private final Random random; private final AtomicReference<OLogSequenceNumber> lastCheckpoint; private ConcurrentWriter(long seed, CountDownLatch startLatch, OWriteAheadLog writeAheadLog, NavigableMap<OLogSequenceNumber, WriteAheadLogTest.TestRecord> recordConcurrentMap, AtomicReference<OLogSequenceNumber> lastCheckpoint) { this.lastCheckpoint = lastCheckpoint; random = new Random(seed); this.startLatch = startLatch; this.writeAheadLog = writeAheadLog; this.recordConcurrentMap = recordConcurrentMap; } @Override public Void call() throws Exception { startLatch.await(); try { while (writeAheadLog.size() < 3072L * 1024 * 1024) { int recordSize = random.nextInt(OWALPage.PAGE_SIZE / 2 - 128) + 128; WriteAheadLogTest.TestRecord testRecord = new WriteAheadLogTest.TestRecord(recordSize, random.nextBoolean()); OLogSequenceNumber lsn = writeAheadLog.log(testRecord); if (testRecord.isUpdateMasterRecord()) { OLogSequenceNumber checkpoint = lastCheckpoint.get(); while (checkpoint == null || checkpoint.compareTo(testRecord.getLsn()) < 0) { if (lastCheckpoint.compareAndSet(checkpoint, testRecord.getLsn())) break; checkpoint = lastCheckpoint.get(); } } Assert.assertNull(recordConcurrentMap.put(lsn, testRecord)); } return null; } catch (Exception e) { e.printStackTrace(); throw e; } } }
0true
core_src_test_java_com_orientechnologies_orient_core_storage_impl_local_paginated_wal_WriteAheadLogConcurrencyTest.java
1,567
public static enum ClusterRebalanceType { /** * Re-balancing is allowed once a shard replication group is active */ ALWAYS, /** * Re-balancing is allowed only once all primary shards on all indices are active. */ INDICES_PRIMARIES_ACTIVE, /** * Re-balancing is allowed only once all shards on all indices are active. */ INDICES_ALL_ACTIVE }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_decider_ClusterRebalanceAllocationDecider.java
2,265
public abstract class NetworkUtils { private final static ESLogger logger = Loggers.getLogger(NetworkUtils.class); public static enum StackType { IPv4, IPv6, Unknown } public static final String IPv4_SETTING = "java.net.preferIPv4Stack"; public static final String IPv6_SETTING = "java.net.preferIPv6Addresses"; public static final String NON_LOOPBACK_ADDRESS = "non_loopback_address"; private final static InetAddress localAddress; static { InetAddress localAddressX = null; try { localAddressX = InetAddress.getLocalHost(); } catch (UnknownHostException e) { logger.trace("Failed to find local host", e); } localAddress = localAddressX; } public static Boolean defaultReuseAddress() { return OsUtils.WINDOWS ? null : true; } public static boolean isIPv4() { return System.getProperty("java.net.preferIPv4Stack") != null && System.getProperty("java.net.preferIPv4Stack").equals("true"); } public static InetAddress getIPv4Localhost() throws UnknownHostException { return getLocalhost(StackType.IPv4); } public static InetAddress getIPv6Localhost() throws UnknownHostException { return getLocalhost(StackType.IPv6); } public static InetAddress getLocalAddress() { return localAddress; } public static String getLocalHostName(String defaultHostName) { if (localAddress == null) { return defaultHostName; } String hostName = localAddress.getHostName(); if (hostName == null) { return defaultHostName; } return hostName; } public static String getLocalHostAddress(String defaultHostAddress) { if (localAddress == null) { return defaultHostAddress; } String hostAddress = localAddress.getHostAddress(); if (hostAddress == null) { return defaultHostAddress; } return hostAddress; } public static InetAddress getLocalhost(StackType ip_version) throws UnknownHostException { if (ip_version == StackType.IPv4) return InetAddress.getByName("127.0.0.1"); else return InetAddress.getByName("::1"); } public static boolean canBindToMcastAddress() { return OsUtils.LINUX || OsUtils.SOLARIS || OsUtils.HP; } /** * Returns the first non-loopback address on any interface on the current host. * * @param ip_version Constraint on IP version of address to be returned, 4 or 6 */ public static InetAddress getFirstNonLoopbackAddress(StackType ip_version) throws SocketException { InetAddress address = null; Enumeration intfs = NetworkInterface.getNetworkInterfaces(); List<NetworkInterface> intfsList = Lists.newArrayList(); while (intfs.hasMoreElements()) { intfsList.add((NetworkInterface) intfs.nextElement()); } // order by index, assuming first ones are more interesting try { final Method getIndexMethod = NetworkInterface.class.getDeclaredMethod("getIndex"); getIndexMethod.setAccessible(true); CollectionUtil.timSort(intfsList, new Comparator<NetworkInterface>() { @Override public int compare(NetworkInterface o1, NetworkInterface o2) { try { return ((Integer) getIndexMethod.invoke(o1)).intValue() - ((Integer) getIndexMethod.invoke(o2)).intValue(); } catch (Exception e) { throw new ElasticsearchIllegalStateException("failed to fetch index of network interface"); } } }); } catch (Exception e) { // ignore } for (NetworkInterface intf : intfsList) { try { if (!intf.isUp() || intf.isLoopback()) continue; } catch (Exception e) { // might happen when calling on a network interface that does not exists continue; } address = getFirstNonLoopbackAddress(intf, ip_version); if (address != null) { return address; } } return null; } /** * Returns the first non-loopback address on the given interface on the current host. * * @param intf the interface to be checked * @param ipVersion Constraint on IP version of address to be returned, 4 or 6 */ public static InetAddress getFirstNonLoopbackAddress(NetworkInterface intf, StackType ipVersion) throws SocketException { if (intf == null) throw new IllegalArgumentException("Network interface pointer is null"); for (Enumeration addresses = intf.getInetAddresses(); addresses.hasMoreElements(); ) { InetAddress address = (InetAddress) addresses.nextElement(); if (!address.isLoopbackAddress()) { if ((address instanceof Inet4Address && ipVersion == StackType.IPv4) || (address instanceof Inet6Address && ipVersion == StackType.IPv6)) return address; } } return null; } /** * Returns the first address with the proper ipVersion on the given interface on the current host. * * @param intf the interface to be checked * @param ipVersion Constraint on IP version of address to be returned, 4 or 6 */ public static InetAddress getFirstAddress(NetworkInterface intf, StackType ipVersion) throws SocketException { if (intf == null) throw new IllegalArgumentException("Network interface pointer is null"); for (Enumeration addresses = intf.getInetAddresses(); addresses.hasMoreElements(); ) { InetAddress address = (InetAddress) addresses.nextElement(); if ((address instanceof Inet4Address && ipVersion == StackType.IPv4) || (address instanceof Inet6Address && ipVersion == StackType.IPv6)) return address; } return null; } /** * A function to check if an interface supports an IP version (i.e has addresses * defined for that IP version). * * @param intf * @return */ public static boolean interfaceHasIPAddresses(NetworkInterface intf, StackType ipVersion) throws SocketException, UnknownHostException { boolean supportsVersion = false; if (intf != null) { // get all the InetAddresses defined on the interface Enumeration addresses = intf.getInetAddresses(); while (addresses != null && addresses.hasMoreElements()) { // get the next InetAddress for the current interface InetAddress address = (InetAddress) addresses.nextElement(); // check if we find an address of correct version if ((address instanceof Inet4Address && (ipVersion == StackType.IPv4)) || (address instanceof Inet6Address && (ipVersion == StackType.IPv6))) { supportsVersion = true; break; } } } else { throw new UnknownHostException("network interface not found"); } return supportsVersion; } /** * Tries to determine the type of IP stack from the available interfaces and their addresses and from the * system properties (java.net.preferIPv4Stack and java.net.preferIPv6Addresses) * * @return StackType.IPv4 for an IPv4 only stack, StackYTypeIPv6 for an IPv6 only stack, and StackType.Unknown * if the type cannot be detected */ public static StackType getIpStackType() { boolean isIPv4StackAvailable = isStackAvailable(true); boolean isIPv6StackAvailable = isStackAvailable(false); // if only IPv4 stack available if (isIPv4StackAvailable && !isIPv6StackAvailable) { return StackType.IPv4; } // if only IPv6 stack available else if (isIPv6StackAvailable && !isIPv4StackAvailable) { return StackType.IPv6; } // if dual stack else if (isIPv4StackAvailable && isIPv6StackAvailable) { // get the System property which records user preference for a stack on a dual stack machine if (Boolean.getBoolean(IPv4_SETTING)) // has preference over java.net.preferIPv6Addresses return StackType.IPv4; if (Boolean.getBoolean(IPv6_SETTING)) return StackType.IPv6; return StackType.IPv6; } return StackType.Unknown; } public static boolean isStackAvailable(boolean ipv4) { Collection<InetAddress> allAddrs = getAllAvailableAddresses(); for (InetAddress addr : allAddrs) if (ipv4 && addr instanceof Inet4Address || (!ipv4 && addr instanceof Inet6Address)) return true; return false; } /** * Returns all the available interfaces, including first level sub interfaces. */ public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException { List<NetworkInterface> allInterfaces = new ArrayList<NetworkInterface>(); for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) { NetworkInterface intf = interfaces.nextElement(); allInterfaces.add(intf); Enumeration<NetworkInterface> subInterfaces = intf.getSubInterfaces(); if (subInterfaces != null && subInterfaces.hasMoreElements()) { while (subInterfaces.hasMoreElements()) { allInterfaces.add(subInterfaces.nextElement()); } } } return allInterfaces; } public static Collection<InetAddress> getAllAvailableAddresses() { Set<InetAddress> retval = new HashSet<InetAddress>(); Enumeration en; try { en = NetworkInterface.getNetworkInterfaces(); if (en == null) return retval; while (en.hasMoreElements()) { NetworkInterface intf = (NetworkInterface) en.nextElement(); Enumeration<InetAddress> addrs = intf.getInetAddresses(); while (addrs.hasMoreElements()) retval.add(addrs.nextElement()); } } catch (SocketException e) { logger.warn("Failed to derive all available interfaces", e); } return retval; } private NetworkUtils() { } }
0true
src_main_java_org_elasticsearch_common_network_NetworkUtils.java
1,435
clusterService.submitStateUpdateTask("update-settings", Priority.URGENT, new AckedClusterStateUpdateTask() { @Override public boolean mustAck(DiscoveryNode discoveryNode) { return true; } @Override public void onAllNodesAcked(@Nullable Throwable t) { listener.onResponse(new ClusterStateUpdateResponse(true)); } @Override public void onAckTimeout() { listener.onResponse(new ClusterStateUpdateResponse(false)); } @Override public TimeValue ackTimeout() { return request.ackTimeout(); } @Override public TimeValue timeout() { return request.masterNodeTimeout(); } @Override public void onFailure(String source, Throwable t) { listener.onFailure(t); } @Override public ClusterState execute(ClusterState currentState) { String[] actualIndices = currentState.metaData().concreteIndices(request.indices()); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(currentState.routingTable()); MetaData.Builder metaDataBuilder = MetaData.builder(currentState.metaData()); // allow to change any settings to a close index, and only allow dynamic settings to be changed // on an open index Set<String> openIndices = Sets.newHashSet(); Set<String> closeIndices = Sets.newHashSet(); for (String index : actualIndices) { if (currentState.metaData().index(index).state() == IndexMetaData.State.OPEN) { openIndices.add(index); } else { closeIndices.add(index); } } if (!removedSettings.isEmpty() && !openIndices.isEmpty()) { throw new ElasticsearchIllegalArgumentException(String.format(Locale.ROOT, "Can't update non dynamic settings[%s] for open indices[%s]", removedSettings, openIndices )); } int updatedNumberOfReplicas = openSettings.getAsInt(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, -1); if (updatedNumberOfReplicas != -1) { routingTableBuilder.updateNumberOfReplicas(updatedNumberOfReplicas, actualIndices); metaDataBuilder.updateNumberOfReplicas(updatedNumberOfReplicas, actualIndices); logger.info("updating number_of_replicas to [{}] for indices {}", updatedNumberOfReplicas, actualIndices); } ClusterBlocks.Builder blocks = ClusterBlocks.builder().blocks(currentState.blocks()); Boolean updatedReadOnly = openSettings.getAsBoolean(IndexMetaData.SETTING_READ_ONLY, null); if (updatedReadOnly != null) { for (String index : actualIndices) { if (updatedReadOnly) { blocks.addIndexBlock(index, IndexMetaData.INDEX_READ_ONLY_BLOCK); } else { blocks.removeIndexBlock(index, IndexMetaData.INDEX_READ_ONLY_BLOCK); } } } Boolean updateMetaDataBlock = openSettings.getAsBoolean(IndexMetaData.SETTING_BLOCKS_METADATA, null); if (updateMetaDataBlock != null) { for (String index : actualIndices) { if (updateMetaDataBlock) { blocks.addIndexBlock(index, IndexMetaData.INDEX_METADATA_BLOCK); } else { blocks.removeIndexBlock(index, IndexMetaData.INDEX_METADATA_BLOCK); } } } Boolean updateWriteBlock = openSettings.getAsBoolean(IndexMetaData.SETTING_BLOCKS_WRITE, null); if (updateWriteBlock != null) { for (String index : actualIndices) { if (updateWriteBlock) { blocks.addIndexBlock(index, IndexMetaData.INDEX_WRITE_BLOCK); } else { blocks.removeIndexBlock(index, IndexMetaData.INDEX_WRITE_BLOCK); } } } Boolean updateReadBlock = openSettings.getAsBoolean(IndexMetaData.SETTING_BLOCKS_READ, null); if (updateReadBlock != null) { for (String index : actualIndices) { if (updateReadBlock) { blocks.addIndexBlock(index, IndexMetaData.INDEX_READ_BLOCK); } else { blocks.removeIndexBlock(index, IndexMetaData.INDEX_READ_BLOCK); } } } if (!openIndices.isEmpty()) { String[] indices = openIndices.toArray(new String[openIndices.size()]); metaDataBuilder.updateSettings(openSettings, indices); } if (!closeIndices.isEmpty()) { String[] indices = closeIndices.toArray(new String[closeIndices.size()]); metaDataBuilder.updateSettings(closeSettings, indices); } ClusterState updatedState = ClusterState.builder(currentState).metaData(metaDataBuilder).routingTable(routingTableBuilder).blocks(blocks).build(); // now, reroute in case things change that require it (like number of replicas) RoutingAllocation.Result routingResult = allocationService.reroute(updatedState); updatedState = ClusterState.builder(updatedState).routingResult(routingResult).build(); return updatedState; } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { } });
0true
src_main_java_org_elasticsearch_cluster_metadata_MetaDataUpdateSettingsService.java
1,725
static class StartsWithPredicate implements Predicate<Object, Object>, Serializable { String pref; StartsWithPredicate(String pref) { this.pref = pref; } public boolean apply(Map.Entry<Object, Object> mapEntry) { String val = (String) mapEntry.getValue(); if (val == null) return false; if (val.startsWith(pref)) return true; return false; } }
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
4,070
public class ParentQuery extends Query { private final Query originalParentQuery; private final String parentType; private final Filter childrenFilter; private Query rewrittenParentQuery; private IndexReader rewriteIndexReader; public ParentQuery(Query parentQuery, String parentType, Filter childrenFilter) { this.originalParentQuery = parentQuery; this.parentType = parentType; this.childrenFilter = childrenFilter; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } ParentQuery that = (ParentQuery) obj; if (!originalParentQuery.equals(that.originalParentQuery)) { return false; } if (!parentType.equals(that.parentType)) { return false; } if (getBoost() != that.getBoost()) { return false; } return true; } @Override public int hashCode() { int result = originalParentQuery.hashCode(); result = 31 * result + parentType.hashCode(); result = 31 * result + Float.floatToIntBits(getBoost()); return result; } @Override public String toString(String field) { StringBuilder sb = new StringBuilder(); sb.append("ParentQuery[").append(parentType).append("](") .append(originalParentQuery.toString(field)).append(')') .append(ToStringUtils.boost(getBoost())); return sb.toString(); } @Override // See TopChildrenQuery#rewrite public Query rewrite(IndexReader reader) throws IOException { if (rewrittenParentQuery == null) { rewriteIndexReader = reader; rewrittenParentQuery = originalParentQuery.rewrite(reader); } return this; } @Override public void extractTerms(Set<Term> terms) { rewrittenParentQuery.extractTerms(terms); } @Override public Weight createWeight(IndexSearcher searcher) throws IOException { SearchContext searchContext = SearchContext.current(); searchContext.idCache().refresh(searchContext.searcher().getTopReaderContext().leaves()); Recycler.V<ObjectFloatOpenHashMap<HashedBytesArray>> uidToScore = searchContext.cacheRecycler().objectFloatMap(-1); ParentUidCollector collector = new ParentUidCollector(uidToScore.v(), searchContext, parentType); final Query parentQuery; if (rewrittenParentQuery == null) { parentQuery = rewrittenParentQuery = searcher.rewrite(originalParentQuery); } else { assert rewriteIndexReader == searcher.getIndexReader(); parentQuery = rewrittenParentQuery; } IndexSearcher indexSearcher = new IndexSearcher(searcher.getIndexReader()); indexSearcher.setSimilarity(searcher.getSimilarity()); indexSearcher.search(parentQuery, collector); if (uidToScore.v().isEmpty()) { uidToScore.release(); return Queries.newMatchNoDocsQuery().createWeight(searcher); } ChildWeight childWeight = new ChildWeight(parentQuery.createWeight(searcher), childrenFilter, searchContext, uidToScore); searchContext.addReleasable(childWeight); return childWeight; } private static class ParentUidCollector extends NoopCollector { private final ObjectFloatOpenHashMap<HashedBytesArray> uidToScore; private final SearchContext searchContext; private final String parentType; private Scorer scorer; private IdReaderTypeCache typeCache; ParentUidCollector(ObjectFloatOpenHashMap<HashedBytesArray> uidToScore, SearchContext searchContext, String parentType) { this.uidToScore = uidToScore; this.searchContext = searchContext; this.parentType = parentType; } @Override public void collect(int doc) throws IOException { if (typeCache == null) { return; } HashedBytesArray parentUid = typeCache.idByDoc(doc); uidToScore.put(parentUid, scorer.score()); } @Override public void setScorer(Scorer scorer) throws IOException { this.scorer = scorer; } @Override public void setNextReader(AtomicReaderContext context) throws IOException { typeCache = searchContext.idCache().reader(context.reader()).type(parentType); } } private class ChildWeight extends Weight implements Releasable { private final Weight parentWeight; private final Filter childrenFilter; private final SearchContext searchContext; private final Recycler.V<ObjectFloatOpenHashMap<HashedBytesArray>> uidToScore; private ChildWeight(Weight parentWeight, Filter childrenFilter, SearchContext searchContext, Recycler.V<ObjectFloatOpenHashMap<HashedBytesArray>> uidToScore) { this.parentWeight = parentWeight; this.childrenFilter = new ApplyAcceptedDocsFilter(childrenFilter); this.searchContext = searchContext; this.uidToScore = uidToScore; } @Override public Explanation explain(AtomicReaderContext context, int doc) throws IOException { return new Explanation(getBoost(), "not implemented yet..."); } @Override public Query getQuery() { return ParentQuery.this; } @Override public float getValueForNormalization() throws IOException { float sum = parentWeight.getValueForNormalization(); sum *= getBoost() * getBoost(); return sum; } @Override public void normalize(float norm, float topLevelBoost) { } @Override public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException { DocIdSet childrenDocSet = childrenFilter.getDocIdSet(context, acceptDocs); if (DocIdSets.isEmpty(childrenDocSet)) { return null; } IdReaderTypeCache idTypeCache = searchContext.idCache().reader(context.reader()).type(parentType); if (idTypeCache == null) { return null; } return new ChildScorer(this, uidToScore.v(), childrenDocSet.iterator(), idTypeCache); } @Override public boolean release() throws ElasticsearchException { Releasables.release(uidToScore); return true; } } private static class ChildScorer extends Scorer { private final ObjectFloatOpenHashMap<HashedBytesArray> uidToScore; private final DocIdSetIterator childrenIterator; private final IdReaderTypeCache typeCache; private int currentChildDoc = -1; private float currentScore; ChildScorer(Weight weight, ObjectFloatOpenHashMap<HashedBytesArray> uidToScore, DocIdSetIterator childrenIterator, IdReaderTypeCache typeCache) { super(weight); this.uidToScore = uidToScore; this.childrenIterator = childrenIterator; this.typeCache = typeCache; } @Override public float score() throws IOException { return currentScore; } @Override public int freq() throws IOException { // We don't have the original child query hit info here... // But the freq of the children could be collector and returned here, but makes this Scorer more expensive. return 1; } @Override public int docID() { return currentChildDoc; } @Override public int nextDoc() throws IOException { while (true) { currentChildDoc = childrenIterator.nextDoc(); if (currentChildDoc == DocIdSetIterator.NO_MORE_DOCS) { return currentChildDoc; } HashedBytesArray uid = typeCache.parentIdByDoc(currentChildDoc); if (uid == null) { continue; } if (uidToScore.containsKey(uid)) { // Can use lget b/c uidToScore is only used by one thread at the time (via CacheRecycler) currentScore = uidToScore.lget(); return currentChildDoc; } } } @Override public int advance(int target) throws IOException { currentChildDoc = childrenIterator.advance(target); if (currentChildDoc == DocIdSetIterator.NO_MORE_DOCS) { return currentChildDoc; } HashedBytesArray uid = typeCache.parentIdByDoc(currentChildDoc); if (uid == null) { return nextDoc(); } if (uidToScore.containsKey(uid)) { // Can use lget b/c uidToScore is only used by one thread at the time (via CacheRecycler) currentScore = uidToScore.lget(); return currentChildDoc; } else { return nextDoc(); } } @Override public long cost() { return childrenIterator.cost(); } } }
1no label
src_main_java_org_elasticsearch_index_search_child_ParentQuery.java
2,396
public class BigArraysTests extends ElasticsearchTestCase { public static PageCacheRecycler randomCacheRecycler() { return randomBoolean() ? null : new MockPageCacheRecycler(ImmutableSettings.EMPTY, new ThreadPool()); } public void testByteArrayGrowth() { final int totalLen = randomIntBetween(1, 4000000); final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen); ByteArray array = BigArrays.newByteArray(startLen, randomCacheRecycler(), randomBoolean()); byte[] ref = new byte[totalLen]; for (int i = 0; i < totalLen; ++i) { ref[i] = randomByte(); array = BigArrays.grow(array, i + 1); array.set(i, ref[i]); } for (int i = 0; i < totalLen; ++i) { assertEquals(ref[i], array.get(i)); } array.release(); } public void testIntArrayGrowth() { final int totalLen = randomIntBetween(1, 1000000); final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen); IntArray array = BigArrays.newIntArray(startLen, randomCacheRecycler(), randomBoolean()); int[] ref = new int[totalLen]; for (int i = 0; i < totalLen; ++i) { ref[i] = randomInt(); array = BigArrays.grow(array, i + 1); array.set(i, ref[i]); } for (int i = 0; i < totalLen; ++i) { assertEquals(ref[i], array.get(i)); } array.release(); } public void testLongArrayGrowth() { final int totalLen = randomIntBetween(1, 1000000); final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen); LongArray array = BigArrays.newLongArray(startLen, randomCacheRecycler(), randomBoolean()); long[] ref = new long[totalLen]; for (int i = 0; i < totalLen; ++i) { ref[i] = randomLong(); array = BigArrays.grow(array, i + 1); array.set(i, ref[i]); } for (int i = 0; i < totalLen; ++i) { assertEquals(ref[i], array.get(i)); } array.release(); } public void testDoubleArrayGrowth() { final int totalLen = randomIntBetween(1, 1000000); final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen); DoubleArray array = BigArrays.newDoubleArray(startLen, randomCacheRecycler(), randomBoolean()); double[] ref = new double[totalLen]; for (int i = 0; i < totalLen; ++i) { ref[i] = randomDouble(); array = BigArrays.grow(array, i + 1); array.set(i, ref[i]); } for (int i = 0; i < totalLen; ++i) { assertEquals(ref[i], array.get(i), 0.001d); } array.release(); } public void testObjectArrayGrowth() { final int totalLen = randomIntBetween(1, 1000000); final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen); ObjectArray<Object> array = BigArrays.newObjectArray(startLen, randomCacheRecycler()); final Object[] pool = new Object[100]; for (int i = 0; i < pool.length; ++i) { pool[i] = new Object(); } Object[] ref = new Object[totalLen]; for (int i = 0; i < totalLen; ++i) { ref[i] = randomFrom(pool); array = BigArrays.grow(array, i + 1); array.set(i, ref[i]); } for (int i = 0; i < totalLen; ++i) { assertSame(ref[i], array.get(i)); } array.release(); } public void testDoubleArrayFill() { final int len = randomIntBetween(1, 100000); final int fromIndex = randomIntBetween(0, len - 1); final int toIndex = randomBoolean() ? Math.min(fromIndex + randomInt(100), len) // single page : randomIntBetween(fromIndex, len); // likely multiple pages final DoubleArray array2 = BigArrays.newDoubleArray(len, randomCacheRecycler(), randomBoolean()); final double[] array1 = new double[len]; for (int i = 0; i < len; ++i) { array1[i] = randomDouble(); array2.set(i, array1[i]); } final double rand = randomDouble(); Arrays.fill(array1, fromIndex, toIndex, rand); array2.fill(fromIndex, toIndex, rand); for (int i = 0; i < len; ++i) { assertEquals(array1[i], array2.get(i), 0.001d); } array2.release(); } public void testLongArrayFill() { final int len = randomIntBetween(1, 100000); final int fromIndex = randomIntBetween(0, len - 1); final int toIndex = randomBoolean() ? Math.min(fromIndex + randomInt(100), len) // single page : randomIntBetween(fromIndex, len); // likely multiple pages final LongArray array2 = BigArrays.newLongArray(len, randomCacheRecycler(), randomBoolean()); final long[] array1 = new long[len]; for (int i = 0; i < len; ++i) { array1[i] = randomLong(); array2.set(i, array1[i]); } final long rand = randomLong(); Arrays.fill(array1, fromIndex, toIndex, rand); array2.fill(fromIndex, toIndex, rand); for (int i = 0; i < len; ++i) { assertEquals(array1[i], array2.get(i)); } array2.release(); } public void testByteArrayBulkGet() { final byte[] array1 = new byte[randomIntBetween(1, 4000000)]; getRandom().nextBytes(array1); final ByteArray array2 = BigArrays.newByteArray(array1.length, randomCacheRecycler(), randomBoolean()); for (int i = 0; i < array1.length; ++i) { array2.set(i, array1[i]); } final BytesRef ref = new BytesRef(); for (int i = 0; i < 1000; ++i) { final int offset = randomInt(array1.length - 1); final int len = randomInt(Math.min(randomBoolean() ? 10 : Integer.MAX_VALUE, array1.length - offset)); array2.get(offset, len, ref); assertEquals(new BytesRef(array1, offset, len), ref); } array2.release(); } public void testByteArrayBulkSet() { final byte[] array1 = new byte[randomIntBetween(1, 4000000)]; getRandom().nextBytes(array1); final ByteArray array2 = BigArrays.newByteArray(array1.length, randomCacheRecycler(), randomBoolean()); for (int i = 0; i < array1.length; ) { final int len = Math.min(array1.length - i, randomBoolean() ? randomInt(10) : randomInt(3 * BigArrays.BYTE_PAGE_SIZE)); array2.set(i, array1, i, len); i += len; } for (int i = 0; i < array1.length; ++i) { assertEquals(array1[i], array2.get(i)); } array2.release(); } }
0true
src_test_java_org_elasticsearch_common_util_BigArraysTests.java
764
public class ListSetOperation extends CollectionBackupAwareOperation { private int index; private Data value; private long itemId = -1; private long oldItemId = -1; public ListSetOperation() { } public ListSetOperation(String name, int index, Data value) { super(name); this.index = index; this.value = value; } @Override public boolean shouldBackup() { return true; } @Override public Operation getBackupOperation() { return new ListSetBackupOperation(name, oldItemId, itemId, value); } @Override public int getId() { return CollectionDataSerializerHook.LIST_SET; } @Override public void beforeRun() throws Exception { } @Override public void run() throws Exception { final ListContainer container = getOrCreateListContainer(); itemId = container.nextId(); final CollectionItem item = container.set(index, itemId, value); oldItemId = item.getItemId(); response = item.getValue(); } @Override public void afterRun() throws Exception { publishEvent(ItemEventType.REMOVED, (Data) response); publishEvent(ItemEventType.ADDED, value); } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeInt(index); value.writeData(out); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); index = in.readInt(); value = new Data(); value.readData(in); } }
0true
hazelcast_src_main_java_com_hazelcast_collection_list_ListSetOperation.java
2,224
AVG { @Override public float combine(double queryBoost, double queryScore, double funcScore, double maxBoost) { return toFloat((queryBoost * (Math.min(funcScore, maxBoost) + queryScore) / 2.0)); } @Override public String getName() { return "avg"; } @Override public ComplexExplanation explain(float queryBoost, Explanation queryExpl, Explanation funcExpl, float maxBoost) { float score = toFloat(queryBoost * (queryExpl.getValue() + Math.min(funcExpl.getValue(), maxBoost)) / 2.0); ComplexExplanation res = new ComplexExplanation(true, score, "function score, product of:"); ComplexExplanation minExpl = new ComplexExplanation(true, Math.min(funcExpl.getValue(), maxBoost), "Math.min of"); minExpl.addDetail(funcExpl); minExpl.addDetail(new Explanation(maxBoost, "maxBoost")); ComplexExplanation avgExpl = new ComplexExplanation(true, toFloat((Math.min(funcExpl.getValue(), maxBoost) + queryExpl.getValue()) / 2.0), "avg of"); avgExpl.addDetail(queryExpl); avgExpl.addDetail(minExpl); res.addDetail(avgExpl); res.addDetail(new Explanation(queryBoost, "queryBoost")); return res; } },
0true
src_main_java_org_elasticsearch_common_lucene_search_function_CombineFunction.java
1,187
public class Elasticsearch extends Bootstrap { public static void close(String[] args) { Bootstrap.close(args); } public static void main(String[] args) { Bootstrap.main(args); } }
0true
src_main_java_org_elasticsearch_bootstrap_Elasticsearch.java
1,522
public class ValueGroupCountMapReduce { public static final String PROPERTY = Tokens.makeNamespace(ValueGroupCountMapReduce.class) + ".property"; public static final String CLASS = Tokens.makeNamespace(ValueGroupCountMapReduce.class) + ".class"; public static final String TYPE = Tokens.makeNamespace(ValueGroupCountMapReduce.class) + ".type"; public enum Counters { PROPERTIES_COUNTED } public static Configuration createConfiguration(final Class<? extends Element> klass, final String key, final Class<? extends Writable> type) { final Configuration configuration = new EmptyConfiguration(); configuration.setClass(CLASS, klass, Element.class); configuration.set(PROPERTY, key); configuration.setClass(TYPE, type, Writable.class); return configuration; } public static class Map extends Mapper<NullWritable, FaunusVertex, WritableComparable, LongWritable> { private String property; private WritableHandler handler; private boolean isVertex; // making use of in-map aggregation/combiner private CounterMap<Object> map; private int mapSpillOver; private SafeMapperOutputs outputs; @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { this.map = new CounterMap<Object>(); this.mapSpillOver = context.getConfiguration().getInt(Tokens.TITAN_HADOOP_PIPELINE_MAP_SPILL_OVER, Tokens.DEFAULT_MAP_SPILL_OVER); this.property = context.getConfiguration().get(PROPERTY); this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class); this.handler = new WritableHandler(context.getConfiguration().getClass(TYPE, Text.class, WritableComparable.class)); this.outputs = new SafeMapperOutputs(context); } @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, WritableComparable, LongWritable>.Context context) throws IOException, InterruptedException { if (this.isVertex) { if (value.hasPaths()) { this.map.incr(ElementPicker.getProperty(value, this.property), value.pathCount()); DEFAULT_COMPAT.incrementContextCounter(context, Counters.PROPERTIES_COUNTED, 1L); } } else { for (final Edge e : value.getEdges(Direction.OUT)) { final StandardFaunusEdge edge = (StandardFaunusEdge) e; if (edge.hasPaths()) { this.map.incr(ElementPicker.getProperty(edge, this.property), edge.pathCount()); DEFAULT_COMPAT.incrementContextCounter(context, Counters.PROPERTIES_COUNTED, 1L); } } } // protected against memory explosion if (this.map.size() > this.mapSpillOver) { this.dischargeMap(context); } this.outputs.write(Tokens.GRAPH, NullWritable.get(), value); } private final LongWritable longWritable = new LongWritable(); public void dischargeMap(final Mapper<NullWritable, FaunusVertex, WritableComparable, LongWritable>.Context context) throws IOException, InterruptedException { for (final java.util.Map.Entry<Object, Long> entry : this.map.entrySet()) { this.longWritable.set(entry.getValue()); context.write(this.handler.set(entry.getKey()), this.longWritable); } this.map.clear(); } @Override public void cleanup(final Mapper<NullWritable, FaunusVertex, WritableComparable, LongWritable>.Context context) throws IOException, InterruptedException { this.dischargeMap(context); this.outputs.close(); } } public static class Combiner extends Reducer<WritableComparable, LongWritable, WritableComparable, LongWritable> { private final LongWritable longWritable = new LongWritable(); @Override public void reduce(final WritableComparable key, final Iterable<LongWritable> values, final Reducer<WritableComparable, LongWritable, WritableComparable, LongWritable>.Context context) throws IOException, InterruptedException { long totalCount = 0; for (final LongWritable token : values) { totalCount = totalCount + token.get(); } this.longWritable.set(totalCount); context.write(key, this.longWritable); } } public static class Reduce extends Reducer<WritableComparable, LongWritable, WritableComparable, LongWritable> { private SafeReducerOutputs outputs; @Override public void setup(final Reducer.Context context) throws IOException, InterruptedException { this.outputs = new SafeReducerOutputs(context); } private final LongWritable longWritable = new LongWritable(); @Override public void reduce(final WritableComparable key, final Iterable<LongWritable> values, final Reducer<WritableComparable, LongWritable, WritableComparable, LongWritable>.Context context) throws IOException, InterruptedException { long totalCount = 0; for (final LongWritable token : values) { totalCount = totalCount + token.get(); } this.longWritable.set(totalCount); this.outputs.write(Tokens.SIDEEFFECT, key, this.longWritable); } @Override public void cleanup(final Reducer<WritableComparable, LongWritable, WritableComparable, LongWritable>.Context context) throws IOException, InterruptedException { this.outputs.close(); } } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_sideeffect_ValueGroupCountMapReduce.java
974
public class OCompositeKeySerializer implements OBinarySerializer<OCompositeKey>, OStreamSerializer { public static final String NAME = "cks"; public static final OCompositeKeySerializer INSTANCE = new OCompositeKeySerializer(); public static final byte ID = 14; @SuppressWarnings("unchecked") public int getObjectSize(OCompositeKey compositeKey, Object... hints) { final OType[] types = getKeyTypes(hints); final List<Object> keys = compositeKey.getKeys(); int size = 2 * OIntegerSerializer.INT_SIZE; final OBinarySerializerFactory factory = OBinarySerializerFactory.INSTANCE; for (int i = 0; i < keys.size(); i++) { final Object key = keys.get(i); final OType type; if (types.length > i) type = types[i]; else type = OType.getTypeByClass(key.getClass()); size += OBinarySerializerFactory.TYPE_IDENTIFIER_SIZE + ((OBinarySerializer<Object>) factory.getObjectSerializer(type)).getObjectSize(key); } return size; } public void serialize(OCompositeKey compositeKey, byte[] stream, int startPosition, Object... hints) { final OType[] types = getKeyTypes(hints); final List<Object> keys = compositeKey.getKeys(); final int keysSize = keys.size(); final int oldStartPosition = startPosition; startPosition += OIntegerSerializer.INT_SIZE; OIntegerSerializer.INSTANCE.serialize(keysSize, stream, startPosition); startPosition += OIntegerSerializer.INT_SIZE; final OBinarySerializerFactory factory = OBinarySerializerFactory.INSTANCE; for (int i = 0; i < keys.size(); i++) { final Object key = keys.get(i); final OType type; if (types.length > i) type = types[i]; else type = OType.getTypeByClass(key.getClass()); @SuppressWarnings("unchecked") OBinarySerializer<Object> binarySerializer = (OBinarySerializer<Object>) factory.getObjectSerializer(type); stream[startPosition] = binarySerializer.getId(); startPosition += OBinarySerializerFactory.TYPE_IDENTIFIER_SIZE; binarySerializer.serialize(key, stream, startPosition); startPosition += binarySerializer.getObjectSize(key); } OIntegerSerializer.INSTANCE.serialize((startPosition - oldStartPosition), stream, oldStartPosition); } @SuppressWarnings("unchecked") public OCompositeKey deserialize(byte[] stream, int startPosition) { final OCompositeKey compositeKey = new OCompositeKey(); startPosition += OIntegerSerializer.INT_SIZE; final int keysSize = OIntegerSerializer.INSTANCE.deserialize(stream, startPosition); startPosition += OIntegerSerializer.INSTANCE.getObjectSize(keysSize); final OBinarySerializerFactory factory = OBinarySerializerFactory.INSTANCE; for (int i = 0; i < keysSize; i++) { final byte serializerId = stream[startPosition]; startPosition += OBinarySerializerFactory.TYPE_IDENTIFIER_SIZE; OBinarySerializer<Object> binarySerializer = (OBinarySerializer<Object>) factory.getObjectSerializer(serializerId); final Object key = binarySerializer.deserialize(stream, startPosition); compositeKey.addKey(key); startPosition += binarySerializer.getObjectSize(key); } return compositeKey; } public int getObjectSize(byte[] stream, int startPosition) { return OIntegerSerializer.INSTANCE.deserialize(stream, startPosition); } public byte getId() { return ID; } public byte[] toStream(final Object iObject) throws IOException { throw new UnsupportedOperationException("CSV storage format is out of dated and is not supported."); } public Object fromStream(final byte[] iStream) throws IOException { final OCompositeKey compositeKey = new OCompositeKey(); final OMemoryInputStream inputStream = new OMemoryInputStream(iStream); final int keysSize = inputStream.getAsInteger(); for (int i = 0; i < keysSize; i++) { final byte[] keyBytes = inputStream.getAsByteArray(); final String keyString = OBinaryProtocol.bytes2string(keyBytes); final int typeSeparatorPos = keyString.indexOf(','); final OType type = OType.valueOf(keyString.substring(0, typeSeparatorPos)); compositeKey.addKey(ORecordSerializerStringAbstract.simpleValueFromStream(keyString.substring(typeSeparatorPos + 1), type)); } return compositeKey; } public String getName() { return NAME; } public int getObjectSizeNative(byte[] stream, int startPosition) { return OIntegerSerializer.INSTANCE.deserializeNative(stream, startPosition); } public void serializeNative(OCompositeKey compositeKey, byte[] stream, int startPosition, Object... hints) { final OType[] types = getKeyTypes(hints); final List<Object> keys = compositeKey.getKeys(); final int keysSize = keys.size(); final int oldStartPosition = startPosition; startPosition += OIntegerSerializer.INT_SIZE; OIntegerSerializer.INSTANCE.serializeNative(keysSize, stream, startPosition); startPosition += OIntegerSerializer.INT_SIZE; final OBinarySerializerFactory factory = OBinarySerializerFactory.INSTANCE; for (int i = 0; i < keys.size(); i++) { final Object key = keys.get(i); final OType type; if (types.length > i) type = types[i]; else type = OType.getTypeByClass(key.getClass()); @SuppressWarnings("unchecked") OBinarySerializer<Object> binarySerializer = (OBinarySerializer<Object>) factory.getObjectSerializer(type); stream[startPosition] = binarySerializer.getId(); startPosition += OBinarySerializerFactory.TYPE_IDENTIFIER_SIZE; binarySerializer.serializeNative(key, stream, startPosition); startPosition += binarySerializer.getObjectSize(key); } OIntegerSerializer.INSTANCE.serializeNative((startPosition - oldStartPosition), stream, oldStartPosition); } public OCompositeKey deserializeNative(byte[] stream, int startPosition) { final OCompositeKey compositeKey = new OCompositeKey(); startPosition += OIntegerSerializer.INT_SIZE; final int keysSize = OIntegerSerializer.INSTANCE.deserializeNative(stream, startPosition); startPosition += OIntegerSerializer.INSTANCE.getObjectSize(keysSize); final OBinarySerializerFactory factory = OBinarySerializerFactory.INSTANCE; for (int i = 0; i < keysSize; i++) { final byte serializerId = stream[startPosition]; startPosition += OBinarySerializerFactory.TYPE_IDENTIFIER_SIZE; OBinarySerializer<Object> binarySerializer = (OBinarySerializer<Object>) factory.getObjectSerializer(serializerId); final Object key = binarySerializer.deserializeNative(stream, startPosition); compositeKey.addKey(key); startPosition += binarySerializer.getObjectSize(key); } return compositeKey; } @Override public void serializeInDirectMemory(OCompositeKey compositeKey, ODirectMemoryPointer pointer, long offset, Object... hints) { final OType[] types = getKeyTypes(hints); final List<Object> keys = compositeKey.getKeys(); final int keysSize = keys.size(); final long oldStartOffset = offset; offset += OIntegerSerializer.INT_SIZE; pointer.setInt(offset, keysSize); offset += OIntegerSerializer.INT_SIZE; final OBinarySerializerFactory factory = OBinarySerializerFactory.INSTANCE; for (int i = 0; i < keys.size(); i++) { final Object key = keys.get(i); final OType type; if (types.length > i) type = types[i]; else type = OType.getTypeByClass(key.getClass()); @SuppressWarnings("unchecked") OBinarySerializer<Object> binarySerializer = (OBinarySerializer<Object>) factory.getObjectSerializer(type); pointer.setByte(offset, binarySerializer.getId()); offset += OBinarySerializerFactory.TYPE_IDENTIFIER_SIZE; binarySerializer.serializeInDirectMemory(key, pointer, offset); offset += binarySerializer.getObjectSize(key); } pointer.setInt(oldStartOffset, (int) (offset - oldStartOffset)); } private OType[] getKeyTypes(Object[] hints) { final OType[] types; if (hints != null && hints.length > 0) types = (OType[]) hints; else types = new OType[0]; return types; } @Override public OCompositeKey deserializeFromDirectMemory(ODirectMemoryPointer pointer, long offset) { final OCompositeKey compositeKey = new OCompositeKey(); offset += OIntegerSerializer.INT_SIZE; final int keysSize = pointer.getInt(offset); offset += OIntegerSerializer.INT_SIZE; final OBinarySerializerFactory factory = OBinarySerializerFactory.INSTANCE; for (int i = 0; i < keysSize; i++) { final byte serializerId = pointer.getByte(offset); offset += OBinarySerializerFactory.TYPE_IDENTIFIER_SIZE; OBinarySerializer<Object> binarySerializer = (OBinarySerializer<Object>) factory.getObjectSerializer(serializerId); final Object key = binarySerializer.deserializeFromDirectMemory(pointer, offset); compositeKey.addKey(key); offset += binarySerializer.getObjectSize(key); } return compositeKey; } @Override public int getObjectSizeInDirectMemory(ODirectMemoryPointer pointer, long offset) { return pointer.getInt(offset); } public boolean isFixedLength() { return false; } public int getFixedLength() { return 0; } @Override public OCompositeKey preprocess(OCompositeKey value, Object... hints) { if (value == null) return null; final OType[] types = getKeyTypes(hints); final List<Object> keys = value.getKeys(); final OCompositeKey compositeKey = new OCompositeKey(); final OBinarySerializerFactory factory = OBinarySerializerFactory.INSTANCE; for (int i = 0; i < keys.size(); i++) { final Object key = keys.get(i); final OType type; if (types.length > i) type = types[i]; else type = OType.getTypeByClass(key.getClass()); OBinarySerializer<Object> keySerializer = ((OBinarySerializer<Object>) factory.getObjectSerializer(type)); compositeKey.addKey(keySerializer.preprocess(key)); } return compositeKey; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_binary_impl_index_OCompositeKeySerializer.java
1,195
public abstract class OQueryTargetOperator extends OQueryOperator { protected OQueryTargetOperator(final String iKeyword, final int iPrecedence, final boolean iLogical) { super(iKeyword, iPrecedence, false); } public abstract Collection<OIdentifiable> filterRecords(final ODatabaseComplex<?> iRecord, final List<String> iTargetClasses, final OSQLFilterCondition iCondition, final Object iLeft, final Object iRight); /** * At run-time the evaluation per record must return always true since the recordset are filtered at the beginning unless an * operator can work in both modes. In this case sub-class must extend it. */ @Override public Object evaluateRecord(final OIdentifiable iRecord, ODocument iCurrentResult, final OSQLFilterCondition iCondition, final Object iLeft, final Object iRight, OCommandContext iContext) { return true; } }
0true
core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryTargetOperator.java
1,211
public interface QueueStoreFactory<T> { QueueStore<T> newQueueStore(String name, Properties properties); }
0true
hazelcast_src_main_java_com_hazelcast_core_QueueStoreFactory.java
635
public final class ClientMembershipEvent implements IdentifiedDataSerializable { public static final int MEMBER_ADDED = MembershipEvent.MEMBER_ADDED; public static final int MEMBER_REMOVED = MembershipEvent.MEMBER_REMOVED; public static final int MEMBER_ATTRIBUTE_CHANGED = MembershipEvent.MEMBER_ATTRIBUTE_CHANGED; private Member member; private MemberAttributeChange memberAttributeChange; private int eventType; public ClientMembershipEvent() { } public ClientMembershipEvent(Member member, int eventType) { this(member, null, eventType); } public ClientMembershipEvent(Member member, MemberAttributeChange memberAttributeChange) { this(member, memberAttributeChange, MEMBER_ATTRIBUTE_CHANGED); } private ClientMembershipEvent(Member member, MemberAttributeChange memberAttributeChange, int eventType) { this.member = member; this.eventType = eventType; this.memberAttributeChange = memberAttributeChange; } /** * Returns the membership event type; #MEMBER_ADDED or #MEMBER_REMOVED * * @return the membership event type */ public int getEventType() { return eventType; } /** * Returns the removed or added member. * * @return member which is removed/added */ public Member getMember() { return member; } /** * Returns the member attribute chance operation to execute * if event type is {@link #MEMBER_ATTRIBUTE_CHANGED}. * * @return MemberAttributeChange to execute */ public MemberAttributeChange getMemberAttributeChange() { return memberAttributeChange; } @Override public void writeData(ObjectDataOutput out) throws IOException { member.writeData(out); out.writeInt(eventType); out.writeBoolean(memberAttributeChange != null); if (memberAttributeChange != null) { memberAttributeChange.writeData(out); } } @Override public void readData(ObjectDataInput in) throws IOException { member = new MemberImpl(); member.readData(in); eventType = in.readInt(); if (in.readBoolean()) { memberAttributeChange = new MemberAttributeChange(); memberAttributeChange.readData(in); } } @Override public int getFactoryId() { return ClusterDataSerializerHook.F_ID; } @Override public int getId() { return ClusterDataSerializerHook.MEMBERSHIP_EVENT; } }
0true
hazelcast_src_main_java_com_hazelcast_cluster_client_ClientMembershipEvent.java
1,539
new IntroSorter() { float pivotWeight; @Override protected void swap(int i, int j) { final String tmpIdx = indices[i]; indices[i] = indices[j]; indices[j] = tmpIdx; final float tmpDelta = deltas[i]; deltas[i] = deltas[j]; deltas[j] = tmpDelta; } @Override protected int compare(int i, int j) { return Float.compare(deltas[j], deltas[i]); } @Override protected void setPivot(int i) { pivotWeight = deltas[i]; } @Override protected int comparePivot(int j) { return Float.compare(deltas[j], pivotWeight); } }.sort(0, deltas.length);
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_allocator_BalancedShardsAllocator.java
6,202
public class RandomizingClient implements InternalClient { private final SearchType defaultSearchType; private final InternalClient delegate; public RandomizingClient(InternalClient client, Random random) { this.delegate = client; // we don't use the QUERY_AND_FETCH types that break quite a lot of tests // given that they return `size*num_shards` hits instead of `size` defaultSearchType = RandomPicks.randomFrom(random, Arrays.asList( SearchType.DFS_QUERY_THEN_FETCH, SearchType.QUERY_THEN_FETCH)); } @Override public void close() { delegate.close(); } @Override public AdminClient admin() { return delegate.admin(); } @Override public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> ActionFuture<Response> execute( Action<Request, Response, RequestBuilder> action, Request request) { return delegate.execute(action, request); } @Override public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void execute( Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) { delegate.execute(action, request, listener); } @Override public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> RequestBuilder prepareExecute( Action<Request, Response, RequestBuilder> action) { return delegate.prepareExecute(action); } @Override public ActionFuture<IndexResponse> index(IndexRequest request) { return delegate.index(request); } @Override public void index(IndexRequest request, ActionListener<IndexResponse> listener) { delegate.index(request, listener); } @Override public IndexRequestBuilder prepareIndex() { return delegate.prepareIndex(); } @Override public ActionFuture<UpdateResponse> update(UpdateRequest request) { return delegate.update(request); } @Override public void update(UpdateRequest request, ActionListener<UpdateResponse> listener) { delegate.update(request, listener); } @Override public UpdateRequestBuilder prepareUpdate() { return delegate.prepareUpdate(); } @Override public UpdateRequestBuilder prepareUpdate(String index, String type, String id) { return delegate.prepareUpdate(index, type, id); } @Override public IndexRequestBuilder prepareIndex(String index, String type) { return delegate.prepareIndex(index, type); } @Override public IndexRequestBuilder prepareIndex(String index, String type, String id) { return delegate.prepareIndex(index, type, id); } @Override public ActionFuture<DeleteResponse> delete(DeleteRequest request) { return delegate.delete(request); } @Override public void delete(DeleteRequest request, ActionListener<DeleteResponse> listener) { delegate.delete(request, listener); } @Override public DeleteRequestBuilder prepareDelete() { return delegate.prepareDelete(); } @Override public DeleteRequestBuilder prepareDelete(String index, String type, String id) { return delegate.prepareDelete(index, type, id); } @Override public ActionFuture<BulkResponse> bulk(BulkRequest request) { return delegate.bulk(request); } @Override public void bulk(BulkRequest request, ActionListener<BulkResponse> listener) { delegate.bulk(request, listener); } @Override public BulkRequestBuilder prepareBulk() { return delegate.prepareBulk(); } @Override public ActionFuture<DeleteByQueryResponse> deleteByQuery(DeleteByQueryRequest request) { return delegate.deleteByQuery(request); } @Override public void deleteByQuery(DeleteByQueryRequest request, ActionListener<DeleteByQueryResponse> listener) { delegate.deleteByQuery(request, listener); } @Override public DeleteByQueryRequestBuilder prepareDeleteByQuery(String... indices) { return delegate.prepareDeleteByQuery(indices); } @Override public ActionFuture<GetResponse> get(GetRequest request) { return delegate.get(request); } @Override public void get(GetRequest request, ActionListener<GetResponse> listener) { delegate.get(request, listener); } @Override public GetRequestBuilder prepareGet() { return delegate.prepareGet(); } @Override public GetRequestBuilder prepareGet(String index, String type, String id) { return delegate.prepareGet(index, type, id); } @Override public ActionFuture<MultiGetResponse> multiGet(MultiGetRequest request) { return delegate.multiGet(request); } @Override public void multiGet(MultiGetRequest request, ActionListener<MultiGetResponse> listener) { delegate.multiGet(request, listener); } @Override public MultiGetRequestBuilder prepareMultiGet() { return delegate.prepareMultiGet(); } @Override public ActionFuture<CountResponse> count(CountRequest request) { return delegate.count(request); } @Override public void count(CountRequest request, ActionListener<CountResponse> listener) { delegate.count(request, listener); } @Override public CountRequestBuilder prepareCount(String... indices) { return delegate.prepareCount(indices); } @Override public ActionFuture<SuggestResponse> suggest(SuggestRequest request) { return delegate.suggest(request); } @Override public void suggest(SuggestRequest request, ActionListener<SuggestResponse> listener) { delegate.suggest(request, listener); } @Override public SuggestRequestBuilder prepareSuggest(String... indices) { return delegate.prepareSuggest(indices); } @Override public ActionFuture<SearchResponse> search(SearchRequest request) { return delegate.search(request); } @Override public void search(SearchRequest request, ActionListener<SearchResponse> listener) { delegate.search(request, listener); } @Override public SearchRequestBuilder prepareSearch(String... indices) { return delegate.prepareSearch(indices).setSearchType(defaultSearchType); } @Override public ActionFuture<SearchResponse> searchScroll(SearchScrollRequest request) { return delegate.searchScroll(request); } @Override public void searchScroll(SearchScrollRequest request, ActionListener<SearchResponse> listener) { delegate.searchScroll(request, listener); } @Override public SearchScrollRequestBuilder prepareSearchScroll(String scrollId) { return delegate.prepareSearchScroll(scrollId); } @Override public ActionFuture<MultiSearchResponse> multiSearch(MultiSearchRequest request) { return delegate.multiSearch(request); } @Override public void multiSearch(MultiSearchRequest request, ActionListener<MultiSearchResponse> listener) { delegate.multiSearch(request, listener); } @Override public MultiSearchRequestBuilder prepareMultiSearch() { return delegate.prepareMultiSearch(); } @Override public ActionFuture<SearchResponse> moreLikeThis(MoreLikeThisRequest request) { return delegate.moreLikeThis(request); } @Override public void moreLikeThis(MoreLikeThisRequest request, ActionListener<SearchResponse> listener) { delegate.moreLikeThis(request, listener); } @Override public MoreLikeThisRequestBuilder prepareMoreLikeThis(String index, String type, String id) { return delegate.prepareMoreLikeThis(index, type, id); } @Override public ActionFuture<TermVectorResponse> termVector(TermVectorRequest request) { return delegate.termVector(request); } @Override public void termVector(TermVectorRequest request, ActionListener<TermVectorResponse> listener) { delegate.termVector(request, listener); } @Override public TermVectorRequestBuilder prepareTermVector(String index, String type, String id) { return delegate.prepareTermVector(index, type, id); } @Override public ActionFuture<MultiTermVectorsResponse> multiTermVectors(MultiTermVectorsRequest request) { return delegate.multiTermVectors(request); } @Override public void multiTermVectors(MultiTermVectorsRequest request, ActionListener<MultiTermVectorsResponse> listener) { delegate.multiTermVectors(request, listener); } @Override public MultiTermVectorsRequestBuilder prepareMultiTermVectors() { return delegate.prepareMultiTermVectors(); } @Override public ActionFuture<PercolateResponse> percolate(PercolateRequest request) { return delegate.percolate(request); } @Override public void percolate(PercolateRequest request, ActionListener<PercolateResponse> listener) { delegate.percolate(request, listener); } @Override public PercolateRequestBuilder preparePercolate() { return delegate.preparePercolate(); } @Override public ActionFuture<MultiPercolateResponse> multiPercolate(MultiPercolateRequest request) { return delegate.multiPercolate(request); } @Override public void multiPercolate(MultiPercolateRequest request, ActionListener<MultiPercolateResponse> listener) { delegate.multiPercolate(request, listener); } @Override public MultiPercolateRequestBuilder prepareMultiPercolate() { return delegate.prepareMultiPercolate(); } @Override public ExplainRequestBuilder prepareExplain(String index, String type, String id) { return delegate.prepareExplain(index, type, id); } @Override public ActionFuture<ExplainResponse> explain(ExplainRequest request) { return delegate.explain(request); } @Override public void explain(ExplainRequest request, ActionListener<ExplainResponse> listener) { delegate.explain(request, listener); } @Override public ClearScrollRequestBuilder prepareClearScroll() { return delegate.prepareClearScroll(); } @Override public ActionFuture<ClearScrollResponse> clearScroll(ClearScrollRequest request) { return delegate.clearScroll(request); } @Override public void clearScroll(ClearScrollRequest request, ActionListener<ClearScrollResponse> listener) { delegate.clearScroll(request, listener); } @Override public ThreadPool threadPool() { return delegate.threadPool(); } @Override public Settings settings() { return delegate.settings(); } @Override public String toString() { return "randomized(" + super.toString() + ")"; } }
1no label
src_test_java_org_elasticsearch_test_client_RandomizingClient.java
1,488
@SuppressWarnings("unchecked") public class OObjectDatabaseTxPooled extends OObjectDatabaseTx implements ODatabasePooled { private OObjectDatabasePool ownerPool; public OObjectDatabaseTxPooled(final OObjectDatabasePool iOwnerPool, final String iURL, final String iUserName, final String iUserPassword) { super(iURL); ownerPool = iOwnerPool; super.open(iUserName, iUserPassword); } public void reuse(final Object iOwner, final Object[] iAdditionalArgs) { ownerPool = (OObjectDatabasePool) iOwner; if (isClosed()) open((String) iAdditionalArgs[0], (String) iAdditionalArgs[1]); init(); // getMetadata().reload(); ODatabaseRecordThreadLocal.INSTANCE.set(getUnderlying()); try { ODatabase current = underlying; while (!(current instanceof ODatabaseRaw) && ((ODatabaseComplex<?>) current).getUnderlying() != null) current = ((ODatabaseComplex<?>) current).getUnderlying(); ((ODatabaseRaw) current).callOnOpenListeners(); } catch (Exception e) { OLogManager.instance().error(this, "Error on reusing database '%s' in pool", e, getName()); } } @Override public OObjectDatabaseTxPooled open(String iUserName, String iUserPassword) { throw new UnsupportedOperationException( "Database instance was retrieved from a pool. You cannot open the database in this way. Use directly a OObjectDatabaseTx instance if you want to manually open the connection"); } @Override public OObjectDatabaseTxPooled create() { throw new UnsupportedOperationException( "Database instance was retrieved from a pool. You cannot open the database in this way. Use directly a OObjectDatabaseTx instance if you want to manually open the connection"); } @Override public boolean isClosed() { return ownerPool == null || super.isClosed(); } /** * Avoid to close it but rather release itself to the owner pool. */ @Override public void close() { if (isClosed()) return; objects2Records.clear(); records2Objects.clear(); rid2Records.clear(); checkOpeness(); try { rollback(); } catch (Exception e) { OLogManager.instance().error(this, "Error on releasing database '%s' in pool", e, getName()); } try { ODatabase current = underlying; while (!(current instanceof ODatabaseRaw) && ((ODatabaseComplex<?>) current).getUnderlying() != null) current = ((ODatabaseComplex<?>) current).getUnderlying(); ((ODatabaseRaw) current).callOnCloseListeners(); } catch (Exception e) { OLogManager.instance().error(this, "Error on releasing database '%s' in pool", e, getName()); } getLevel1Cache().clear(); if (ownerPool != null) { final OObjectDatabasePool localCopy = ownerPool; ownerPool = null; localCopy.release(this); } } public void forceClose() { super.close(); } @Override protected void checkOpeness() { if (ownerPool == null) throw new ODatabaseException( "Database instance has been released to the pool. Get another database instance from the pool with the right username and password"); super.checkOpeness(); } public boolean isUnderlyingOpen() { return !super.isClosed(); } }
1no label
object_src_main_java_com_orientechnologies_orient_object_db_OObjectDatabaseTxPooled.java
1,219
public class AllTest { private static final int ONE_SECOND = 1000; private static final int STATS_SECONDS = 10; private static final int SIZE = 10000; final Logger logger = Logger.getLogger("All-test"); final HazelcastInstance hazelcast; private volatile boolean running = true; private final int nThreads; private final List<Runnable> operations = new ArrayList<Runnable>(); private final ExecutorService ex; private final Random random = new Random(); private final AtomicInteger messagesReceived = new AtomicInteger(0); private final AtomicInteger messagesSend = new AtomicInteger(0); AllTest(int nThreads) { this.nThreads = nThreads; ex = Executors.newFixedThreadPool(nThreads); hazelcast = Hazelcast.newHazelcastInstance(null); List<Runnable> mapOperations = loadMapOperations(); List<Runnable> qOperations = loadQOperations(); List<Runnable> topicOperations = loadTopicOperations(); this.operations.addAll(mapOperations); this.operations.addAll(qOperations); this.operations.addAll(topicOperations); Collections.shuffle(operations); } /** * Starts the test * @param args the number of threads to start */ public static void main(String[] args) { int nThreads = (args.length == 0) ? 10 : Integer.parseInt(args[0]); final AllTest allTest = new AllTest(nThreads); allTest.start(); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { while (true) { try { //noinspection BusyWait Thread.sleep(STATS_SECONDS * ONE_SECOND); System.out.println("cluster SIZE:" + allTest.hazelcast.getCluster().getMembers().size()); allTest.mapStats(); allTest.qStats(); allTest.topicStats(); } catch (InterruptedException ignored) { return; } } } }); } private void qStats() { // LocalQueueOperationStats qOpStats = hazelcast.getQueue("myQ").getLocalQueueStats().getOperationStats(); // long period = ((qOpStats.getPeriodEnd() - qOpStats.getPeriodStart()) / 1000); // if (period == 0) { // return; // } // log(qOpStats); // log("Q Operations per Second : " + (qOpStats.getOfferOperationCount() + qOpStats.getEmptyPollOperationCount() + // qOpStats.getEmptyPollOperationCount() + qOpStats.getRejectedOfferOperationCount()) / period); } private void log(Object message) { if (message != null) { logger.info(message.toString()); } } private void mapStats() { // LocalMapOperationStats mapOpStats = hazelcast.getMap("myMap").getLocalMapStats().getOperationStats(); // long period = ((mapOpStats.getPeriodEnd() - mapOpStats.getPeriodStart()) / 1000); // if (period == 0) { // return; // } // log(mapOpStats); // log("Map Operations per Second : " + mapOpStats.total() / period); } private void topicStats() { log("Topic Messages Sent : " + messagesSend.getAndSet(0) / STATS_SECONDS + "::: Messages Received: " + messagesReceived .getAndSet(0) / STATS_SECONDS); } private void addOperation(List<Runnable> operations, Runnable runnable, int priority) { for (int i = 0; i < priority; i++) { operations.add(runnable); } } private void start() { for (int i = 0; i < nThreads; i++) { ex.submit(new Runnable() { public void run() { while (running) { int opId = random.nextInt(operations.size()); Runnable operation = operations.get(opId); operation.run(); // System.out.println("Runnning..." + Thread.currentThread()); } } }); } } private void stop() { running = false; } /** * An example customer class */ public static class Customer implements Serializable { private int year; private String name; private byte[] field = new byte[100]; public Customer(int i, String s) { this.year = i; this.name = s; } } private List<Runnable> loadTopicOperations() { ITopic topic = hazelcast.getTopic("myTopic"); topic.addMessageListener(new MessageListener() { public void onMessage(Message message) { messagesReceived.incrementAndGet(); } }); List<Runnable> operations = new ArrayList<Runnable>(); addOperation(operations, new Runnable() { public void run() { ITopic topic = hazelcast.getTopic("myTopic"); topic.publish(String.valueOf(random.nextInt(100000000))); messagesSend.incrementAndGet(); } }, 10); return operations; } private List<Runnable> loadQOperations() { List<Runnable> operations = new ArrayList<Runnable>(); addOperation(operations, new Runnable() { public void run() { IQueue q = hazelcast.getQueue("myQ"); q.offer(new byte[100]); } }, 10); addOperation(operations, new Runnable() { public void run() { IQueue q = hazelcast.getQueue("myQ"); try { q.offer(new byte[100], 10, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } } }, 10); addOperation(operations, new Runnable() { public void run() { IQueue q = hazelcast.getQueue("myQ"); q.contains(new byte[100]); } }, 1); addOperation(operations, new Runnable() { public void run() { IQueue q = hazelcast.getQueue("myQ"); q.isEmpty(); } }, 1); addOperation(operations, new Runnable() { public void run() { IQueue q = hazelcast.getQueue("myQ"); q.size(); } }, 1); addOperation(operations, new Runnable() { public void run() { IQueue q = hazelcast.getQueue("myQ"); q.remove(new byte[100]); } }, 1); addOperation(operations, new Runnable() { public void run() { IQueue q = hazelcast.getQueue("myQ"); q.remainingCapacity(); } }, 1); addOperation(operations, new Runnable() { public void run() { IQueue q = hazelcast.getQueue("myQ"); q.poll(); } }, 10); addOperation(operations, new Runnable() { public void run() { IQueue q = hazelcast.getQueue("myQ"); q.add(new byte[100]); } }, 10); addOperation(operations, new Runnable() { public void run() { IQueue q = hazelcast.getQueue("myQ"); try { q.take(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }, 10); addOperation(operations, new Runnable() { public void run() { IQueue q = hazelcast.getQueue("myQ"); List list = new ArrayList(); for (int i = 0; i < 10; i++) { list.add(new byte[100]); } q.addAll(list); } }, 1); addOperation(operations, new Runnable() { public void run() { IQueue q = hazelcast.getQueue("myQ"); List list = new ArrayList(); q.drainTo(list); } }, 1); return operations; } private List<Runnable> loadMapOperations() { ArrayList<Runnable> operations = new ArrayList<Runnable>(); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.evict(random.nextInt(SIZE)); } }, 5); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); try { map.getAsync(random.nextInt(SIZE)).get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } }, 1); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.containsKey(random.nextInt(SIZE)); } }, 2); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.containsValue(new Customer(random.nextInt(100), String.valueOf(random.nextInt(100000)))); } }, 2); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); int key = random.nextInt(SIZE); map.lock(key); try { Thread.sleep(1); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { map.unlock(key); } } }, 1); // addOperation(operations, new Runnable() { // public void run() { // IMap map = hazelcast.getMap("myMap"); // int key = random.nextInt(SIZE); // map.lockMap(10, TimeUnit.MILLISECONDS); // try { // Thread.sleep(1); // } catch (InterruptedException e) { // } finally { // map.unlockMap(); // } // } // }, 1); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); int key = random.nextInt(SIZE); boolean locked = map.tryLock(key); if (locked) { try { Thread.sleep(1); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { map.unlock(key); } } } }, 1); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); int key = random.nextInt(SIZE); boolean locked = false; try { locked = map.tryLock(key, 10, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } if (locked) { try { Thread.sleep(1); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { map.unlock(key); } } } }, 1); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); Iterator it = map.entrySet().iterator(); for (int i = 0; i < 10 && it.hasNext(); i++) { it.next(); } } }, 1); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.getEntryView(random.nextInt(SIZE)); } }, 2); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.isEmpty(); } }, 3); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.put(random.nextInt(SIZE), new Customer(random.nextInt(100), String.valueOf(random.nextInt(10000)))); } }, 50); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.tryPut(random.nextInt(SIZE), new Customer(random.nextInt(100), String.valueOf(random.nextInt(10000))), 10, TimeUnit.MILLISECONDS); } }, 5); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); try { map.putAsync(random.nextInt(SIZE), new Customer(random.nextInt(100), String.valueOf(random.nextInt(10000))) ).get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } }, 5); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.put(random.nextInt(SIZE), new Customer(random.nextInt(100), String.valueOf(random.nextInt(10000))), 10, TimeUnit.MILLISECONDS); } }, 5); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.putIfAbsent(random.nextInt(SIZE), new Customer(random.nextInt(100), String.valueOf(random.nextInt(10000))), 10, TimeUnit.MILLISECONDS); } }, 5); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.putIfAbsent(random.nextInt(SIZE), new Customer(random.nextInt(100), String.valueOf(random.nextInt(10000)))); } }, 5); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); Map localMap = new HashMap(); for (int i = 0; i < 10; i++) { localMap.put(random.nextInt(SIZE), new Customer(random.nextInt(100), String.valueOf(random.nextInt(10000)))); } map.putAll(localMap); } }, 1); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.get(random.nextInt(SIZE)); } }, 100); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.remove(random.nextInt(SIZE)); } }, 10); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.tryRemove(random.nextInt(SIZE), 10, TimeUnit.MILLISECONDS); } }, 10); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.removeAsync(random.nextInt(SIZE)); } }, 10); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.remove(random.nextInt(SIZE), new Customer(random.nextInt(100), String.valueOf(random.nextInt(10000)))); } }, 10); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.replace(random.nextInt(SIZE), new Customer(random.nextInt(100), String.valueOf(random.nextInt(10000)))); } }, 4); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.replace(random.nextInt(SIZE), new Customer(random.nextInt(100), String.valueOf(random.nextInt(10000))), new Customer(random.nextInt(100), String.valueOf(random.nextInt(10000)))); } }, 5); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.size(); } }, 4); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); Iterator it = map.entrySet(new SqlPredicate("year=" + random.nextInt(100))).iterator(); while (it.hasNext()) { it.next(); } } }, 1); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); Iterator it = map.entrySet(new SqlPredicate("name=" + random.nextInt(10000))).iterator(); while (it.hasNext()) { it.next(); } } }, 10); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); Iterator it = map.keySet(new SqlPredicate("name=" + random.nextInt(10000))).iterator(); while (it.hasNext()) { it.next(); } } }, 10); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); Iterator it = map.localKeySet().iterator(); while (it.hasNext()) { it.next(); } } }, 10); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); Iterator it = map.localKeySet(new SqlPredicate("name=" + random.nextInt(10000))).iterator(); while (it.hasNext()) { it.next(); } } }, 10); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); final CountDownLatch latch = new CountDownLatch(1); EntryListener listener = new EntryAdapter() { @Override public void onEntryEvent(EntryEvent event) { latch.countDown(); } }; String id = map.addEntryListener(listener, true); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } map.removeEntryListener(id); } }, 1); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.addIndex("year", true); } }, 1); addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); final CountDownLatch latch = new CountDownLatch(1); EntryListener listener = new EntryAdapter() { @Override public void onEntryEvent(EntryEvent event) { latch.countDown(); } }; String id = map.addLocalEntryListener(listener); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } map.removeEntryListener(id); } }, 1); return operations; } }
0true
hazelcast_src_main_java_com_hazelcast_examples_AllTest.java
409
}, new TxJob() { @Override public void run(IndexTransaction tx) { tx.add(defStore, defDoc, TEXT, "the slow brown fox jumps over the lazy dog", false); } });
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexProviderTest.java
1,200
objectFloatMap = build(type, limit, smartSize, availableProcessors, new Recycler.C<ObjectFloatOpenHashMap>() { @Override public ObjectFloatOpenHashMap newInstance(int sizing) { return new ObjectFloatOpenHashMap(size(sizing)); } @Override public void clear(ObjectFloatOpenHashMap value) { value.clear(); } });
0true
src_main_java_org_elasticsearch_cache_recycler_CacheRecycler.java
419
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface AdminPresentationMapKey { /** * <p>A simple name for this key</p> * * @return the simple name */ String keyName(); /** * <p>The friendly name to present to a user for this value field title in a GUI. If supporting i18N, * the friendly name may be a key to retrieve a localized friendly name using</p> * the GWT support for i18N. * * @return The friendly name */ String friendlyKeyName(); }
0true
common_src_main_java_org_broadleafcommerce_common_presentation_AdminPresentationMapKey.java
1,384
@SuppressWarnings("unchecked") public class ODocumentWrapper implements Serializable { @ODocumentInstance protected ODocument document; public ODocumentWrapper() { } public ODocumentWrapper(final ORID iRID) { this(new ODocument(iRID)); } public ODocumentWrapper(final String iClassName) { this(new ODocument(iClassName)); } public ODocumentWrapper(final ODocument iDocument) { document = iDocument; } @OAfterDeserialization public void fromStream(final ODocument iDocument) { document = iDocument; } public ODocument toStream() { return document; } public <RET extends ODocumentWrapper> RET load() { document = (ODocument) document.load(); return (RET) this; } public <RET extends ODocumentWrapper> RET load(final String iFetchPlan) { document = document.load(iFetchPlan); return (RET) this; } public <RET extends ODocumentWrapper> RET load(final String iFetchPlan, final boolean iIgnoreCache) { document = document.load(iFetchPlan, iIgnoreCache); return (RET) this; } public <RET extends ODocumentWrapper> RET load(final String iFetchPlan, final boolean iIgnoreCache, final boolean loadTombstone) { document = document.load(iFetchPlan, iIgnoreCache, loadTombstone); return (RET) this; } public <RET extends ODocumentWrapper> RET reload() { document.reload(); return (RET) this; } public <RET extends ODocumentWrapper> RET reload(final String iFetchPlan) { document.reload(iFetchPlan, true); return (RET) this; } public <RET extends ODocumentWrapper> RET reload(final String iFetchPlan, final boolean iIgnoreCache) { document.reload(iFetchPlan, iIgnoreCache); return (RET) this; } public <RET extends ODocumentWrapper> RET save() { document.save(); return (RET) this; } public <RET extends ODocumentWrapper> RET save(final String iClusterName) { document.save(iClusterName); return (RET) this; } public ODocument getDocument() { return document; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((document == null) ? 0 : document.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; final ODocumentWrapper other = (ODocumentWrapper) obj; if (document == null) { if (other.document != null) return false; } else if (!document.equals(other.document)) return false; return true; } @Override public String toString() { return document != null ? document.toString() : "?"; } }
0true
core_src_main_java_com_orientechnologies_orient_core_type_ODocumentWrapper.java
340
public class PackageExplorerPart extends ViewPart implements ISetSelectionTarget, IMenuListener, IShowInTarget, IRefreshable, IPackagesViewPart, IPropertyChangeListener, IViewPartInputProvider { private static final String PERF_CREATE_PART_CONTROL= "org.eclipse.jdt.ui/perf/explorer/createPartControl"; //$NON-NLS-1$ private static final String PERF_MAKE_ACTIONS= "org.eclipse.jdt.ui/perf/explorer/makeActions"; //$NON-NLS-1$ private static final int HIERARCHICAL_LAYOUT= 0x1; private static final int FLAT_LAYOUT= 0x2; public static final int PROJECTS_AS_ROOTS= 1; public static final int WORKING_SETS_AS_ROOTS= 2; public final static String VIEW_ID= PLUGIN_ID + ".view.PackageExplorer"; // Persistence tags. private static final String TAG_LAYOUT= "layout"; //$NON-NLS-1$ private static final String TAG_GROUP_LIBRARIES= "group_libraries"; //$NON-NLS-1$ private static final String TAG_ROOT_MODE= "rootMode"; //$NON-NLS-1$ private static final String TAG_LINK_EDITOR= "linkWithEditor"; //$NON-NLS-1$ private static final String TAG_MEMENTO= "memento"; //$NON-NLS-1$ private boolean fIsCurrentLayoutFlat; // true means flat, false means hierarchical private boolean fShowLibrariesNode; private boolean fLinkingEnabled; private int fRootMode; private WorkingSetModel fWorkingSetModel; private PackageExplorerLabelProvider fLabelProvider; private DecoratingJavaLabelProvider fDecoratingLabelProvider; private PackageExplorerContentProvider fContentProvider; private FilterUpdater fFilterUpdater; private PackageExplorerActionGroup fActionSet; private ProblemTreeViewer fViewer; private Menu fContextMenu; private IMemento fMemento; /** * Helper to open and activate editors. * @since 3.5 */ private OpenAndLinkWithEditorHelper fOpenAndLinkWithEditorHelper; private String fWorkingSetLabel; private final IDialogSettings fDialogSettings; private final IPartListener2 fLinkWithEditorListener= new IPartListener2() { public void partVisible(IWorkbenchPartReference partRef) {} public void partBroughtToTop(IWorkbenchPartReference partRef) {} public void partClosed(IWorkbenchPartReference partRef) {} public void partDeactivated(IWorkbenchPartReference partRef) {} public void partHidden(IWorkbenchPartReference partRef) {} public void partOpened(IWorkbenchPartReference partRef) {} public void partInputChanged(IWorkbenchPartReference partRef) { IWorkbenchPage activePage= JavaPlugin.getActivePage(); if (partRef instanceof IEditorReference && activePage != null && activePage.getActivePartReference() == partRef) { editorActivated(((IEditorReference) partRef).getEditor(true)); } } public void partActivated(IWorkbenchPartReference partRef) { if (partRef instanceof IEditorReference) { editorActivated(((IEditorReference) partRef).getEditor(true)); } } }; private final ITreeViewerListener fExpansionListener= new ITreeViewerListener() { public void treeCollapsed(TreeExpansionEvent event) { } public void treeExpanded(TreeExpansionEvent event) { Object element= event.getElement(); if (element instanceof ICompilationUnit || element instanceof IClassFile) expandMainType(element); } }; private class PackageExplorerProblemTreeViewer extends ProblemTreeViewer { // fix for 64372 Projects showing up in Package Explorer twice [package explorer] private final List<Object> fPendingRefreshes; public PackageExplorerProblemTreeViewer(Composite parent, int style) { super(parent, style); fPendingRefreshes= Collections.synchronizedList(new ArrayList<Object>()); } @Override public void add(Object parentElement, Object[] childElements) { if (fPendingRefreshes.contains(parentElement)) { return; } super.add(parentElement, childElements); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.AbstractTreeViewer#internalRefresh(java.lang.Object, boolean) */ @Override protected void internalRefresh(Object element, boolean updateLabels) { try { fPendingRefreshes.add(element); super.internalRefresh(element, updateLabels); } finally { fPendingRefreshes.remove(element); } } @Override protected boolean evaluateExpandableWithFilters(Object parent) { if (parent instanceof IJavaProject || parent instanceof ICompilationUnit || parent instanceof IClassFile || parent instanceof ClassPathContainer) { return false; } if (parent instanceof IPackageFragmentRoot && ((IPackageFragmentRoot) parent).isArchive()) { return false; } return true; } @Override protected boolean isFiltered(Object object, Object parent, ViewerFilter[] filters) { boolean res= super.isFiltered(object, parent, filters); if (res && isEssential(object)) { return false; } return res; } /* Checks if a filtered object in essential (i.e. is a parent that * should not be removed). */ private boolean isEssential(Object object) { try { if (!isFlatLayout() && object instanceof IPackageFragment) { IPackageFragment fragment = (IPackageFragment) object; if (!fragment.isDefaultPackage() && fragment.hasSubpackages()) { return hasFilteredChildren(fragment); } } } catch (JavaModelException e) { JavaPlugin.log(e); } return false; } @Override protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) { IStructuredSelection is= (IStructuredSelection)invalidSelection; @SuppressWarnings("unchecked") List<Object> ns= newSelection instanceof IStructuredSelection ? new ArrayList<Object>(((IStructuredSelection)newSelection).toList()) : new ArrayList<Object>(); boolean changed= false; for (Iterator<?> iter= is.iterator(); iter.hasNext();) { Object element= iter.next(); if (element instanceof IJavaProject) { IProject project= ((IJavaProject)element).getProject(); if (!project.isOpen() && project.exists()) { ns.add(project); changed= true; } } else if (element instanceof IProject) { IProject project= (IProject)element; if (project.isOpen()) { IJavaProject jProject= JavaCore.create(project); if (jProject != null && jProject.exists()) ns.add(jProject); changed= true; } } } if (changed) { newSelection= new StructuredSelection(ns); setSelection(newSelection); } super.handleInvalidSelection(invalidSelection, newSelection); } /** * {@inheritDoc} */ @Override protected Object[] addAditionalProblemParents(Object[] elements) { if (getRootMode() == WORKING_SETS_AS_ROOTS && elements != null) { return fWorkingSetModel.addWorkingSets(elements); } return elements; } } public PackageExplorerPart() { // exception: initialize from preference fDialogSettings= JavaPlugin.getDefault().getDialogSettingsSection(getClass().getName()); // on by default fShowLibrariesNode= fDialogSettings.get(TAG_GROUP_LIBRARIES) == null || fDialogSettings.getBoolean(TAG_GROUP_LIBRARIES); fLinkingEnabled= fDialogSettings.getBoolean(TAG_LINK_EDITOR); try { fIsCurrentLayoutFlat= fDialogSettings.getInt(TAG_LAYOUT) == FLAT_LAYOUT; } catch (NumberFormatException e) { fIsCurrentLayoutFlat= true; } try { fRootMode= fDialogSettings.getInt(TAG_ROOT_MODE); } catch (NumberFormatException e) { fRootMode= PROJECTS_AS_ROOTS; } } @Override public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); if (memento == null) { String persistedMemento= fDialogSettings.get(TAG_MEMENTO); if (persistedMemento != null) { try { memento= XMLMemento.createReadRoot(new StringReader(persistedMemento)); } catch (WorkbenchException e) { // don't do anything. Simply don't restore the settings } } } fMemento= memento; if (memento != null) { restoreLayoutState(memento); restoreLinkingEnabled(memento); restoreRootMode(memento); } if (getRootMode() == WORKING_SETS_AS_ROOTS) { createWorkingSetModel(); } } private void restoreRootMode(IMemento memento) { Integer value= memento.getInteger(TAG_ROOT_MODE); fRootMode= value == null ? PROJECTS_AS_ROOTS : value.intValue(); if (fRootMode != PROJECTS_AS_ROOTS && fRootMode != WORKING_SETS_AS_ROOTS) fRootMode= PROJECTS_AS_ROOTS; } private void restoreLayoutState(IMemento memento) { Integer layoutState= memento.getInteger(TAG_LAYOUT); fIsCurrentLayoutFlat= layoutState == null || layoutState.intValue() == FLAT_LAYOUT; // on by default Integer groupLibraries= memento.getInteger(TAG_GROUP_LIBRARIES); fShowLibrariesNode= groupLibraries == null || groupLibraries.intValue() != 0; } /** * Returns the package explorer part of the active perspective. If * there isn't any package explorer part <code>null</code> is returned. * @return the package explorer from the active perspective */ public static PackageExplorerPart getFromActivePerspective() { IWorkbenchPage activePage= JavaPlugin.getActivePage(); if (activePage == null) return null; IViewPart view= activePage.findView(VIEW_ID); if (view instanceof PackageExplorerPart) return (PackageExplorerPart)view; return null; } /** * Makes the package explorer part visible in the active perspective. If there * isn't a package explorer part registered <code>null</code> is returned. * Otherwise the opened view part is returned. * @return the opened package explorer */ public static PackageExplorerPart openInActivePerspective() { try { return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID); } catch(PartInitException pe) { return null; } } @Override public void dispose() { XMLMemento memento= XMLMemento.createWriteRoot("packageExplorer"); //$NON-NLS-1$ saveState(memento); StringWriter writer= new StringWriter(); try { memento.save(writer); fDialogSettings.put(TAG_MEMENTO, writer.getBuffer().toString()); } catch (IOException e) { // don't do anything. Simply don't store the settings } if (fContextMenu != null && !fContextMenu.isDisposed()) fContextMenu.dispose(); getSite().getPage().removePartListener(fLinkWithEditorListener); // always remove even if we didn't register JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this); if (fViewer != null) fViewer.removeTreeListener(fExpansionListener); if (fActionSet != null) fActionSet.dispose(); if (fFilterUpdater != null) ResourcesPlugin.getWorkspace().removeResourceChangeListener(fFilterUpdater); if (fWorkingSetModel != null) fWorkingSetModel.dispose(); super.dispose(); } /* (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ @Override public void createPartControl(Composite parent) { final PerformanceStats stats= PerformanceStats.getStats(PERF_CREATE_PART_CONTROL, this); stats.startRun(); fViewer= createViewer(parent); fViewer.setUseHashlookup(true); initDragAndDrop(); setProviders(); JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this); MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(this); fContextMenu= menuMgr.createContextMenu(fViewer.getTree()); fViewer.getTree().setMenu(fContextMenu); // Register viewer with site. This must be done before making the actions. IWorkbenchPartSite site= getSite(); site.registerContextMenu(menuMgr, fViewer); site.setSelectionProvider(fViewer); makeActions(); // call before registering for selection changes // Set input after filter and sorter has been set. This avoids resorting and refiltering. restoreFilterAndSorter(); fViewer.setInput(findInputElement()); initFrameActions(); initKeyListener(); fViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { fActionSet.handleDoubleClick(event); } }); fOpenAndLinkWithEditorHelper= new OpenAndLinkWithEditorHelper(fViewer) { @Override protected void activate(ISelection selection) { try { final Object selectedElement= SelectionUtil.getSingleElement(selection); if (EditorUtility.isOpenInEditor(selectedElement) != null) EditorUtility.openInEditor(selectedElement, true); } catch (PartInitException ex) { // ignore if no editor input can be found } } @Override protected void linkToEditor(ISelection selection) { PackageExplorerPart.this.linkToEditor(selection); } @Override protected void open(ISelection selection, boolean activate) { fActionSet.handleOpen(selection, activate); } }; IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager)); fViewer.addTreeListener(fExpansionListener); // Set help for the view JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW); fillActionBars(); updateTitle(); fFilterUpdater= new FilterUpdater(fViewer); ResourcesPlugin.getWorkspace().addResourceChangeListener(fFilterUpdater); // Sync'ing the package explorer has to be done here. It can't be done // when restoring the link state since the package explorers input isn't // set yet. setLinkingEnabled(isLinkingEnabled()); stats.endRun(); } private void initFrameActions() { fActionSet.getUpAction().update(); fActionSet.getBackAction().update(); fActionSet.getForwardAction().update(); } private ProblemTreeViewer createViewer(Composite composite) { return new PackageExplorerProblemTreeViewer(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); } /** * Answers whether this part shows the packages flat or hierarchical. * @return <true> if flat layout is selected * * @since 2.1 */ public boolean isFlatLayout() { return fIsCurrentLayoutFlat; } private void setProviders() { //content provider must be set before the label provider fContentProvider= createContentProvider(); fContentProvider.setIsFlatLayout(fIsCurrentLayoutFlat); fContentProvider.setShowLibrariesNode(fShowLibrariesNode); fViewer.setContentProvider(fContentProvider); fViewer.setComparer(createElementComparer()); fLabelProvider= createLabelProvider(); fLabelProvider.setIsFlatLayout(fIsCurrentLayoutFlat); fDecoratingLabelProvider= new DecoratingJavaLabelProvider(fLabelProvider, false, fIsCurrentLayoutFlat); fViewer.setLabelProvider(fDecoratingLabelProvider); // problem decoration provided by PackageLabelProvider } public void setShowLibrariesNode(boolean enabled) { fShowLibrariesNode= enabled; saveDialogSettings(); fContentProvider.setShowLibrariesNode(enabled); fViewer.getControl().setRedraw(false); fViewer.refresh(); fViewer.getControl().setRedraw(true); } boolean isLibrariesNodeShown() { return fShowLibrariesNode; } public void setFlatLayout(boolean enable) { // Update current state and inform content and label providers fIsCurrentLayoutFlat= enable; saveDialogSettings(); if (fViewer != null) { fContentProvider.setIsFlatLayout(isFlatLayout()); fLabelProvider.setIsFlatLayout(isFlatLayout()); fDecoratingLabelProvider.setFlatPackageMode(isFlatLayout()); fViewer.getControl().setRedraw(false); fViewer.refresh(); fViewer.getControl().setRedraw(true); } } /** * This method should only be called inside this class * and from test cases. * @return the created content provider */ public PackageExplorerContentProvider createContentProvider() { IPreferenceStore store= PreferenceConstants.getPreferenceStore(); boolean showCUChildren= store.getBoolean(PreferenceConstants.SHOW_CU_CHILDREN); if (getRootMode() == PROJECTS_AS_ROOTS) return new PackageExplorerContentProvider(showCUChildren); else return new WorkingSetAwareContentProvider(showCUChildren, fWorkingSetModel); } private PackageExplorerLabelProvider createLabelProvider() { return new PackageExplorerLabelProvider(fContentProvider); } private IElementComparer createElementComparer() { if (getRootMode() == PROJECTS_AS_ROOTS) return null; else return WorkingSetModel.COMPARER; } private void fillActionBars() { IActionBars actionBars= getViewSite().getActionBars(); fActionSet.fillActionBars(actionBars); } private Object findInputElement() { if (getRootMode() == WORKING_SETS_AS_ROOTS) { return fWorkingSetModel; } else { Object input= getSite().getPage().getInput(); if (input instanceof IWorkspace) { return JavaCore.create(((IWorkspace)input).getRoot()); } else if (input instanceof IContainer) { IJavaElement element= JavaCore.create((IContainer)input); if (element != null && element.exists()) return element; return input; } //1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective // we can't handle the input // fall back to show the workspace return JavaCore.create(JavaPlugin.getWorkspace().getRoot()); } } /* (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#getAdapter(java.lang.Class) */ @Override public Object getAdapter(@SuppressWarnings("rawtypes") Class key) { if (key.equals(ISelectionProvider.class)) return fViewer; if (key == IShowInSource.class) { return getShowInSource(); } if (key == IShowInTargetList.class) { return new IShowInTargetList() { public String[] getShowInTargetIds() { return new String[] { JavaPlugin.ID_RES_NAV }; } }; } if (key == IContextProvider.class) { return JavaUIHelp.getHelpContextProvider(this, IJavaHelpContextIds.PACKAGES_VIEW); } return super.getAdapter(key); } /** * Returns the tool tip text for the given element. * @param element the element * @return the tooltip */ String getToolTipText(Object element) { String result; if (!(element instanceof IResource)) { if (element instanceof IJavaModel) { result= PackagesMessages.PackageExplorerPart_workspace; } else if (element instanceof IJavaElement){ result= JavaElementLabels.getTextLabel(element, JavaElementLabels.ALL_FULLY_QUALIFIED); } else if (element instanceof IWorkingSet) { result= ((IWorkingSet)element).getLabel(); } else if (element instanceof WorkingSetModel) { result= PackagesMessages.PackageExplorerPart_workingSetModel; } else { result= fLabelProvider.getText(element); } } else { IPath path= ((IResource) element).getFullPath(); if (path.isRoot()) { result= PackagesMessages.PackageExplorer_title; } else { result= BasicElementLabels.getPathLabel(path, false); } } if (fRootMode == PROJECTS_AS_ROOTS) { if (fWorkingSetLabel == null) return result; if (result.length() == 0) return Messages.format(PackagesMessages.PackageExplorer_toolTip, new String[] { fWorkingSetLabel }); return Messages.format(PackagesMessages.PackageExplorer_toolTip2, new String[] { result, fWorkingSetLabel }); } else { // Working set mode. During initialization element and action set can be null. if (element != null && !(element instanceof IWorkingSet) && !(element instanceof WorkingSetModel) && fActionSet != null) { FrameList frameList= fActionSet.getFrameList(); int index= frameList.getCurrentIndex(); IWorkingSet ws= null; while(index >= 0) { Frame frame= frameList.getFrame(index); if (frame instanceof TreeFrame) { Object input= ((TreeFrame)frame).getInput(); if (input instanceof IWorkingSet) { ws= (IWorkingSet) input; break; } } index--; } if (ws != null) { return Messages.format(PackagesMessages.PackageExplorer_toolTip3, new String[] { BasicElementLabels.getWorkingSetLabel(ws) , result}); } else { return result; } } else { return result; } } } @Override public String getTitleToolTip() { if (fViewer == null) return super.getTitleToolTip(); return getToolTipText(fViewer.getInput()); } /* (non-Javadoc) * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ @Override public void setFocus() { fViewer.getTree().setFocus(); } private ISelection getSelection() { return fViewer.getSelection(); } //---- Action handling ---------------------------------------------------------- /* (non-Javadoc) * @see IMenuListener#menuAboutToShow(IMenuManager) */ public void menuAboutToShow(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); fActionSet.setContext(new ActionContext(getSelection())); fActionSet.fillContextMenu(menu); fActionSet.setContext(null); } private void makeActions() { final PerformanceStats stats= PerformanceStats.getStats(PERF_MAKE_ACTIONS, this); stats.startRun(); fActionSet= new PackageExplorerActionGroup(this); if (fWorkingSetModel != null) fActionSet.getWorkingSetActionGroup().setWorkingSetModel(fWorkingSetModel); stats.endRun(); } // ---- Event handling ---------------------------------------------------------- private void initDragAndDrop() { initDrag(); initDrop(); } private void initDrag() { new JdtViewerDragSupport(fViewer).start(); } private void initDrop() { JdtViewerDropSupport dropSupport= new JdtViewerDropSupport(fViewer); dropSupport.addDropTargetListener(new WorkingSetDropAdapter(this)); dropSupport.start(); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.viewsupport.IRefreshable#refresh(org.eclipse.jface.viewers.IStructuredSelection) */ public void refresh(IStructuredSelection selection) { Object[] selectedElements= selection.toArray(); for (int i= 0; i < selectedElements.length; i++) { fViewer.refresh(selectedElements[i]); } } /* (non-Javadoc) * @see org.eclipse.ui.part.ISetSelectionTarget#selectReveal(org.eclipse.jface.viewers.ISelection) */ public void selectReveal(final ISelection selection) { Control ctrl= getTreeViewer().getControl(); if (ctrl == null || ctrl.isDisposed()) return; fContentProvider.runPendingUpdates(); fViewer.setSelection(convertSelection(selection), true); } public ISelection convertSelection(ISelection s) { if (!(s instanceof IStructuredSelection)) return s; Object[] elements= ((IStructuredSelection)s).toArray(); boolean changed= false; for (int i= 0; i < elements.length; i++) { Object convertedElement= convertElement(elements[i]); changed= changed || convertedElement != elements[i]; elements[i]= convertedElement; } if (changed) return new StructuredSelection(elements); else return s; } private Object convertElement(Object original) { if (original instanceof IJavaElement) { if (original instanceof ICompilationUnit) { ICompilationUnit cu= (ICompilationUnit) original; IJavaProject javaProject= cu.getJavaProject(); if (javaProject != null && javaProject.exists() && ! javaProject.isOnClasspath(cu)) { // could be a working copy of a .java file that is not on classpath IResource resource= cu.getResource(); if (resource != null) return resource; } } return original; } else if (original instanceof IResource) { IJavaElement je= JavaCore.create((IResource)original); if (je != null && je.exists()) { IJavaProject javaProject= je.getJavaProject(); if (javaProject != null && javaProject.exists()) { if (javaProject.equals(je) || javaProject.isOnClasspath(je)) { return je; } else { // a working copy of a .java file that is not on classpath return original; } } } } else if (original instanceof IAdaptable) { IAdaptable adaptable= (IAdaptable)original; IJavaElement je= (IJavaElement) adaptable.getAdapter(IJavaElement.class); if (je != null && je.exists()) return je; IResource r= (IResource) adaptable.getAdapter(IResource.class); if (r != null) { je= JavaCore.create(r); if (je != null && je.exists()) return je; else return r; } } return original; } public void selectAndReveal(Object element) { selectReveal(new StructuredSelection(element)); } public boolean isLinkingEnabled() { return fLinkingEnabled; } /** * Links to editor (if option enabled) * @param selection the selection */ private void linkToEditor(ISelection selection) { Object obj= SelectionUtil.getSingleElement(selection); if (obj != null) { IEditorPart part= EditorUtility.isOpenInEditor(obj); if (part != null) { IWorkbenchPage page= getSite().getPage(); page.bringToTop(part); if (obj instanceof IJavaElement) EditorUtility.revealInEditor(part, (IJavaElement)obj); } } } @Override public void saveState(IMemento memento) { if (fViewer == null && fMemento != null) { // part has not been created -> keep the old state memento.putMemento(fMemento); return; } memento.putInteger(TAG_ROOT_MODE, fRootMode); if (fWorkingSetModel != null) fWorkingSetModel.saveState(memento); saveLayoutState(memento); saveLinkingEnabled(memento); if (fActionSet != null) { fActionSet.saveFilterAndSorterState(memento); } } private void saveLinkingEnabled(IMemento memento) { memento.putInteger(TAG_LINK_EDITOR, fLinkingEnabled ? 1 : 0); } private void saveLayoutState(IMemento memento) { if (memento != null) { memento.putInteger(TAG_LAYOUT, getLayoutAsInt()); memento.putInteger(TAG_GROUP_LIBRARIES, fShowLibrariesNode ? 1 : 0); } } private void saveDialogSettings() { fDialogSettings.put(TAG_GROUP_LIBRARIES, fShowLibrariesNode); fDialogSettings.put(TAG_LAYOUT, getLayoutAsInt()); fDialogSettings.put(TAG_ROOT_MODE, fRootMode); fDialogSettings.put(TAG_LINK_EDITOR, fLinkingEnabled); } private int getLayoutAsInt() { if (fIsCurrentLayoutFlat) return FLAT_LAYOUT; else return HIERARCHICAL_LAYOUT; } private void restoreFilterAndSorter() { fViewer.addFilter(new OutputFolderFilter()); setComparator(); if (fMemento != null) fActionSet.restoreFilterAndSorterState(fMemento); } private void restoreLinkingEnabled(IMemento memento) { Integer val= memento.getInteger(TAG_LINK_EDITOR); fLinkingEnabled= val != null && val.intValue() != 0; } /** * Create the KeyListener for doing the refresh on the viewer. */ private void initKeyListener() { fViewer.getControl().addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent event) { fActionSet.handleKeyEvent(event); } }); } /** * An editor has been activated. Set the selection in this Packages Viewer * to be the editor's input, if linking is enabled. * @param editor the activated editor */ void editorActivated(IEditorPart editor) { IEditorInput editorInput= editor.getEditorInput(); if (editorInput == null) return; Object input= getInputFromEditor(editorInput); if (input == null) return; if (!inputIsSelected(editorInput)) showInput(input); else getTreeViewer().getTree().showSelection(); } private Object getInputFromEditor(IEditorInput editorInput) { Object input= JavaUI.getEditorInputJavaElement(editorInput); if (input instanceof ICompilationUnit) { ICompilationUnit cu= (ICompilationUnit) input; if (!cu.getJavaProject().isOnClasspath(cu)) { // test needed for Java files in non-source folders (bug 207839) input= cu.getResource(); } } if (input == null) { input= editorInput.getAdapter(IFile.class); } if (input == null && editorInput instanceof IStorageEditorInput) { try { input= ((IStorageEditorInput) editorInput).getStorage(); } catch (CoreException e) { // ignore } } return input; } private boolean inputIsSelected(IEditorInput input) { IStructuredSelection selection= (IStructuredSelection)fViewer.getSelection(); if (selection.size() != 1) return false; IEditorInput selectionAsInput= EditorUtility.getEditorInput(selection.getFirstElement()); return input.equals(selectionAsInput); } boolean showInput(Object input) { Object element= null; if (input instanceof IFile && isOnClassPath((IFile)input)) { element= JavaCore.create((IFile)input); } if (element == null) // try a non Java resource element= input; if (element != null) { ISelection newSelection= new StructuredSelection(element); if (fViewer.getSelection().equals(newSelection)) { fViewer.reveal(element); } else { fViewer.setSelection(newSelection, true); while (element != null && fViewer.getSelection().isEmpty()) { // Try to select parent in case element is filtered element= getParent(element); if (element != null) { newSelection= new StructuredSelection(element); fViewer.setSelection(newSelection, true); } } } return true; } return false; } private boolean isOnClassPath(IFile file) { IJavaProject jproject= JavaCore.create(file.getProject()); return jproject.isOnClasspath(file); } /** * Returns the element's parent. * @param element the element * * @return the parent or <code>null</code> if there's no parent */ private Object getParent(Object element) { if (element instanceof IJavaElement) return ((IJavaElement)element).getParent(); else if (element instanceof IResource) return ((IResource)element).getParent(); else if (element instanceof IJarEntryResource) { return ((IJarEntryResource)element).getParent(); } return null; } /** * A compilation unit or class was expanded, expand * the main type. * @param element the element */ void expandMainType(Object element) { try { IType type= null; if (element instanceof ICompilationUnit) { ICompilationUnit cu= (ICompilationUnit)element; IType[] types= cu.getTypes(); if (types.length > 0) type= types[0]; } else if (element instanceof IClassFile) { IClassFile cf= (IClassFile)element; type= cf.getType(); } if (type != null) { final IType type2= type; Control ctrl= fViewer.getControl(); if (ctrl != null && !ctrl.isDisposed()) { ctrl.getDisplay().asyncExec(new Runnable() { public void run() { Control ctrl2= fViewer.getControl(); if (ctrl2 != null && !ctrl2.isDisposed()) fViewer.expandToLevel(type2, 1); } }); } } } catch(JavaModelException e) { // no reveal } } /** * Returns the TreeViewer. * @return the tree viewer */ public TreeViewer getTreeViewer() { return fViewer; } boolean isExpandable(Object element) { if (fViewer == null) return false; return fViewer.isExpandable(element); } void setWorkingSetLabel(String workingSetName) { fWorkingSetLabel= workingSetName; setTitleToolTip(getTitleToolTip()); } void updateToolbar() { IActionBars actionBars= getViewSite().getActionBars(); fActionSet.updateToolBar(actionBars.getToolBarManager()); } /** * Updates the title text and title tool tip. * Called whenever the input of the viewer changes. */ void updateTitle() { Object input= fViewer.getInput(); if (input == null || (input instanceof IJavaModel)) { setContentDescription(""); //$NON-NLS-1$ setTitleToolTip(""); //$NON-NLS-1$ } else { String inputText= JavaElementLabels.getTextLabel(input, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS); setContentDescription(inputText); setTitleToolTip(getToolTipText(input)); } } /** * Sets the decorator for the package explorer. * * @param decorator a label decorator or <code>null</code> for no decorations. * @deprecated To be removed */ @Deprecated public void setLabelDecorator(ILabelDecorator decorator) { } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (fViewer == null) return; boolean refreshViewer= false; if (PreferenceConstants.SHOW_CU_CHILDREN.equals(event.getProperty())) { boolean showCUChildren= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN); ((StandardJavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren); refreshViewer= true; } else if (MembersOrderPreferenceCache.isMemberOrderProperty(event.getProperty())) { refreshViewer= true; } if (refreshViewer) fViewer.refresh(); } /* (non-Javadoc) * @see IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { if (fViewer != null) { return fViewer.getInput(); } return null; } public void collapseAll() { try { fViewer.getControl().setRedraw(false); fViewer.collapseToLevel(getViewPartInput(), AbstractTreeViewer.ALL_LEVELS); } finally { fViewer.getControl().setRedraw(true); } } /* (non-Javadoc) * @see org.eclipse.ui.part.IShowInTarget#show(org.eclipse.ui.part.ShowInContext) */ public boolean show(ShowInContext context) { ISelection selection= context.getSelection(); if (selection instanceof IStructuredSelection) { // fix for 64634 Navigate/Show in/Package Explorer doesn't work IStructuredSelection structuredSelection= ((IStructuredSelection) selection); if (structuredSelection.size() == 1) { int res= tryToReveal(structuredSelection.getFirstElement()); if (res == IStatus.OK) return true; if (res == IStatus.CANCEL) return false; } else if (structuredSelection.size() > 1) { selectReveal(structuredSelection); return true; } } Object input= context.getInput(); if (input instanceof IEditorInput) { Object elementOfInput= getInputFromEditor((IEditorInput) input); return elementOfInput != null && (tryToReveal(elementOfInput) == IStatus.OK); } return false; } /** * Returns the <code>IShowInSource</code> for this view. * @return the <code>IShowInSource</code> */ protected IShowInSource getShowInSource() { return new IShowInSource() { public ShowInContext getShowInContext() { return new ShowInContext( getTreeViewer().getInput(), getTreeViewer().getSelection()); } }; } /* (non-Javadoc) * @see org.eclipse.jdt.ui.IPackagesViewPart#setLinkingEnabled(boolean) */ public void setLinkingEnabled(boolean enabled) { fLinkingEnabled= enabled; saveDialogSettings(); IWorkbenchPage page= getSite().getPage(); if (enabled) { page.addPartListener(fLinkWithEditorListener); IEditorPart editor = page.getActiveEditor(); if (editor != null) editorActivated(editor); } else { page.removePartListener(fLinkWithEditorListener); } fOpenAndLinkWithEditorHelper.setLinkWithEditor(enabled); } /** * Returns the name for the given element. Used as the name for the current frame. * * @param element the element * @return the name of the frame */ String getFrameName(Object element) { if (element instanceof IJavaElement) { return ((IJavaElement) element).getElementName(); } else if (element instanceof WorkingSetModel) { return ""; //$NON-NLS-1$ } else { return fLabelProvider.getText(element); } } public int tryToReveal(Object element) { if (revealElementOrParent(element)) return IStatus.OK; WorkingSetFilterActionGroup workingSetGroup= fActionSet.getWorkingSetActionGroup().getFilterGroup(); if (workingSetGroup != null) { IWorkingSet workingSet= workingSetGroup.getWorkingSet(); if (workingSetGroup.isFiltered(getVisibleParent(element), element)) { String message; if (element instanceof IJavaElement) { String elementLabel= JavaElementLabels.getElementLabel((IJavaElement)element, JavaElementLabels.ALL_DEFAULT); message= Messages.format(PackagesMessages.PackageExplorerPart_notFoundSepcific, new String[] {elementLabel, BasicElementLabels.getWorkingSetLabel(workingSet)}); } else { message= Messages.format(PackagesMessages.PackageExplorer_notFound, BasicElementLabels.getWorkingSetLabel(workingSet)); } if (MessageDialog.openQuestion(getSite().getShell(), PackagesMessages.PackageExplorer_filteredDialog_title, message)) { workingSetGroup.setWorkingSet(null, true); if (revealElementOrParent(element)) return IStatus.OK; } else { return IStatus.CANCEL; } } } // try to remove filters CustomFiltersActionGroup filterGroup= fActionSet.getCustomFilterActionGroup(); String[] currentFilters= filterGroup.internalGetEnabledFilterIds(); String[] newFilters= filterGroup.removeFiltersFor(getVisibleParent(element), element, getTreeViewer().getContentProvider()); if (currentFilters.length > newFilters.length) { String message; if (element instanceof IJavaElement) { String elementLabel= JavaElementLabels.getElementLabel((IJavaElement)element, JavaElementLabels.ALL_DEFAULT); message= Messages.format(PackagesMessages.PackageExplorerPart_removeFiltersSpecific, elementLabel); } else { message= PackagesMessages.PackageExplorer_removeFilters; } if (MessageDialog.openQuestion(getSite().getShell(), PackagesMessages.PackageExplorer_filteredDialog_title, message)) { filterGroup.setFilters(newFilters); if (revealElementOrParent(element)) return IStatus.OK; } else { return IStatus.CANCEL; } } FrameAction action= fActionSet.getUpAction(); while (action.getFrameList().getCurrentIndex() > 0) { // only try to go up if there is a parent frame // fix for bug# 63769 Endless loop after Show in Package Explorer if (action.getFrameList().getSource().getFrame(IFrameSource.PARENT_FRAME, 0) == null) break; action.run(); if (revealElementOrParent(element)) return IStatus.OK; } return IStatus.ERROR; } private boolean revealElementOrParent(Object element) { if (revealAndVerify(element)) return true; element= getVisibleParent(element); if (element != null) { if (revealAndVerify(element)) return true; if (element instanceof IJavaElement) { IResource resource= ((IJavaElement)element).getResource(); if (resource != null) { if (revealAndVerify(resource)) return true; } } } return false; } private Object getVisibleParent(Object object) { // Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19104 if (object == null) return null; if (!(object instanceof IJavaElement)) return object; IJavaElement element2= (IJavaElement) object; switch (element2.getElementType()) { case IJavaElement.IMPORT_DECLARATION: case IJavaElement.PACKAGE_DECLARATION: case IJavaElement.IMPORT_CONTAINER: case IJavaElement.TYPE: case IJavaElement.METHOD: case IJavaElement.FIELD: case IJavaElement.INITIALIZER: // select parent cu/classfile element2= (IJavaElement)element2.getOpenable(); break; case IJavaElement.JAVA_MODEL: element2= null; break; } return element2; } private boolean revealAndVerify(Object element) { if (element == null) return false; selectReveal(new StructuredSelection(element)); return ! getSite().getSelectionProvider().getSelection().isEmpty(); } public void rootModeChanged(int newMode) { fRootMode= newMode; saveDialogSettings(); if (getRootMode() == WORKING_SETS_AS_ROOTS && fWorkingSetModel == null) { createWorkingSetModel(); if (fActionSet != null) { fActionSet.getWorkingSetActionGroup().setWorkingSetModel(fWorkingSetModel); } } IStructuredSelection selection= new StructuredSelection(((IStructuredSelection) fViewer.getSelection()).toArray()); Object input= fViewer.getInput(); boolean isRootInputChange= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).equals(input) || (fWorkingSetModel != null && fWorkingSetModel.equals(input)) || input instanceof IWorkingSet; try { fViewer.getControl().setRedraw(false); if (isRootInputChange) { fViewer.setInput(null); } setProviders(); setComparator(); fActionSet.getWorkingSetActionGroup().fillFilters(fViewer); if (isRootInputChange) { fViewer.setInput(findInputElement()); } fViewer.setSelection(selection, true); } finally { fViewer.getControl().setRedraw(true); } if (isRootInputChange && getRootMode() == WORKING_SETS_AS_ROOTS && fWorkingSetModel.needsConfiguration()) { ConfigureWorkingSetAction action= new ConfigureWorkingSetAction(getSite()); action.setWorkingSetModel(fWorkingSetModel); action.run(); fWorkingSetModel.configured(); } setTitleToolTip(getTitleToolTip()); } private void createWorkingSetModel() { SafeRunner.run(new ISafeRunnable() { public void run() throws Exception { fWorkingSetModel= new WorkingSetModel(fMemento); } public void handleException(Throwable exception) { fWorkingSetModel= new WorkingSetModel(null); } }); } /** * @return the selected working set to filter if in root mode {@link #PROJECTS_AS_ROOTS} */ public IWorkingSet getFilterWorkingSet() { if (getRootMode() != PROJECTS_AS_ROOTS) return null; if (fActionSet == null) return null; return fActionSet.getWorkingSetActionGroup().getFilterGroup().getWorkingSet(); } public WorkingSetModel getWorkingSetModel() { return fWorkingSetModel; } /** * Returns the root mode: Either {@link #PROJECTS_AS_ROOTS} or {@link #WORKING_SETS_AS_ROOTS}. * @return returns the root mode */ public int getRootMode() { return fRootMode; } private void setComparator() { if (getRootMode() == WORKING_SETS_AS_ROOTS) { fViewer.setComparator(new WorkingSetAwareJavaElementSorter()); } else { fViewer.setComparator(new JavaElementComparator()); } } public PackageExplorerActionGroup getPackageExplorerActionGroup() { return fActionSet; } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_explorer_PackageExplorerPart.java
1,143
public class RemoveOrderMultishipOptionActivity extends BaseActivity<CartOperationContext> { @Resource(name = "blOrderMultishipOptionService") protected OrderMultishipOptionService orderMultishipOptionService; @Resource(name = "blOrderItemService") protected OrderItemService orderItemService; @Override public CartOperationContext execute(CartOperationContext context) throws Exception { CartOperationRequest request = context.getSeedData(); Long orderItemId = request.getItemRequest().getOrderItemId(); OrderItem orderItem = orderItemService.readOrderItemById(orderItemId); if (orderItem instanceof BundleOrderItem) { for (OrderItem discrete : ((BundleOrderItem) orderItem).getDiscreteOrderItems()) { orderMultishipOptionService.deleteOrderItemOrderMultishipOptions(discrete.getId()); } } else { orderMultishipOptionService.deleteOrderItemOrderMultishipOptions(orderItemId); } return context; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_workflow_remove_RemoveOrderMultishipOptionActivity.java
1,408
public final class ODistributedVersion implements ORecordVersion { public static final int STREAMED_SIZE = OBinaryProtocol.SIZE_INT + OBinaryProtocol.SIZE_LONG + OBinaryProtocol.SIZE_LONG; public static final OBinaryConverter CONVERTER = OBinaryConverterFactory.getConverter(); private int counter; private long timestamp; private long macAddress; public ODistributedVersion() { } public ODistributedVersion(int counter) { this.counter = counter; this.timestamp = System.currentTimeMillis(); this.macAddress = OVersionFactory.instance().getMacAddress(); } public ODistributedVersion(int counter, long timestamp, long macAddress) { this.counter = counter; this.timestamp = timestamp; this.macAddress = macAddress; } @Override public void increment() { if (isTombstone()) throw new IllegalStateException("Record was deleted and can not be updated."); counter++; timestamp = System.currentTimeMillis(); macAddress = OVersionFactory.instance().getMacAddress(); } @Override public void decrement() { if (isTombstone()) throw new IllegalStateException("Record was deleted and can not be updated."); counter--; timestamp = System.currentTimeMillis(); macAddress = OVersionFactory.instance().getMacAddress(); } @Override public boolean isUntracked() { return counter == -1; } @Override public boolean isTemporary() { return counter < -1; } @Override public boolean isValid() { return counter > -1; } @Override public void setCounter(int iVersion) { counter = iVersion; } @Override public int getCounter() { return counter; } @Override public boolean isTombstone() { return counter < 0; } public void convertToTombstone() { if (isTombstone()) throw new IllegalStateException("Record was deleted and can not be updated."); counter++; counter = -counter; timestamp = System.currentTimeMillis(); macAddress = OVersionFactory.instance().getMacAddress(); } @Override public byte[] toStream() { final byte[] buffer = new byte[STREAMED_SIZE]; getSerializer().writeTo(buffer, 0, this); return buffer; } @Override public void fromStream(byte[] stream) { getSerializer().readFrom(stream, 0, this); } @Override public void copyFrom(ORecordVersion version) { ODistributedVersion other = (ODistributedVersion) version; update(other.counter, other.timestamp, other.macAddress); } public void update(int recordVersion, long timestamp, long macAddress) { this.counter = recordVersion; this.timestamp = timestamp; this.macAddress = macAddress; } @Override public void reset() { counter = 0; timestamp = System.currentTimeMillis(); macAddress = OVersionFactory.instance().getMacAddress(); } @Override public void setRollbackMode() { counter = Integer.MIN_VALUE + counter; } @Override public void clearRollbackMode() { counter = counter - Integer.MIN_VALUE; } @Override public void disable() { counter = -1; } @Override public void revive() { counter = -counter; } @Override public ORecordVersion copy() { ODistributedVersion copy = new ODistributedVersion(); copy.counter = counter; copy.timestamp = timestamp; copy.macAddress = macAddress; return copy; } @Override public ORecordVersionSerializer getSerializer() { return ODistributedVersionSerializer.INSTANCE; } @Override public boolean equals(Object other) { return other instanceof ODistributedVersion && ((ODistributedVersion) other).compareTo(this) == 0; } @Override public int hashCode() { int result = counter; result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); result = 31 * result + (int) (macAddress ^ (macAddress >>> 32)); return result; } @Override public String toString() { return ODistributedVersionSerializer.INSTANCE.toString(this); } @Override public int compareTo(ORecordVersion o) { ODistributedVersion other = (ODistributedVersion) o; final int myCounter; if (isTombstone()) myCounter = -counter; else myCounter = counter; final int otherCounter; if (o.isTombstone()) otherCounter = -o.getCounter(); else otherCounter = o.getCounter(); if (myCounter != otherCounter) return myCounter > otherCounter ? 1 : -1; if (timestamp != other.timestamp) return (timestamp > other.timestamp) ? 1 : -1; if (macAddress > other.macAddress) return 1; else if (macAddress < other.macAddress) return -1; else return 0; } public long getTimestamp() { return timestamp; } public long getMacAddress() { return macAddress; } @Override public void writeExternal(ObjectOutput out) throws IOException { ODistributedVersionSerializer.INSTANCE.writeTo(out, this); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { ODistributedVersionSerializer.INSTANCE.readFrom(in, this); } private static final class ODistributedVersionSerializer implements ORecordVersionSerializer { private static final ODistributedVersionSerializer INSTANCE = new ODistributedVersionSerializer(); @Override public void writeTo(DataOutput out, ORecordVersion version) throws IOException { final ODistributedVersion distributedVersion = (ODistributedVersion) version; out.writeInt(distributedVersion.counter); out.writeLong(distributedVersion.timestamp); out.writeLong(distributedVersion.macAddress); } @Override public void readFrom(DataInput in, ORecordVersion version) throws IOException { final ODistributedVersion distributedVersion = (ODistributedVersion) version; distributedVersion.counter = in.readInt(); distributedVersion.timestamp = in.readLong(); distributedVersion.macAddress = in.readLong(); } @Override public void writeTo(OutputStream stream, ORecordVersion version) throws IOException { final ODistributedVersion distributedVersion = (ODistributedVersion) version; OBinaryProtocol.int2bytes(distributedVersion.counter, stream); OBinaryProtocol.long2bytes(distributedVersion.timestamp, stream); OBinaryProtocol.long2bytes(distributedVersion.macAddress, stream); } @Override public void readFrom(InputStream stream, ORecordVersion version) throws IOException { final ODistributedVersion distributedVersion = (ODistributedVersion) version; distributedVersion.counter = OBinaryProtocol.bytes2int(stream); distributedVersion.timestamp = OBinaryProtocol.bytes2long(stream); distributedVersion.macAddress = OBinaryProtocol.bytes2long(stream); } @Override public int writeTo(byte[] stream, int pos, ORecordVersion version) { final ODistributedVersion distributedVersion = (ODistributedVersion) version; int len = 0; OBinaryProtocol.int2bytes(distributedVersion.counter, stream, pos + len); len += OBinaryProtocol.SIZE_INT; OBinaryProtocol.long2bytes(distributedVersion.timestamp, stream, pos + len); len += OBinaryProtocol.SIZE_LONG; OBinaryProtocol.long2bytes(distributedVersion.macAddress, stream, pos + len); len += OBinaryProtocol.SIZE_LONG; return len; } @Override public int readFrom(byte[] iStream, int pos, ORecordVersion version) { final ODistributedVersion distributedVersion = (ODistributedVersion) version; int len = 0; distributedVersion.counter = OBinaryProtocol.bytes2int(iStream, pos + len); len += OBinaryProtocol.SIZE_INT; distributedVersion.timestamp = OBinaryProtocol.bytes2long(iStream, pos + len); len += OBinaryProtocol.SIZE_LONG; distributedVersion.macAddress = OBinaryProtocol.bytes2long(iStream, pos + len); len += OBinaryProtocol.SIZE_LONG; return len; } @Override public int writeTo(OFile file, long pos, ORecordVersion version) throws IOException { final ODistributedVersion distributedVersion = (ODistributedVersion) version; int len = 0; file.writeInt(pos + len, distributedVersion.counter); len += OBinaryProtocol.SIZE_INT; file.writeLong(pos + len, distributedVersion.timestamp); len += OBinaryProtocol.SIZE_LONG; file.writeLong(pos + len, distributedVersion.macAddress); len += OBinaryProtocol.SIZE_LONG; return len; } @Override public long readFrom(OFile file, long pos, ORecordVersion version) throws IOException { final ODistributedVersion distributedVersion = (ODistributedVersion) version; int len = 0; distributedVersion.counter = file.readInt(pos + len); len += OBinaryProtocol.SIZE_INT; distributedVersion.timestamp = file.readLong(pos + len); len += OBinaryProtocol.SIZE_LONG; distributedVersion.macAddress = file.readLong(pos + len); len += OBinaryProtocol.SIZE_LONG; return len; } @Override public int fastWriteTo(byte[] iStream, int pos, ORecordVersion version) { final ODistributedVersion distributedVersion = (ODistributedVersion) version; int len = 0; CONVERTER.putInt(iStream, pos + len, distributedVersion.counter, ByteOrder.nativeOrder()); len += OBinaryProtocol.SIZE_INT; CONVERTER.putLong(iStream, pos + len, distributedVersion.timestamp, ByteOrder.nativeOrder()); len += OBinaryProtocol.SIZE_LONG; CONVERTER.putLong(iStream, pos + len, distributedVersion.macAddress, ByteOrder.nativeOrder()); len += OBinaryProtocol.SIZE_LONG; return len; } @Override public int fastReadFrom(byte[] iStream, int pos, ORecordVersion version) { final ODistributedVersion distributedVersion = (ODistributedVersion) version; int len = 0; distributedVersion.counter = CONVERTER.getInt(iStream, pos + len, ByteOrder.nativeOrder()); len += OBinaryProtocol.SIZE_INT; distributedVersion.timestamp = CONVERTER.getLong(iStream, pos + len, ByteOrder.nativeOrder()); len += OBinaryProtocol.SIZE_LONG; distributedVersion.macAddress = CONVERTER.getLong(iStream, pos + len, ByteOrder.nativeOrder()); len += OBinaryProtocol.SIZE_LONG; return len; } @Override public byte[] toByteArray(ORecordVersion version) { int size = STREAMED_SIZE; byte[] buffer = new byte[size]; fastWriteTo(buffer, 0, version); return buffer; } @Override public String toString(ORecordVersion version) { final ODistributedVersion distributedVersion = (ODistributedVersion) version; return distributedVersion.counter + "." + distributedVersion.timestamp + "." + distributedVersion.macAddress; } @Override public void fromString(String string, ORecordVersion version) { final ODistributedVersion distributedVersion = (ODistributedVersion) version; String[] parts = string.split("\\."); if (parts.length != 3) throw new IllegalArgumentException( "Not correct format of distributed version. Expected <recordVersion>.<timestamp>.<macAddress>"); distributedVersion.counter = Integer.valueOf(parts[0]); distributedVersion.timestamp = Long.valueOf(parts[1]); distributedVersion.macAddress = Long.valueOf(parts[2]); } } }
0true
core_src_main_java_com_orientechnologies_orient_core_version_ODistributedVersion.java
428
return new EventHandler<PortableEntryEvent>() { public void handle(PortableEntryEvent event) { V value = null; V oldValue = null; if (includeValue) { value = (V) toObject(event.getValue()); oldValue = (V) toObject(event.getOldValue()); } K key = (K) toObject(event.getKey()); Member member = getContext().getClusterService().getMember(event.getUuid()); EntryEvent<K, V> entryEvent = new EntryEvent<K, V>(name, member, event.getEventType().getType(), key, oldValue, value); switch (event.getEventType()) { case ADDED: listener.entryAdded(entryEvent); break; case REMOVED: listener.entryRemoved(entryEvent); break; case UPDATED: listener.entryUpdated(entryEvent); break; case EVICTED: listener.entryEvicted(entryEvent); break; default: throw new IllegalArgumentException("Not a known event type " + event.getEventType()); } } @Override public void onListenerRegister() { } };
1no label
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientMultiMapProxy.java