Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
6,016
final class CandidateScorer { private final WordScorer scorer; private final int maxNumCorrections; private final int gramSize; public CandidateScorer(WordScorer scorer, int maxNumCorrections, int gramSize) { this.scorer = scorer; this.maxNumCorrections = maxNumCorrections; this.gramSize = gramSize; } public Correction[] findBestCandiates(CandidateSet[] sets, float errorFraction, double cutoffScore) throws IOException { if (sets.length == 0) { return Correction.EMPTY; } PriorityQueue<Correction> corrections = new PriorityQueue<Correction>(maxNumCorrections) { @Override protected boolean lessThan(Correction a, Correction b) { return a.score < b.score; } }; int numMissspellings = 1; if (errorFraction >= 1.0) { numMissspellings = (int) errorFraction; } else { numMissspellings = Math.round(errorFraction * sets.length); } findCandidates(sets, new Candidate[sets.length], 0, Math.max(1, numMissspellings), corrections, cutoffScore, 0.0); Correction[] result = new Correction[corrections.size()]; for (int i = result.length - 1; i >= 0; i--) { result[i] = corrections.pop(); } assert corrections.size() == 0; return result; } public void findCandidates(CandidateSet[] candidates, Candidate[] path, int ord, int numMissspellingsLeft, PriorityQueue<Correction> corrections, double cutoffScore, final double pathScore) throws IOException { CandidateSet current = candidates[ord]; if (ord == candidates.length - 1) { path[ord] = current.originalTerm; updateTop(candidates, path, corrections, cutoffScore, pathScore + scorer.score(path, candidates, ord, gramSize)); if (numMissspellingsLeft > 0) { for (int i = 0; i < current.candidates.length; i++) { path[ord] = current.candidates[i]; updateTop(candidates, path, corrections, cutoffScore, pathScore + scorer.score(path, candidates, ord, gramSize)); } } } else { if (numMissspellingsLeft > 0) { path[ord] = current.originalTerm; findCandidates(candidates, path, ord + 1, numMissspellingsLeft, corrections, cutoffScore, pathScore + scorer.score(path, candidates, ord, gramSize)); for (int i = 0; i < current.candidates.length; i++) { path[ord] = current.candidates[i]; findCandidates(candidates, path, ord + 1, numMissspellingsLeft - 1, corrections, cutoffScore, pathScore + scorer.score(path, candidates, ord, gramSize)); } } else { path[ord] = current.originalTerm; findCandidates(candidates, path, ord + 1, 0, corrections, cutoffScore, pathScore + scorer.score(path, candidates, ord, gramSize)); } } } private void updateTop(CandidateSet[] candidates, Candidate[] path, PriorityQueue<Correction> corrections, double cutoffScore, double score) throws IOException { score = Math.exp(score); assert Math.abs(score - score(path, candidates)) < 0.00001; if (score > cutoffScore) { if (corrections.size() < maxNumCorrections) { Candidate[] c = new Candidate[candidates.length]; System.arraycopy(path, 0, c, 0, path.length); corrections.add(new Correction(score, c)); } else if (corrections.top().score < score) { Correction top = corrections.top(); System.arraycopy(path, 0, top.candidates, 0, path.length); top.score = score; corrections.updateTop(); } } } public double score(Candidate[] path, CandidateSet[] candidates) throws IOException { double score = 0.0d; for (int i = 0; i < candidates.length; i++) { score += scorer.score(path, candidates, i, gramSize); } return Math.exp(score); } }
1no label
src_main_java_org_elasticsearch_search_suggest_phrase_CandidateScorer.java
1,542
@Component("blSocialSignInAdapter") public class BroadleafSocialSignInAdapter implements SignInAdapter { @Resource(name="blUserDetailsService") private UserDetailsService userDetailsService; @Override public String signIn(String username, Connection<?> connection, NativeWebRequest request) { UserDetails principal = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(token); return null; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_social_BroadleafSocialSignInAdapter.java
3,413
public class IgnoreGatewayRecoveryException extends IndexShardException { public IgnoreGatewayRecoveryException(ShardId shardId, String msg) { super(shardId, msg); } public IgnoreGatewayRecoveryException(ShardId shardId, String msg, Throwable cause) { super(shardId, msg, cause); } }
0true
src_main_java_org_elasticsearch_index_gateway_IgnoreGatewayRecoveryException.java
774
public class CollectionReserveRemoveOperation extends CollectionOperation { String transactionId; private Data value; private long reservedItemId = -1; public CollectionReserveRemoveOperation() { } public CollectionReserveRemoveOperation(String name, long reservedItemId, Data value, String transactionId) { super(name); this.reservedItemId = reservedItemId; this.value = value; this.transactionId = transactionId; } @Override public int getId() { return CollectionDataSerializerHook.COLLECTION_RESERVE_REMOVE; } @Override public void beforeRun() throws Exception { } @Override public void run() throws Exception { response = getOrCreateContainer().reserveRemove(reservedItemId, value, transactionId); } @Override public void afterRun() throws Exception { } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeLong(reservedItemId); value.writeData(out); out.writeUTF(transactionId); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); reservedItemId = in.readLong(); value = new Data(); value.readData(in); transactionId = in.readUTF(); } }
0true
hazelcast_src_main_java_com_hazelcast_collection_txn_CollectionReserveRemoveOperation.java
451
public class ReadOnlyKeyColumnValueStore extends KCVSProxy { public ReadOnlyKeyColumnValueStore(KeyColumnValueStore store) { super(store); } @Override public void acquireLock(StaticBuffer key, StaticBuffer column, StaticBuffer expectedValue, StoreTransaction txh) throws BackendException { throw new UnsupportedOperationException("Cannot lock on a read-only store"); } @Override public void mutate(StaticBuffer key, List<Entry> additions, List<StaticBuffer> deletions, StoreTransaction txh) throws BackendException { throw new UnsupportedOperationException("Cannot mutate a read-only store"); } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_ReadOnlyKeyColumnValueStore.java
585
getEntriesBetween(iRangeFrom, iRangeTo, iInclusive, new IndexEntriesResultListener() { @Override public boolean addResult(ODocument entry) { result.add(entry); return true; } });
0true
core_src_main_java_com_orientechnologies_orient_core_index_OIndexAbstract.java
1,477
public class HazelcastTimestampsRegion<Cache extends RegionCache> extends AbstractGeneralRegion<Cache> implements TimestampsRegion { public HazelcastTimestampsRegion(final HazelcastInstance instance, final String name, final Properties props, final Cache cache) { super(instance, name, props, cache); } }
0true
hazelcast-hibernate_hazelcast-hibernate4_src_main_java_com_hazelcast_hibernate_region_HazelcastTimestampsRegion.java
4,470
class RecoveryFilesInfoRequest extends TransportRequest { private long recoveryId; private ShardId shardId; List<String> phase1FileNames; List<Long> phase1FileSizes; List<String> phase1ExistingFileNames; List<Long> phase1ExistingFileSizes; long phase1TotalSize; long phase1ExistingTotalSize; RecoveryFilesInfoRequest() { } RecoveryFilesInfoRequest(long recoveryId, ShardId shardId, List<String> phase1FileNames, List<Long> phase1FileSizes, List<String> phase1ExistingFileNames, List<Long> phase1ExistingFileSizes, long phase1TotalSize, long phase1ExistingTotalSize) { this.recoveryId = recoveryId; this.shardId = shardId; this.phase1FileNames = phase1FileNames; this.phase1FileSizes = phase1FileSizes; this.phase1ExistingFileNames = phase1ExistingFileNames; this.phase1ExistingFileSizes = phase1ExistingFileSizes; this.phase1TotalSize = phase1TotalSize; this.phase1ExistingTotalSize = phase1ExistingTotalSize; } public long recoveryId() { return this.recoveryId; } public ShardId shardId() { return shardId; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); recoveryId = in.readLong(); shardId = ShardId.readShardId(in); int size = in.readVInt(); phase1FileNames = new ArrayList<String>(size); for (int i = 0; i < size; i++) { phase1FileNames.add(in.readString()); } size = in.readVInt(); phase1FileSizes = new ArrayList<Long>(size); for (int i = 0; i < size; i++) { phase1FileSizes.add(in.readVLong()); } size = in.readVInt(); phase1ExistingFileNames = new ArrayList<String>(size); for (int i = 0; i < size; i++) { phase1ExistingFileNames.add(in.readString()); } size = in.readVInt(); phase1ExistingFileSizes = new ArrayList<Long>(size); for (int i = 0; i < size; i++) { phase1ExistingFileSizes.add(in.readVLong()); } phase1TotalSize = in.readVLong(); phase1ExistingTotalSize = in.readVLong(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeLong(recoveryId); shardId.writeTo(out); out.writeVInt(phase1FileNames.size()); for (String phase1FileName : phase1FileNames) { out.writeString(phase1FileName); } out.writeVInt(phase1FileSizes.size()); for (Long phase1FileSize : phase1FileSizes) { out.writeVLong(phase1FileSize); } out.writeVInt(phase1ExistingFileNames.size()); for (String phase1ExistingFileName : phase1ExistingFileNames) { out.writeString(phase1ExistingFileName); } out.writeVInt(phase1ExistingFileSizes.size()); for (Long phase1ExistingFileSize : phase1ExistingFileSizes) { out.writeVLong(phase1ExistingFileSize); } out.writeVLong(phase1TotalSize); out.writeVLong(phase1ExistingTotalSize); } }
1no label
src_main_java_org_elasticsearch_indices_recovery_RecoveryFilesInfoRequest.java
200
public class PermanentBackendException extends BackendException { private static final long serialVersionUID = 203482308203400L; /** * @param msg Exception message */ public PermanentBackendException(String msg) { super(msg); } /** * @param msg Exception message * @param cause Cause of the exception */ public PermanentBackendException(String msg, Throwable cause) { super(msg, cause); } /** * Constructs an exception with a generic message * * @param cause Cause of the exception */ public PermanentBackendException(Throwable cause) { this("Permanent failure in storage backend", cause); } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_PermanentBackendException.java
139
public static class Group { public static class Name { public static final String Description = "StructuredContentImpl_Description"; public static final String Internal = "StructuredContentImpl_Internal"; public static final String Rules = "StructuredContentImpl_Rules"; } public static class Order { public static final int Description = 1000; public static final int Internal = 2000; public static final int Rules = 1000; } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContentImpl.java
25
abstract class EntrySetView extends AbstractSet<Map.Entry<K, V>> { private transient int size = -1, sizeModCount; @Override public int size() { if (fromStart && toEnd) return m.size(); if (size == -1 || sizeModCount != m.modCount) { sizeModCount = m.modCount; size = 0; Iterator<?> i = iterator(); while (i.hasNext()) { size++; i.next(); } } return size; } @Override public boolean isEmpty() { OMVRBTreeEntryPosition<K, V> n = absLowest(); return n == null || tooHigh(n.getKey()); } @Override public boolean contains(final Object o) { if (!(o instanceof OMVRBTreeEntry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final K key = entry.getKey(); if (!inRange(key)) return false; V nodeValue = m.get(key); return nodeValue != null && valEquals(nodeValue, entry.getValue()); } @Override public boolean remove(final Object o) { if (!(o instanceof OMVRBTreeEntry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final K key = entry.getKey(); if (!inRange(key)) return false; final OMVRBTreeEntry<K, V> node = m.getEntry(key, PartialSearchMode.NONE); if (node != null && valEquals(node.getValue(), entry.getValue())) { m.deleteEntry(node); return true; } return false; } }
0true
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
1,655
Thread thread = new Thread() { public void run() { try { Thread.sleep(3000 * finalI); HazelcastInstance instance = nodeFactory.newHazelcastInstance(config); instances.set(finalI, instance); Thread.sleep(rand.nextInt(100)); if (finalI != 0) { // do not run on master node, // let partition assignment be made during put ops. for (int j = 0; j < 10000; j++) { instance.getMap(name).put(getName() + "-" + j, "value"); } } } catch (InterruptedException e) { e.printStackTrace(); } finally { latch.countDown(); } } };
0true
hazelcast_src_test_java_com_hazelcast_map_BackupTest.java
1,873
public class Modules { public static Module createModule(String moduleClass, Settings settings) throws ClassNotFoundException { return createModule((Class<? extends Module>) settings.getClassLoader().loadClass(moduleClass), settings); } public static Module createModule(Class<? extends Module> moduleClass, @Nullable Settings settings) { Constructor<? extends Module> constructor; try { constructor = moduleClass.getConstructor(Settings.class); try { return constructor.newInstance(settings); } catch (Exception e) { throw new ElasticsearchException("Failed to create module [" + moduleClass + "]", e); } } catch (NoSuchMethodException e) { try { constructor = moduleClass.getConstructor(); try { return constructor.newInstance(); } catch (Exception e1) { throw new ElasticsearchException("Failed to create module [" + moduleClass + "]", e); } } catch (NoSuchMethodException e1) { throw new ElasticsearchException("No constructor for [" + moduleClass + "]"); } } } public static void processModules(Iterable<Module> modules) { for (Module module : modules) { if (module instanceof PreProcessModule) { for (Module module1 : modules) { ((PreProcessModule) module).processModule(module1); } } } } }
0true
src_main_java_org_elasticsearch_common_inject_Modules.java
2,690
metaDataBlobContainer.deleteBlobsByFilter(new BlobContainer.BlobNameFilter() { @Override public boolean accept(String blobName) { return blobName.startsWith("metadata-") && !newMetaData.equals(blobName); } });
0true
src_main_java_org_elasticsearch_gateway_blobstore_BlobStoreGateway.java
2,923
public class PreBuiltCharFilterFactoryFactory implements CharFilterFactoryFactory { private final CharFilterFactory charFilterFactory; public PreBuiltCharFilterFactoryFactory(CharFilterFactory charFilterFactory) { this.charFilterFactory = charFilterFactory; } @Override public CharFilterFactory create(String name, Settings settings) { Version indexVersion = settings.getAsVersion(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT); if (!Version.CURRENT.equals(indexVersion)) { return PreBuiltCharFilters.valueOf(name.toUpperCase(Locale.ROOT)).getCharFilterFactory(indexVersion); } return charFilterFactory; } }
1no label
src_main_java_org_elasticsearch_index_analysis_PreBuiltCharFilterFactoryFactory.java
776
public class ORecordIteratorClusters<REC extends ORecordInternal<?>> extends OIdentifiableIterator<REC> { protected int[] clusterIds; protected int currentClusterIdx; protected ORecord<?> currentRecord; protected ORID beginRange; protected ORID endRange; public ORecordIteratorClusters(final ODatabaseRecord iDatabase, final ODatabaseRecord iLowLevelDatabase, final int[] iClusterIds, final boolean iUseCache, final boolean iterateThroughTombstones) { super(iDatabase, iLowLevelDatabase, iUseCache, iterateThroughTombstones); clusterIds = iClusterIds; config(); } protected ORecordIteratorClusters(final ODatabaseRecord iDatabase, final ODatabaseRecord iLowLevelDatabase, final boolean iUseCache, final boolean iterateThroughTombstones) { super(iDatabase, iLowLevelDatabase, iUseCache, iterateThroughTombstones); } public ORecordIteratorClusters<REC> setRange(final ORID iBegin, final ORID iEnd) { beginRange = iBegin; endRange = iEnd; if (currentRecord != null && outsideOfTheRange(currentRecord.getIdentity())) { currentRecord = null; } return this; } @Override public boolean hasPrevious() { checkDirection(false); if (currentRecord != null) return true; if (limit > -1 && browsedRecords >= limit) // LIMIT REACHED return false; if (browsedRecords >= totalAvailableRecords) return false; if (liveUpdated) updateClusterRange(); ORecordInternal<?> record = getRecord(); // ITERATE UNTIL THE PREVIOUS GOOD RECORD while (currentClusterIdx > -1) { while (prevPosition()) { currentRecord = readCurrentRecord(record, 0); if (currentRecord != null) if (include(currentRecord)) // FOUND return true; } // CLUSTER EXHAUSTED, TRY WITH THE PREVIOUS ONE currentClusterIdx--; updateClusterRange(); } if (txEntries != null && txEntries.size() - (currentTxEntryPosition + 1) > 0) return true; currentRecord = null; return false; } public boolean hasNext() { checkDirection(true); if (Thread.interrupted()) // INTERRUPTED return false; if (currentRecord != null) return true; if (limit > -1 && browsedRecords >= limit) // LIMIT REACHED return false; if (browsedRecords >= totalAvailableRecords) return false; // COMPUTE THE NUMBER OF RECORDS TO BROWSE if (liveUpdated) updateClusterRange(); ORecordInternal<?> record = getRecord(); // ITERATE UNTIL THE NEXT GOOD RECORD while (currentClusterIdx < clusterIds.length) { while (nextPosition()) { if (outsideOfTheRange(current)) continue; currentRecord = readCurrentRecord(record, 0); if (currentRecord != null) if (include(currentRecord)) // FOUND return true; } // CLUSTER EXHAUSTED, TRY WITH THE NEXT ONE currentClusterIdx++; if (currentClusterIdx >= clusterIds.length) break; updateClusterRange(); } // CHECK IN TX IF ANY if (txEntries != null && txEntries.size() - (currentTxEntryPosition + 1) > 0) return true; currentRecord = null; return false; } private boolean outsideOfTheRange(ORID orid) { if (beginRange != null && orid.compareTo(beginRange) < 0) return true; if (endRange != null && orid.compareTo(endRange) > 0) return true; return false; } /** * Return the element at the current position and move forward the cursor to the next position available. * * @return the next record found, otherwise the NoSuchElementException exception is thrown when no more records are found. */ @SuppressWarnings("unchecked") public REC next() { checkDirection(true); if (currentRecord != null) try { // RETURN LAST LOADED RECORD return (REC) currentRecord; } finally { currentRecord = null; } ORecordInternal<?> record; // MOVE FORWARD IN THE CURRENT CLUSTER while (hasNext()) { if (currentRecord != null) try { // RETURN LAST LOADED RECORD return (REC) currentRecord; } finally { currentRecord = null; } record = getTransactionEntry(); if (record == null) record = readCurrentRecord(null, +1); if (record != null) // FOUND if (include(record)) return (REC) record; } record = getTransactionEntry(); if (record != null) return (REC) record; throw new NoSuchElementException("Direction: forward, last position was: " + current + ", range: " + beginRange + "-" + endRange); } /** * Return the element at the current position and move backward the cursor to the previous position available. * * @return the previous record found, otherwise the NoSuchElementException exception is thrown when no more records are found. */ @SuppressWarnings("unchecked") @Override public REC previous() { checkDirection(false); if (currentRecord != null) try { // RETURN LAST LOADED RECORD return (REC) currentRecord; } finally { currentRecord = null; } ORecordInternal<?> record = getRecord(); // MOVE BACKWARD IN THE CURRENT CLUSTER while (hasPrevious()) { if (currentRecord != null) try { // RETURN LAST LOADED RECORD return (REC) currentRecord; } finally { currentRecord = null; } if (record == null) record = readCurrentRecord(null, -1); if (record != null) // FOUND if (include(record)) return (REC) record; } record = getTransactionEntry(); if (record != null) return (REC) record; return null; } protected boolean include(final ORecord<?> iRecord) { return true; } /** * Move the iterator to the begin of the range. If no range was specified move to the first record of the cluster. * * @return The object itself */ @Override public ORecordIteratorClusters<REC> begin() { currentClusterIdx = 0; current.clusterId = clusterIds[currentClusterIdx]; if (liveUpdated) updateClusterRange(); resetCurrentPosition(); nextPosition(); final ORecordInternal<?> record = getRecord(); currentRecord = readCurrentRecord(record, 0); if (currentRecord != null && !include(currentRecord)) { currentRecord = null; hasNext(); } return this; } /** * Move the iterator to the end of the range. If no range was specified move to the last record of the cluster. * * @return The object itself */ @Override public ORecordIteratorClusters<REC> last() { currentClusterIdx = clusterIds.length - 1; if (liveUpdated) updateClusterRange(); current.clusterId = currentClusterIdx; resetCurrentPosition(); prevPosition(); final ORecordInternal<?> record = getRecord(); currentRecord = readCurrentRecord(record, 0); if (currentRecord != null && !include(currentRecord)) { currentRecord = null; hasPrevious(); } return this; } /** * Tell to the iterator that the upper limit must be checked at every cycle. Useful when concurrent deletes or additions change * the size of the cluster while you're browsing it. Default is false. * * @param iLiveUpdated * True to activate it, otherwise false (default) * @see #isLiveUpdated() */ @Override public ORecordIteratorClusters<REC> setLiveUpdated(boolean iLiveUpdated) { super.setLiveUpdated(iLiveUpdated); if (iLiveUpdated) { firstClusterEntry = OClusterPositionFactory.INSTANCE.valueOf(0); lastClusterEntry = OClusterPositionFactory.INSTANCE.getMaxValue(); } else { updateClusterRange(); } return this; } protected void updateClusterRange() { current.clusterId = clusterIds[currentClusterIdx]; final OClusterPosition[] range = database.getStorage().getClusterDataRange(current.clusterId); firstClusterEntry = range[0]; lastClusterEntry = range[1]; resetCurrentPosition(); } protected void config() { if (clusterIds.length == 0) return; currentClusterIdx = 0; // START FROM THE FIRST CLUSTER updateClusterRange(); totalAvailableRecords = database.countClusterElements(clusterIds, isIterateThroughTombstones()); txEntries = database.getTransaction().getNewRecordEntriesByClusterIds(clusterIds); if (txEntries != null) // ADJUST TOTAL ELEMENT BASED ON CURRENT TRANSACTION'S ENTRIES for (ORecordOperation entry : txEntries) { if (entry.getRecord().getIdentity().isTemporary() && entry.type != ORecordOperation.DELETED) totalAvailableRecords++; else if (entry.type == ORecordOperation.DELETED) totalAvailableRecords--; } begin(); } @Override public String toString() { return String.format("ORecordIteratorCluster.clusters(%s).currentRecord(%s).range(%s-%s)", Arrays.toString(clusterIds), currentRecord, beginRange, endRange); } }
1no label
core_src_main_java_com_orientechnologies_orient_core_iterator_ORecordIteratorClusters.java
578
public class OptimizeRequestBuilder extends BroadcastOperationRequestBuilder<OptimizeRequest, OptimizeResponse, OptimizeRequestBuilder> { public OptimizeRequestBuilder(IndicesAdminClient indicesClient) { super((InternalIndicesAdminClient) indicesClient, new OptimizeRequest()); } /** * Should the call block until the optimize completes. Defaults to <tt>true</tt>. */ public OptimizeRequestBuilder setWaitForMerge(boolean waitForMerge) { request.waitForMerge(waitForMerge); return this; } /** * Will optimize the index down to <= maxNumSegments. By default, will cause the optimize * process to optimize down to half the configured number of segments. */ public OptimizeRequestBuilder setMaxNumSegments(int maxNumSegments) { request.maxNumSegments(maxNumSegments); return this; } /** * Should the optimization only expunge deletes from the index, without full optimization. * Defaults to full optimization (<tt>false</tt>). */ public OptimizeRequestBuilder setOnlyExpungeDeletes(boolean onlyExpungeDeletes) { request.onlyExpungeDeletes(onlyExpungeDeletes); return this; } /** * Should flush be performed after the optimization. Defaults to <tt>true</tt>. */ public OptimizeRequestBuilder setFlush(boolean flush) { request.flush(flush); return this; } @Override protected void doExecute(ActionListener<OptimizeResponse> listener) { ((IndicesAdminClient) client).optimize(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_optimize_OptimizeRequestBuilder.java
1,235
public interface Client { /** * Closes the client. */ void close(); /** * The admin client that can be used to perform administrative operations. */ AdminClient admin(); /** * Executes a generic action, denoted by an {@link Action}. * * @param action The action type to execute. * @param request The action request. * @param <Request> The request type. * @param <Response> the response type. * @param <RequestBuilder> The request builder type. * @return A future allowing to get back the response. */ <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> ActionFuture<Response> execute(final Action<Request, Response, RequestBuilder> action, final Request request); /** * Executes a generic action, denoted by an {@link Action}. * * @param action The action type to execute. * @param request The action request. * @param listener The listener to receive the response back. * @param <Request> The request type. * @param <Response> The response type. * @param <RequestBuilder> The request builder type. */ <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void execute(final Action<Request, Response, RequestBuilder> action, final Request request, ActionListener<Response> listener); /** * Prepares a request builder to execute, specified by {@link Action}. * * @param action The action type to execute. * @param <Request> The request type. * @param <Response> The response type. * @param <RequestBuilder> The request builder. * @return The request builder, that can, at a later stage, execute the request. */ <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> RequestBuilder prepareExecute(final Action<Request, Response, RequestBuilder> action); /** * Index a JSON source associated with a given index and type. * <p/> * <p>The id is optional, if it is not provided, one will be generated automatically. * * @param request The index request * @return The result future * @see Requests#indexRequest(String) */ ActionFuture<IndexResponse> index(IndexRequest request); /** * Index a document associated with a given index and type. * <p/> * <p>The id is optional, if it is not provided, one will be generated automatically. * * @param request The index request * @param listener A listener to be notified with a result * @see Requests#indexRequest(String) */ void index(IndexRequest request, ActionListener<IndexResponse> listener); /** * Index a document associated with a given index and type. * <p/> * <p>The id is optional, if it is not provided, one will be generated automatically. */ IndexRequestBuilder prepareIndex(); /** * Updates a document based on a script. * * @param request The update request * @return The result future */ ActionFuture<UpdateResponse> update(UpdateRequest request); /** * Updates a document based on a script. * * @param request The update request * @param listener A listener to be notified with a result */ void update(UpdateRequest request, ActionListener<UpdateResponse> listener); /** * Updates a document based on a script. */ UpdateRequestBuilder prepareUpdate(); /** * Updates a document based on a script. */ UpdateRequestBuilder prepareUpdate(String index, String type, String id); /** * Index a document associated with a given index and type. * <p/> * <p>The id is optional, if it is not provided, one will be generated automatically. * * @param index The index to index the document to * @param type The type to index the document to */ IndexRequestBuilder prepareIndex(String index, String type); /** * Index a document associated with a given index and type. * <p/> * <p>The id is optional, if it is not provided, one will be generated automatically. * * @param index The index to index the document to * @param type The type to index the document to * @param id The id of the document */ IndexRequestBuilder prepareIndex(String index, String type, @Nullable String id); /** * Deletes a document from the index based on the index, type and id. * * @param request The delete request * @return The result future * @see Requests#deleteRequest(String) */ ActionFuture<DeleteResponse> delete(DeleteRequest request); /** * Deletes a document from the index based on the index, type and id. * * @param request The delete request * @param listener A listener to be notified with a result * @see Requests#deleteRequest(String) */ void delete(DeleteRequest request, ActionListener<DeleteResponse> listener); /** * Deletes a document from the index based on the index, type and id. */ DeleteRequestBuilder prepareDelete(); /** * Deletes a document from the index based on the index, type and id. * * @param index The index to delete the document from * @param type The type of the document to delete * @param id The id of the document to delete */ DeleteRequestBuilder prepareDelete(String index, String type, String id); /** * Executes a bulk of index / delete operations. * * @param request The bulk request * @return The result future * @see org.elasticsearch.client.Requests#bulkRequest() */ ActionFuture<BulkResponse> bulk(BulkRequest request); /** * Executes a bulk of index / delete operations. * * @param request The bulk request * @param listener A listener to be notified with a result * @see org.elasticsearch.client.Requests#bulkRequest() */ void bulk(BulkRequest request, ActionListener<BulkResponse> listener); /** * Executes a bulk of index / delete operations. */ BulkRequestBuilder prepareBulk(); /** * Deletes all documents from one or more indices based on a query. * * @param request The delete by query request * @return The result future * @see Requests#deleteByQueryRequest(String...) */ ActionFuture<DeleteByQueryResponse> deleteByQuery(DeleteByQueryRequest request); /** * Deletes all documents from one or more indices based on a query. * * @param request The delete by query request * @param listener A listener to be notified with a result * @see Requests#deleteByQueryRequest(String...) */ void deleteByQuery(DeleteByQueryRequest request, ActionListener<DeleteByQueryResponse> listener); /** * Deletes all documents from one or more indices based on a query. */ DeleteByQueryRequestBuilder prepareDeleteByQuery(String... indices); /** * Gets the document that was indexed from an index with a type and id. * * @param request The get request * @return The result future * @see Requests#getRequest(String) */ ActionFuture<GetResponse> get(GetRequest request); /** * Gets the document that was indexed from an index with a type and id. * * @param request The get request * @param listener A listener to be notified with a result * @see Requests#getRequest(String) */ void get(GetRequest request, ActionListener<GetResponse> listener); /** * Gets the document that was indexed from an index with a type and id. */ GetRequestBuilder prepareGet(); /** * Gets the document that was indexed from an index with a type (optional) and id. */ GetRequestBuilder prepareGet(String index, @Nullable String type, String id); /** * Multi get documents. */ ActionFuture<MultiGetResponse> multiGet(MultiGetRequest request); /** * Multi get documents. */ void multiGet(MultiGetRequest request, ActionListener<MultiGetResponse> listener); /** * Multi get documents. */ MultiGetRequestBuilder prepareMultiGet(); /** * A count of all the documents matching a specific query. * * @param request The count request * @return The result future * @see Requests#countRequest(String...) */ ActionFuture<CountResponse> count(CountRequest request); /** * A count of all the documents matching a specific query. * * @param request The count request * @param listener A listener to be notified of the result * @see Requests#countRequest(String...) */ void count(CountRequest request, ActionListener<CountResponse> listener); /** * A count of all the documents matching a specific query. */ CountRequestBuilder prepareCount(String... indices); /** * Suggestion matching a specific phrase. * * @param request The suggest request * @return The result future * @see Requests#suggestRequest(String...) */ ActionFuture<SuggestResponse> suggest(SuggestRequest request); /** * Suggestions matching a specific phrase. * * @param request The suggest request * @param listener A listener to be notified of the result * @see Requests#suggestRequest(String...) */ void suggest(SuggestRequest request, ActionListener<SuggestResponse> listener); /** * Suggestions matching a specific phrase. */ SuggestRequestBuilder prepareSuggest(String... indices); /** * Search across one or more indices and one or more types with a query. * * @param request The search request * @return The result future * @see Requests#searchRequest(String...) */ ActionFuture<SearchResponse> search(SearchRequest request); /** * Search across one or more indices and one or more types with a query. * * @param request The search request * @param listener A listener to be notified of the result * @see Requests#searchRequest(String...) */ void search(SearchRequest request, ActionListener<SearchResponse> listener); /** * Search across one or more indices and one or more types with a query. */ SearchRequestBuilder prepareSearch(String... indices); /** * A search scroll request to continue searching a previous scrollable search request. * * @param request The search scroll request * @return The result future * @see Requests#searchScrollRequest(String) */ ActionFuture<SearchResponse> searchScroll(SearchScrollRequest request); /** * A search scroll request to continue searching a previous scrollable search request. * * @param request The search scroll request * @param listener A listener to be notified of the result * @see Requests#searchScrollRequest(String) */ void searchScroll(SearchScrollRequest request, ActionListener<SearchResponse> listener); /** * A search scroll request to continue searching a previous scrollable search request. */ SearchScrollRequestBuilder prepareSearchScroll(String scrollId); /** * Performs multiple search requests. */ ActionFuture<MultiSearchResponse> multiSearch(MultiSearchRequest request); /** * Performs multiple search requests. */ void multiSearch(MultiSearchRequest request, ActionListener<MultiSearchResponse> listener); /** * Performs multiple search requests. */ MultiSearchRequestBuilder prepareMultiSearch(); /** * A more like this action to search for documents that are "like" a specific document. * * @param request The more like this request * @return The response future */ ActionFuture<SearchResponse> moreLikeThis(MoreLikeThisRequest request); /** * A more like this action to search for documents that are "like" a specific document. * * @param request The more like this request * @param listener A listener to be notified of the result */ void moreLikeThis(MoreLikeThisRequest request, ActionListener<SearchResponse> listener); /** * A more like this action to search for documents that are "like" a specific document. * * @param index The index to load the document from * @param type The type of the document * @param id The id of the document */ MoreLikeThisRequestBuilder prepareMoreLikeThis(String index, String type, String id); /** * An action that returns the term vectors for a specific document. * * @param request The term vector request * @return The response future */ ActionFuture<TermVectorResponse> termVector(TermVectorRequest request); /** * An action that returns the term vectors for a specific document. * * @param request The term vector request * @return The response future */ void termVector(TermVectorRequest request, ActionListener<TermVectorResponse> listener); /** * Builder for the term vector request. * * @param index The index to load the document from * @param type The type of the document * @param id The id of the document */ TermVectorRequestBuilder prepareTermVector(String index, String type, String id); /** * Multi get term vectors. */ ActionFuture<MultiTermVectorsResponse> multiTermVectors(MultiTermVectorsRequest request); /** * Multi get term vectors. */ void multiTermVectors(MultiTermVectorsRequest request, ActionListener<MultiTermVectorsResponse> listener); /** * Multi get term vectors. */ MultiTermVectorsRequestBuilder prepareMultiTermVectors(); /** * Percolates a request returning the matches documents. */ ActionFuture<PercolateResponse> percolate(PercolateRequest request); /** * Percolates a request returning the matches documents. */ void percolate(PercolateRequest request, ActionListener<PercolateResponse> listener); /** * Percolates a request returning the matches documents. */ PercolateRequestBuilder preparePercolate(); /** * Performs multiple percolate requests. */ ActionFuture<MultiPercolateResponse> multiPercolate(MultiPercolateRequest request); /** * Performs multiple percolate requests. */ void multiPercolate(MultiPercolateRequest request, ActionListener<MultiPercolateResponse> listener); /** * Performs multiple percolate requests. */ MultiPercolateRequestBuilder prepareMultiPercolate(); /** * Computes a score explanation for the specified request. * * @param index The index this explain is targeted for * @param type The type this explain is targeted for * @param id The document identifier this explain is targeted for */ ExplainRequestBuilder prepareExplain(String index, String type, String id); /** * Computes a score explanation for the specified request. * * @param request The request encapsulating the query and document identifier to compute a score explanation for */ ActionFuture<ExplainResponse> explain(ExplainRequest request); /** * Computes a score explanation for the specified request. * * @param request The request encapsulating the query and document identifier to compute a score explanation for * @param listener A listener to be notified of the result */ void explain(ExplainRequest request, ActionListener<ExplainResponse> listener); /** * Clears the search contexts associated with specified scroll ids. */ ClearScrollRequestBuilder prepareClearScroll(); /** * Clears the search contexts associated with specified scroll ids. */ ActionFuture<ClearScrollResponse> clearScroll(ClearScrollRequest request); /** * Clears the search contexts associated with specified scroll ids. */ void clearScroll(ClearScrollRequest request, ActionListener<ClearScrollResponse> listener); }
0true
src_main_java_org_elasticsearch_client_Client.java
2,767
public class NettyHttpRequest extends HttpRequest { private final org.jboss.netty.handler.codec.http.HttpRequest request; private final Channel channel; private final Map<String, String> params; private final String rawPath; private final BytesReference content; public NettyHttpRequest(org.jboss.netty.handler.codec.http.HttpRequest request, Channel channel) { this.request = request; this.channel = channel; this.params = new HashMap<String, String>(); if (request.getContent().readable()) { this.content = new ChannelBufferBytesReference(request.getContent()); } else { this.content = BytesArray.EMPTY; } String uri = request.getUri(); int pathEndPos = uri.indexOf('?'); if (pathEndPos < 0) { this.rawPath = uri; } else { this.rawPath = uri.substring(0, pathEndPos); RestUtils.decodeQueryString(uri, pathEndPos + 1, params); } } @Override public Method method() { HttpMethod httpMethod = request.getMethod(); if (httpMethod == HttpMethod.GET) return Method.GET; if (httpMethod == HttpMethod.POST) return Method.POST; if (httpMethod == HttpMethod.PUT) return Method.PUT; if (httpMethod == HttpMethod.DELETE) return Method.DELETE; if (httpMethod == HttpMethod.HEAD) { return Method.HEAD; } if (httpMethod == HttpMethod.OPTIONS) { return Method.OPTIONS; } return Method.GET; } @Override public String uri() { return request.getUri(); } @Override public String rawPath() { return rawPath; } @Override public Map<String, String> params() { return params; } @Override public boolean hasContent() { return content.length() > 0; } @Override public boolean contentUnsafe() { // Netty http decoder always copies over the http content return false; } @Override public BytesReference content() { return content; } /** * Returns the remote address where this rest request channel is "connected to". The * returned {@link SocketAddress} is supposed to be down-cast into more * concrete type such as {@link java.net.InetSocketAddress} to retrieve * the detailed information. */ @Override public SocketAddress getRemoteAddress() { return channel.getRemoteAddress(); } /** * Returns the local address where this request channel is bound to. The returned * {@link SocketAddress} is supposed to be down-cast into more concrete * type such as {@link java.net.InetSocketAddress} to retrieve the detailed * information. */ @Override public SocketAddress getLocalAddress() { return channel.getLocalAddress(); } @Override public String header(String name) { return request.headers().get(name); } @Override public Iterable<Map.Entry<String, String>> headers() { return request.headers().entries(); } @Override public boolean hasParam(String key) { return params.containsKey(key); } @Override public String param(String key) { return params.get(key); } @Override public String param(String key, String defaultValue) { String value = params.get(key); if (value == null) { return defaultValue; } return value; } }
1no label
src_main_java_org_elasticsearch_http_netty_NettyHttpRequest.java
1,590
public enum STATUS { OFFLINE, STARTING, ONLINE, SHUTDOWNING };
0true
server_src_main_java_com_orientechnologies_orient_server_distributed_ODistributedServerManager.java
1,452
public abstract class TitanHadoopSetupCommon implements TitanHadoopSetup { private static final StaticBuffer DEFAULT_COLUMN = StaticArrayBuffer.of(new byte[0]); private static final SliceQuery DEFAULT_SLICE_QUERY = new SliceQuery(DEFAULT_COLUMN, DEFAULT_COLUMN); @Override public SliceQuery inputSlice(final FaunusVertexQueryFilter inputFilter) { //For now, only return the full range because the current input format needs to read the hidden //vertex-state property to determine if the vertex is a ghost. If we filter, that relation would fall out as well. return DEFAULT_SLICE_QUERY; } @Override public void close() { //Do nothing } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_formats_util_input_TitanHadoopSetupCommon.java
605
public class TransportUpdateSettingsAction extends TransportMasterNodeOperationAction<UpdateSettingsRequest, UpdateSettingsResponse> { private final MetaDataUpdateSettingsService updateSettingsService; @Inject public TransportUpdateSettingsAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool, MetaDataUpdateSettingsService updateSettingsService) { super(settings, transportService, clusterService, threadPool); this.updateSettingsService = updateSettingsService; } @Override protected String executor() { // we go async right away.... return ThreadPool.Names.SAME; } @Override protected String transportAction() { return UpdateSettingsAction.NAME; } @Override protected UpdateSettingsRequest newRequest() { return new UpdateSettingsRequest(); } @Override protected UpdateSettingsResponse newResponse() { return new UpdateSettingsResponse(); } @Override protected void doExecute(UpdateSettingsRequest request, ActionListener<UpdateSettingsResponse> listener) { request.indices(clusterService.state().metaData().concreteIndices(request.indices(), request.indicesOptions())); super.doExecute(request, listener); } @Override protected void masterOperation(final UpdateSettingsRequest request, final ClusterState state, final ActionListener<UpdateSettingsResponse> listener) throws ElasticsearchException { UpdateSettingsClusterStateUpdateRequest clusterStateUpdateRequest = new UpdateSettingsClusterStateUpdateRequest() .indices(request.indices()) .settings(request.settings()) .ackTimeout(request.timeout()) .masterNodeTimeout(request.masterNodeTimeout()); updateSettingsService.updateSettings(clusterStateUpdateRequest, new ClusterStateUpdateListener() { @Override public void onResponse(ClusterStateUpdateResponse response) { listener.onResponse(new UpdateSettingsResponse(response.isAcknowledged())); } @Override public void onFailure(Throwable t) { logger.debug("failed to update settings on indices [{}]", t, request.indices()); listener.onFailure(t); } }); } }
1no label
src_main_java_org_elasticsearch_action_admin_indices_settings_put_TransportUpdateSettingsAction.java
778
private final SchemaCache.StoreRetrieval typeCacheRetrieval = new SchemaCache.StoreRetrieval() { @Override public Long retrieveSchemaByName(String typeName, StandardTitanTx tx) { tx.getTxHandle().disableCache(); //Disable cache to make sure that schema is only cached once and cache eviction works! TitanVertex v = Iterables.getOnlyElement(tx.getVertices(BaseKey.SchemaName, typeName),null); tx.getTxHandle().enableCache(); return v!=null?v.getLongId():null; } @Override public EntryList retrieveSchemaRelations(final long schemaId, final BaseRelationType type, final Direction dir, final StandardTitanTx tx) { SliceQuery query = queryCache.getQuery(type,dir); tx.getTxHandle().disableCache(); //Disable cache to make sure that schema is only cached once! EntryList result = edgeQuery(schemaId, query, tx.getTxHandle()); tx.getTxHandle().enableCache(); return result; } };
1no label
titan-core_src_main_java_com_thinkaurelius_titan_graphdb_database_StandardTitanGraph.java
73
public abstract class TransactionManagerProvider extends Service { public TransactionManagerProvider( String name ) { super( name ); } public abstract AbstractTransactionManager loadTransactionManager( String txLogDir, XaDataSourceManager xaDataSourceManager, KernelPanicEventGenerator kpe, RemoteTxHook rollbackHook, StringLogger msgLog, FileSystemAbstraction fileSystem, TransactionStateFactory stateFactory ); }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TransactionManagerProvider.java
96
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class ClientIssueTest extends HazelcastTestSupport { @After @Before public void cleanup() throws Exception { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } @Test public void testInitialMemberListener() throws InterruptedException { final HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(); final HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(); final ClientConfig clientConfig = new ClientConfig(); final CountDownLatch latch1 = new CountDownLatch(1); clientConfig.addListenerConfig(new ListenerConfig().setImplementation(new StaticMemberListener(latch1))); final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); assertTrue("Before starting", latch1.await(5, TimeUnit.SECONDS)); final CountDownLatch latch2 = new CountDownLatch(1); client.getCluster().addMembershipListener(new StaticMemberListener(latch2)); assertTrue("After starting", latch2.await(5, TimeUnit.SECONDS)); } static class StaticMemberListener implements MembershipListener, InitialMembershipListener { final CountDownLatch latch; StaticMemberListener(CountDownLatch latch) { this.latch = latch; } public void init(InitialMembershipEvent event) { latch.countDown(); } public void memberAdded(MembershipEvent membershipEvent) { } public void memberRemoved(MembershipEvent membershipEvent) { } public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) { } } @Test public void testClientPortConnection() { final Config config1 = new Config(); config1.getGroupConfig().setName("foo"); config1.getNetworkConfig().setPort(5701); final HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config1); instance1.getMap("map").put("key", "value"); final Config config2 = new Config(); config2.getGroupConfig().setName("bar"); config2.getNetworkConfig().setPort(5702); final HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(config2); final ClientConfig clientConfig = new ClientConfig(); clientConfig.getGroupConfig().setName("bar"); final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); final IMap<Object, Object> map = client.getMap("map"); assertNull(map.put("key", "value")); assertEquals(1, map.size()); } /** * Test for issues #267 and #493 */ @Test public void testIssue493() throws Exception { final HazelcastInstance hz1 = Hazelcast.newHazelcastInstance(); final HazelcastInstance hz2 = Hazelcast.newHazelcastInstance(); ClientConfig clientConfig = new ClientConfig(); clientConfig.setRedoOperation(true); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); final ILock lock = client.getLock("lock"); for (int k = 0; k < 10; k++) { lock.lock(); try { Thread.sleep(100); } finally { lock.unlock(); } } lock.lock(); hz1.shutdown(); lock.unlock(); } @Test @Category(ProblematicTest.class) public void testOperationRedo() throws Exception { final HazelcastInstance hz1 = Hazelcast.newHazelcastInstance(); final HazelcastInstance hz2 = Hazelcast.newHazelcastInstance(); ClientConfig clientConfig = new ClientConfig(); clientConfig.setRedoOperation(true); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); final Thread thread = new Thread() { public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } hz1.getLifecycleService().terminate(); } }; final IMap map = client.getMap("m"); thread.start(); int expected = 1000; for (int i = 0; i < expected; i++) { map.put(i, "item" + i); } thread.join(); assertEquals(expected, map.size()); } @Test public void testOperationRedo_smartRoutingDisabled() throws Exception { final HazelcastInstance hz1 = Hazelcast.newHazelcastInstance(); final HazelcastInstance hz2 = Hazelcast.newHazelcastInstance(); ClientConfig clientConfig = new ClientConfig(); clientConfig.setRedoOperation(true); clientConfig.setSmartRouting(false); HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); final Thread thread = new Thread() { public void run() { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } hz1.getLifecycleService().terminate(); } }; final IMap map = client.getMap("m"); thread.start(); int expected = 1000; for (int i = 0; i < expected; i++) { map.put(i, i); } thread.join(); assertEquals(expected, map.size()); } @Test public void testGetDistributedObjectsIssue678() { final HazelcastInstance hz = Hazelcast.newHazelcastInstance(); hz.getQueue("queue"); hz.getMap("map"); hz.getSemaphore("s"); final HazelcastInstance instance = HazelcastClient.newHazelcastClient(); final Collection<DistributedObject> distributedObjects = instance.getDistributedObjects(); assertEquals(3, distributedObjects.size()); } @Test public void testMapDestroyIssue764() throws Exception { final HazelcastInstance instance = Hazelcast.newHazelcastInstance(); HazelcastInstance client = HazelcastClient.newHazelcastClient(); assertEquals(0, client.getDistributedObjects().size()); IMap map = client.getMap("m"); assertEquals(1, client.getDistributedObjects().size()); map.destroy(); assertEquals(0, instance.getDistributedObjects().size()); assertEquals(0, client.getDistributedObjects().size()); } /** * Client hangs at map.get after shutdown */ @Test public void testIssue821() { final HazelcastInstance instance = Hazelcast.newHazelcastInstance(); final HazelcastInstance client = HazelcastClient.newHazelcastClient(); final IMap<Object, Object> map = client.getMap("default"); map.put("key1", "value1"); instance.shutdown(); try { map.get("key1"); fail(); } catch (HazelcastException ignored) { } assertFalse(instance.getLifecycleService().isRunning()); } @Test public void testClientConnectionEvents() throws InterruptedException { final LinkedList<LifecycleState> list = new LinkedList<LifecycleState>(); list.offer(LifecycleState.STARTING); list.offer(LifecycleState.STARTED); list.offer(LifecycleState.CLIENT_CONNECTED); list.offer(LifecycleState.CLIENT_DISCONNECTED); list.offer(LifecycleState.CLIENT_CONNECTED); final HazelcastInstance instance = Hazelcast.newHazelcastInstance(); final CountDownLatch latch = new CountDownLatch(list.size()); LifecycleListener listener = new LifecycleListener() { public void stateChanged(LifecycleEvent event) { final LifecycleState state = list.poll(); if (state != null && state.equals(event.getState())) { latch.countDown(); } } }; final ListenerConfig listenerConfig = new ListenerConfig(listener); final ClientConfig clientConfig = new ClientConfig(); clientConfig.addListenerConfig(listenerConfig); clientConfig.getNetworkConfig().setConnectionAttemptLimit(100); final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); Thread.sleep(100); instance.shutdown(); Thread.sleep(800); Hazelcast.newHazelcastInstance(); assertTrue(latch.await(10, TimeUnit.SECONDS)); } /** * add membership listener */ @Test public void testIssue1181() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); Hazelcast.newHazelcastInstance(); final ClientConfig clientConfig = new ClientConfig(); clientConfig.addListenerConfig(new ListenerConfig().setImplementation(new InitialMembershipListener() { public void init(InitialMembershipEvent event) { for (int i = 0; i < event.getMembers().size(); i++) { latch.countDown(); } } public void memberAdded(MembershipEvent membershipEvent) { } public void memberRemoved(MembershipEvent membershipEvent) { } public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) { } })); HazelcastClient.newHazelcastClient(clientConfig); assertTrue(latch.await(10, TimeUnit.SECONDS)); } @Test public void testInterceptor() throws InterruptedException { final HazelcastInstance instance = Hazelcast.newHazelcastInstance(); final HazelcastInstance client = HazelcastClient.newHazelcastClient(); final IMap<Object, Object> map = client.getMap("map"); final MapInterceptorImpl interceptor = new MapInterceptorImpl(); final String id = map.addInterceptor(interceptor); assertNotNull(id); map.put("key1", "value"); assertEquals("value", map.get("key1")); map.put("key1", "value1"); assertEquals("getIntercepted", map.get("key1")); assertFalse(map.replace("key1", "getIntercepted", "val")); assertTrue(map.replace("key1", "value1", "val")); assertEquals("val", map.get("key1")); map.put("key2", "oldValue"); assertEquals("oldValue", map.get("key2")); map.put("key2", "newValue"); assertEquals("putIntercepted", map.get("key2")); map.put("key3", "value2"); assertEquals("value2", map.get("key3")); assertEquals("removeIntercepted", map.remove("key3")); } static class MapInterceptorImpl implements MapInterceptor { MapInterceptorImpl() { } public Object interceptGet(Object value) { if ("value1".equals(value)) { return "getIntercepted"; } return null; } public void afterGet(Object value) { } public Object interceptPut(Object oldValue, Object newValue) { if ("oldValue".equals(oldValue) && "newValue".equals(newValue)) { return "putIntercepted"; } return null; } public void afterPut(Object value) { } public Object interceptRemove(Object removedValue) { if ("value2".equals(removedValue)) { return "removeIntercepted"; } return null; } public void afterRemove(Object value) { } } @Test public void testClientPortableWithoutRegisteringToNode() { Hazelcast.newHazelcastInstance(); final SerializationConfig serializationConfig = new SerializationConfig(); serializationConfig.addPortableFactory(5, new PortableFactory() { public Portable create(int classId) { return new SamplePortable(); } }); final ClientConfig clientConfig = new ClientConfig(); clientConfig.setSerializationConfig(serializationConfig); final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); final IMap<Integer, SamplePortable> sampleMap = client.getMap(randomString()); sampleMap.put(1, new SamplePortable(666)); final SamplePortable samplePortable = sampleMap.get(1); assertEquals(666, samplePortable.a); } @Test public void testCredentials() { final Config config = new Config(); config.getGroupConfig().setName("foo").setPassword("bar"); final HazelcastInstance instance = Hazelcast.newHazelcastInstance(config); final ClientConfig clientConfig = new ClientConfig(); final ClientSecurityConfig securityConfig = clientConfig.getSecurityConfig(); securityConfig.setCredentialsClassname(MyCredentials.class.getName()); final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); } public static class MyCredentials extends UsernamePasswordCredentials { public MyCredentials() { super("foo", "bar"); } } public void testListenerReconnect() throws InterruptedException { final HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(); final HazelcastInstance client = HazelcastClient.newHazelcastClient(); final CountDownLatch latch = new CountDownLatch(2); final IMap<Object, Object> m = client.getMap("m"); final String id = m.addEntryListener(new EntryAdapter() { public void entryAdded(EntryEvent event) { latch.countDown(); } @Override public void entryUpdated(EntryEvent event) { latch.countDown(); } }, true); m.put("key1", "value1"); final HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(); instance1.shutdown(); final Thread thread = new Thread() { @Override public void run() { while (!isInterrupted()) { m.put("key2", "value2"); try { Thread.sleep(100); } catch (InterruptedException ignored) { } } } }; thread.start(); assertTrueEventually(new AssertTask() { public void run() { try { assertTrue(latch.await(10, TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } } }); thread.interrupt(); assertTrue(m.removeEntryListener(id)); assertFalse(m.removeEntryListener("foo")); } static class SamplePortable implements Portable { public int a; public SamplePortable(int a) { this.a = a; } public SamplePortable() { } public int getFactoryId() { return 5; } public int getClassId() { return 6; } public void writePortable(PortableWriter writer) throws IOException { writer.writeInt("a", a); } public void readPortable(PortableReader reader) throws IOException { a = reader.readInt("a"); } } @Test public void testNearCache_WhenRegisteredNodeIsDead() { final HazelcastInstance instance = Hazelcast.newHazelcastInstance(); final ClientConfig clientConfig = new ClientConfig(); final String mapName = randomMapName(); NearCacheConfig nearCacheConfig = new NearCacheConfig(); nearCacheConfig.setName(mapName); nearCacheConfig.setInvalidateOnChange(true); clientConfig.addNearCacheConfig(nearCacheConfig); final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); final IMap<Object, Object> map = client.getMap(mapName); map.put("a", "b"); map.get("a"); //put to nearCache instance.shutdown(); Hazelcast.newHazelcastInstance(); assertEquals(null, map.get("a")); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_ClientIssueTest.java
1,392
public static class Builder { private String uuid; private long version; private Settings transientSettings = ImmutableSettings.Builder.EMPTY_SETTINGS; private Settings persistentSettings = ImmutableSettings.Builder.EMPTY_SETTINGS; private final ImmutableOpenMap.Builder<String, IndexMetaData> indices; private final ImmutableOpenMap.Builder<String, IndexTemplateMetaData> templates; private final ImmutableOpenMap.Builder<String, Custom> customs; public Builder() { uuid = "_na_"; indices = ImmutableOpenMap.builder(); templates = ImmutableOpenMap.builder(); customs = ImmutableOpenMap.builder(); } public Builder(MetaData metaData) { this.uuid = metaData.uuid; this.transientSettings = metaData.transientSettings; this.persistentSettings = metaData.persistentSettings; this.version = metaData.version; this.indices = ImmutableOpenMap.builder(metaData.indices); this.templates = ImmutableOpenMap.builder(metaData.templates); this.customs = ImmutableOpenMap.builder(metaData.customs); } public Builder put(IndexMetaData.Builder indexMetaDataBuilder) { // we know its a new one, increment the version and store indexMetaDataBuilder.version(indexMetaDataBuilder.version() + 1); IndexMetaData indexMetaData = indexMetaDataBuilder.build(); indices.put(indexMetaData.index(), indexMetaData); return this; } public Builder put(IndexMetaData indexMetaData, boolean incrementVersion) { if (indices.get(indexMetaData.index()) == indexMetaData) { return this; } // if we put a new index metadata, increment its version if (incrementVersion) { indexMetaData = IndexMetaData.builder(indexMetaData).version(indexMetaData.version() + 1).build(); } indices.put(indexMetaData.index(), indexMetaData); return this; } public IndexMetaData get(String index) { return indices.get(index); } public Builder remove(String index) { indices.remove(index); return this; } public Builder removeAllIndices() { indices.clear(); return this; } public Builder put(IndexTemplateMetaData.Builder template) { return put(template.build()); } public Builder put(IndexTemplateMetaData template) { templates.put(template.name(), template); return this; } public Builder removeTemplate(String templateName) { templates.remove(templateName); return this; } public Custom getCustom(String type) { return customs.get(type); } public Builder putCustom(String type, Custom custom) { customs.put(type, custom); return this; } public Builder removeCustom(String type) { customs.remove(type); return this; } public Builder updateSettings(Settings settings, String... indices) { if (indices == null || indices.length == 0) { indices = this.indices.keys().toArray(String.class); } for (String index : indices) { IndexMetaData indexMetaData = this.indices.get(index); if (indexMetaData == null) { throw new IndexMissingException(new Index(index)); } put(IndexMetaData.builder(indexMetaData) .settings(settingsBuilder().put(indexMetaData.settings()).put(settings))); } return this; } public Builder updateNumberOfReplicas(int numberOfReplicas, String... indices) { if (indices == null || indices.length == 0) { indices = this.indices.keys().toArray(String.class); } for (String index : indices) { IndexMetaData indexMetaData = this.indices.get(index); if (indexMetaData == null) { throw new IndexMissingException(new Index(index)); } put(IndexMetaData.builder(indexMetaData).numberOfReplicas(numberOfReplicas)); } return this; } public Settings transientSettings() { return this.transientSettings; } public Builder transientSettings(Settings settings) { this.transientSettings = settings; return this; } public Settings persistentSettings() { return this.persistentSettings; } public Builder persistentSettings(Settings settings) { this.persistentSettings = settings; return this; } public Builder version(long version) { this.version = version; return this; } public Builder generateUuidIfNeeded() { if (uuid.equals("_na_")) { uuid = Strings.randomBase64UUID(); } return this; } public MetaData build() { return new MetaData(uuid, version, transientSettings, persistentSettings, indices.build(), templates.build(), customs.build()); } public static String toXContent(MetaData metaData) throws IOException { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); builder.startObject(); toXContent(metaData, builder, ToXContent.EMPTY_PARAMS); builder.endObject(); return builder.string(); } public static void toXContent(MetaData metaData, XContentBuilder builder, ToXContent.Params params) throws IOException { boolean globalPersistentOnly = params.paramAsBoolean(GLOBAL_PERSISTENT_ONLY_PARAM, false); builder.startObject("meta-data"); builder.field("version", metaData.version()); builder.field("uuid", metaData.uuid); if (!metaData.persistentSettings().getAsMap().isEmpty()) { builder.startObject("settings"); for (Map.Entry<String, String> entry : metaData.persistentSettings().getAsMap().entrySet()) { builder.field(entry.getKey(), entry.getValue()); } builder.endObject(); } if (!globalPersistentOnly && !metaData.transientSettings().getAsMap().isEmpty()) { builder.startObject("transient_settings"); for (Map.Entry<String, String> entry : metaData.transientSettings().getAsMap().entrySet()) { builder.field(entry.getKey(), entry.getValue()); } builder.endObject(); } builder.startObject("templates"); for (ObjectCursor<IndexTemplateMetaData> cursor : metaData.templates().values()) { IndexTemplateMetaData.Builder.toXContent(cursor.value, builder, params); } builder.endObject(); if (!globalPersistentOnly && !metaData.indices().isEmpty()) { builder.startObject("indices"); for (IndexMetaData indexMetaData : metaData) { IndexMetaData.Builder.toXContent(indexMetaData, builder, params); } builder.endObject(); } for (ObjectObjectCursor<String, Custom> cursor : metaData.customs()) { Custom.Factory factory = lookupFactorySafe(cursor.key); if (!globalPersistentOnly || factory.isPersistent()) { builder.startObject(cursor.key); factory.toXContent(cursor.value, builder, params); builder.endObject(); } } builder.endObject(); } public static MetaData fromXContent(XContentParser parser) throws IOException { Builder builder = new Builder(); // we might get here after the meta-data element, or on a fresh parser XContentParser.Token token = parser.currentToken(); String currentFieldName = parser.currentName(); if (!"meta-data".equals(currentFieldName)) { token = parser.nextToken(); if (token == XContentParser.Token.START_OBJECT) { // move to the field name (meta-data) token = parser.nextToken(); // move to the next object token = parser.nextToken(); } currentFieldName = parser.currentName(); if (token == null) { // no data... return builder.build(); } } while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { if ("settings".equals(currentFieldName)) { builder.persistentSettings(ImmutableSettings.settingsBuilder().put(SettingsLoader.Helper.loadNestedFromMap(parser.mapOrdered())).build()); } else if ("indices".equals(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { builder.put(IndexMetaData.Builder.fromXContent(parser), false); } } else if ("templates".equals(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { builder.put(IndexTemplateMetaData.Builder.fromXContent(parser)); } } else { // check if its a custom index metadata Custom.Factory<Custom> factory = lookupFactory(currentFieldName); if (factory == null) { //TODO warn parser.skipChildren(); } else { builder.putCustom(factory.type(), factory.fromXContent(parser)); } } } else if (token.isValue()) { if ("version".equals(currentFieldName)) { builder.version = parser.longValue(); } else if ("uuid".equals(currentFieldName)) { builder.uuid = parser.text(); } } } return builder.build(); } public static MetaData readFrom(StreamInput in) throws IOException { Builder builder = new Builder(); builder.version = in.readLong(); builder.uuid = in.readString(); builder.transientSettings(readSettingsFromStream(in)); builder.persistentSettings(readSettingsFromStream(in)); int size = in.readVInt(); for (int i = 0; i < size; i++) { builder.put(IndexMetaData.Builder.readFrom(in), false); } size = in.readVInt(); for (int i = 0; i < size; i++) { builder.put(IndexTemplateMetaData.Builder.readFrom(in)); } int customSize = in.readVInt(); for (int i = 0; i < customSize; i++) { String type = in.readString(); Custom customIndexMetaData = lookupFactorySafe(type).readFrom(in); builder.putCustom(type, customIndexMetaData); } return builder.build(); } public static void writeTo(MetaData metaData, StreamOutput out) throws IOException { out.writeLong(metaData.version); out.writeString(metaData.uuid); writeSettingsToStream(metaData.transientSettings(), out); writeSettingsToStream(metaData.persistentSettings(), out); out.writeVInt(metaData.indices.size()); for (IndexMetaData indexMetaData : metaData) { IndexMetaData.Builder.writeTo(indexMetaData, out); } out.writeVInt(metaData.templates.size()); for (ObjectCursor<IndexTemplateMetaData> cursor : metaData.templates.values()) { IndexTemplateMetaData.Builder.writeTo(cursor.value, out); } out.writeVInt(metaData.customs().size()); for (ObjectObjectCursor<String, Custom> cursor : metaData.customs()) { out.writeString(cursor.key); lookupFactorySafe(cursor.key).writeTo(cursor.value, out); } } }
1no label
src_main_java_org_elasticsearch_cluster_metadata_MetaData.java
3,583
private static class MessageListenerImpl implements MessageListener { private final ClientEndpoint endpoint; private final ClientEngine clientEngine; private final int callId; public MessageListenerImpl(ClientEndpoint endpoint, ClientEngine clientEngine, int callId) { this.endpoint = endpoint; this.clientEngine = clientEngine; this.callId = callId; } @Override public void onMessage(Message message) { if (!endpoint.live()) { return; } Data messageData = clientEngine.toData(message.getMessageObject()); String publisherUuid = message.getPublishingMember().getUuid(); PortableMessage portableMessage = new PortableMessage(messageData, message.getPublishTime(), publisherUuid); endpoint.sendEvent(portableMessage, callId); } }
1no label
hazelcast_src_main_java_com_hazelcast_topic_client_AddMessageListenerRequest.java
1,011
private class ShardTransportHandler extends BaseTransportRequestHandler<ShardSingleOperationRequest> { @Override public ShardSingleOperationRequest newInstance() { return new ShardSingleOperationRequest(); } @Override public String executor() { return executor; } @Override public void messageReceived(final ShardSingleOperationRequest request, final TransportChannel channel) throws Exception { Response response = shardOperation(request.request(), request.shardId()); channel.sendResponse(response); } }
0true
src_main_java_org_elasticsearch_action_support_single_custom_TransportSingleCustomOperationAction.java
1,813
@Component("blBasicFieldPersistenceProvider") @Scope("prototype") public class BasicFieldPersistenceProvider extends FieldPersistenceProviderAdapter { protected static final Log LOG = LogFactory.getLog(BasicFieldPersistenceProvider.class); protected boolean canHandlePersistence(PopulateValueRequest populateValueRequest, Serializable instance) { BasicFieldMetadata metadata = populateValueRequest.getMetadata(); Property property = populateValueRequest.getProperty(); //don't handle map fields here - we'll get them in a separate provider boolean response = detectBasicType(metadata, property); if (!response) { //we'll allow this provider to handle money filter mapping for persistence response = metadata.getFieldType() == SupportedFieldType.MONEY; } return response; } protected boolean detectBasicType(BasicFieldMetadata metadata, Property property) { return (metadata.getFieldType() == SupportedFieldType.BOOLEAN || metadata.getFieldType() == SupportedFieldType.DATE || metadata.getFieldType() == SupportedFieldType.INTEGER || metadata.getFieldType() == SupportedFieldType.DECIMAL || metadata.getFieldType() == SupportedFieldType.EMAIL || metadata.getFieldType() == SupportedFieldType.FOREIGN_KEY || metadata.getFieldType() == SupportedFieldType.ADDITIONAL_FOREIGN_KEY || metadata.getFieldType() == SupportedFieldType.STRING || metadata.getFieldType() == SupportedFieldType.ID) && (property == null || !property.getName().contains(FieldManager.MAPFIELDSEPARATOR)); } protected boolean detectAdditionalSearchTypes(BasicFieldMetadata metadata, Property property) { return (metadata.getFieldType() == SupportedFieldType.BROADLEAF_ENUMERATION || metadata.getFieldType() == SupportedFieldType.EXPLICIT_ENUMERATION || metadata.getFieldType() == SupportedFieldType.DATA_DRIVEN_ENUMERATION) && (property == null || !property.getName().contains(FieldManager.MAPFIELDSEPARATOR)); } protected boolean canHandleExtraction(ExtractValueRequest extractValueRequest, Property property) { BasicFieldMetadata metadata = extractValueRequest.getMetadata(); //don't handle map fields here - we'll get them in a separate provider return detectBasicType(metadata, property); } protected boolean canHandleSearchMapping(AddSearchMappingRequest addSearchMappingRequest, List<FilterMapping> filterMappings) { BasicFieldMetadata metadata = (BasicFieldMetadata) addSearchMappingRequest.getMergedProperties().get(addSearchMappingRequest.getPropertyName()); Property property = null; //don't handle map fields here - we'll get them in a separate provider boolean response = detectBasicType(metadata, property) || detectAdditionalSearchTypes(metadata, property); if (!response) { //we'll allow this provider to handle money filter mapping for searches response = metadata.getFieldType() == SupportedFieldType.MONEY; } return response; } @Override public FieldProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) { if (!canHandlePersistence(populateValueRequest, instance)) { return FieldProviderResponse.NOT_HANDLED; } try { switch (populateValueRequest.getMetadata().getFieldType()) { case BOOLEAN: boolean v = Boolean.valueOf(populateValueRequest.getRequestedValue()); try { populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), v); } catch (IllegalArgumentException e) { char c = v ? 'Y' : 'N'; populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), c); } break; case DATE: populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), populateValueRequest.getDataFormatProvider().getSimpleDateFormatter().parse(populateValueRequest.getRequestedValue())); break; case DECIMAL: if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType())) { populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), new BigDecimal(populateValueRequest.getRequestedValue())); } else { populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), new Double(populateValueRequest.getRequestedValue())); } break; case MONEY: if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType())) { populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), new BigDecimal(populateValueRequest.getRequestedValue())); } else if (Double.class.isAssignableFrom(populateValueRequest.getReturnType())) { LOG.warn("The requested Money field is of type double and could result in a loss of precision." + " Broadleaf recommends that the type of all Money fields are 'BigDecimal' in order to avoid" + " this loss of precision that could occur."); populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), new Double(populateValueRequest.getRequestedValue())); } else { populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), new Money(new BigDecimal(populateValueRequest.getRequestedValue()))); } break; case INTEGER: if (int.class.isAssignableFrom(populateValueRequest.getReturnType()) || Integer.class.isAssignableFrom(populateValueRequest.getReturnType())) { populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Integer.valueOf(populateValueRequest.getRequestedValue())); } else if (byte.class.isAssignableFrom(populateValueRequest.getReturnType()) || Byte.class.isAssignableFrom(populateValueRequest.getReturnType())) { populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Byte.valueOf(populateValueRequest.getRequestedValue())); } else if (short.class.isAssignableFrom(populateValueRequest.getReturnType()) || Short.class.isAssignableFrom(populateValueRequest.getReturnType())) { populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Short.valueOf(populateValueRequest.getRequestedValue())); } else if (long.class.isAssignableFrom(populateValueRequest.getReturnType()) || Long.class.isAssignableFrom(populateValueRequest.getReturnType())) { populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Long.valueOf(populateValueRequest.getRequestedValue())); } break; case STRING: case EMAIL: populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), populateValueRequest.getRequestedValue()); break; case FOREIGN_KEY: { Serializable foreignInstance; if (StringUtils.isEmpty(populateValueRequest.getRequestedValue())) { foreignInstance = null; } else { if (SupportedFieldType.INTEGER.toString().equals(populateValueRequest.getMetadata().getSecondaryType().toString())) { foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao().retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()), Long.valueOf(populateValueRequest.getRequestedValue())); } else { foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao().retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()), populateValueRequest.getRequestedValue()); } } if (Collection.class.isAssignableFrom(populateValueRequest.getReturnType())) { Collection collection; try { collection = (Collection) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName()); } catch (FieldNotAvailableException e) { throw new IllegalArgumentException(e); } if (!collection.contains(foreignInstance)) { collection.add(foreignInstance); } } else if (Map.class.isAssignableFrom(populateValueRequest.getReturnType())) { throw new IllegalArgumentException("Map structures are not supported for foreign key fields."); } else { populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), foreignInstance); } break; } case ADDITIONAL_FOREIGN_KEY: { Serializable foreignInstance; if (StringUtils.isEmpty(populateValueRequest.getRequestedValue())) { foreignInstance = null; } else { if (SupportedFieldType.INTEGER.toString().equals(populateValueRequest.getMetadata().getSecondaryType().toString())) { foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao().retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()), Long.valueOf(populateValueRequest.getRequestedValue())); } else { foreignInstance = populateValueRequest.getPersistenceManager().getDynamicEntityDao().retrieve(Class.forName(populateValueRequest.getMetadata().getForeignKeyClass()), populateValueRequest.getRequestedValue()); } } if (Collection.class.isAssignableFrom(populateValueRequest.getReturnType())) { Collection collection; try { collection = (Collection) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName()); } catch (FieldNotAvailableException e) { throw new IllegalArgumentException(e); } if (!collection.contains(foreignInstance)) { collection.add(foreignInstance); } } else if (Map.class.isAssignableFrom(populateValueRequest.getReturnType())) { throw new IllegalArgumentException("Map structures are not supported for foreign key fields."); } else { populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), foreignInstance); } break; } case ID: if (populateValueRequest.getSetId()) { switch (populateValueRequest.getMetadata().getSecondaryType()) { case INTEGER: populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), Long.valueOf(populateValueRequest.getRequestedValue())); break; case STRING: populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), populateValueRequest.getRequestedValue()); break; } } break; } } catch (Exception e) { throw new PersistenceException(e); } return FieldProviderResponse.HANDLED; } @Override public FieldProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException { if (!canHandleExtraction(extractValueRequest, property)) { return FieldProviderResponse.NOT_HANDLED; } try { if (extractValueRequest.getRequestedValue() != null) { String val = null; if (extractValueRequest.getMetadata().getForeignKeyCollection()) { ((BasicFieldMetadata) property.getMetadata()).setFieldType(extractValueRequest.getMetadata().getFieldType()); } else if (extractValueRequest.getMetadata().getFieldType().equals(SupportedFieldType.BOOLEAN) && extractValueRequest.getRequestedValue() instanceof Character) { val = (extractValueRequest.getRequestedValue().equals('Y')) ? "true" : "false"; } else if (Date.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) { val = extractValueRequest.getDataFormatProvider().getSimpleDateFormatter ().format((Date) extractValueRequest.getRequestedValue()); } else if (Timestamp.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) { val = extractValueRequest.getDataFormatProvider().getSimpleDateFormatter ().format(new Date(((Timestamp) extractValueRequest.getRequestedValue()).getTime())); } else if (Calendar.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) { val = extractValueRequest.getDataFormatProvider().getSimpleDateFormatter ().format(((Calendar) extractValueRequest.getRequestedValue()).getTime()); } else if (Double.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) { val = extractValueRequest.getDataFormatProvider().getDecimalFormatter().format(extractValueRequest.getRequestedValue()); } else if (BigDecimal.class.isAssignableFrom(extractValueRequest.getRequestedValue().getClass())) { val = extractValueRequest.getDataFormatProvider().getDecimalFormatter().format(extractValueRequest.getRequestedValue()); } else if (extractValueRequest.getMetadata().getForeignKeyClass() != null) { try { val = extractValueRequest.getFieldManager().getFieldValue (extractValueRequest.getRequestedValue(), extractValueRequest.getMetadata().getForeignKeyProperty()).toString(); //see if there's a name property and use it for the display value String entityName = null; if (extractValueRequest.getRequestedValue() instanceof AdminMainEntity) { entityName = ((AdminMainEntity) extractValueRequest.getRequestedValue()).getMainEntityName(); } Object temp = null; if (!StringUtils.isEmpty(extractValueRequest.getMetadata().getForeignKeyDisplayValueProperty())) { String nameProperty = extractValueRequest.getMetadata().getForeignKeyDisplayValueProperty(); try { temp = extractValueRequest.getFieldManager().getFieldValue(extractValueRequest.getRequestedValue(), nameProperty); } catch (FieldNotAvailableException e) { //do nothing } } if (temp == null && StringUtils.isEmpty(entityName)) { try { temp = extractValueRequest.getFieldManager().getFieldValue(extractValueRequest.getRequestedValue(), "name"); } catch (FieldNotAvailableException e) { //do nothing } } if (temp != null) { extractValueRequest.setDisplayVal(temp.toString()); } else if (!StringUtils.isEmpty(entityName)) { extractValueRequest.setDisplayVal(entityName); } } catch (FieldNotAvailableException e) { throw new IllegalArgumentException(e); } } else { val = extractValueRequest.getRequestedValue().toString(); } property.setValue(val); property.setDisplayValue(extractValueRequest.getDisplayVal()); } } catch (IllegalAccessException e) { throw new PersistenceException(e); } return FieldProviderResponse.HANDLED; } @Override public FieldProviderResponse addSearchMapping(AddSearchMappingRequest addSearchMappingRequest, List<FilterMapping> filterMappings) { if (!canHandleSearchMapping(addSearchMappingRequest, filterMappings)) { return FieldProviderResponse.NOT_HANDLED; } Class clazz; try { clazz = Class.forName(addSearchMappingRequest.getMergedProperties().get(addSearchMappingRequest .getPropertyName()).getInheritedFromType()); } catch (ClassNotFoundException e) { throw new PersistenceException(e); } Field field = addSearchMappingRequest.getFieldManager().getField(clazz, addSearchMappingRequest.getPropertyName()); Class<?> targetType = null; if (field != null) { targetType = field.getType(); } BasicFieldMetadata metadata = (BasicFieldMetadata) addSearchMappingRequest.getMergedProperties().get (addSearchMappingRequest.getPropertyName()); FilterAndSortCriteria fasc = addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()); FilterMapping filterMapping = new FilterMapping() .withInheritedFromClass(clazz) .withFullPropertyName(addSearchMappingRequest.getPropertyName()) .withFilterValues(fasc.getFilterValues()) .withSortDirection(fasc.getSortDirection()); filterMappings.add(filterMapping); if (fasc.hasSpecialFilterValue()) { filterMapping.setDirectFilterValues(new EmptyFilterValues()); // Handle special values on a case by case basis List<String> specialValues = fasc.getSpecialFilterValues(); if (specialValues.contains(FilterAndSortCriteria.IS_NULL_FILTER_VALUE)) { filterMapping.setRestriction(new Restriction().withPredicateProvider(new IsNullPredicateProvider())); } } else { switch (metadata.getFieldType()) { case BOOLEAN: if (targetType == null || targetType.equals(Boolean.class) || targetType.equals(boolean.class)) { filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.BOOLEAN.getType(), addSearchMappingRequest.getPropertyName())); } else { filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.CHARACTER.getType(), addSearchMappingRequest.getPropertyName())); } break; case DATE: filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.DATE.getType(), addSearchMappingRequest.getPropertyName())); break; case DECIMAL: case MONEY: filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.DECIMAL.getType(), addSearchMappingRequest.getPropertyName())); break; case INTEGER: filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG.getType(), addSearchMappingRequest.getPropertyName())); break; case BROADLEAF_ENUMERATION: filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_EQUAL.getType(), addSearchMappingRequest.getPropertyName())); break; default: filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_LIKE.getType(), addSearchMappingRequest.getPropertyName())); break; case FOREIGN_KEY: if (!addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()).getFilterValues().isEmpty()) { ForeignKey foreignKey = (ForeignKey) addSearchMappingRequest.getPersistencePerspective().getPersistencePerspectiveItems().get (PersistencePerspectiveItemType.FOREIGNKEY); if (metadata.getForeignKeyCollection()) { if (ForeignKeyRestrictionType.COLLECTION_SIZE_EQ.toString().equals(foreignKey .getRestrictionType().toString())) { filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory() .getRestriction(RestrictionType.COLLECTION_SIZE_EQUAL.getType(), addSearchMappingRequest.getPropertyName())); filterMapping.setFieldPath(new FieldPath()); } else { filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG.getType(), addSearchMappingRequest.getPropertyName())); filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty())); } } else if (addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()) .getFilterValues().get(0) == null || "null".equals(addSearchMappingRequest.getRequestedCto().get (addSearchMappingRequest.getPropertyName()).getFilterValues().get(0))) { filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.IS_NULL_LONG.getType(), addSearchMappingRequest.getPropertyName())); } else if (metadata.getSecondaryType() == SupportedFieldType.STRING) { filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_EQUAL.getType(), addSearchMappingRequest.getPropertyName())); filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty())); } else { filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG_EQUAL.getType(), addSearchMappingRequest.getPropertyName())); filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty())); } } break; case ADDITIONAL_FOREIGN_KEY: int additionalForeignKeyIndexPosition = Arrays.binarySearch(addSearchMappingRequest .getPersistencePerspective() .getAdditionalForeignKeys(), new ForeignKey(addSearchMappingRequest.getPropertyName(), null, null), new Comparator<ForeignKey>() { @Override public int compare(ForeignKey o1, ForeignKey o2) { return o1.getManyToField().compareTo(o2.getManyToField()); } }); ForeignKey foreignKey = null; if (additionalForeignKeyIndexPosition >= 0) { foreignKey = addSearchMappingRequest.getPersistencePerspective().getAdditionalForeignKeys()[additionalForeignKeyIndexPosition]; } // in the case of a to-one lookup, an explicit ForeignKey is not passed in. The system should then // default to just using a ForeignKeyRestrictionType.ID_EQ if (metadata.getForeignKeyCollection()) { if (ForeignKeyRestrictionType.COLLECTION_SIZE_EQ.toString().equals(foreignKey .getRestrictionType().toString())) { filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory() .getRestriction(RestrictionType.COLLECTION_SIZE_EQUAL.getType(), addSearchMappingRequest.getPropertyName())); filterMapping.setFieldPath(new FieldPath()); } else { filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG.getType(), addSearchMappingRequest.getPropertyName())); filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty())); } } else if (CollectionUtils.isEmpty(addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()).getFilterValues()) || addSearchMappingRequest.getRequestedCto().get(addSearchMappingRequest.getPropertyName()) .getFilterValues().get(0) == null || "null".equals(addSearchMappingRequest.getRequestedCto().get (addSearchMappingRequest.getPropertyName()).getFilterValues().get(0))) { filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.IS_NULL_LONG.getType(), addSearchMappingRequest.getPropertyName())); } else if (metadata.getSecondaryType() == SupportedFieldType.STRING) { filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_EQUAL.getType(), addSearchMappingRequest.getPropertyName())); filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty())); } else { filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG_EQUAL.getType(), addSearchMappingRequest.getPropertyName())); filterMapping.setFieldPath(new FieldPath().withTargetProperty(addSearchMappingRequest.getPropertyName() + "." + metadata.getForeignKeyProperty())); } break; case ID: switch (metadata.getSecondaryType()) { case INTEGER: filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.LONG_EQUAL.getType(), addSearchMappingRequest.getPropertyName())); break; case STRING: filterMapping.setRestriction(addSearchMappingRequest.getRestrictionFactory().getRestriction(RestrictionType.STRING_EQUAL.getType(), addSearchMappingRequest.getPropertyName())); break; } break; } } return FieldProviderResponse.HANDLED; } @Override public int getOrder() { return FieldPersistenceProvider.BASIC; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_provider_BasicFieldPersistenceProvider.java
3,233
public static class Longs extends ScriptDocValues { private final LongValues values; private final MutableDateTime date = new MutableDateTime(0, DateTimeZone.UTC); private final SlicedLongList list; public Longs(LongValues values) { this.values = values; this.list = new SlicedLongList(values.isMultiValued() ? 10 : 1); } public LongValues getInternalValues() { return this.values; } @Override public boolean isEmpty() { return values.setDocument(docId) == 0; } public long getValue() { int numValues = values.setDocument(docId); if (numValues == 0) { return 0l; } return values.nextValue(); } public List<Long> getValues() { if (!listLoaded) { final int numValues = values.setDocument(docId); list.offset = 0; list.grow(numValues); list.length = numValues; for (int i = 0; i < numValues; i++) { list.values[i] = values.nextValue(); } listLoaded = true; } return list; } public MutableDateTime getDate() { date.setMillis(getValue()); return date; } }
0true
src_main_java_org_elasticsearch_index_fielddata_ScriptDocValues.java
524
@Deprecated public class BLResourceBundleMessageSource extends ResourceBundleMessageSource implements InitializingBean { private static final Log LOG = LogFactory.getLog(BLResourceBundleMessageSource.class); public BLResourceBundleMessageSource(String[] basenames, ResourceBundleExtensionPoint resourceBundleExtensionPoint) { super(); List<String> bundles = new ArrayList<String>(); if (resourceBundleExtensionPoint != null) { String[] bundleNames = resourceBundleExtensionPoint.getBasenameExtensions(); if (bundleNames != null) { for (int i = 0; i < bundleNames.length; i++) { bundles.add(bundleNames[i]); } } if (basenames != null) { for (int i = 0; i < basenames.length; i++) { bundles.add(basenames[i]); } } } setBasenames(bundles.toArray(new String[0])); } @Override public void afterPropertiesSet() throws Exception { LOG.fatal("***INCORRECT CONFIGURATION***\n" + "This class should no longer be used as it does not merge property files together. If this is being used\n" + "in the admin application then this configuration is definitely an error as no properties will be resolved.\n" + "It is possible that the frontend application is not seriously effected by using this class but you should\n" + "modify your configuration to instead use org.broadleafcommerce.common.util.BroadleafMergeResourceBundleMessageSource\n" + "instead as soon as possible."); } }
0true
common_src_main_java_org_broadleafcommerce_common_util_BLResourceBundleMessageSource.java
1,097
public class QueueStoreConfig { private boolean enabled = true; private String className = null; private String factoryClassName = null; private Properties properties = new Properties(); private QueueStore storeImplementation; private QueueStoreFactory factoryImplementation; private QueueStoreConfigReadOnly readOnly; public QueueStoreConfig() { } public QueueStoreConfig(QueueStoreConfig config) { enabled = config.isEnabled(); className = config.getClassName(); storeImplementation = config.getStoreImplementation(); factoryClassName = config.getFactoryClassName(); factoryImplementation = config.getFactoryImplementation(); properties.putAll(config.getProperties()); } public QueueStore getStoreImplementation() { return storeImplementation; } public QueueStoreConfig setStoreImplementation(QueueStore storeImplementation) { this.storeImplementation = storeImplementation; return this; } public QueueStoreConfigReadOnly getAsReadOnly() { if (readOnly == null){ readOnly = new QueueStoreConfigReadOnly(this); } return readOnly; } public boolean isEnabled() { return enabled; } public QueueStoreConfig setEnabled(boolean enabled) { this.enabled = enabled; return this; } public String getClassName() { return className; } public QueueStoreConfig setClassName(String className) { this.className = className; return this; } public Properties getProperties() { return properties; } public QueueStoreConfig setProperties(Properties properties) { ValidationUtil.isNotNull(properties, "properties"); this.properties = properties; return this; } public String getProperty(String name){ return properties.getProperty(name); } public QueueStoreConfig setProperty(String name, String value){ properties.put(name, value); return this; } public String getFactoryClassName() { return factoryClassName; } public QueueStoreConfig setFactoryClassName(String factoryClassName) { this.factoryClassName = factoryClassName; return this; } public QueueStoreFactory getFactoryImplementation() { return factoryImplementation; } public QueueStoreConfig setFactoryImplementation(QueueStoreFactory factoryImplementation) { this.factoryImplementation = factoryImplementation; return this; } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("QueueStoreConfig"); sb.append("{enabled=").append(enabled); sb.append(", className='").append(className).append('\''); sb.append(", properties=").append(properties); sb.append('}'); return sb.toString(); } }
0true
hazelcast_src_main_java_com_hazelcast_config_QueueStoreConfig.java
2,755
public abstract class HttpRequest extends RestRequest { }
0true
src_main_java_org_elasticsearch_http_HttpRequest.java
189
FakeXAResource externalResource = new FakeXAResource("BananaStorageFacility"){ @Override public void rollback( Xid xid ) { super.rollback(xid); externalResourceWasRolledBack.set( true ); } };
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_UseJOTMAsTxManagerIT.java
1,150
public interface ExecutionCallback<V> { /** * Called when an execution is completed successfully. * * @param response result of execution */ void onResponse(V response); /** * Called when an execution is completed with an error. * @param t exception thrown */ void onFailure(Throwable t); }
0true
hazelcast_src_main_java_com_hazelcast_core_ExecutionCallback.java
594
public class LogStatusHandler implements StatusHandler { private static final Log LOG = LogFactory.getLog(LogStatusHandler.class); public void handleStatus(String serviceName, ServiceStatusType status) { if (status.equals(ServiceStatusType.DOWN)) { LOG.error(serviceName + " is reporting a status of DOWN"); } else if (status.equals(ServiceStatusType.PAUSED)) { LOG.warn(serviceName + " is reporting a status of PAUSED"); } else { LOG.info(serviceName + " is reporting a status of UP"); } } }
0true
common_src_main_java_org_broadleafcommerce_common_vendor_service_monitor_handler_LogStatusHandler.java
1,764
map.addEntryListener(new EntryAdapter<Object, Object>() { public void entryEvicted(EntryEvent event) { latch.countDown(); } }, false);
0true
hazelcast_src_test_java_com_hazelcast_map_EvictionTest.java
237
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class ClientExecutorServiceSubmitTest { 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 = NullPointerException.class) public void testSubmitCallableNullTask() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); Callable callable = null; final Future<String> f = service.submit(callable); } @Test public void testSubmitCallableToMember() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final Callable getUuidCallable = new GetMemberUuidTask(); final Member member = instance2.getCluster().getLocalMember(); final Future<String> result = service.submitToMember(getUuidCallable, member); assertEquals(member.getUuid(), result.get()); } @Test public void testSubmitCallableToMembers() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final Callable getUuidCallable = new GetMemberUuidTask(); final Collection collection = instance2.getCluster().getMembers(); final Map<Member, Future<String>> map = service.submitToMembers(getUuidCallable, collection); for (Member member : map.keySet()) { final Future<String> result = map.get(member); String uuid = result.get(); assertEquals(member.getUuid(), uuid); } } @Test public void testSubmitCallable_withMemberSelector() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final String msg = randomString(); final Callable callable = new AppendCallable(msg); final MemberSelector selectAll = new SelectAllMembers(); final Future<String> f = service.submit(callable, selectAll); assertEquals(msg + AppendCallable.APPENDAGE, f.get()); } @Test public void testSubmitCallableToMembers_withMemberSelector() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final Callable getUuidCallable = new GetMemberUuidTask(); final MemberSelector selectAll = new SelectAllMembers(); final Map<Member, Future<String>> map = service.submitToMembers(getUuidCallable, selectAll); for (Member member : map.keySet()) { final Future<String> result = map.get(member); String uuid = result.get(); assertEquals(member.getUuid(), uuid); } } @Test public void submitCallableToAllMembers() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final String msg = randomString(); final Callable callable = new AppendCallable(msg); final Map<Member, Future<String>> map = service.submitToAllMembers(callable); for (Member member : map.keySet()) { final Future<String> result = map.get(member); assertEquals(msg + AppendCallable.APPENDAGE, result.get()); } } @Test public void submitRunnableToMember_withExecutionCallback() { final IExecutorService service = client.getExecutorService(randomString()); final String mapName = randomString(); final Runnable runnable = new MapPutRunnable(mapName); final Member member = instance2.getCluster().getLocalMember(); final CountDownLatch responseLatch = new CountDownLatch(1); service.submitToMember(runnable, member, new ExecutionCallback() { public void onResponse(Object response) { responseLatch.countDown(); } public void onFailure(Throwable t) { } }); Map map = client.getMap(mapName); assertOpenEventually(responseLatch); assertEquals(1, map.size()); } @Test public void submitRunnableToMembers_withMultiExecutionCallback() { final IExecutorService service = client.getExecutorService(randomString()); final String mapName = randomString(); final Runnable runnable = new MapPutRunnable(mapName); final Collection collection = instance2.getCluster().getMembers(); final CountDownLatch responseLatch = new CountDownLatch(CLUSTER_SIZE); final CountDownLatch completeLatch = new CountDownLatch(1); service.submitToMembers(runnable, collection, new MultiExecutionCallback() { public void onResponse(Member member, Object value) { responseLatch.countDown(); } public void onComplete(Map<Member, Object> values) { completeLatch.countDown(); } }); Map map = client.getMap(mapName); assertOpenEventually(responseLatch); assertOpenEventually(completeLatch); assertEquals(CLUSTER_SIZE, map.size()); } @Test public void testSubmitCallableToMember_withExecutionCallback() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final Callable getUuidCallable = new GetMemberUuidTask(); final Member member = instance2.getCluster().getLocalMember(); final CountDownLatch responseLatch = new CountDownLatch(1); final AtomicReference<Object> result = new AtomicReference<Object>(); service.submitToMember(getUuidCallable, member, new ExecutionCallback() { @Override public void onResponse(Object response) { result.set(response); responseLatch.countDown(); } @Override public void onFailure(Throwable t) { } }); assertOpenEventually(responseLatch); assertEquals(member.getUuid(), result.get()); } /** * fails randomly. * Example stack trace is here: * https://hazelcast-l337.ci.cloudbees.com/job/Hazelcast-3.x-OpenJDK7/com.hazelcast$hazelcast-client/133/testReport/com.hazelcast.client.executor/ClientExecutorServiceSubmitTest/submitCallableToMember_withMultiExecutionCallback/ */ @Test @Category(ProblematicTest.class) public void submitCallableToMember_withMultiExecutionCallback() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final CountDownLatch responseLatch = new CountDownLatch(CLUSTER_SIZE); final CountDownLatch completeLatch = new CountDownLatch(CLUSTER_SIZE); final String msg = randomString(); final Callable callable = new AppendCallable(msg); final Collection collection = instance2.getCluster().getMembers(); service.submitToMembers(callable, collection, new MultiExecutionCallback() { public void onResponse(Member member, Object value) { if (value.equals(msg + AppendCallable.APPENDAGE)) { responseLatch.countDown(); } } public void onComplete(Map<Member, Object> values) { for (Member member : values.keySet()) { Object value = values.get(member); if (value.equals(msg + AppendCallable.APPENDAGE)) { completeLatch.countDown(); } } } }); assertOpenEventually(responseLatch); assertOpenEventually(completeLatch); } @Test public void submitRunnable_withExecutionCallback() { final IExecutorService service = client.getExecutorService(randomString()); final CountDownLatch responseLatch = new CountDownLatch(1); final String mapName = randomString(); final Runnable runnable = new MapPutRunnable(mapName); final MemberSelector selector = new SelectAllMembers(); service.submit(runnable, selector, new ExecutionCallback() { public void onResponse(Object response) { responseLatch.countDown(); } public void onFailure(Throwable t) { } }); IMap map = client.getMap(mapName); assertOpenEventually(responseLatch); assertEquals(1, map.size()); } @Test public void submitRunnableToMembers_withExecutionCallback() { final IExecutorService service = client.getExecutorService(randomString()); final CountDownLatch responseLatch = new CountDownLatch(CLUSTER_SIZE); final CountDownLatch completeLatch = new CountDownLatch(1); final String mapName = randomString(); final Runnable runnable = new MapPutRunnable(mapName); final MemberSelector selector = new SelectAllMembers(); service.submitToMembers(runnable, selector, new MultiExecutionCallback() { public void onResponse(Member member, Object value) { responseLatch.countDown(); } public void onComplete(Map<Member, Object> values) { completeLatch.countDown(); } }); IMap map = client.getMap(mapName); assertOpenEventually(responseLatch); assertOpenEventually(completeLatch); assertEquals(CLUSTER_SIZE, map.size()); } @Test public void submitCallable_withExecutionCallback() { final IExecutorService service = client.getExecutorService(randomString()); final CountDownLatch responseLatch = new CountDownLatch(1); final String msg = randomString(); final Callable runnable = new AppendCallable(msg); final MemberSelector selector = new SelectAllMembers(); final AtomicReference<Object> result = new AtomicReference<Object>(); service.submit(runnable, selector, new ExecutionCallback() { public void onResponse(Object response) { result.set(response); responseLatch.countDown(); } public void onFailure(Throwable t) { } }); assertOpenEventually(responseLatch); assertEquals(msg + AppendCallable.APPENDAGE, result.get()); } @Test public void submitCallableToMembers_withExecutionCallback() { final IExecutorService service = client.getExecutorService(randomString()); final CountDownLatch responseLatch = new CountDownLatch(CLUSTER_SIZE); final CountDownLatch completeLatch = new CountDownLatch(1); final String msg = randomString(); final Callable callable = new AppendCallable(msg); final MemberSelector selector = new SelectAllMembers(); service.submitToMembers(callable, selector, new MultiExecutionCallback() { public void onResponse(Member member, Object value) { if (value.equals(msg + AppendCallable.APPENDAGE)) { responseLatch.countDown(); } } public void onComplete(Map<Member, Object> values) { completeLatch.countDown(); } }); assertOpenEventually(responseLatch); assertOpenEventually(completeLatch); } @Test public void submitRunnableToAllMembers_withMultiExecutionCallback() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final CountDownLatch responseLatch = new CountDownLatch(CLUSTER_SIZE); final CountDownLatch completeLatch = new CountDownLatch(1); final String mapName = randomString(); final Runnable runnable = new MapPutRunnable(mapName); service.submitToAllMembers(runnable, new MultiExecutionCallback() { public void onResponse(Member member, Object value) { responseLatch.countDown(); } public void onComplete(Map<Member, Object> values) { completeLatch.countDown(); } }); IMap map = client.getMap(mapName); assertOpenEventually(responseLatch); assertOpenEventually(completeLatch); assertEquals(CLUSTER_SIZE, map.size()); } @Test public void submitCallableToAllMembers_withMultiExecutionCallback() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final CountDownLatch responseLatch = new CountDownLatch(CLUSTER_SIZE); final CountDownLatch completeLatch = new CountDownLatch(CLUSTER_SIZE); final String msg = randomString(); final Callable callable = new AppendCallable(msg); service.submitToAllMembers(callable, new MultiExecutionCallback() { public void onResponse(Member member, Object value) { if (value.equals(msg + AppendCallable.APPENDAGE)) { responseLatch.countDown(); } } public void onComplete(Map<Member, Object> values) { for (Member member : values.keySet()) { Object value = values.get(member); if (value.equals(msg + AppendCallable.APPENDAGE)) { completeLatch.countDown(); } } } }); assertOpenEventually(responseLatch); assertOpenEventually(completeLatch); } @Test public void submitRunnable() { final IExecutorService service = client.getExecutorService(randomString()); final String mapName = randomString(); final Runnable runnable = new MapPutRunnable(mapName); service.submit(runnable); final IMap map = client.getMap(mapName); assertTrueEventually(new AssertTask() { public void run() throws Exception { assertEquals(1, map.size()); } }); } @Test public void testSubmitRunnable_WithResult() throws ExecutionException, InterruptedException { IExecutorService service = client.getExecutorService(randomString()); final String mapName = randomString(); final Object givenResult = "givenResult"; final Future future = service.submit(new MapPutRunnable(mapName), givenResult); final Object result = future.get(); final IMap map = client.getMap(mapName); assertEquals(givenResult, result); assertEquals(1, map.size()); } @Test public void testSubmitCallable() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final String msg = randomString(); final Callable callable = new AppendCallable(msg); final Future result = service.submit(callable); assertEquals(msg + AppendCallable.APPENDAGE, result.get()); } @Test public void testSubmitRunnable_withExecutionCallback() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final String mapName = randomString(); final Runnable runnable = new MapPutRunnable(mapName); final CountDownLatch responseLatch = new CountDownLatch(1); service.submit(runnable, new ExecutionCallback() { public void onResponse(Object response) { responseLatch.countDown(); } public void onFailure(Throwable t) { } }); IMap map = client.getMap(mapName); assertOpenEventually(responseLatch); assertEquals(1, map.size()); } @Test public void testSubmitCallable_withExecutionCallback() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final String msg = randomString(); final Callable callable = new AppendCallable(msg); final AtomicReference result = new AtomicReference(); final CountDownLatch responseLatch = new CountDownLatch(1); service.submit(callable, new ExecutionCallback() { public void onResponse(Object response) { result.set(response); responseLatch.countDown(); } public void onFailure(Throwable t) { } }); assertOpenEventually(responseLatch); assertEquals(msg + AppendCallable.APPENDAGE, result.get()); } @Test public void submitCallableToKeyOwner() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final String msg = randomString(); final Callable callable = new AppendCallable(msg); final Future<String> result = service.submitToKeyOwner(callable, "key"); assertEquals(msg + AppendCallable.APPENDAGE, result.get()); } @Test public void submitRunnableToKeyOwner() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final String mapName = randomString(); final Runnable runnable = new MapPutRunnable(mapName); final CountDownLatch responseLatch = new CountDownLatch(1); service.submitToKeyOwner(runnable, "key", new ExecutionCallback() { public void onResponse(Object response) { responseLatch.countDown(); } public void onFailure(Throwable t) { } }); IMap map = client.getMap(mapName); assertOpenEventually(responseLatch); assertEquals(1, map.size()); } @Test public void submitCallableToKeyOwner_withExecutionCallback() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final String msg = randomString(); final Callable callable = new AppendCallable(msg); final CountDownLatch responseLatch = new CountDownLatch(1); final AtomicReference result = new AtomicReference(); service.submitToKeyOwner(callable, "key", new ExecutionCallback() { public void onResponse(Object response) { result.set(response); responseLatch.countDown(); } public void onFailure(Throwable t) { } }); assertOpenEventually(responseLatch, 5); assertEquals(msg + AppendCallable.APPENDAGE, result.get()); } @Test public void submitRunnablePartitionAware() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final String mapName = randomString(); final String key = HazelcastTestSupport.generateKeyOwnedBy(instance2); final Member member = instance2.getCluster().getLocalMember(); //this task should execute on a node owning the given key argument, //the action is to put the UUid of the executing node into a map with the given name final Runnable runnable = new MapPutPartitionAwareRunnable(mapName, key); final CountDownLatch responseLatch = new CountDownLatch(1); service.submit(runnable); final IMap map = client.getMap(mapName); assertTrueEventually(new AssertTask() { public void run() throws Exception { assertTrue(map.containsKey(member.getUuid())); } }); } @Test public void submitRunnablePartitionAware_withResult() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final String expectedResult = "result"; final String mapName = randomString(); final String key = HazelcastTestSupport.generateKeyOwnedBy(instance2); final Member member = instance2.getCluster().getLocalMember(); final Runnable runnable = new MapPutPartitionAwareRunnable(mapName, key); Future result = service.submit(runnable, expectedResult); final IMap map = client.getMap(mapName); assertEquals(expectedResult, result.get()); assertTrueEventually(new AssertTask() { public void run() throws Exception { assertTrue(map.containsKey(member.getUuid())); } }); } @Test public void submitRunnablePartitionAware_withExecutionCallback() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final String expectedResult = "result"; final String mapName = randomString(); final String key = HazelcastTestSupport.generateKeyOwnedBy(instance2); final Member member = instance2.getCluster().getLocalMember(); final Runnable runnable = new MapPutPartitionAwareRunnable(mapName, key); final CountDownLatch responseLatch = new CountDownLatch(1); service.submit(runnable, new ExecutionCallback() { @Override public void onResponse(Object response) { responseLatch.countDown(); } @Override public void onFailure(Throwable t) { } }); final IMap map = client.getMap(mapName); assertOpenEventually(responseLatch); assertTrue(map.containsKey(member.getUuid())); } @Test public void submitCallablePartitionAware() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final String mapName = randomString(); final IMap map = client.getMap(mapName); final String key = HazelcastTestSupport.generateKeyOwnedBy(instance2); final Member member = instance2.getCluster().getLocalMember(); final Callable runnable = new MapPutPartitionAwareCallable(mapName, key); final Future result = service.submit(runnable); assertEquals(member.getUuid(), result.get()); assertTrue(map.containsKey(member.getUuid())); } @Test public void submitCallablePartitionAware_WithExecutionCallback() throws Exception { final IExecutorService service = client.getExecutorService(randomString()); final String mapName = randomString(); final IMap map = client.getMap(mapName); final String key = HazelcastTestSupport.generateKeyOwnedBy(instance2); final Member member = instance2.getCluster().getLocalMember(); final Callable runnable = new MapPutPartitionAwareCallable(mapName, key); final AtomicReference result = new AtomicReference(); final CountDownLatch responseLatch = new CountDownLatch(1); service.submit(runnable, new ExecutionCallback() { public void onResponse(Object response) { result.set(response); responseLatch.countDown(); } public void onFailure(Throwable t) { } }); assertOpenEventually(responseLatch); assertEquals(member.getUuid(), result.get()); assertTrue(map.containsKey(member.getUuid())); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceSubmitTest.java
675
constructors[COLLECTION_ROLLBACK] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new CollectionRollbackOperation(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
1,678
runnable = new Runnable() { public void run() { map.putAsync(null, "value"); } };
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
1,303
pool.submit(new Runnable() { public void run() { String command = threadCommand; String[] threadArgs = command.replaceAll("\\$t", "" + threadID).trim() .split(" "); // TODO &t #4 m.putmany x k if ("m.putmany".equals(threadArgs[0]) || "m.removemany".equals(threadArgs[0])) { if (threadArgs.length < 4) { command += " " + Integer.parseInt(threadArgs[1]) * threadID; } } handleCommand(command); } });
0true
hazelcast_src_main_java_com_hazelcast_examples_TestApp.java
3,591
public static class Builder extends NumberFieldMapper.Builder<Builder, LongFieldMapper> { protected Long nullValue = Defaults.NULL_VALUE; public Builder(String name) { super(name, new FieldType(Defaults.FIELD_TYPE)); builder = this; } public Builder nullValue(long nullValue) { this.nullValue = nullValue; return this; } @Override public LongFieldMapper build(BuilderContext context) { fieldType.setOmitNorms(fieldType.omitNorms() && boost == 1.0f); LongFieldMapper fieldMapper = new LongFieldMapper(buildNames(context), precisionStep, boost, fieldType, docValues, nullValue, ignoreMalformed(context), coerce(context), postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo); fieldMapper.includeInAll(includeInAll); return fieldMapper; } }
0true
src_main_java_org_elasticsearch_index_mapper_core_LongFieldMapper.java
478
listener.onMessage("\n--- DB1: " + makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<String>() { public String call() { return indexOneValue.toString(); } }));
0true
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java
479
public class TransportGetAliasesAction extends TransportMasterNodeReadOperationAction<GetAliasesRequest, GetAliasesResponse> { @Inject public TransportGetAliasesAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool) { super(settings, transportService, clusterService, threadPool); } @Override protected String transportAction() { return GetAliasesAction.NAME; } @Override protected String executor() { // very lightweight operation all in memory no need to fork to a thread pool return ThreadPool.Names.SAME; } @Override protected GetAliasesRequest newRequest() { return new GetAliasesRequest(); } @Override protected GetAliasesResponse newResponse() { return new GetAliasesResponse(); } @Override protected void masterOperation(GetAliasesRequest request, ClusterState state, ActionListener<GetAliasesResponse> listener) throws ElasticsearchException { String[] concreteIndices = state.metaData().concreteIndices(request.indices(), request.indicesOptions()); request.indices(concreteIndices); @SuppressWarnings("unchecked") // ImmutableList to List results incompatible type ImmutableOpenMap<String, List<AliasMetaData>> result = (ImmutableOpenMap) state.metaData().findAliases(request.aliases(), request.indices()); listener.onResponse(new GetAliasesResponse(result)); } }
1no label
src_main_java_org_elasticsearch_action_admin_indices_alias_get_TransportGetAliasesAction.java
1,900
class NearCacheSizeEstimator implements SizeEstimator<NearCache.CacheRecord> { private final AtomicLong size = new AtomicLong(0L); protected NearCacheSizeEstimator() { super(); } @Override public long getCost(NearCache.CacheRecord record) { // immediate check nothing to do if record is null if (record == null) { return 0; } final long cost = record.getCost(); // if cost is zero, type of cached object is not Data. // then omit. if (cost == 0) { return 0; } final int numberOfIntegers = 4; long size = 0; // entry size in CHM size += numberOfIntegers * ((Integer.SIZE / Byte.SIZE)); size += cost; return size; } @Override public long getSize() { return size.longValue(); } public void add(long size) { this.size.addAndGet(size); } public void reset() { size.set(0L); } }
0true
hazelcast_src_main_java_com_hazelcast_map_NearCacheSizeEstimator.java
6,270
public class IsFalseAssertion extends Assertion { private static final ESLogger logger = Loggers.getLogger(IsFalseAssertion.class); public IsFalseAssertion(String field) { super(field, false); } @Override @SuppressWarnings("unchecked") protected void doAssert(Object actualValue, Object expectedValue) { logger.trace("assert that [{}] doesn't have a true value", actualValue); if (actualValue == null) { return; } String actualString = actualValue.toString(); assertThat(errorMessage(), actualString, anyOf( equalTo(""), equalToIgnoringCase(Boolean.FALSE.toString()), equalTo("0") )); } private String errorMessage() { return "field [" + getField() + "] has a true value but it shouldn't"; } }
1no label
src_test_java_org_elasticsearch_test_rest_section_IsFalseAssertion.java
124
static final class AdaptedRunnableAction extends ForkJoinTask<Void> implements RunnableFuture<Void> { final Runnable runnable; AdaptedRunnableAction(Runnable runnable) { if (runnable == null) throw new NullPointerException(); this.runnable = runnable; } public final Void getRawResult() { return null; } public final void setRawResult(Void v) { } public final boolean exec() { runnable.run(); return true; } public final void run() { invoke(); } private static final long serialVersionUID = 5232453952276885070L; }
0true
src_main_java_jsr166e_ForkJoinTask.java
378
private class ExecuteReplicaUpdateCallable implements Callable<Boolean> { private final ORecordId rid; private final ORecordInternal<?> record; public ExecuteReplicaUpdateCallable(ORecordInternal<?> record) { this.rid = (ORecordId) record.getIdentity(); this.record = record; } @Override public Boolean call() throws Exception { final ORecordMetadata loadedRecordMetadata = getRecordMetadata(rid); final boolean result; if (loadedRecordMetadata == null) result = processReplicaAdd(); else if (loadedRecordMetadata.getRecordVersion().compareTo(record.getRecordVersion()) < 0) result = processReplicaUpdate(loadedRecordMetadata); else return false; if (!result) throw new IllegalStateException("Passed in replica was not stored in DB"); return true; } private boolean processReplicaUpdate(ORecordMetadata loadedRecordMetadata) throws Exception { ORecordInternal<?> replicaToUpdate = record; boolean result; final ORecordVersion replicaVersion = record.getRecordVersion(); final byte recordType = record.getRecordType(); try { if (loadedRecordMetadata.getRecordVersion().isTombstone() && !replicaVersion.isTombstone()) { replicaToUpdate = mergeWithRecord(null); callbackHooks(TYPE.BEFORE_REPLICA_ADD, replicaToUpdate); } else if (!loadedRecordMetadata.getRecordVersion().isTombstone() && !replicaVersion.isTombstone()) { replicaToUpdate = mergeWithRecord(rid); callbackHooks(TYPE.BEFORE_REPLICA_UPDATE, replicaToUpdate); } else if (!loadedRecordMetadata.getRecordVersion().isTombstone() && replicaVersion.isTombstone()) { replicaToUpdate = load(rid, "*:0", false, true); replicaToUpdate.getRecordVersion().copyFrom(replicaVersion); callbackHooks(TYPE.BEFORE_REPLICA_DELETE, replicaToUpdate); } byte[] stream = replicaToUpdate.toStream(); final int dataSegmentId = dataSegmentStrategy.assignDataSegmentId(ODatabaseRecordAbstract.this, replicaToUpdate); result = underlying.updateReplica(dataSegmentId, rid, stream, replicaVersion, recordType); if (loadedRecordMetadata.getRecordVersion().isTombstone() && !replicaVersion.isTombstone()) { callbackHooks(TYPE.AFTER_REPLICA_ADD, replicaToUpdate); replicaToUpdate.unsetDirty(); getLevel1Cache().updateRecord(replicaToUpdate); } else if (!loadedRecordMetadata.getRecordVersion().isTombstone() && !replicaVersion.isTombstone()) { callbackHooks(TYPE.AFTER_REPLICA_UPDATE, replicaToUpdate); replicaToUpdate.unsetDirty(); getLevel1Cache().updateRecord(replicaToUpdate); } else if (!loadedRecordMetadata.getRecordVersion().isTombstone() && replicaVersion.isTombstone()) { callbackHooks(TYPE.AFTER_REPLICA_DELETE, replicaToUpdate); replicaToUpdate.unsetDirty(); getLevel1Cache().deleteRecord(rid); } } catch (Exception e) { if (loadedRecordMetadata.getRecordVersion().isTombstone() && !replicaVersion.isTombstone()) { callbackHooks(TYPE.REPLICA_ADD_FAILED, replicaToUpdate); } else if (!loadedRecordMetadata.getRecordVersion().isTombstone() && !replicaVersion.isTombstone()) { callbackHooks(TYPE.REPLICA_UPDATE_FAILED, replicaToUpdate); } else if (!loadedRecordMetadata.getRecordVersion().isTombstone() && replicaVersion.isTombstone()) { callbackHooks(TYPE.REPLICA_DELETE_FAILED, replicaToUpdate); } throw e; } return result; } private boolean processReplicaAdd() throws Exception { ORecordInternal<?> replicaToAdd = record; boolean result; final ORecordVersion replicaVersion = record.getRecordVersion(); try { if (!replicaVersion.isTombstone()) { replicaToAdd = mergeWithRecord(null); callbackHooks(TYPE.BEFORE_REPLICA_ADD, replicaToAdd); } else replicaToAdd = (ORecordInternal<?>) record.copy(); byte[] stream = replicaToAdd.toStream(); final int dataSegmentId = dataSegmentStrategy.assignDataSegmentId(ODatabaseRecordAbstract.this, replicaToAdd); result = underlying.updateReplica(dataSegmentId, rid, stream, replicaVersion, replicaToAdd.getRecordType()); if (!replicaVersion.isTombstone()) { callbackHooks(TYPE.AFTER_REPLICA_ADD, replicaToAdd); replicaToAdd.unsetDirty(); getLevel1Cache().updateRecord(replicaToAdd); } } catch (Exception e) { if (!replicaVersion.isTombstone()) callbackHooks(TYPE.AFTER_REPLICA_ADD, replicaToAdd); throw e; } return result; } private ORecordInternal<?> mergeWithRecord(ORID rid) { final ORecordInternal<?> replicaToAdd; if (record instanceof ODocument) { if (rid == null) replicaToAdd = new ODocument(); else replicaToAdd = load(rid, "*:0", false, true); ((ODocument) replicaToAdd).merge((ODocument) record, false, false); replicaToAdd.getRecordVersion().copyFrom(record.getRecordVersion()); replicaToAdd.setIdentity(this.rid); } else replicaToAdd = (ORecordInternal<?>) record.copy(); return replicaToAdd; } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_record_ODatabaseRecordAbstract.java
2,471
}, timer, TimeValue.timeValueMillis(100) /* enough timeout to catch them in the pending list... */, new Runnable() { @Override public void run() { timedOut.countDown(); } }
0true
src_test_java_org_elasticsearch_common_util_concurrent_PrioritizedExecutorsTests.java
462
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class ClientSemaphoreTest { static HazelcastInstance client; static HazelcastInstance server; @BeforeClass public static void init(){ server = Hazelcast.newHazelcastInstance(); client = HazelcastClient.newHazelcastClient(); } @AfterClass public static void destroy() { client.shutdown(); Hazelcast.shutdownAll(); } @Test public void testSemaphoreInit() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); assertTrue(semaphore.init(10)); } @Test(expected = IllegalArgumentException.class) public void testSemaphoreNegInit() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(-1); } @Test public void testRelease() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(0); semaphore.release(); assertEquals(1, semaphore.availablePermits()); } @Test public void testdrainPermits() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(10); assertEquals(10, semaphore.drainPermits()); } @Test public void testAvailablePermits_AfterDrainPermits() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(10); semaphore.drainPermits(); assertEquals(0, semaphore.availablePermits()); } @Test public void testTryAcquire_whenDrainPermits() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(10); semaphore.drainPermits(); assertFalse(semaphore.tryAcquire()); } @Test public void testAvailablePermits() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(10); assertEquals(10, semaphore.availablePermits()); } @Test public void testAvailableReducePermits() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(10); semaphore.reducePermits(5); assertEquals(5, semaphore.availablePermits()); } @Test public void testAvailableReducePermits_WhenZero() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(0); semaphore.reducePermits(1); assertEquals(0, semaphore.availablePermits()); } @Test public void testTryAcquire_whenAvailable() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(1); assertTrue(semaphore.tryAcquire()); } @Test public void testTryAcquire_whenUnAvailable() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(0); assertFalse(semaphore.tryAcquire()); } @Test public void testTryAcquire_whenAvailableWithTimeOut() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(1); assertTrue(semaphore.tryAcquire(1, TimeUnit.MILLISECONDS)); } @Test public void testTryAcquire_whenUnAvailableWithTimeOut() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(0); assertFalse(semaphore.tryAcquire(1, TimeUnit.MILLISECONDS)); } @Test public void testTryAcquireMultiPermits_whenAvailable() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(10); assertTrue(semaphore.tryAcquire(5)); } @Test public void testTryAcquireMultiPermits_whenUnAvailable() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(5); assertFalse(semaphore.tryAcquire(10)); } @Test public void testTryAcquireMultiPermits_whenAvailableWithTimeOut() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(10); assertTrue(semaphore.tryAcquire(5, 1, TimeUnit.MILLISECONDS)); } @Test public void testTryAcquireMultiPermits_whenUnAvailableWithTimeOut() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(5); assertFalse(semaphore.tryAcquire(10, 1, TimeUnit.MILLISECONDS)); } @Test public void testTryAcquire_afterRelease() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(0); semaphore.release(); assertTrue(semaphore.tryAcquire()); } @Test public void testMulitReleaseTryAcquire() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(0); semaphore.release(5); assertTrue(semaphore.tryAcquire(5)); } @Test public void testAcquire_Threaded() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(0); final CountDownLatch latch = new CountDownLatch(1); new Thread(){ public void run() { try { semaphore.acquire(); latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); Thread.sleep(1000); semaphore.release(2); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertEquals(1, semaphore.availablePermits()); } @Test public void tryAcquire_Threaded() throws Exception { final ISemaphore semaphore = client.getSemaphore(randomString()); semaphore.init(0); final CountDownLatch latch = new CountDownLatch(1); new Thread(){ public void run() { try { if(semaphore.tryAcquire(1, 5, TimeUnit.SECONDS)){ latch.countDown(); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); semaphore.release(2); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertEquals(1, semaphore.availablePermits()); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_semaphore_ClientSemaphoreTest.java
250
public interface CurrencyCodeIdentifiable { public String getCurrencyCode(); }
0true
common_src_main_java_org_broadleafcommerce_common_currency_util_CurrencyCodeIdentifiable.java
30
public class IncrementCommandParser extends TypeAwareCommandParser { public IncrementCommandParser(TextCommandType type) { super(type); } public TextCommand parser(SocketTextReader socketTextReader, String cmd, int space) { StringTokenizer st = new StringTokenizer(cmd); st.nextToken(); String key = null; int value = 0; boolean noReply = false; if (st.hasMoreTokens()) { key = st.nextToken(); } else { return new ErrorCommand(ERROR_CLIENT); } if (st.hasMoreTokens()) { value = Integer.parseInt(st.nextToken()); } else { return new ErrorCommand(ERROR_CLIENT); } if (st.hasMoreTokens()) { noReply = "noreply".equals(st.nextToken()); } return new IncrementCommand(type, key, value, noReply); } }
0true
hazelcast_src_main_java_com_hazelcast_ascii_memcache_IncrementCommandParser.java
594
public interface JoinOperation extends UrgentSystemOperation { }
0true
hazelcast_src_main_java_com_hazelcast_cluster_JoinOperation.java
2,295
return new FilterRecycler<T>() { @Override protected Recycler<T> getDelegate() { return defaultRecycler; } @Override public Recycler.V<T> obtain(int sizing) { if (sizing > 0 && sizing < minSize) { return smallObjectRecycler.obtain(sizing); } return super.obtain(sizing); } @Override public void close() { defaultRecycler.close(); smallObjectRecycler.close(); } };
0true
src_main_java_org_elasticsearch_common_recycler_Recyclers.java
1,675
runnable = new Runnable() { public void run() { map.delete(null); } };
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
1,945
public class MapKeySetRequest extends AllPartitionsClientRequest implements Portable, RetryableRequest, SecureRequest { private String name; public MapKeySetRequest() { } public MapKeySetRequest(String name) { this.name = name; } @Override protected OperationFactory createOperationFactory() { return new MapKeySetOperationFactory(name); } @Override protected Object reduce(Map<Integer, Object> map) { Set res = new HashSet(); MapService service = getService(); for (Object o : map.values()) { Set keys = ((MapKeySet) service.toObject(o)).getKeySet(); res.addAll(keys); } return new MapKeySet(res); } public String getServiceName() { return MapService.SERVICE_NAME; } @Override public int getFactoryId() { return MapPortableHook.F_ID; } public int getClassId() { return MapPortableHook.KEY_SET; } public void write(PortableWriter writer) throws IOException { writer.writeUTF("n", name); } public void read(PortableReader reader) throws IOException { name = reader.readUTF("n"); } public Permission getRequiredPermission() { return new MapPermission(name, ActionConstants.ACTION_READ); } }
0true
hazelcast_src_main_java_com_hazelcast_map_client_MapKeySetRequest.java
547
public class TransactionUtils { /** * Intended for use in all @Transactional definitions. For instance: * <pre>@Transactional(TransactionUtils.DEFAULT_TRANSACTION_MANAGER)</pre> */ public static final String DEFAULT_TRANSACTION_MANAGER = "blTransactionManager"; private static final Log LOG = LogFactory.getLog(TransactionUtils.class); public static TransactionStatus createTransaction(String name, int propagationBehavior, PlatformTransactionManager transactionManager) { return createTransaction(name, propagationBehavior, transactionManager, false); } public static TransactionStatus createTransaction(String name, int propagationBehavior, PlatformTransactionManager transactionManager, boolean isReadOnly) { DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName(name); def.setReadOnly(isReadOnly); def.setPropagationBehavior(propagationBehavior); return transactionManager.getTransaction(def); } public static TransactionStatus createTransaction(int propagationBehavior, PlatformTransactionManager transactionManager, boolean isReadOnly) { DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setReadOnly(isReadOnly); def.setPropagationBehavior(propagationBehavior); return transactionManager.getTransaction(def); } public static void finalizeTransaction(TransactionStatus status, PlatformTransactionManager transactionManager, boolean isError) { boolean isActive = false; try { if (!status.isRollbackOnly()) { isActive = true; } } catch (Exception e) { //do nothing } if (isError || !isActive) { try { transactionManager.rollback(status); } catch (Exception e) { LOG.error("Rolling back caused exception. Logging and continuing.", e); } } else { transactionManager.commit(status); } } }
0true
common_src_main_java_org_broadleafcommerce_common_util_TransactionUtils.java
2,653
transportService.sendRequest(nodeToSend, UnicastPingRequestHandler.ACTION, pingRequest, TransportRequestOptions.options().withTimeout((long) (timeout.millis() * 1.25)), new BaseTransportResponseHandler<UnicastPingResponse>() { @Override public UnicastPingResponse newInstance() { return new UnicastPingResponse(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void handleResponse(UnicastPingResponse response) { logger.trace("[{}] received response from {}: {}", id, nodeToSend, Arrays.toString(response.pingResponses)); try { DiscoveryNodes discoveryNodes = nodesProvider.nodes(); for (PingResponse pingResponse : response.pingResponses) { if (pingResponse.target().id().equals(discoveryNodes.localNodeId())) { // that's us, ignore continue; } if (!pingResponse.clusterName().equals(clusterName)) { // not part of the cluster logger.debug("[{}] filtering out response from {}, not same cluster_name [{}]", id, pingResponse.target(), pingResponse.clusterName().value()); continue; } ConcurrentMap<DiscoveryNode, PingResponse> responses = receivedResponses.get(response.id); if (responses == null) { logger.warn("received ping response {} with no matching id [{}]", pingResponse, response.id); } else { responses.put(pingResponse.target(), pingResponse); } } } finally { latch.countDown(); } } @Override public void handleException(TransportException exp) { latch.countDown(); if (exp instanceof ConnectTransportException) { // ok, not connected... logger.trace("failed to connect to {}", exp, nodeToSend); } else { logger.warn("failed to send ping to [{}]", exp, node); } } });
0true
src_main_java_org_elasticsearch_discovery_zen_ping_unicast_UnicastZenPing.java
1,301
public class DataPropagationTask implements Callable<Void> { private ODatabaseDocumentTx baseDB; private ODatabaseDocumentTx testDB; public DataPropagationTask(ODatabaseDocumentTx baseDB, ODatabaseDocumentTx testDocumentTx) { this.baseDB = new ODatabaseDocumentTx(baseDB.getURL()); this.testDB = new ODatabaseDocumentTx(testDocumentTx.getURL()); } @Override public Void call() throws Exception { Random random = new Random(); baseDB.open("admin", "admin"); testDB.open("admin", "admin"); try { while (true) { final ODocument document = new ODocument("TestClass"); document.field("id", idGen.getAndIncrement()); document.field("timestamp", System.currentTimeMillis()); document.field("stringValue", "sfe" + random.nextLong()); byte[] binaryValue = new byte[random.nextInt(2 * 65536) + 65537]; random.nextBytes(binaryValue); document.field("binaryValue", binaryValue); saveDoc(document); } } finally { baseDB.close(); testDB.close(); } } private void saveDoc(ODocument document) { ODatabaseRecordThreadLocal.INSTANCE.set(baseDB); ODocument testDoc = new ODocument(); document.copyTo(testDoc); document.save(); ODatabaseRecordThreadLocal.INSTANCE.set(testDB); testDoc.save(); ODatabaseRecordThreadLocal.INSTANCE.set(baseDB); } }
0true
server_src_test_java_com_orientechnologies_orient_core_storage_impl_local_paginated_LocalPaginatedStorageSmallCacheBigRecordsCrashRestore.java
854
public abstract class ModifyRequest extends PartitionClientRequest implements Portable, SecureRequest { String name; Data update; public ModifyRequest() { } public ModifyRequest(String name, Data update) { this.name = name; this.update = update; } @Override protected int getPartition() { ClientEngine clientEngine = getClientEngine(); Data key = clientEngine.getSerializationService().toData(name); return clientEngine.getPartitionService().getPartitionId(key); } @Override public String getServiceName() { return AtomicReferenceService.SERVICE_NAME; } @Override public int getFactoryId() { return AtomicReferencePortableHook.F_ID; } @Override public void write(PortableWriter writer) throws IOException { writer.writeUTF("n", name); ObjectDataOutput out = writer.getRawDataOutput(); writeNullableData(out, update); } @Override public void read(PortableReader reader) throws IOException { name = reader.readUTF("n"); ObjectDataInput in = reader.getRawDataInput(); update = readNullableData(in); } @Override public Permission getRequiredPermission() { return new AtomicReferencePermission(name, ActionConstants.ACTION_MODIFY); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_ModifyRequest.java
2,569
public class ZenDiscovery extends AbstractLifecycleComponent<Discovery> implements Discovery, DiscoveryNodesProvider { private final ThreadPool threadPool; private final TransportService transportService; private final ClusterService clusterService; private AllocationService allocationService; private final ClusterName clusterName; private final DiscoveryNodeService discoveryNodeService; private final ZenPingService pingService; private final MasterFaultDetection masterFD; private final NodesFaultDetection nodesFD; private final PublishClusterStateAction publishClusterState; private final MembershipAction membership; private final Version version; private final TimeValue pingTimeout; // a flag that should be used only for testing private final boolean sendLeaveRequest; private final ElectMasterService electMaster; private final boolean masterElectionFilterClientNodes; private final boolean masterElectionFilterDataNodes; private DiscoveryNode localNode; private final CopyOnWriteArrayList<InitialStateDiscoveryListener> initialStateListeners = new CopyOnWriteArrayList<InitialStateDiscoveryListener>(); private volatile boolean master = false; private volatile DiscoveryNodes latestDiscoNodes; private volatile Thread currentJoinThread; private final AtomicBoolean initialStateSent = new AtomicBoolean(); @Nullable private NodeService nodeService; @Inject public ZenDiscovery(Settings settings, ClusterName clusterName, ThreadPool threadPool, TransportService transportService, ClusterService clusterService, NodeSettingsService nodeSettingsService, DiscoveryNodeService discoveryNodeService, ZenPingService pingService, Version version) { super(settings); this.clusterName = clusterName; this.threadPool = threadPool; this.clusterService = clusterService; this.transportService = transportService; this.discoveryNodeService = discoveryNodeService; this.pingService = pingService; this.version = version; // also support direct discovery.zen settings, for cases when it gets extended this.pingTimeout = settings.getAsTime("discovery.zen.ping.timeout", settings.getAsTime("discovery.zen.ping_timeout", componentSettings.getAsTime("ping_timeout", componentSettings.getAsTime("initial_ping_timeout", timeValueSeconds(3))))); this.sendLeaveRequest = componentSettings.getAsBoolean("send_leave_request", true); this.masterElectionFilterClientNodes = settings.getAsBoolean("discovery.zen.master_election.filter_client", true); this.masterElectionFilterDataNodes = settings.getAsBoolean("discovery.zen.master_election.filter_data", false); logger.debug("using ping.timeout [{}], master_election.filter_client [{}], master_election.filter_data [{}]", pingTimeout, masterElectionFilterClientNodes, masterElectionFilterDataNodes); this.electMaster = new ElectMasterService(settings); nodeSettingsService.addListener(new ApplySettings()); this.masterFD = new MasterFaultDetection(settings, threadPool, transportService, this); this.masterFD.addListener(new MasterNodeFailureListener()); this.nodesFD = new NodesFaultDetection(settings, threadPool, transportService); this.nodesFD.addListener(new NodeFailureListener()); this.publishClusterState = new PublishClusterStateAction(settings, transportService, this, new NewClusterStateListener()); this.pingService.setNodesProvider(this); this.membership = new MembershipAction(settings, transportService, this, new MembershipListener()); transportService.registerHandler(RejoinClusterRequestHandler.ACTION, new RejoinClusterRequestHandler()); } @Override public void setNodeService(@Nullable NodeService nodeService) { this.nodeService = nodeService; } @Override public void setAllocationService(AllocationService allocationService) { this.allocationService = allocationService; } @Override protected void doStart() throws ElasticsearchException { Map<String, String> nodeAttributes = discoveryNodeService.buildAttributes(); // note, we rely on the fact that its a new id each time we start, see FD and "kill -9" handling final String nodeId = DiscoveryService.generateNodeId(settings); localNode = new DiscoveryNode(settings.get("name"), nodeId, transportService.boundAddress().publishAddress(), nodeAttributes, version); latestDiscoNodes = new DiscoveryNodes.Builder().put(localNode).localNodeId(localNode.id()).build(); nodesFD.updateNodes(latestDiscoNodes); pingService.start(); // do the join on a different thread, the DiscoveryService waits for 30s anyhow till it is discovered asyncJoinCluster(); } @Override protected void doStop() throws ElasticsearchException { pingService.stop(); masterFD.stop("zen disco stop"); nodesFD.stop(); initialStateSent.set(false); if (sendLeaveRequest) { if (!master && latestDiscoNodes.masterNode() != null) { try { membership.sendLeaveRequestBlocking(latestDiscoNodes.masterNode(), localNode, TimeValue.timeValueSeconds(1)); } catch (Exception e) { logger.debug("failed to send leave request to master [{}]", e, latestDiscoNodes.masterNode()); } } else { DiscoveryNode[] possibleMasters = electMaster.nextPossibleMasters(latestDiscoNodes.nodes().values(), 5); for (DiscoveryNode possibleMaster : possibleMasters) { if (localNode.equals(possibleMaster)) { continue; } try { membership.sendLeaveRequest(latestDiscoNodes.masterNode(), possibleMaster); } catch (Exception e) { logger.debug("failed to send leave request from master [{}] to possible master [{}]", e, latestDiscoNodes.masterNode(), possibleMaster); } } } } master = false; if (currentJoinThread != null) { try { currentJoinThread.interrupt(); } catch (Exception e) { // ignore } } } @Override protected void doClose() throws ElasticsearchException { masterFD.close(); nodesFD.close(); publishClusterState.close(); membership.close(); pingService.close(); } @Override public DiscoveryNode localNode() { return localNode; } @Override public void addListener(InitialStateDiscoveryListener listener) { this.initialStateListeners.add(listener); } @Override public void removeListener(InitialStateDiscoveryListener listener) { this.initialStateListeners.remove(listener); } @Override public String nodeDescription() { return clusterName.value() + "/" + localNode.id(); } @Override public DiscoveryNodes nodes() { DiscoveryNodes latestNodes = this.latestDiscoNodes; if (latestNodes != null) { return latestNodes; } // have not decided yet, just send the local node return DiscoveryNodes.builder().put(localNode).localNodeId(localNode.id()).build(); } @Override public NodeService nodeService() { return this.nodeService; } @Override public void publish(ClusterState clusterState, AckListener ackListener) { if (!master) { throw new ElasticsearchIllegalStateException("Shouldn't publish state when not master"); } latestDiscoNodes = clusterState.nodes(); nodesFD.updateNodes(clusterState.nodes()); publishClusterState.publish(clusterState, ackListener); } private void asyncJoinCluster() { if (currentJoinThread != null) { // we are already joining, ignore... logger.trace("a join thread already running"); return; } threadPool.generic().execute(new Runnable() { @Override public void run() { currentJoinThread = Thread.currentThread(); try { innerJoinCluster(); } finally { currentJoinThread = null; } } }); } private void innerJoinCluster() { boolean retry = true; while (retry) { if (lifecycle.stoppedOrClosed()) { return; } retry = false; DiscoveryNode masterNode = findMaster(); if (masterNode == null) { logger.trace("no masterNode returned"); retry = true; continue; } if (localNode.equals(masterNode)) { this.master = true; nodesFD.start(); // start the nodes FD clusterService.submitStateUpdateTask("zen-disco-join (elected_as_master)", Priority.URGENT, new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder() .localNodeId(localNode.id()) .masterNodeId(localNode.id()) // put our local node .put(localNode); // update the fact that we are the master... latestDiscoNodes = builder.build(); ClusterBlocks clusterBlocks = ClusterBlocks.builder().blocks(currentState.blocks()).removeGlobalBlock(NO_MASTER_BLOCK).build(); return ClusterState.builder(currentState).nodes(latestDiscoNodes).blocks(clusterBlocks).build(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { sendInitialStateEventIfNeeded(); } }); } else { this.master = false; try { // first, make sure we can connect to the master transportService.connectToNode(masterNode); } catch (Exception e) { logger.warn("failed to connect to master [{}], retrying...", e, masterNode); retry = true; continue; } // send join request try { membership.sendJoinRequestBlocking(masterNode, localNode, pingTimeout); } catch (Exception e) { if (e instanceof ElasticsearchException) { logger.info("failed to send join request to master [{}], reason [{}]", masterNode, ((ElasticsearchException) e).getDetailedMessage()); } else { logger.info("failed to send join request to master [{}], reason [{}]", masterNode, e.getMessage()); } if (logger.isTraceEnabled()) { logger.trace("detailed failed reason", e); } // failed to send the join request, retry retry = true; continue; } masterFD.start(masterNode, "initial_join"); // no need to submit the received cluster state, we will get it from the master when it publishes // the fact that we joined } } } private void handleLeaveRequest(final DiscoveryNode node) { if (lifecycleState() != Lifecycle.State.STARTED) { // not started, ignore a node failure return; } if (master) { clusterService.submitStateUpdateTask("zen-disco-node_left(" + node + ")", Priority.URGENT, new ClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { DiscoveryNodes.Builder builder = DiscoveryNodes.builder(currentState.nodes()).remove(node.id()); latestDiscoNodes = builder.build(); currentState = ClusterState.builder(currentState).nodes(latestDiscoNodes).build(); // check if we have enough master nodes, if not, we need to move into joining the cluster again if (!electMaster.hasEnoughMasterNodes(currentState.nodes())) { return rejoin(currentState, "not enough master nodes"); } // eagerly run reroute to remove dead nodes from routing table RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder(currentState).build()); return ClusterState.builder(currentState).routingResult(routingResult).build(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); } }); } else { handleMasterGone(node, "shut_down"); } } private void handleNodeFailure(final DiscoveryNode node, String reason) { if (lifecycleState() != Lifecycle.State.STARTED) { // not started, ignore a node failure return; } if (!master) { // nothing to do here... return; } clusterService.submitStateUpdateTask("zen-disco-node_failed(" + node + "), reason " + reason, Priority.URGENT, new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { DiscoveryNodes.Builder builder = DiscoveryNodes.builder(currentState.nodes()) .remove(node.id()); latestDiscoNodes = builder.build(); currentState = ClusterState.builder(currentState).nodes(latestDiscoNodes).build(); // check if we have enough master nodes, if not, we need to move into joining the cluster again if (!electMaster.hasEnoughMasterNodes(currentState.nodes())) { return rejoin(currentState, "not enough master nodes"); } // eagerly run reroute to remove dead nodes from routing table RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder(currentState).build()); return ClusterState.builder(currentState).routingResult(routingResult).build(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { sendInitialStateEventIfNeeded(); } }); } private void handleMinimumMasterNodesChanged(final int minimumMasterNodes) { if (lifecycleState() != Lifecycle.State.STARTED) { // not started, ignore a node failure return; } if (!master) { // nothing to do here... return; } clusterService.submitStateUpdateTask("zen-disco-minimum_master_nodes_changed", Priority.URGENT, new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { final int prevMinimumMasterNode = ZenDiscovery.this.electMaster.minimumMasterNodes(); ZenDiscovery.this.electMaster.minimumMasterNodes(minimumMasterNodes); // check if we have enough master nodes, if not, we need to move into joining the cluster again if (!electMaster.hasEnoughMasterNodes(currentState.nodes())) { return rejoin(currentState, "not enough master nodes on change of minimum_master_nodes from [" + prevMinimumMasterNode + "] to [" + minimumMasterNodes + "]"); } return currentState; } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { sendInitialStateEventIfNeeded(); } }); } private void handleMasterGone(final DiscoveryNode masterNode, final String reason) { if (lifecycleState() != Lifecycle.State.STARTED) { // not started, ignore a master failure return; } if (master) { // we might get this on both a master telling us shutting down, and then the disconnect failure return; } logger.info("master_left [{}], reason [{}]", masterNode, reason); clusterService.submitStateUpdateTask("zen-disco-master_failed (" + masterNode + ")", Priority.URGENT, new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { if (!masterNode.id().equals(currentState.nodes().masterNodeId())) { // master got switched on us, no need to send anything return currentState; } DiscoveryNodes discoveryNodes = DiscoveryNodes.builder(currentState.nodes()) // make sure the old master node, which has failed, is not part of the nodes we publish .remove(masterNode.id()) .masterNodeId(null).build(); if (!electMaster.hasEnoughMasterNodes(discoveryNodes)) { return rejoin(ClusterState.builder(currentState).nodes(discoveryNodes).build(), "not enough master nodes after master left (reason = " + reason + ")"); } final DiscoveryNode electedMaster = electMaster.electMaster(discoveryNodes); // elect master if (localNode.equals(electedMaster)) { master = true; masterFD.stop("got elected as new master since master left (reason = " + reason + ")"); nodesFD.start(); discoveryNodes = DiscoveryNodes.builder(discoveryNodes).masterNodeId(localNode.id()).build(); latestDiscoNodes = discoveryNodes; return ClusterState.builder(currentState).nodes(latestDiscoNodes).build(); } else { nodesFD.stop(); if (electedMaster != null) { discoveryNodes = DiscoveryNodes.builder(discoveryNodes).masterNodeId(electedMaster.id()).build(); masterFD.restart(electedMaster, "possible elected master since master left (reason = " + reason + ")"); latestDiscoNodes = discoveryNodes; return ClusterState.builder(currentState) .nodes(latestDiscoNodes) .build(); } else { return rejoin(ClusterState.builder(currentState).nodes(discoveryNodes).build(), "master_left and no other node elected to become master"); } } } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { sendInitialStateEventIfNeeded(); } }); } void handleNewClusterStateFromMaster(final ClusterState newState, final PublishClusterStateAction.NewClusterStateListener.NewStateProcessed newStateProcessed) { if (master) { clusterService.submitStateUpdateTask("zen-disco-master_receive_cluster_state_from_another_master [" + newState.nodes().masterNode() + "]", Priority.URGENT, new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { if (newState.version() > currentState.version()) { logger.warn("received cluster state from [{}] which is also master but with a newer cluster_state, rejoining to cluster...", newState.nodes().masterNode()); return rejoin(currentState, "zen-disco-master_receive_cluster_state_from_another_master [" + newState.nodes().masterNode() + "]"); } else { logger.warn("received cluster state from [{}] which is also master but with an older cluster_state, telling [{}] to rejoin the cluster", newState.nodes().masterNode(), newState.nodes().masterNode()); transportService.sendRequest(newState.nodes().masterNode(), RejoinClusterRequestHandler.ACTION, new RejoinClusterRequest(currentState.nodes().localNodeId()), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleException(TransportException exp) { logger.warn("failed to send rejoin request to [{}]", exp, newState.nodes().masterNode()); } }); return currentState; } } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { newStateProcessed.onNewClusterStateProcessed(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); newStateProcessed.onNewClusterStateFailed(t); } }); } else { if (newState.nodes().localNode() == null) { logger.warn("received a cluster state from [{}] and not part of the cluster, should not happen", newState.nodes().masterNode()); newStateProcessed.onNewClusterStateFailed(new ElasticsearchIllegalStateException("received state from a node that is not part of the cluster")); } else { if (currentJoinThread != null) { logger.debug("got a new state from master node, though we are already trying to rejoin the cluster"); } clusterService.submitStateUpdateTask("zen-disco-receive(from master [" + newState.nodes().masterNode() + "])", Priority.URGENT, new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { // we don't need to do this, since we ping the master, and get notified when it has moved from being a master // because it doesn't have enough master nodes... //if (!electMaster.hasEnoughMasterNodes(newState.nodes())) { // return disconnectFromCluster(newState, "not enough master nodes on new cluster state received from [" + newState.nodes().masterNode() + "]"); //} latestDiscoNodes = newState.nodes(); // check to see that we monitor the correct master of the cluster if (masterFD.masterNode() == null || !masterFD.masterNode().equals(latestDiscoNodes.masterNode())) { masterFD.restart(latestDiscoNodes.masterNode(), "new cluster state received and we are monitoring the wrong master [" + masterFD.masterNode() + "]"); } ClusterState.Builder builder = ClusterState.builder(newState); // if the routing table did not change, use the original one if (newState.routingTable().version() == currentState.routingTable().version()) { builder.routingTable(currentState.routingTable()); } // same for metadata if (newState.metaData().version() == currentState.metaData().version()) { builder.metaData(currentState.metaData()); } else { // if its not the same version, only copy over new indices or ones that changed the version MetaData.Builder metaDataBuilder = MetaData.builder(newState.metaData()).removeAllIndices(); for (IndexMetaData indexMetaData : newState.metaData()) { IndexMetaData currentIndexMetaData = currentState.metaData().index(indexMetaData.index()); if (currentIndexMetaData == null || currentIndexMetaData.version() != indexMetaData.version()) { metaDataBuilder.put(indexMetaData, false); } else { metaDataBuilder.put(currentIndexMetaData, false); } } builder.metaData(metaDataBuilder); } return builder.build(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); newStateProcessed.onNewClusterStateFailed(t); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { sendInitialStateEventIfNeeded(); newStateProcessed.onNewClusterStateProcessed(); } }); } } } private ClusterState handleJoinRequest(final DiscoveryNode node) { if (!master) { throw new ElasticsearchIllegalStateException("Node [" + localNode + "] not master for join request from [" + node + "]"); } ClusterState state = clusterService.state(); if (!transportService.addressSupported(node.address().getClass())) { // TODO, what should we do now? Maybe inform that node that its crap? logger.warn("received a wrong address type from [{}], ignoring...", node); } else { // try and connect to the node, if it fails, we can raise an exception back to the client... transportService.connectToNode(node); state = clusterService.state(); // validate the join request, will throw a failure if it fails, which will get back to the // node calling the join request membership.sendValidateJoinRequestBlocking(node, state, pingTimeout); clusterService.submitStateUpdateTask("zen-disco-receive(join from node[" + node + "])", Priority.URGENT, new ClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { if (currentState.nodes().nodeExists(node.id())) { // the node already exists in the cluster logger.warn("received a join request for an existing node [{}]", node); // still send a new cluster state, so it will be re published and possibly update the other node return ClusterState.builder(currentState).build(); } DiscoveryNodes.Builder builder = DiscoveryNodes.builder(currentState.nodes()); for (DiscoveryNode existingNode : currentState.nodes()) { if (node.address().equals(existingNode.address())) { builder.remove(existingNode.id()); logger.warn("received join request from node [{}], but found existing node {} with same address, removing existing node", node, existingNode); } } latestDiscoNodes = builder.build(); // add the new node now (will update latestDiscoNodes on publish) return ClusterState.builder(currentState).nodes(latestDiscoNodes.newNode(node)).build(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); } }); } return state; } private DiscoveryNode findMaster() { ZenPing.PingResponse[] fullPingResponses = pingService.pingAndWait(pingTimeout); if (fullPingResponses == null) { logger.trace("No full ping responses"); return null; } if (logger.isTraceEnabled()) { StringBuilder sb = new StringBuilder("full ping responses:"); if (fullPingResponses.length == 0) { sb.append(" {none}"); } else { for (ZenPing.PingResponse pingResponse : fullPingResponses) { sb.append("\n\t--> ").append("target [").append(pingResponse.target()).append("], master [").append(pingResponse.master()).append("]"); } } logger.trace(sb.toString()); } // filter responses List<ZenPing.PingResponse> pingResponses = Lists.newArrayList(); for (ZenPing.PingResponse pingResponse : fullPingResponses) { DiscoveryNode node = pingResponse.target(); if (masterElectionFilterClientNodes && (node.clientNode() || (!node.masterNode() && !node.dataNode()))) { // filter out the client node, which is a client node, or also one that is not data and not master (effectively, client) } else if (masterElectionFilterDataNodes && (!node.masterNode() && node.dataNode())) { // filter out data node that is not also master } else { pingResponses.add(pingResponse); } } if (logger.isDebugEnabled()) { StringBuilder sb = new StringBuilder("filtered ping responses: (filter_client[").append(masterElectionFilterClientNodes).append("], filter_data[").append(masterElectionFilterDataNodes).append("])"); if (pingResponses.isEmpty()) { sb.append(" {none}"); } else { for (ZenPing.PingResponse pingResponse : pingResponses) { sb.append("\n\t--> ").append("target [").append(pingResponse.target()).append("], master [").append(pingResponse.master()).append("]"); } } logger.debug(sb.toString()); } List<DiscoveryNode> pingMasters = newArrayList(); for (ZenPing.PingResponse pingResponse : pingResponses) { if (pingResponse.master() != null) { pingMasters.add(pingResponse.master()); } } Set<DiscoveryNode> possibleMasterNodes = Sets.newHashSet(); possibleMasterNodes.add(localNode); for (ZenPing.PingResponse pingResponse : pingResponses) { possibleMasterNodes.add(pingResponse.target()); } // if we don't have enough master nodes, we bail, even if we get a response that indicates // there is a master by other node, we don't see enough... if (!electMaster.hasEnoughMasterNodes(possibleMasterNodes)) { return null; } if (pingMasters.isEmpty()) { // lets tie break between discovered nodes DiscoveryNode electedMaster = electMaster.electMaster(possibleMasterNodes); if (localNode.equals(electedMaster)) { return localNode; } } else { DiscoveryNode electedMaster = electMaster.electMaster(pingMasters); if (electedMaster != null) { return electedMaster; } } return null; } private ClusterState rejoin(ClusterState clusterState, String reason) { logger.warn(reason + ", current nodes: {}", clusterState.nodes()); nodesFD.stop(); masterFD.stop(reason); master = false; ClusterBlocks clusterBlocks = ClusterBlocks.builder().blocks(clusterState.blocks()) .addGlobalBlock(NO_MASTER_BLOCK) .addGlobalBlock(GatewayService.STATE_NOT_RECOVERED_BLOCK) .build(); // clear the routing table, we have no master, so we need to recreate the routing when we reform the cluster RoutingTable routingTable = RoutingTable.builder().build(); // we also clean the metadata, since we are going to recover it if we become master MetaData metaData = MetaData.builder().build(); // clean the nodes, we are now not connected to anybody, since we try and reform the cluster latestDiscoNodes = new DiscoveryNodes.Builder().put(localNode).localNodeId(localNode.id()).build(); asyncJoinCluster(); return ClusterState.builder(clusterState) .blocks(clusterBlocks) .nodes(latestDiscoNodes) .routingTable(routingTable) .metaData(metaData) .build(); } private void sendInitialStateEventIfNeeded() { if (initialStateSent.compareAndSet(false, true)) { for (InitialStateDiscoveryListener listener : initialStateListeners) { listener.initialStateProcessed(); } } } private class NewClusterStateListener implements PublishClusterStateAction.NewClusterStateListener { @Override public void onNewClusterState(ClusterState clusterState, NewStateProcessed newStateProcessed) { handleNewClusterStateFromMaster(clusterState, newStateProcessed); } } private class MembershipListener implements MembershipAction.MembershipListener { @Override public ClusterState onJoin(DiscoveryNode node) { return handleJoinRequest(node); } @Override public void onLeave(DiscoveryNode node) { handleLeaveRequest(node); } } private class NodeFailureListener implements NodesFaultDetection.Listener { @Override public void onNodeFailure(DiscoveryNode node, String reason) { handleNodeFailure(node, reason); } } private class MasterNodeFailureListener implements MasterFaultDetection.Listener { @Override public void onMasterFailure(DiscoveryNode masterNode, String reason) { handleMasterGone(masterNode, reason); } @Override public void onDisconnectedFromMaster() { // got disconnected from the master, send a join request DiscoveryNode masterNode = latestDiscoNodes.masterNode(); try { membership.sendJoinRequest(masterNode, localNode); } catch (Exception e) { logger.warn("failed to send join request on disconnection from master [{}]", masterNode); } } } static class RejoinClusterRequest extends TransportRequest { private String fromNodeId; RejoinClusterRequest(String fromNodeId) { this.fromNodeId = fromNodeId; } RejoinClusterRequest() { } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); fromNodeId = in.readOptionalString(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeOptionalString(fromNodeId); } } class RejoinClusterRequestHandler extends BaseTransportRequestHandler<RejoinClusterRequest> { static final String ACTION = "discovery/zen/rejoin"; @Override public RejoinClusterRequest newInstance() { return new RejoinClusterRequest(); } @Override public void messageReceived(final RejoinClusterRequest request, final TransportChannel channel) throws Exception { clusterService.submitStateUpdateTask("received a request to rejoin the cluster from [" + request.fromNodeId + "]", Priority.URGENT, new ClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { try { channel.sendResponse(TransportResponse.Empty.INSTANCE); } catch (Exception e) { logger.warn("failed to send response on rejoin cluster request handling", e); } return rejoin(currentState, "received a request to rejoin the cluster from [" + request.fromNodeId + "]"); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); } }); } @Override public String executor() { return ThreadPool.Names.SAME; } } class ApplySettings implements NodeSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { int minimumMasterNodes = settings.getAsInt("discovery.zen.minimum_master_nodes", ZenDiscovery.this.electMaster.minimumMasterNodes()); if (minimumMasterNodes != ZenDiscovery.this.electMaster.minimumMasterNodes()) { logger.info("updating discovery.zen.minimum_master_nodes from [{}] to [{}]", ZenDiscovery.this.electMaster.minimumMasterNodes(), minimumMasterNodes); handleMinimumMasterNodesChanged(minimumMasterNodes); } } } }
1no label
src_main_java_org_elasticsearch_discovery_zen_ZenDiscovery.java
694
constructors[LIST_ADD_ALL] = new ConstructorFunction<Integer, Portable>() { public Portable createNew(Integer arg) { return new ListAddAllRequest(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java
3,173
private static class ToDoublePreprocessor extends Preprocessor { @Override public String toString(BytesRef ref) { assertTrue(ref.length > 0); return Double.toString(Double.parseDouble(super.toString(ref))); } @Override public int compare(BytesRef a, BytesRef b) { Double _a = Double.parseDouble(super.toString(a)); return _a.compareTo(Double.parseDouble(super.toString(b))); } }
0true
src_test_java_org_elasticsearch_index_fielddata_DuelFieldDataTests.java
1,716
return new UnmodifiableIterator<VType>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public VType next() { return iterator.next().value; } };
0true
src_main_java_org_elasticsearch_common_collect_ImmutableOpenLongMap.java
1,222
public abstract class OStorageAbstract extends OSharedContainerImpl implements OStorage { protected final String url; protected final String mode; protected OStorageConfiguration configuration; protected String name; protected AtomicLong version = new AtomicLong(); protected OLevel2RecordCache level2Cache; protected volatile STATUS status = STATUS.CLOSED; protected final OSharedResourceAdaptiveExternal lock; public OStorageAbstract(final String name, final String URL, final String mode, final int timeout, final OCacheLevelTwoLocator cacheLocator) { if (OStringSerializerHelper.contains(name, '/')) this.name = name.substring(name.lastIndexOf("/") + 1); else this.name = name; if (OStringSerializerHelper.contains(name, ',')) throw new IllegalArgumentException("Invalid character in storage name: " + this.name); level2Cache = new OLevel2RecordCache(this, cacheLocator); level2Cache.startup(); url = URL; this.mode = mode; lock = new OSharedResourceAdaptiveExternal(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean(), timeout, true); } public OStorage getUnderlying() { return this; } public OStorageConfiguration getConfiguration() { return configuration; } public boolean isClosed() { return status == STATUS.CLOSED; } public boolean checkForRecordValidity(final OPhysicalPosition ppos) { return ppos != null && !ppos.recordVersion.isTombstone() && ppos.dataSegmentId > -1; } public String getName() { return name; } /** * Returns the configured local Level-2 cache component. Cache component is always created even if not used. * * @return */ public OLevel2RecordCache getLevel2Cache() { return level2Cache; } public String getURL() { return url; } public void close() { close(false); } public void close(final boolean iForce) { if (!checkForClose(iForce)) return; lock.acquireExclusiveLock(); try { for (Object resource : sharedResources.values()) { if (resource instanceof OSharedResource) ((OSharedResource) resource).releaseExclusiveLock(); if (resource instanceof OCloseable) ((OCloseable) resource).close(); } sharedResources.clear(); Orient.instance().unregisterStorage(this); } finally { lock.releaseExclusiveLock(); } } /** * Returns current storage's version as serial. */ public long getVersion() { return version.get(); } public boolean dropCluster(final String iClusterName, final boolean iTruncate) { return dropCluster(getClusterIdByName(iClusterName), iTruncate); } protected boolean checkForClose(final boolean iForce) { lock.acquireSharedLock(); try { if (status == STATUS.CLOSED) return false; final int remainingUsers = getUsers() > 0 ? removeUser() : 0; return iForce || (!OGlobalConfiguration.STORAGE_KEEP_OPEN.getValueAsBoolean() && remainingUsers == 0); } finally { lock.releaseSharedLock(); } } public int getUsers() { return lock.getUsers(); } public int addUser() { return lock.addUser(); } public int removeUser() { return lock.removeUser(); } public OSharedResourceAdaptiveExternal getLock() { return lock; } public long countRecords() { long tot = 0; for (OCluster c : getClusterInstances()) if (c != null) tot += c.getEntries() - c.getTombstonesCount(); return tot; } public <V> V callInLock(final Callable<V> iCallable, final boolean iExclusiveLock) { if (iExclusiveLock) lock.acquireExclusiveLock(); else lock.acquireSharedLock(); try { return iCallable.call(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new OException("Error on nested call in lock", e); } finally { if (iExclusiveLock) lock.releaseExclusiveLock(); else lock.releaseSharedLock(); } } @Override public String toString() { return url != null ? url : "?"; } public STATUS getStatus() { return status; } public void checkForClusterPermissions(final String iClusterName) { // CHECK FOR ORESTRICTED OMetadata metaData = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata(); if (metaData != null) { final Set<OClass> classes = metaData.getSchema().getClassesRelyOnCluster(iClusterName); for (OClass c : classes) { if (c.isSubClassOf(OSecurityShared.RESTRICTED_CLASSNAME)) throw new OSecurityException("Class " + c.getName() + " cannot be truncated because has record level security enabled (extends " + OSecurityShared.RESTRICTED_CLASSNAME + ")"); } } } @Override public boolean isDistributed() { return false; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_storage_OStorageAbstract.java
106
{ @Override public Void doWork( State state ) { state.tx.success(); state.tx.finish(); return null; } } );
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestManualAcquireLock.java
92
INTERSECT { @Override public boolean evaluate(Object value, Object condition) { Preconditions.checkArgument(condition instanceof Geoshape); if (value == null) return false; Preconditions.checkArgument(value instanceof Geoshape); return ((Geoshape) value).intersect((Geoshape) condition); } @Override public String toString() { return "intersect"; } @Override public boolean hasNegation() { return true; } @Override public TitanPredicate negate() { return DISJOINT; } },
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Geo.java
89
public class StaticAssetServiceImplTest extends TestCase { public void testConvertURLProperties() throws Exception { StaticAssetServiceImpl staticAssetService = new StaticAssetServiceImpl(); staticAssetService.setStaticAssetUrlPrefix("cmsstatic"); staticAssetService.setStaticAssetEnvironmentUrlPrefix("http://images.mysite.com/myapp/cmsstatic"); String url = staticAssetService.convertAssetPath("/cmsstatic/product.jpg","myapp", false); assertTrue(url.equals("http://images.mysite.com/myapp/cmsstatic/product.jpg")); staticAssetService.setStaticAssetEnvironmentUrlPrefix("http://images.mysite.com"); url = staticAssetService.convertAssetPath("/cmsstatic/product.jpg","myapp", false); assertTrue(url.equals("http://images.mysite.com/product.jpg")); url = staticAssetService.convertAssetPath("/cmsstatic/product.jpg","myapp", true); assertTrue(url.equals("https://images.mysite.com/product.jpg")); staticAssetService.setStaticAssetEnvironmentUrlPrefix(null); url = staticAssetService.convertAssetPath("/cmsstatic/product.jpg","myapp", true); assertTrue(url.equals("/myapp/cmsstatic/product.jpg")); url = staticAssetService.convertAssetPath("cmsstatic/product.jpg","myapp", true); assertTrue(url.equals("/myapp/cmsstatic/product.jpg")); } }
0true
admin_broadleaf-contentmanagement-module_src_test_java_org_broadleafcommerce_cms_file_service_StaticAssetServiceImplTest.java
58
public class HttpPostCommandParser implements CommandParser { public TextCommand parser(SocketTextReader socketTextReader, String cmd, int space) { StringTokenizer st = new StringTokenizer(cmd); st.nextToken(); String uri = null; if (st.hasMoreTokens()) { uri = st.nextToken(); } else { return new ErrorCommand(ERROR_CLIENT); } return new HttpPostCommand(socketTextReader, uri); } }
0true
hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpPostCommandParser.java
582
public class PaymentException extends BroadleafException { private static final long serialVersionUID = 1L; protected PaymentResponse paymentResponse; public PaymentException() { super(); } public PaymentException(String message, Throwable cause) { super(message, cause); } public PaymentException(String message) { super(message); } public PaymentException(Throwable cause) { super(cause); } public PaymentResponse getPaymentResponse() { return paymentResponse; } public void setPaymentResponse(PaymentResponse paymentResponse) { this.paymentResponse = paymentResponse; } }
0true
common_src_main_java_org_broadleafcommerce_common_vendor_service_exception_PaymentException.java
203
new IProblemChangedListener() { public void problemsChanged(IResource[] changedResources, boolean isMarkerChange) { // Remove annotations that were resolved by changes to // other resources. // TODO: It would be better to match the markers to the // annotations, and decide which annotations to remove. scheduleParsing(); } };
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonEditor.java
1,595
class ApplySettings implements NodeSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { boolean newEnableRelocation = settings.getAsBoolean(CLUSTER_ROUTING_ALLOCATION_SNAPSHOT_RELOCATION_ENABLED, enableRelocation); if (newEnableRelocation != enableRelocation) { logger.info("updating [{}] from [{}], to [{}]", CLUSTER_ROUTING_ALLOCATION_SNAPSHOT_RELOCATION_ENABLED, enableRelocation, newEnableRelocation); enableRelocation = newEnableRelocation; } } }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_decider_SnapshotInProgressAllocationDecider.java
2,077
public interface BytesStream { BytesReference bytes(); }
0true
src_main_java_org_elasticsearch_common_io_BytesStream.java
2,299
return new FilterRecycler<T>() { private final Object lock; { this.lock = new Object(); } @Override protected Recycler<T> getDelegate() { return recycler; } @Override public org.elasticsearch.common.recycler.Recycler.V<T> obtain(int sizing) { synchronized (lock) { return super.obtain(sizing); } } @Override public org.elasticsearch.common.recycler.Recycler.V<T> obtain() { synchronized (lock) { return super.obtain(); } } @Override protected Recycler.V<T> wrap(final Recycler.V<T> delegate) { return new Recycler.V<T>() { @Override public boolean release() throws ElasticsearchException { synchronized (lock) { return delegate.release(); } } @Override public T v() { return delegate.v(); } @Override public boolean isRecycled() { return delegate.isRecycled(); } }; } };
0true
src_main_java_org_elasticsearch_common_recycler_Recyclers.java
936
threadPool.executor(executor).execute(new Runnable() { @Override public void run() { try { onOperation(shard, shardIndex, shardOperation(shardRequest)); } catch (Throwable e) { onOperation(shard, shardIt, shardIndex, e); } } });
0true
src_main_java_org_elasticsearch_action_support_broadcast_TransportBroadcastOperationAction.java
958
public abstract class ClusterInfoRequestBuilder<Request extends ClusterInfoRequest<Request>, Response extends ActionResponse, Builder extends ClusterInfoRequestBuilder<Request, Response, Builder>> extends MasterNodeReadOperationRequestBuilder<Request, Response, Builder> { protected ClusterInfoRequestBuilder(InternalGenericClient client, Request request) { super(client, request); } @SuppressWarnings("unchecked") public Builder setIndices(String... indices) { request.indices(indices); return (Builder) this; } @SuppressWarnings("unchecked") public Builder addIndices(String... indices) { request.indices(ObjectArrays.concat(request.indices(), indices, String.class)); return (Builder) this; } @SuppressWarnings("unchecked") public Builder setTypes(String... types) { request.types(types); return (Builder) this; } @SuppressWarnings("unchecked") public Builder addTypes(String... types) { request.types(ObjectArrays.concat(request.types(), types, String.class)); return (Builder) this; } @SuppressWarnings("unchecked") public Builder setIndicesOptions(IndicesOptions indicesOptions) { request.indicesOptions(indicesOptions); return (Builder) this; } }
0true
src_main_java_org_elasticsearch_action_support_master_info_ClusterInfoRequestBuilder.java
1,010
public interface OStringBuilderSerializable { public OStringBuilderSerializable toStream(StringBuilder iOutput) throws OSerializationException; public OStringBuilderSerializable fromStream(StringBuilder iInput) throws OSerializationException; }
0true
core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_string_OStringBuilderSerializable.java
193
public abstract class LockKeyColumnValueStoreTest extends AbstractKCVSTest { private static final Logger log = LoggerFactory.getLogger(LockKeyColumnValueStoreTest.class); public static final int CONCURRENCY = 8; public static final int NUM_TX = 2; public static final String DB_NAME = "test"; protected static final long EXPIRE_MS = 5000L; /* * Don't change these back to static. We can run test classes concurrently * now. There are multiple concrete subclasses of this abstract class. If * the subclasses run in separate threads and were to concurrently mutate * static state on this common superclass, then thread safety fails. * * Anything final and deeply immutable is of course fair game for static, * but these are mutable. */ public KeyColumnValueStoreManager[] manager; public StoreTransaction[][] tx; public KeyColumnValueStore[] store; private StaticBuffer k, c1, c2, v1, v2; private final String concreteClassName; public LockKeyColumnValueStoreTest() { concreteClassName = getClass().getSimpleName(); } @Before public void setUp() throws Exception { StoreManager tmp = null; try { tmp = openStorageManager(0); tmp.clearStorage(); } finally { tmp.close(); } for (int i = 0; i < CONCURRENCY; i++) { LocalLockMediators.INSTANCE.clear(concreteClassName + i); } open(); k = KeyValueStoreUtil.getBuffer("key"); c1 = KeyValueStoreUtil.getBuffer("col1"); c2 = KeyValueStoreUtil.getBuffer("col2"); v1 = KeyValueStoreUtil.getBuffer("val1"); v2 = KeyValueStoreUtil.getBuffer("val2"); } public abstract KeyColumnValueStoreManager openStorageManager(int id) throws BackendException; public void open() throws BackendException { manager = new KeyColumnValueStoreManager[CONCURRENCY]; tx = new StoreTransaction[CONCURRENCY][NUM_TX]; store = new KeyColumnValueStore[CONCURRENCY]; for (int i = 0; i < CONCURRENCY; i++) { manager[i] = openStorageManager(i); StoreFeatures storeFeatures = manager[i].getFeatures(); store[i] = manager[i].openDatabase(DB_NAME); for (int j = 0; j < NUM_TX; j++) { tx[i][j] = manager[i].beginTransaction(getTxConfig()); log.debug("Began transaction of class {}", tx[i][j].getClass().getCanonicalName()); } ModifiableConfiguration sc = GraphDatabaseConfiguration.buildConfiguration(); sc.set(GraphDatabaseConfiguration.LOCK_LOCAL_MEDIATOR_GROUP,concreteClassName + i); sc.set(GraphDatabaseConfiguration.UNIQUE_INSTANCE_ID,"inst"+i); sc.set(GraphDatabaseConfiguration.LOCK_RETRY,10); sc.set(GraphDatabaseConfiguration.LOCK_EXPIRE, new StandardDuration(EXPIRE_MS, TimeUnit.MILLISECONDS)); if (!storeFeatures.hasLocking()) { Preconditions.checkArgument(storeFeatures.isKeyConsistent(),"Store needs to support some form of locking"); KeyColumnValueStore lockerStore = manager[i].openDatabase(DB_NAME + "_lock_"); ConsistentKeyLocker c = new ConsistentKeyLocker.Builder(lockerStore, manager[i]).fromConfig(sc).mediatorName(concreteClassName + i).build(); store[i] = new ExpectedValueCheckingStore(store[i], c); for (int j = 0; j < NUM_TX; j++) tx[i][j] = new ExpectedValueCheckingTransaction(tx[i][j], manager[i].beginTransaction(getConsistentTxConfig(manager[i])), GraphDatabaseConfiguration.STORAGE_READ_WAITTIME.getDefaultValue()); } } } public StoreTransaction newTransaction(KeyColumnValueStoreManager manager) throws BackendException { StoreTransaction transaction = manager.beginTransaction(getTxConfig()); if (!manager.getFeatures().hasLocking() && manager.getFeatures().isKeyConsistent()) { transaction = new ExpectedValueCheckingTransaction(transaction, manager.beginTransaction(getConsistentTxConfig(manager)), GraphDatabaseConfiguration.STORAGE_READ_WAITTIME.getDefaultValue()); } return transaction; } @After public void tearDown() throws Exception { close(); } public void close() throws BackendException { for (int i = 0; i < CONCURRENCY; i++) { store[i].close(); for (int j = 0; j < NUM_TX; j++) { log.debug("Committing tx[{}][{}] = {}", new Object[]{i, j, tx[i][j]}); if (tx[i][j] != null) tx[i][j].commit(); } manager[i].close(); } LocalLockMediators.INSTANCE.clear(); } @Test public void singleLockAndUnlock() throws BackendException { store[0].acquireLock(k, c1, null, tx[0][0]); store[0].mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c1, v1)), NO_DELETIONS, tx[0][0]); tx[0][0].commit(); tx[0][0] = newTransaction(manager[0]); Assert.assertEquals(v1, KCVSUtil.get(store[0], k, c1, tx[0][0])); } @Test public void transactionMayReenterLock() throws BackendException { store[0].acquireLock(k, c1, null, tx[0][0]); store[0].acquireLock(k, c1, null, tx[0][0]); store[0].acquireLock(k, c1, null, tx[0][0]); store[0].mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c1, v1)), NO_DELETIONS, tx[0][0]); tx[0][0].commit(); tx[0][0] = newTransaction(manager[0]); Assert.assertEquals(v1, KCVSUtil.get(store[0], k, c1, tx[0][0])); } @Test(expected = PermanentLockingException.class) public void expectedValueMismatchCausesMutateFailure() throws BackendException { store[0].acquireLock(k, c1, v1, tx[0][0]); store[0].mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c1, v1)), NO_DELETIONS, tx[0][0]); } @Test public void testLocalLockContention() throws BackendException { store[0].acquireLock(k, c1, null, tx[0][0]); try { store[0].acquireLock(k, c1, null, tx[0][1]); Assert.fail("Lock contention exception not thrown"); } catch (BackendException e) { Assert.assertTrue(e instanceof PermanentLockingException || e instanceof TemporaryLockingException); } try { store[0].acquireLock(k, c1, null, tx[0][1]); Assert.fail("Lock contention exception not thrown (2nd try)"); } catch (BackendException e) { Assert.assertTrue(e instanceof PermanentLockingException || e instanceof TemporaryLockingException); } } @Test public void testRemoteLockContention() throws InterruptedException, BackendException { // acquire lock on "host1" store[0].acquireLock(k, c1, null, tx[0][0]); Thread.sleep(50L); try { // acquire same lock on "host2" store[1].acquireLock(k, c1, null, tx[1][0]); } catch (BackendException e) { /* Lock attempts between hosts with different LocalLockMediators, * such as tx[0][0] and tx[1][0] in this example, should * not generate locking failures until one of them tries * to issue a mutate or mutateMany call. An exception * thrown during the acquireLock call above suggests that * the LocalLockMediators for these two transactions are * not really distinct, which would be a severe and fundamental * bug in this test. */ Assert.fail("Contention between remote transactions detected too soon"); } Thread.sleep(50L); try { // This must fail since "host1" took the lock first store[1].mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c1, v2)), NO_DELETIONS, tx[1][0]); Assert.fail("Expected lock contention between remote transactions did not occur"); } catch (BackendException e) { Assert.assertTrue(e instanceof PermanentLockingException || e instanceof TemporaryLockingException); } // This should succeed store[0].mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c1, v1)), NO_DELETIONS, tx[0][0]); tx[0][0].commit(); tx[0][0] = newTransaction(manager[0]); Assert.assertEquals(v1, KCVSUtil.get(store[0], k, c1, tx[0][0])); } @Test public void singleTransactionWithMultipleLocks() throws BackendException { tryWrites(store[0], manager[0], tx[0][0], store[0], tx[0][0]); /* * tryWrites commits transactions. set committed tx references to null * to prevent a second commit attempt in close(). */ tx[0][0] = null; } @Test public void twoLocalTransactionsWithIndependentLocks() throws BackendException { tryWrites(store[0], manager[0], tx[0][0], store[0], tx[0][1]); /* * tryWrites commits transactions. set committed tx references to null * to prevent a second commit attempt in close(). */ tx[0][0] = null; tx[0][1] = null; } @Test public void twoTransactionsWithIndependentLocks() throws BackendException { tryWrites(store[0], manager[0], tx[0][0], store[1], tx[1][0]); /* * tryWrites commits transactions. set committed tx references to null * to prevent a second commit attempt in close(). */ tx[0][0] = null; tx[1][0] = null; } @Test public void expiredLocalLockIsIgnored() throws BackendException, InterruptedException { tryLocks(store[0], tx[0][0], store[0], tx[0][1], true); } @Test public void expiredRemoteLockIsIgnored() throws BackendException, InterruptedException { tryLocks(store[0], tx[0][0], store[1], tx[1][0], false); } @Test public void repeatLockingDoesNotExtendExpiration() throws BackendException, InterruptedException { /* * This test is intrinsically racy and unreliable. There's no guarantee * that the thread scheduler will put our test thread back on a core in * a timely fashion after our Thread.sleep() argument elapses. * Theoretically, Thread.sleep could also receive spurious wakeups that * alter the timing of the test. */ long start = System.currentTimeMillis(); long gracePeriodMS = 50L; long loopDurationMS = (EXPIRE_MS - gracePeriodMS); long targetMS = start + loopDurationMS; int steps = 20; // Initial lock acquisition by tx[0][0] store[0].acquireLock(k, k, null, tx[0][0]); // Repeat lock acquistion until just before expiration for (int i = 0; i <= steps; i++) { if (targetMS <= System.currentTimeMillis()) { break; } store[0].acquireLock(k, k, null, tx[0][0]); Thread.sleep(loopDurationMS / steps); } // tx[0][0]'s lock is about to expire (or already has) Thread.sleep(gracePeriodMS * 2); // tx[0][0]'s lock has expired (barring spurious wakeup) try { // Lock (k,k) with tx[0][1] now that tx[0][0]'s lock has expired store[0].acquireLock(k, k, null, tx[0][1]); // If acquireLock returns without throwing an Exception, we're OK } catch (BackendException e) { log.debug("Relocking exception follows", e); Assert.fail("Relocking following expiration failed"); } } @Test public void parallelNoncontendedLockStressTest() throws BackendException, InterruptedException { final Executor stressPool = Executors.newFixedThreadPool(CONCURRENCY); final CountDownLatch stressComplete = new CountDownLatch(CONCURRENCY); final long maxWalltimeAllowedMS = 90 * 1000L; final int lockOperationsPerThread = 100; final LockStressor[] ls = new LockStressor[CONCURRENCY]; for (int i = 0; i < CONCURRENCY; i++) { ls[i] = new LockStressor(manager[i], store[i], stressComplete, lockOperationsPerThread, KeyColumnValueStoreUtil.longToByteBuffer(i)); stressPool.execute(ls[i]); } Assert.assertTrue("Timeout exceeded", stressComplete.await(maxWalltimeAllowedMS, TimeUnit.MILLISECONDS)); // All runnables submitted to the executor are done for (int i = 0; i < CONCURRENCY; i++) { if (0 < ls[i].temporaryFailures) { log.warn("Recorded {} temporary failures for thread index {}", ls[i].temporaryFailures, i); } Assert.assertEquals(lockOperationsPerThread, ls[i].succeeded + ls[i].temporaryFailures); } } @Test public void testLocksOnMultipleStores() throws Exception { final int numStores = 6; Preconditions.checkState(numStores % 3 == 0); final StaticBuffer key = BufferUtil.getLongBuffer(1); final StaticBuffer col = BufferUtil.getLongBuffer(2); final StaticBuffer val2 = BufferUtil.getLongBuffer(8); // Create mocks LockerProvider mockLockerProvider = createStrictMock(LockerProvider.class); Locker mockLocker = createStrictMock(Locker.class); // Create EVCSManager with mockLockerProvider ExpectedValueCheckingStoreManager expManager = new ExpectedValueCheckingStoreManager(manager[0], "multi_store_lock_mgr", mockLockerProvider, new StandardDuration(100L, TimeUnit.MILLISECONDS)); // Begin EVCTransaction BaseTransactionConfig txCfg = StandardBaseTransactionConfig.of(times); ExpectedValueCheckingTransaction tx = expManager.beginTransaction(txCfg); // openDatabase calls getLocker, and we do it numStores times expect(mockLockerProvider.getLocker(anyObject(String.class))).andReturn(mockLocker).times(numStores); // acquireLock calls writeLock, and we do it 2/3 * numStores times mockLocker.writeLock(eq(new KeyColumn(key, col)), eq(tx.getConsistentTx())); expectLastCall().times(numStores / 3 * 2); // mutateMany calls checkLocks, and we do it 2/3 * numStores times mockLocker.checkLocks(tx.getConsistentTx()); expectLastCall().times(numStores / 3 * 2); replay(mockLockerProvider); replay(mockLocker); /* * Acquire a lock on several distinct stores (numStores total distinct * stores) and build mutations. */ ImmutableMap.Builder<String, Map<StaticBuffer, KCVMutation>> builder = ImmutableMap.builder(); for (int i = 0; i < numStores; i++) { String storeName = "multi_store_lock_" + i; KeyColumnValueStore s = expManager.openDatabase(storeName); if (i % 3 < 2) s.acquireLock(key, col, null, tx); if (i % 3 > 0) builder.put(storeName, ImmutableMap.of(key, new KCVMutation(ImmutableList.of(StaticArrayEntry.of(col, val2)), ImmutableList.<StaticBuffer>of()))); } // Mutate expManager.mutateMany(builder.build(), tx); // Shutdown expManager.close(); // Check the mocks verify(mockLockerProvider); verify(mockLocker); } private void tryWrites(KeyColumnValueStore store1, KeyColumnValueStoreManager checkmgr, StoreTransaction tx1, KeyColumnValueStore store2, StoreTransaction tx2) throws BackendException { Assert.assertNull(KCVSUtil.get(store1, k, c1, tx1)); Assert.assertNull(KCVSUtil.get(store2, k, c2, tx2)); store1.acquireLock(k, c1, null, tx1); store2.acquireLock(k, c2, null, tx2); store1.mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c1, v1)), NO_DELETIONS, tx1); store2.mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c2, v2)), NO_DELETIONS, tx2); tx1.commit(); if (tx2 != tx1) tx2.commit(); StoreTransaction checktx = newTransaction(checkmgr); Assert.assertEquals(v1, KCVSUtil.get(store1, k, c1, checktx)); Assert.assertEquals(v2, KCVSUtil.get(store2, k, c2, checktx)); checktx.commit(); } private void tryLocks(KeyColumnValueStore s1, StoreTransaction tx1, KeyColumnValueStore s2, StoreTransaction tx2, boolean detectLocally) throws BackendException, InterruptedException { s1.acquireLock(k, k, null, tx1); // Require local lock contention, if requested by our caller // Remote lock contention is checked by separate cases if (detectLocally) { try { s2.acquireLock(k, k, null, tx2); Assert.fail("Expected lock contention between transactions did not occur"); } catch (BackendException e) { Assert.assertTrue(e instanceof PermanentLockingException || e instanceof TemporaryLockingException); } } // Let the original lock expire Thread.sleep(EXPIRE_MS + 100L); // This should succeed now that the original lock is expired s2.acquireLock(k, k, null, tx2); // Mutate to check for remote contention s2.mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c2, v2)), NO_DELETIONS, tx2); } /** * Run lots of acquireLock() and commit() ops on a provided store and txn. * <p/> * Used by {@link #parallelNoncontendedLockStressTest()}. * * @author "Dan LaRocque <[email protected]>" */ private class LockStressor implements Runnable { private final KeyColumnValueStoreManager manager; private final KeyColumnValueStore store; private final CountDownLatch doneLatch; private final int opCount; private final StaticBuffer toLock; private int succeeded = 0; private int temporaryFailures = 0; private LockStressor(KeyColumnValueStoreManager manager, KeyColumnValueStore store, CountDownLatch doneLatch, int opCount, StaticBuffer toLock) { this.manager = manager; this.store = store; this.doneLatch = doneLatch; this.opCount = opCount; this.toLock = toLock; } @Override public void run() { // Catch & log exceptions for (int opIndex = 0; opIndex < opCount; opIndex++) { StoreTransaction tx = null; try { tx = newTransaction(manager); store.acquireLock(toLock, toLock, null, tx); store.mutate(toLock, ImmutableList.<Entry>of(), Arrays.asList(toLock), tx); tx.commit(); succeeded++; } catch (TemporaryLockingException e) { temporaryFailures++; } catch (Throwable t) { log.error("Unexpected locking-related exception on iteration " + (opIndex + 1) + "/" + opCount, t); } } /* * This latch is the only thing guaranteeing that succeeded's true * value is observable by other threads once we're done with run() * and the latch's await() method returns. */ doneLatch.countDown(); } } }
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_LockKeyColumnValueStoreTest.java
2,166
class NoAcceptDocsIterator extends DocIdSetIterator { private final int maxDoc; private int doc = -1; NoAcceptDocsIterator(int maxDoc) { this.maxDoc = maxDoc; } @Override public int docID() { return doc; } @Override public int nextDoc() { do { doc++; if (doc >= maxDoc) { return doc = NO_MORE_DOCS; } } while (!matchDoc(doc)); return doc; } @Override public int advance(int target) { for (doc = target; doc < maxDoc; doc++) { if (matchDoc(doc)) { return doc; } } return doc = NO_MORE_DOCS; } @Override public long cost() { return maxDoc; } }
1no label
src_main_java_org_elasticsearch_common_lucene_docset_MatchDocIdSet.java
516
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class ClientTopicTest { static HazelcastInstance client; static HazelcastInstance server; @BeforeClass public static void init(){ server = Hazelcast.newHazelcastInstance(); client = HazelcastClient.newHazelcastClient(null); } @AfterClass public static void stop(){ HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } @Test public void testListener() throws InterruptedException{ ITopic topic = client.getTopic(randomString()); final CountDownLatch latch = new CountDownLatch(10); MessageListener listener = new MessageListener() { public void onMessage(Message message) { latch.countDown(); } }; topic.addMessageListener(listener); for (int i=0; i<10; i++){ topic.publish(i); } assertTrue(latch.await(20, TimeUnit.SECONDS)); } @Test public void testRemoveListener() { ITopic topic = client.getTopic(randomString()); MessageListener listener = new MessageListener() { public void onMessage(Message message) { } }; String id = topic.addMessageListener(listener); assertTrue(topic.removeMessageListener(id)); } @Test(expected = UnsupportedOperationException.class) public void testGetLocalTopicStats() throws Exception { ITopic topic = client.getTopic(randomString()); topic.getLocalTopicStats(); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_topic_ClientTopicTest.java
164
public interface SpeedTest { public void cycle() throws Exception; public void init() throws Exception; public void deinit() throws Exception; public void beforeCycle() throws Exception; public void afterCycle() throws Exception; }
0true
commons_src_test_java_com_orientechnologies_common_test_SpeedTest.java
11
public interface DataProvider extends FeedAggregator { /** * An enum which defines the various level of service (LOS) a data provider can provide. * */ public static enum LOS { /** Fast enum. */ fast, /** Medium enum. */ medium, /** Slow enum.*/ slow } /** * Returns a map of data for each feed. This allows the data to be queried in batch and improves performance. * @param feedIDs to retrieve data for * @param startTime the start time of the return data set. * @param endTime the end time of the return data set. * @param timeUnit the time unit of startTime and endTime parameters. * @return map of data for the specified feeds. Each entry in the map has data * with a timestamp that is >= startTime and <= endTime ordered according to the time. */ public Map<String, SortedMap<Long, Map<String, String>>> getData(Set<String> feedIDs, long startTime, long endTime, TimeUnit timeUnit); /** * Check if a request can be fully serviced by a data provider. * @param feedID feed that is requested * @param startTime start time of the request * @param timeUnit the time unit of startTime * @return true if a request can be fully serviced by a data provider. */ public boolean isFullyWithinTimeSpan(String feedID, long startTime, TimeUnit timeUnit); /** * Return the level of service that a data retrieval provider can provide. * @return the level of service. */ public LOS getLOS(); }
0true
mctcore_src_main_java_gov_nasa_arc_mct_api_feed_DataProvider.java
5,068
static class FieldDataWarmer extends IndicesWarmer.Listener { @Override public TerminationHandle warm(final IndexShard indexShard, IndexMetaData indexMetaData, final WarmerContext context, ThreadPool threadPool) { final MapperService mapperService = indexShard.mapperService(); final Map<String, FieldMapper<?>> warmUp = new HashMap<String, FieldMapper<?>>(); boolean parentChild = false; for (DocumentMapper docMapper : mapperService) { for (FieldMapper<?> fieldMapper : docMapper.mappers().mappers()) { if (fieldMapper instanceof ParentFieldMapper) { ParentFieldMapper parentFieldMapper = (ParentFieldMapper) fieldMapper; if (parentFieldMapper.active()) { parentChild = true; } } final FieldDataType fieldDataType = fieldMapper.fieldDataType(); if (fieldDataType == null) { continue; } if (fieldDataType.getLoading() != Loading.EAGER) { continue; } final String indexName = fieldMapper.names().indexName(); if (warmUp.containsKey(indexName)) { continue; } warmUp.put(indexName, fieldMapper); } } final IndexFieldDataService indexFieldDataService = indexShard.indexFieldDataService(); final Executor executor = threadPool.executor(executor()); final CountDownLatch latch = new CountDownLatch(context.newSearcher().reader().leaves().size() * warmUp.size() + (parentChild ? 1 : 0)); for (final AtomicReaderContext ctx : context.newSearcher().reader().leaves()) { for (final FieldMapper<?> fieldMapper : warmUp.values()) { executor.execute(new Runnable() { @Override public void run() { try { final long start = System.nanoTime(); indexFieldDataService.getForField(fieldMapper).load(ctx); if (indexShard.warmerService().logger().isTraceEnabled()) { indexShard.warmerService().logger().trace("warmed fielddata for [{}], took [{}]", fieldMapper.names().name(), TimeValue.timeValueNanos(System.nanoTime() - start)); } } catch (Throwable t) { indexShard.warmerService().logger().warn("failed to warm-up fielddata for [{}]", t, fieldMapper.names().name()); } finally { latch.countDown(); } } }); } } if (parentChild) { executor.execute(new Runnable() { @Override public void run() { try { final long start = System.nanoTime(); indexShard.indexService().cache().idCache().refresh(context.newSearcher().reader().leaves()); if (indexShard.warmerService().logger().isTraceEnabled()) { indexShard.warmerService().logger().trace("warmed id_cache, took [{}]", TimeValue.timeValueNanos(System.nanoTime() - start)); } } catch (Throwable t) { indexShard.warmerService().logger().warn("failed to warm-up id cache", t); } finally { latch.countDown(); } } }); } return new TerminationHandle() { @Override public void awaitTermination() throws InterruptedException { latch.await(); } }; } }
1no label
src_main_java_org_elasticsearch_search_SearchService.java
623
static final class Fields { static final XContentBuilderString ROUTING = new XContentBuilderString("routing"); static final XContentBuilderString STATE = new XContentBuilderString("state"); static final XContentBuilderString PRIMARY = new XContentBuilderString("primary"); static final XContentBuilderString NODE = new XContentBuilderString("node"); static final XContentBuilderString RELOCATING_NODE = new XContentBuilderString("relocating_node"); }
0true
src_main_java_org_elasticsearch_action_admin_indices_stats_ShardStats.java
5,824
public class PlainHighlighter implements Highlighter { private static final String CACHE_KEY = "highlight-plain"; @Override public String[] names() { return new String[] { "plain", "highlighter" }; } public HighlightField highlight(HighlighterContext highlighterContext) { SearchContextHighlight.Field field = highlighterContext.field; SearchContext context = highlighterContext.context; FetchSubPhase.HitContext hitContext = highlighterContext.hitContext; FieldMapper<?> mapper = highlighterContext.mapper; Encoder encoder = field.encoder().equals("html") ? HighlightUtils.Encoders.HTML : HighlightUtils.Encoders.DEFAULT; if (!hitContext.cache().containsKey(CACHE_KEY)) { Map<FieldMapper<?>, org.apache.lucene.search.highlight.Highlighter> mappers = Maps.newHashMap(); hitContext.cache().put(CACHE_KEY, mappers); } Map<FieldMapper<?>, org.apache.lucene.search.highlight.Highlighter> cache = (Map<FieldMapper<?>, org.apache.lucene.search.highlight.Highlighter>) hitContext.cache().get(CACHE_KEY); org.apache.lucene.search.highlight.Highlighter entry = cache.get(mapper); if (entry == null) { Query query = highlighterContext.query.originalQuery(); QueryScorer queryScorer = new CustomQueryScorer(query, field.requireFieldMatch() ? mapper.names().indexName() : null); queryScorer.setExpandMultiTermQuery(true); Fragmenter fragmenter; if (field.numberOfFragments() == 0) { fragmenter = new NullFragmenter(); } else if (field.fragmenter() == null) { fragmenter = new SimpleSpanFragmenter(queryScorer, field.fragmentCharSize()); } else if ("simple".equals(field.fragmenter())) { fragmenter = new SimpleFragmenter(field.fragmentCharSize()); } else if ("span".equals(field.fragmenter())) { fragmenter = new SimpleSpanFragmenter(queryScorer, field.fragmentCharSize()); } else { throw new ElasticsearchIllegalArgumentException("unknown fragmenter option [" + field.fragmenter() + "] for the field [" + highlighterContext.fieldName + "]"); } Formatter formatter = new SimpleHTMLFormatter(field.preTags()[0], field.postTags()[0]); entry = new org.apache.lucene.search.highlight.Highlighter(formatter, encoder, queryScorer); entry.setTextFragmenter(fragmenter); // always highlight across all data entry.setMaxDocCharsToAnalyze(Integer.MAX_VALUE); cache.put(mapper, entry); } // a HACK to make highlighter do highlighting, even though its using the single frag list builder int numberOfFragments = field.numberOfFragments() == 0 ? 1 : field.numberOfFragments(); ArrayList<TextFragment> fragsList = new ArrayList<TextFragment>(); List<Object> textsToHighlight; try { textsToHighlight = HighlightUtils.loadFieldValues(mapper, context, hitContext, field.forceSource()); for (Object textToHighlight : textsToHighlight) { String text = textToHighlight.toString(); Analyzer analyzer = context.mapperService().documentMapper(hitContext.hit().type()).mappers().indexAnalyzer(); TokenStream tokenStream = analyzer.tokenStream(mapper.names().indexName(), text); if (!tokenStream.hasAttribute(CharTermAttribute.class) || !tokenStream.hasAttribute(OffsetAttribute.class)) { // can't perform highlighting if the stream has no terms (binary token stream) or no offsets continue; } TextFragment[] bestTextFragments = entry.getBestTextFragments(tokenStream, text, false, numberOfFragments); for (TextFragment bestTextFragment : bestTextFragments) { if (bestTextFragment != null && bestTextFragment.getScore() > 0) { fragsList.add(bestTextFragment); } } } } catch (Exception e) { throw new FetchPhaseExecutionException(context, "Failed to highlight field [" + highlighterContext.fieldName + "]", e); } if (field.scoreOrdered()) { CollectionUtil.introSort(fragsList, new Comparator<TextFragment>() { public int compare(TextFragment o1, TextFragment o2) { return Math.round(o2.getScore() - o1.getScore()); } }); } String[] fragments; // number_of_fragments is set to 0 but we have a multivalued field if (field.numberOfFragments() == 0 && textsToHighlight.size() > 1 && fragsList.size() > 0) { fragments = new String[fragsList.size()]; for (int i = 0; i < fragsList.size(); i++) { fragments[i] = fragsList.get(i).toString(); } } else { // refine numberOfFragments if needed numberOfFragments = fragsList.size() < numberOfFragments ? fragsList.size() : numberOfFragments; fragments = new String[numberOfFragments]; for (int i = 0; i < fragments.length; i++) { fragments[i] = fragsList.get(i).toString(); } } if (fragments != null && fragments.length > 0) { return new HighlightField(highlighterContext.fieldName, StringText.convertFromStringArray(fragments)); } int noMatchSize = highlighterContext.field.noMatchSize(); if (noMatchSize > 0 && textsToHighlight.size() > 0) { // Pull an excerpt from the beginning of the string but make sure to split the string on a term boundary. String fieldContents = textsToHighlight.get(0).toString(); Analyzer analyzer = context.mapperService().documentMapper(hitContext.hit().type()).mappers().indexAnalyzer(); int end; try { end = findGoodEndForNoHighlightExcerpt(noMatchSize, analyzer.tokenStream(mapper.names().indexName(), fieldContents)); } catch (Exception e) { throw new FetchPhaseExecutionException(context, "Failed to highlight field [" + highlighterContext.fieldName + "]", e); } if (end > 0) { return new HighlightField(highlighterContext.fieldName, new Text[] { new StringText(fieldContents.substring(0, end)) }); } } return null; } private static int findGoodEndForNoHighlightExcerpt(int noMatchSize, TokenStream tokenStream) throws IOException { try { if (!tokenStream.hasAttribute(OffsetAttribute.class)) { // Can't split on term boundaries without offsets return -1; } int end = -1; tokenStream.reset(); while (tokenStream.incrementToken()) { OffsetAttribute attr = tokenStream.getAttribute(OffsetAttribute.class); if (attr.endOffset() >= noMatchSize) { // Jump to the end of this token if it wouldn't put us past the boundary if (attr.endOffset() == noMatchSize) { end = noMatchSize; } return end; } end = attr.endOffset(); } // We've exhausted the token stream so we should just highlight everything. return end; } finally { tokenStream.end(); tokenStream.close(); } } }
1no label
src_main_java_org_elasticsearch_search_highlight_PlainHighlighter.java
3,608
public static class Defaults extends NumberFieldMapper.Defaults { public static final FieldType FIELD_TYPE = new FieldType(NumberFieldMapper.Defaults.FIELD_TYPE); static { FIELD_TYPE.freeze(); } public static final Short NULL_VALUE = null; }
0true
src_main_java_org_elasticsearch_index_mapper_core_ShortFieldMapper.java
1,195
@Service("blPaymentInfoService") public class PaymentInfoServiceImpl implements PaymentInfoService { @Resource(name = "blPaymentInfoDao") protected PaymentInfoDao paymentInfoDao; public PaymentInfo save(PaymentInfo paymentInfo) { return paymentInfoDao.save(paymentInfo); } public PaymentResponseItem save(PaymentResponseItem paymentResponseItem) { return paymentInfoDao.save(paymentResponseItem); } public PaymentLog save(PaymentLog log) { return paymentInfoDao.save(log); } public PaymentInfo readPaymentInfoById(Long paymentId) { return paymentInfoDao.readPaymentInfoById(paymentId); } public List<PaymentInfo> readPaymentInfosForOrder(Order order) { return paymentInfoDao.readPaymentInfosForOrder(order); } public PaymentInfo create() { return paymentInfoDao.create(); } public void delete(PaymentInfo paymentInfo) { paymentInfoDao.delete(paymentInfo); } public PaymentLog createLog() { return paymentInfoDao.createLog(); } public PaymentResponseItem createResponseItem() { PaymentResponseItem returnItem = paymentInfoDao.createResponseItem(); returnItem.setTransactionTimestamp(SystemTime.asDate()); return returnItem; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_service_PaymentInfoServiceImpl.java
1,373
public class AliasAction implements Streamable { public static enum Type { ADD((byte) 0), REMOVE((byte) 1); private final byte value; Type(byte value) { this.value = value; } public byte value() { return value; } public static Type fromValue(byte value) { if (value == 0) { return ADD; } else if (value == 1) { return REMOVE; } else { throw new ElasticsearchIllegalArgumentException("No type for action [" + value + "]"); } } } private Type actionType; private String index; private String alias; @Nullable private String filter; @Nullable private String indexRouting; @Nullable private String searchRouting; private AliasAction() { } public AliasAction(AliasAction other) { this.actionType = other.actionType; this.index = other.index; this.alias = other.alias; this.filter = other.filter; this.indexRouting = other.indexRouting; this.searchRouting = other.searchRouting; } public AliasAction(Type actionType) { this.actionType = actionType; } public AliasAction(Type actionType, String index, String alias) { this.actionType = actionType; this.index = index; this.alias = alias; } public AliasAction(Type actionType, String index, String alias, String filter) { this.actionType = actionType; this.index = index; this.alias = alias; this.filter = filter; } public Type actionType() { return actionType; } public AliasAction index(String index) { this.index = index; return this; } public String index() { return index; } public AliasAction alias(String alias) { this.alias = alias; return this; } public String alias() { return alias; } public String filter() { return filter; } public AliasAction filter(String filter) { this.filter = filter; return this; } public AliasAction filter(Map<String, Object> filter) { if (filter == null || filter.isEmpty()) { this.filter = null; return this; } try { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); builder.map(filter); this.filter = builder.string(); return this; } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + filter + "]", e); } } public AliasAction filter(FilterBuilder filterBuilder) { if (filterBuilder == null) { this.filter = null; return this; } try { XContentBuilder builder = XContentFactory.jsonBuilder(); filterBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.close(); this.filter = builder.string(); return this; } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to build json for alias request", e); } } public AliasAction routing(String routing) { this.indexRouting = routing; this.searchRouting = routing; return this; } public String indexRouting() { return indexRouting; } public AliasAction indexRouting(String indexRouting) { this.indexRouting = indexRouting; return this; } public String searchRouting() { return searchRouting; } public AliasAction searchRouting(String searchRouting) { this.searchRouting = searchRouting; return this; } public static AliasAction readAliasAction(StreamInput in) throws IOException { AliasAction aliasAction = new AliasAction(); aliasAction.readFrom(in); return aliasAction; } @Override public void readFrom(StreamInput in) throws IOException { actionType = Type.fromValue(in.readByte()); index = in.readOptionalString(); alias = in.readOptionalString(); filter = in.readOptionalString(); indexRouting = in.readOptionalString(); searchRouting = in.readOptionalString(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeByte(actionType.value()); out.writeOptionalString(index); out.writeOptionalString(alias); out.writeOptionalString(filter); out.writeOptionalString(indexRouting); out.writeOptionalString(searchRouting); } public static AliasAction newAddAliasAction(String index, String alias) { return new AliasAction(Type.ADD, index, alias); } public static AliasAction newRemoveAliasAction(String index, String alias) { return new AliasAction(Type.REMOVE, index, alias); } }
0true
src_main_java_org_elasticsearch_cluster_metadata_AliasAction.java
2,093
public class BytesStreamInput extends StreamInput { protected byte buf[]; protected int pos; protected int count; private final boolean unsafe; public BytesStreamInput(BytesReference bytes) { if (!bytes.hasArray()) { bytes = bytes.toBytesArray(); } this.buf = bytes.array(); this.pos = bytes.arrayOffset(); this.count = bytes.length(); this.unsafe = false; } public BytesStreamInput(byte buf[], boolean unsafe) { this(buf, 0, buf.length, unsafe); } public BytesStreamInput(byte buf[], int offset, int length, boolean unsafe) { this.buf = buf; this.pos = offset; this.count = Math.min(offset + length, buf.length); this.unsafe = unsafe; } @Override public BytesReference readBytesReference(int length) throws IOException { if (unsafe) { return super.readBytesReference(length); } BytesArray bytes = new BytesArray(buf, pos, length); pos += length; return bytes; } @Override public BytesRef readBytesRef(int length) throws IOException { if (unsafe) { return super.readBytesRef(length); } BytesRef bytes = new BytesRef(buf, pos, length); pos += length; return bytes; } @Override public long skip(long n) throws IOException { if (pos + n > count) { n = count - pos; } if (n < 0) { return 0; } pos += n; return n; } public int position() { return this.pos; } @Override public int read() throws IOException { return (pos < count) ? (buf[pos++] & 0xff) : -1; } @Override public int read(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } if (pos >= count) { return -1; } if (pos + len > count) { len = count - pos; } if (len <= 0) { return 0; } System.arraycopy(buf, pos, b, off, len); pos += len; return len; } public byte[] underlyingBuffer() { return buf; } @Override public byte readByte() throws IOException { if (pos >= count) { throw new EOFException(); } return buf[pos++]; } @Override public void readBytes(byte[] b, int offset, int len) throws IOException { if (len == 0) { return; } if (pos >= count) { throw new EOFException(); } if (pos + len > count) { len = count - pos; } if (len <= 0) { throw new EOFException(); } System.arraycopy(buf, pos, b, offset, len); pos += len; } @Override public void reset() throws IOException { pos = 0; } @Override public void close() throws IOException { // nothing to do here... } }
0true
src_main_java_org_elasticsearch_common_io_stream_BytesStreamInput.java
680
public class OHashIndexBufferStore extends OSingleFileSegment { public OHashIndexBufferStore(String iPath, String iType) throws IOException { super(iPath, iType); } public OHashIndexBufferStore(OStorageLocalAbstract iStorage, OStorageFileConfiguration iConfig) throws IOException { super(iStorage, iConfig); } public OHashIndexBufferStore(OStorageLocalAbstract iStorage, OStorageFileConfiguration iConfig, String iType) throws IOException { super(iStorage, iConfig, iType); } public void setRecordsCount(final long recordsCount) throws IOException { file.writeHeaderLong(0, recordsCount); } public long getRecordsCount() throws IOException { return file.readHeaderLong(0); } public void setKeySerializerId(byte keySerializerId) throws IOException { file.writeHeaderLong(OLongSerializer.LONG_SIZE, keySerializerId); } public byte getKeySerializerId() throws IOException { return (byte) file.readHeaderLong(OLongSerializer.LONG_SIZE); } public void setValueSerializerId(byte valueSerializerId) throws IOException { file.writeHeaderLong(OLongSerializer.LONG_SIZE * 2, valueSerializerId); } public byte getValuerSerializerId() throws IOException { return (byte) file.readHeaderLong(OLongSerializer.LONG_SIZE * 2); } public void storeMetadata(OHashIndexFileLevelMetadata[] filesMetadata) throws IOException { int bufferSize = 0; int counter = 0; for (OHashIndexFileLevelMetadata metadata : filesMetadata) { if (metadata == null) break; counter++; final String fileName = metadata.getFileName(); bufferSize += OStringSerializer.INSTANCE.getObjectSize(fileName); bufferSize += 2 * OLongSerializer.LONG_SIZE; } final int totalSize = bufferSize + 2 * OIntegerSerializer.INT_SIZE; if (file.getFilledUpTo() < totalSize) file.allocateSpace(totalSize - file.getFilledUpTo()); byte[] buffer = new byte[bufferSize]; int offset = 0; for (OHashIndexFileLevelMetadata fileMetadata : filesMetadata) { if (fileMetadata == null) break; OStringSerializer.INSTANCE.serializeNative(fileMetadata.getFileName(), buffer, offset); offset += OStringSerializer.INSTANCE.getObjectSize(fileMetadata.getFileName()); OLongSerializer.INSTANCE.serializeNative(fileMetadata.getBucketsCount(), buffer, offset); offset += OLongSerializer.LONG_SIZE; OLongSerializer.INSTANCE.serializeNative(fileMetadata.getTombstoneIndex(), buffer, offset); offset += OLongSerializer.LONG_SIZE; } file.writeInt(0, counter); file.writeInt(OIntegerSerializer.INT_SIZE, buffer.length); file.write(2 * OIntegerSerializer.INT_SIZE, buffer); } public OHashIndexFileLevelMetadata[] loadMetadata() throws IOException { final int len = file.readInt(0); final OHashIndexFileLevelMetadata[] metadatas = new OHashIndexFileLevelMetadata[64]; final int bufferSize = file.readInt(OIntegerSerializer.INT_SIZE); final byte[] buffer = new byte[bufferSize]; file.read(2 * OIntegerSerializer.INT_SIZE, buffer, buffer.length); int offset = 0; for (int i = 0; i < len; i++) { final String name = OStringSerializer.INSTANCE.deserializeNative(buffer, offset); offset += OStringSerializer.INSTANCE.getObjectSize(name); final long bucketsCount = OLongSerializer.INSTANCE.deserializeNative(buffer, offset); offset += OLongSerializer.LONG_SIZE; final long tombstone = OLongSerializer.INSTANCE.deserializeNative(buffer, offset); offset += OLongSerializer.LONG_SIZE; final OHashIndexFileLevelMetadata metadata = new OHashIndexFileLevelMetadata(name, bucketsCount, tombstone); metadatas[i] = metadata; } return metadatas; } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_hashindex_local_OHashIndexBufferStore.java
1,298
clusterService.submitStateUpdateTask("1", new ClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { invoked3.countDown(); try { block2.await(); } catch (InterruptedException e) { fail(); } return currentState; } @Override public void onFailure(String source, Throwable t) { invoked3.countDown(); fail(); } });
0true
src_test_java_org_elasticsearch_cluster_ClusterServiceTests.java
503
public interface OEngine { public String getName(); public OStorage createStorage(String iURL, Map<String, String> parameters); public void removeStorage(OStorage iStorage); public boolean isShared(); public void shutdown(); }
0true
core_src_main_java_com_orientechnologies_orient_core_engine_OEngine.java
319
new Thread() { public void run() { map.lock(key); map.lock(key); lockedLatch.countDown(); } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapLockTest.java
1,278
public class TestSimulateError { public static TestSimulateError onDataLocalWriteRecord; public static boolean onDataLocalWriteRecord(ODataLocal iODataLocal, long[] iFilePosition, int iClusterSegment, long iClusterPosition, byte[] iContent) { if (onDataLocalWriteRecord != null) return onDataLocalWriteRecord.checkDataLocalWriteRecord(iODataLocal, iFilePosition, iClusterSegment, iClusterPosition, iContent); return true; } public boolean checkDataLocalWriteRecord(ODataLocal iODataLocal, long[] iFilePosition, int iClusterSegment, long iClusterPosition, byte[] iContent) { return true; } }
0true
core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_TestSimulateError.java
730
@SuppressWarnings("deprecation") public class CatalogTest extends BaseTest { @Resource private CatalogService catalogService; @Test(groups = {"testCatalog"}) @Transactional public void testCatalog() throws Exception { Category category = new CategoryImpl(); category.setName("Soaps"); category = catalogService.saveCategory(category); Category category2 = new CategoryImpl(); category2.setName("Towels"); category2 = catalogService.saveCategory(category2); Category category3 = new CategoryImpl(); category3.setName("SuperCategory"); category3 = catalogService.saveCategory(category3); CategoryXref temp = new CategoryXrefImpl(); temp.setCategory(category); temp.setSubCategory(category3); category3.getAllParentCategoryXrefs().add(temp); category3 = catalogService.saveCategory(category3); // Test category hierarchy Long cat3Id = category3.getId(); category3 = null; category3 = catalogService.findCategoryById(cat3Id); category3.getAllParentCategoryXrefs().clear(); CategoryXref temp2 = new CategoryXrefImpl(); temp2.setCategory(category); temp2.setSubCategory(category3); category3.getAllParentCategoryXrefs().add(temp2); CategoryXref temp3 = new CategoryXrefImpl(); temp3.setCategory(category2); temp3.setSubCategory(category3); category3.getAllParentCategoryXrefs().add(temp3); category3 = catalogService.saveCategory(category3); assert category3.getAllParentCategoryXrefs().size() == 2; Product newProduct = new ProductImpl(); Sku newDefaultSku = new SkuImpl(); newDefaultSku = catalogService.saveSku(newDefaultSku); newProduct.setDefaultSku(newDefaultSku); newProduct.setName("Lavender Soap"); Calendar activeStartCal = Calendar.getInstance(); activeStartCal.add(Calendar.DAY_OF_YEAR, -2); newProduct.setActiveStartDate(activeStartCal.getTime()); // newProduct.setAllParentCategories(allParentCategories); newProduct.setDefaultCategory(category); newProduct.getAllParentCategoryXrefs().clear(); newProduct = catalogService.saveProduct(newProduct); CategoryProductXref categoryXref = new CategoryProductXrefImpl(); categoryXref.setProduct(newProduct); categoryXref.setCategory(category); newProduct.getAllParentCategoryXrefs().add(categoryXref); CategoryProductXref categoryXref2 = new CategoryProductXrefImpl(); categoryXref2.setProduct(newProduct); categoryXref2.setCategory(category2); newProduct.getAllParentCategoryXrefs().add(categoryXref2); newProduct = catalogService.saveProduct(newProduct); Long newProductId = newProduct.getId(); Product testProduct = catalogService.findProductById(newProductId); assert testProduct.getId().equals(testProduct.getId()); Category testCategory = catalogService.findCategoryByName("Soaps"); assert testCategory.getId().equals(category.getId()); testCategory = catalogService.findCategoryById(category.getId()); assert testCategory.getId().equals(category.getId()); Map<String, Media> categoryMedia = testCategory.getCategoryMedia(); Media media = new MediaImpl(); media.setAltText("test"); media.setTitle("large"); media.setUrl("http://myUrl"); categoryMedia.put("large", media); catalogService.saveCategory(testCategory); testCategory = catalogService.findCategoryById(category.getId()); assert(testCategory.getCategoryMedia().get("large") != null); List<Category> categories = catalogService.findAllCategories(); assert categories != null && categories.size() == 3; List<Product> products = catalogService.findAllProducts(); boolean foundProduct = false; for (Product product : products ) { if (product.getId().equals(newProductId)) { foundProduct = true; } } assert foundProduct == true; products = catalogService.findProductsByName(newProduct.getName()); foundProduct = false; for (Product product : products ) { if (product.getId().equals(newProductId)) { foundProduct = true; } } assert foundProduct == true; Sku newSku = new SkuImpl(); newSku.setName("Under Armor T-Shirt -- Red"); newSku.setRetailPrice(new Money(14.99)); newSku.setActiveStartDate(activeStartCal.getTime()); newSku = catalogService.saveSku(newSku); List<Sku> allSkus = new ArrayList<Sku>(); allSkus.add(newSku); newProduct.setAdditionalSkus(allSkus); newProduct = catalogService.saveProduct(newProduct); Long skuId = newProduct.getSkus().get(0).getId(); Sku testSku = catalogService.findSkuById(skuId); assert testSku.getId().equals(skuId); List<Sku> testSkus = catalogService.findAllSkus(); boolean foundSku = false; for (Sku sku : testSkus) { if (sku.getId().equals(skuId)) { foundSku = true; } } assert foundSku == true; List<Long> skuIds = new ArrayList<Long>(); skuIds.add(skuId); testSkus = catalogService.findSkusByIds(skuIds); foundSku = false; for (Sku sku : testSkus) { if (sku.getId().equals(skuId)) { foundSku = true; } } assert foundSku == true; } @Test public void testSkus() throws Exception { Sku sku = new SkuImpl(); String longDescription = "This is a great product that will help the Longhorns win."; String description = "This is a great product."; sku.setLongDescription(longDescription); assert sku.getLongDescription().equals(longDescription); sku.setDescription(description); assert sku.getDescription().equals(description); assert sku.isTaxable() == null; sku.setTaxable(null); assert sku.isTaxable() == null; sku.setTaxable(true); assert sku.isTaxable() == true; sku.setTaxable(false); assert sku.isTaxable() == false; sku.setDiscountable(null); assert sku.isDiscountable() == false; sku.setDiscountable(true); assert sku.isDiscountable() == true; sku.setDiscountable(false); assert sku.isDiscountable() == false; assert sku.isAvailable() == true; sku.setAvailable(null); assert sku.isAvailable() == true; sku.setAvailable(true); assert sku.isAvailable() == true; sku.setAvailable(false); assert sku.isAvailable() == false; assert sku.getName() == null; } }
0true
integration_src_test_java_org_broadleafcommerce_core_catalog_service_CatalogTest.java
292
public interface OScriptFormatter { public String getFunctionDefinition(OFunction iFunction); public String getFunctionInvoke(OFunction iFunction, final Object[] iArgs); }
0true
core_src_main_java_com_orientechnologies_orient_core_command_script_formatter_OScriptFormatter.java
162
public class TestTxEntries { private final Random random = new Random(); private final long refTime = System.currentTimeMillis(); private final int refId = 1; private final int refMaster = 1; private final int refMe = 1; private final long startPosition = 1000; private final String storeDir = "dir"; @Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule(); /* * Starts a JVM, executes a tx that fails on prepare and rollbacks, * triggering a bug where an extra start entry for that tx is written * in the xa log. */ @Test public void testStartEntryWrittenOnceOnRollback() throws Exception { final GraphDatabaseService db = new TestGraphDatabaseFactory().setFileSystem( fs.get() ).newImpermanentDatabase( storeDir ); createSomeTransactions( db ); EphemeralFileSystemAbstraction snapshot = fs.snapshot( shutdownDb( db ) ); new TestGraphDatabaseFactory().setFileSystem( snapshot ).newImpermanentDatabase( storeDir ).shutdown(); } @Test public void startEntryShouldBeUniqueIfEitherValueChanges() throws Exception { // Positive Xid hashcode assertCorrectChecksumEquality( randomXid( Boolean.TRUE ) ); // Negative Xid hashcode assertCorrectChecksumEquality( randomXid( Boolean.FALSE ) ); } private void assertCorrectChecksumEquality( Xid refXid ) { Start ref = new Start( refXid, refId, refMaster, refMe, startPosition, refTime, 0l ); assertChecksumsEquals( ref, new Start( refXid, refId, refMaster, refMe, startPosition, refTime, 0l ) ); // Different Xids assertChecksumsNotEqual( ref, new Start( randomXid( null ), refId, refMaster, refMe, startPosition, refTime, 0l ) ); // Different master assertChecksumsNotEqual( ref, new Start( refXid, refId, refMaster+1, refMe, startPosition, refTime, 0l ) ); // Different me assertChecksumsNotEqual( ref, new Start( refXid, refId, refMaster, refMe+1, startPosition, refTime, 0l ) ); } private void assertChecksumsNotEqual( Start ref, Start other ) { assertFalse( ref.getChecksum() == other.getChecksum() ); } private void assertChecksumsEquals( Start ref, Start other ) { assertEquals( ref.getChecksum(), other.getChecksum() ); } private Xid randomXid( Boolean trueForPositive ) { while ( true ) { Xid xid = new XidImpl( randomBytes(), randomBytes() ); if ( trueForPositive == null || xid.hashCode() > 0 == trueForPositive.booleanValue() ) { return xid; } } } private byte[] randomBytes() { byte[] bytes = new byte[random.nextInt( 10 )+5]; for ( int i = 0; i < bytes.length; i++ ) { bytes[i] = (byte) random.nextInt( 255 ); } return bytes; } private void createSomeTransactions( GraphDatabaseService db ) { Transaction tx = db.beginTx(); Node node1 = db.createNode(); Node node2 = db.createNode(); node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "relType1" ) ); tx.success(); tx.finish(); tx = db.beginTx(); node1.delete(); tx.success(); try { // Will throw exception, causing the tx to be rolledback. tx.finish(); } catch ( Exception nothingToSeeHereMoveAlong ) { // InvalidRecordException coming, node1 has rels } /* * The damage has already been done. The following just makes sure * the corrupting tx is flushed to disk, since we will exit * uncleanly. */ tx = db.beginTx(); node1.setProperty( "foo", "bar" ); tx.success(); tx.finish(); } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestTxEntries.java
249
public class OEmptyCache implements OCache { @Override public void startup() { } @Override public void shutdown() { } @Override public boolean isEnabled() { return false; } @Override public boolean enable() { return false; } @Override public boolean disable() { return false; } @Override public ORecordInternal<?> get(ORID id) { return null; } @Override public ORecordInternal<?> put(ORecordInternal<?> record) { return null; } @Override public ORecordInternal<?> remove(ORID id) { return null; } @Override public void clear() { } @Override public int size() { return 0; } @Override public int limit() { return 0; } @Override public Collection<ORID> keys() { return Collections.emptyList(); } @Override public void lock(ORID id) { } @Override public void unlock(ORID id) { } }
0true
core_src_main_java_com_orientechnologies_orient_core_cache_OEmptyCache.java
588
public final class ConfigCheck implements IdentifiedDataSerializable { private String groupName; private String groupPassword; private String joinerType; private boolean partitionGroupEnabled; private PartitionGroupConfig.MemberGroupType memberGroupType; public ConfigCheck() { } public boolean isCompatible(ConfigCheck other) { if (!groupName.equals(other.groupName)) { return false; } if (!groupPassword.equals(other.groupPassword)) { throw new HazelcastException("Incompatible group password!"); } if (!joinerType.equals(other.joinerType)) { throw new HazelcastException("Incompatible joiners! " + joinerType + " -vs- " + other.joinerType); } if (!partitionGroupEnabled && other.partitionGroupEnabled || partitionGroupEnabled && !other.partitionGroupEnabled) { throw new HazelcastException("Incompatible partition groups! " + "this: " + (partitionGroupEnabled ? "enabled" : "disabled") + " / " + memberGroupType + ", other: " + (other.partitionGroupEnabled ? "enabled" : "disabled") + " / " + other.memberGroupType); } if (partitionGroupEnabled && memberGroupType != other.memberGroupType) { throw new HazelcastException("Incompatible partition groups! this: " + memberGroupType + ", other: " + other.memberGroupType); } return true; } public ConfigCheck setGroupName(String groupName) { this.groupName = groupName; return this; } public ConfigCheck setGroupPassword(String groupPassword) { this.groupPassword = groupPassword; return this; } public ConfigCheck setJoinerType(String joinerType) { this.joinerType = joinerType; return this; } public ConfigCheck setPartitionGroupEnabled(boolean partitionGroupEnabled) { this.partitionGroupEnabled = partitionGroupEnabled; return this; } public ConfigCheck setMemberGroupType(PartitionGroupConfig.MemberGroupType memberGroupType) { this.memberGroupType = memberGroupType; return this; } @Override public int getFactoryId() { return ClusterDataSerializerHook.F_ID; } @Override public int getId() { return ClusterDataSerializerHook.CONFIG_CHECK; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(groupName); out.writeUTF(groupPassword); out.writeUTF(joinerType); out.writeBoolean(partitionGroupEnabled); if (partitionGroupEnabled) { out.writeUTF(memberGroupType.toString()); } } @Override public void readData(ObjectDataInput in) throws IOException { groupName = in.readUTF(); groupPassword = in.readUTF(); joinerType = in.readUTF(); partitionGroupEnabled = in.readBoolean(); if (partitionGroupEnabled) { String s = in.readUTF(); try { memberGroupType = PartitionGroupConfig.MemberGroupType.valueOf(s); } catch (IllegalArgumentException ignored) { } } } }
1no label
hazelcast_src_main_java_com_hazelcast_cluster_ConfigCheck.java
3,567
private static final class SuggestField extends Field { private final BytesRef payload; private final CompletionTokenStream.ToFiniteStrings toFiniteStrings; public SuggestField(String name, Reader value, FieldType type, BytesRef payload, CompletionTokenStream.ToFiniteStrings toFiniteStrings) { super(name, value, type); this.payload = payload; this.toFiniteStrings = toFiniteStrings; } public SuggestField(String name, String value, FieldType type, BytesRef payload, CompletionTokenStream.ToFiniteStrings toFiniteStrings) { super(name, value, type); this.payload = payload; this.toFiniteStrings = toFiniteStrings; } @Override public TokenStream tokenStream(Analyzer analyzer) throws IOException { TokenStream ts = super.tokenStream(analyzer); return new CompletionTokenStream(ts, payload, toFiniteStrings); } }
0true
src_main_java_org_elasticsearch_index_mapper_core_CompletionFieldMapper.java