Unnamed: 0
int64 0
6.45k
| func
stringlengths 37
161k
| target
class label 2
classes | project
stringlengths 33
167
|
---|---|---|---|
0 |
public final class StandaloneRandomizedContext {
private StandaloneRandomizedContext() {
}
/**
* Creates a new {@link RandomizedContext} associated to the current thread
*/
public static void createRandomizedContext(Class<?> testClass, Randomness runnerRandomness) {
//the randomized runner is passed in as null, which is fine as long as we don't try to access it afterwards
RandomizedContext randomizedContext = RandomizedContext.create(Thread.currentThread().getThreadGroup(), testClass, null);
randomizedContext.push(runnerRandomness.clone(Thread.currentThread()));
}
/**
* Destroys the {@link RandomizedContext} associated to the current thread
*/
public static void disposeRandomizedContext() {
RandomizedContext.current().dispose();
}
public static void pushRandomness(Randomness randomness) {
RandomizedContext.current().push(randomness);
}
public static void popAndDestroy() {
RandomizedContext.current().popAndDestroy();
}
/**
* Returns the string formatted seed associated to the current thread's randomized context
*/
public static String getSeedAsString() {
return SeedUtils.formatSeed(RandomizedContext.current().getRandomness().getSeed());
}
/**
* Util method to extract the seed out of a {@link Randomness} instance
*/
public static long getSeed(Randomness randomness) {
return randomness.getSeed();
}
}
| 0true
|
src_test_java_com_carrotsearch_randomizedtesting_StandaloneRandomizedContext.java
|
971 |
public class OBinarySerializerFactory {
private final Map<Byte, OBinarySerializer<?>> serializerIdMap = new HashMap<Byte, OBinarySerializer<?>>();
private final Map<Byte, Class<? extends OBinarySerializer<?>>> serializerClassesIdMap = new HashMap<Byte, Class<? extends OBinarySerializer<?>>>();
private final Map<OType, OBinarySerializer<?>> serializerTypeMap = new HashMap<OType, OBinarySerializer<?>>();
/**
* Instance of the factory
*/
public static final OBinarySerializerFactory INSTANCE = new OBinarySerializerFactory();
/**
* Size of the type identifier block size
*/
public static final int TYPE_IDENTIFIER_SIZE = 1;
private OBinarySerializerFactory() {
// STATELESS SERIALIER
registerSerializer(new ONullSerializer(), null);
registerSerializer(OBooleanSerializer.INSTANCE, OType.BOOLEAN);
registerSerializer(OIntegerSerializer.INSTANCE, OType.INTEGER);
registerSerializer(OShortSerializer.INSTANCE, OType.SHORT);
registerSerializer(OLongSerializer.INSTANCE, OType.LONG);
registerSerializer(OFloatSerializer.INSTANCE, OType.FLOAT);
registerSerializer(ODoubleSerializer.INSTANCE, OType.DOUBLE);
registerSerializer(ODateTimeSerializer.INSTANCE, OType.DATETIME);
registerSerializer(OCharSerializer.INSTANCE, null);
registerSerializer(OStringSerializer.INSTANCE, OType.STRING);
registerSerializer(OByteSerializer.INSTANCE, OType.BYTE);
registerSerializer(ODateSerializer.INSTANCE, OType.DATE);
registerSerializer(OLinkSerializer.INSTANCE, OType.LINK);
registerSerializer(OCompositeKeySerializer.INSTANCE, null);
registerSerializer(OStreamSerializerRID.INSTANCE, null);
registerSerializer(OBinaryTypeSerializer.INSTANCE, OType.BINARY);
registerSerializer(ODecimalSerializer.INSTANCE, OType.DECIMAL);
registerSerializer(OStreamSerializerListRID.INSTANCE, null);
registerSerializer(OStreamSerializerOldRIDContainer.INSTANCE, null);
registerSerializer(OStreamSerializerSBTreeIndexRIDContainer.INSTANCE, null);
registerSerializer(OPhysicalPositionSerializer.INSTANCE, null);
registerSerializer(OClusterPositionSerializer.INSTANCE, null);
// STATEFUL SERIALIER
registerSerializer(OSimpleKeySerializer.ID, OSimpleKeySerializer.class);
}
public void registerSerializer(final OBinarySerializer<?> iInstance, final OType iType) {
if (serializerIdMap.containsKey(iInstance.getId()))
throw new IllegalArgumentException("Binary serializer with id " + iInstance.getId() + " has been already registered.");
serializerIdMap.put(iInstance.getId(), iInstance);
if (iType != null)
serializerTypeMap.put(iType, iInstance);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void registerSerializer(final byte iId, final Class<? extends OBinarySerializer> iClass) {
if (serializerClassesIdMap.containsKey(iId))
throw new IllegalStateException("Serializer with id " + iId + " has been already registered.");
serializerClassesIdMap.put(iId, (Class<? extends OBinarySerializer<?>>) iClass);
}
/**
* Obtain OBinarySerializer instance by it's id.
*
* @param identifier
* is serializes identifier.
* @return OBinarySerializer instance.
*/
public OBinarySerializer<?> getObjectSerializer(final byte identifier) {
OBinarySerializer<?> impl = serializerIdMap.get(identifier);
if (impl == null) {
final Class<? extends OBinarySerializer<?>> cls = serializerClassesIdMap.get(identifier);
if (cls != null)
try {
impl = cls.newInstance();
} catch (Exception e) {
OLogManager.instance().error(this, "Cannot create an instance of class %s invoking the empty constructor", cls);
}
}
return impl;
}
/**
* Obtain OBinarySerializer realization for the OType
*
* @param type
* is the OType to obtain serializer algorithm for
* @return OBinarySerializer instance
*/
public OBinarySerializer<?> getObjectSerializer(final OType type) {
return serializerTypeMap.get(type);
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_binary_OBinarySerializerFactory.java
|
3,424 |
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
recoveryStatus = new RecoveryStatus();
recoveryStatus.updateStage(RecoveryStatus.Stage.INIT);
try {
if (indexShard.routingEntry().restoreSource() != null) {
logger.debug("restoring from {} ...", indexShard.routingEntry().restoreSource());
snapshotService.restore(recoveryStatus);
} else {
logger.debug("starting recovery from {} ...", shardGateway);
shardGateway.recover(indexShouldExists, recoveryStatus);
}
lastIndexVersion = recoveryStatus.index().version();
lastTranslogId = -1;
lastTranslogLength = 0;
lastTotalTranslogOperations = recoveryStatus.translog().currentTranslogOperations();
// start the shard if the gateway has not started it already. Note that if the gateway
// moved shard to POST_RECOVERY, it may have been started as well if:
// 1) master sent a new cluster state indicating shard is initializing
// 2) IndicesClusterStateService#applyInitializingShard will send a shard started event
// 3) Master will mark shard as started and this will be processed locally.
IndexShardState shardState = indexShard.state();
if (shardState != IndexShardState.POST_RECOVERY && shardState != IndexShardState.STARTED) {
indexShard.postRecovery("post recovery from gateway");
}
// refresh the shard
indexShard.refresh(new Engine.Refresh("post_gateway").force(true));
recoveryStatus.time(System.currentTimeMillis() - recoveryStatus.startTime());
recoveryStatus.updateStage(RecoveryStatus.Stage.DONE);
if (logger.isDebugEnabled()) {
logger.debug("recovery completed from [{}], took [{}]", shardGateway, timeValueMillis(recoveryStatus.time()));
} else if (logger.isTraceEnabled()) {
StringBuilder sb = new StringBuilder();
sb.append("recovery completed from ").append(shardGateway).append(", took [").append(timeValueMillis(recoveryStatus.time())).append("]\n");
sb.append(" index : files [").append(recoveryStatus.index().numberOfFiles()).append("] with total_size [").append(new ByteSizeValue(recoveryStatus.index().totalSize())).append("], took[").append(TimeValue.timeValueMillis(recoveryStatus.index().time())).append("]\n");
sb.append(" : recovered_files [").append(recoveryStatus.index().numberOfRecoveredFiles()).append("] with total_size [").append(new ByteSizeValue(recoveryStatus.index().recoveredTotalSize())).append("]\n");
sb.append(" : reusing_files [").append(recoveryStatus.index().numberOfReusedFiles()).append("] with total_size [").append(new ByteSizeValue(recoveryStatus.index().reusedTotalSize())).append("]\n");
sb.append(" start : took [").append(TimeValue.timeValueMillis(recoveryStatus.start().time())).append("], check_index [").append(timeValueMillis(recoveryStatus.start().checkIndexTime())).append("]\n");
sb.append(" translog : number_of_operations [").append(recoveryStatus.translog().currentTranslogOperations()).append("], took [").append(TimeValue.timeValueMillis(recoveryStatus.translog().time())).append("]");
logger.trace(sb.toString());
}
listener.onRecoveryDone();
scheduleSnapshotIfNeeded();
} catch (IndexShardGatewayRecoveryException e) {
if (indexShard.state() == IndexShardState.CLOSED) {
// got closed on us, just ignore this recovery
listener.onIgnoreRecovery("shard closed");
return;
}
if ((e.getCause() instanceof IndexShardClosedException) || (e.getCause() instanceof IndexShardNotStartedException)) {
// got closed on us, just ignore this recovery
listener.onIgnoreRecovery("shard closed");
return;
}
listener.onRecoveryFailed(e);
} catch (IndexShardClosedException e) {
listener.onIgnoreRecovery("shard closed");
} catch (IndexShardNotStartedException e) {
listener.onIgnoreRecovery("shard closed");
} catch (Exception e) {
if (indexShard.state() == IndexShardState.CLOSED) {
// got closed on us, just ignore this recovery
listener.onIgnoreRecovery("shard closed");
return;
}
listener.onRecoveryFailed(new IndexShardGatewayRecoveryException(shardId, "failed recovery", e));
}
}
});
| 1no label
|
src_main_java_org_elasticsearch_index_gateway_IndexShardGatewayService.java
|
392 |
final Iterator<OIdentifiable> subIterator = new OLazyIterator<OIdentifiable>() {
private int pos = -1;
public boolean hasNext() {
return pos < size() - 1;
}
public OIdentifiable next() {
return ORecordLazyList.this.rawGet(++pos);
}
public void remove() {
ORecordLazyList.this.remove(pos);
}
public OIdentifiable update(final OIdentifiable iValue) {
return ORecordLazyList.this.set(pos, iValue);
}
};
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_record_ORecordLazyList.java
|
740 |
public class TransportIndexDeleteByQueryAction extends TransportIndexReplicationOperationAction<IndexDeleteByQueryRequest, IndexDeleteByQueryResponse, ShardDeleteByQueryRequest, ShardDeleteByQueryRequest, ShardDeleteByQueryResponse> {
@Inject
public TransportIndexDeleteByQueryAction(Settings settings, ClusterService clusterService, TransportService transportService,
ThreadPool threadPool, TransportShardDeleteByQueryAction shardDeleteByQueryAction) {
super(settings, transportService, clusterService, threadPool, shardDeleteByQueryAction);
}
@Override
protected IndexDeleteByQueryRequest newRequestInstance() {
return new IndexDeleteByQueryRequest();
}
@Override
protected IndexDeleteByQueryResponse newResponseInstance(IndexDeleteByQueryRequest request, AtomicReferenceArray shardsResponses) {
int successfulShards = 0;
int failedShards = 0;
List<ShardOperationFailedException> failures = new ArrayList<ShardOperationFailedException>(3);
for (int i = 0; i < shardsResponses.length(); i++) {
Object shardResponse = shardsResponses.get(i);
if (shardResponse instanceof Throwable) {
failedShards++;
failures.add(new DefaultShardOperationFailedException(request.index(), -1, (Throwable) shardResponse));
} else {
successfulShards++;
}
}
return new IndexDeleteByQueryResponse(request.index(), successfulShards, failedShards, failures);
}
@Override
protected boolean accumulateExceptions() {
return true;
}
@Override
protected String transportAction() {
return DeleteByQueryAction.NAME + "/index";
}
@Override
protected ClusterBlockException checkGlobalBlock(ClusterState state, IndexDeleteByQueryRequest request) {
return state.blocks().globalBlockedException(ClusterBlockLevel.WRITE);
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, IndexDeleteByQueryRequest request) {
return state.blocks().indexBlockedException(ClusterBlockLevel.WRITE, request.index());
}
@Override
protected GroupShardsIterator shards(IndexDeleteByQueryRequest request) {
return clusterService.operationRouting().deleteByQueryShards(clusterService.state(), request.index(), request.routing());
}
@Override
protected ShardDeleteByQueryRequest newShardRequestInstance(IndexDeleteByQueryRequest request, int shardId) {
return new ShardDeleteByQueryRequest(request, shardId);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_deletebyquery_TransportIndexDeleteByQueryAction.java
|
529 |
public class OTransactionBlockedException extends OTransactionException {
private static final long serialVersionUID = 2347493191705052402L;
public OTransactionBlockedException(String message, Throwable cause) {
super(message, cause);
}
public OTransactionBlockedException(String message) {
super(message);
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_exception_OTransactionBlockedException.java
|
1,248 |
public abstract class AbstractClient implements InternalClient {
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> RequestBuilder prepareExecute(final Action<Request, Response, RequestBuilder> action) {
return action.newRequestBuilder(this);
}
@Override
public ActionFuture<IndexResponse> index(final IndexRequest request) {
return execute(IndexAction.INSTANCE, request);
}
@Override
public void index(final IndexRequest request, final ActionListener<IndexResponse> listener) {
execute(IndexAction.INSTANCE, request, listener);
}
@Override
public IndexRequestBuilder prepareIndex() {
return new IndexRequestBuilder(this, null);
}
@Override
public IndexRequestBuilder prepareIndex(String index, String type) {
return prepareIndex(index, type, null);
}
@Override
public IndexRequestBuilder prepareIndex(String index, String type, @Nullable String id) {
return prepareIndex().setIndex(index).setType(type).setId(id);
}
@Override
public ActionFuture<UpdateResponse> update(final UpdateRequest request) {
return execute(UpdateAction.INSTANCE, request);
}
@Override
public void update(final UpdateRequest request, final ActionListener<UpdateResponse> listener) {
execute(UpdateAction.INSTANCE, request, listener);
}
@Override
public UpdateRequestBuilder prepareUpdate() {
return new UpdateRequestBuilder(this, null, null, null);
}
@Override
public UpdateRequestBuilder prepareUpdate(String index, String type, String id) {
return new UpdateRequestBuilder(this, index, type, id);
}
@Override
public ActionFuture<DeleteResponse> delete(final DeleteRequest request) {
return execute(DeleteAction.INSTANCE, request);
}
@Override
public void delete(final DeleteRequest request, final ActionListener<DeleteResponse> listener) {
execute(DeleteAction.INSTANCE, request, listener);
}
@Override
public DeleteRequestBuilder prepareDelete() {
return new DeleteRequestBuilder(this, null);
}
@Override
public DeleteRequestBuilder prepareDelete(String index, String type, String id) {
return prepareDelete().setIndex(index).setType(type).setId(id);
}
@Override
public ActionFuture<BulkResponse> bulk(final BulkRequest request) {
return execute(BulkAction.INSTANCE, request);
}
@Override
public void bulk(final BulkRequest request, final ActionListener<BulkResponse> listener) {
execute(BulkAction.INSTANCE, request, listener);
}
@Override
public BulkRequestBuilder prepareBulk() {
return new BulkRequestBuilder(this);
}
@Override
public ActionFuture<DeleteByQueryResponse> deleteByQuery(final DeleteByQueryRequest request) {
return execute(DeleteByQueryAction.INSTANCE, request);
}
@Override
public void deleteByQuery(final DeleteByQueryRequest request, final ActionListener<DeleteByQueryResponse> listener) {
execute(DeleteByQueryAction.INSTANCE, request, listener);
}
@Override
public DeleteByQueryRequestBuilder prepareDeleteByQuery(String... indices) {
return new DeleteByQueryRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<GetResponse> get(final GetRequest request) {
return execute(GetAction.INSTANCE, request);
}
@Override
public void get(final GetRequest request, final ActionListener<GetResponse> listener) {
execute(GetAction.INSTANCE, request, listener);
}
@Override
public GetRequestBuilder prepareGet() {
return new GetRequestBuilder(this, null);
}
@Override
public GetRequestBuilder prepareGet(String index, String type, String id) {
return prepareGet().setIndex(index).setType(type).setId(id);
}
@Override
public ActionFuture<MultiGetResponse> multiGet(final MultiGetRequest request) {
return execute(MultiGetAction.INSTANCE, request);
}
@Override
public void multiGet(final MultiGetRequest request, final ActionListener<MultiGetResponse> listener) {
execute(MultiGetAction.INSTANCE, request, listener);
}
@Override
public MultiGetRequestBuilder prepareMultiGet() {
return new MultiGetRequestBuilder(this);
}
@Override
public ActionFuture<SearchResponse> search(final SearchRequest request) {
return execute(SearchAction.INSTANCE, request);
}
@Override
public void search(final SearchRequest request, final ActionListener<SearchResponse> listener) {
execute(SearchAction.INSTANCE, request, listener);
}
@Override
public SearchRequestBuilder prepareSearch(String... indices) {
return new SearchRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<SearchResponse> searchScroll(final SearchScrollRequest request) {
return execute(SearchScrollAction.INSTANCE, request);
}
@Override
public void searchScroll(final SearchScrollRequest request, final ActionListener<SearchResponse> listener) {
execute(SearchScrollAction.INSTANCE, request, listener);
}
@Override
public SearchScrollRequestBuilder prepareSearchScroll(String scrollId) {
return new SearchScrollRequestBuilder(this, scrollId);
}
@Override
public ActionFuture<MultiSearchResponse> multiSearch(MultiSearchRequest request) {
return execute(MultiSearchAction.INSTANCE, request);
}
@Override
public void multiSearch(MultiSearchRequest request, ActionListener<MultiSearchResponse> listener) {
execute(MultiSearchAction.INSTANCE, request, listener);
}
@Override
public MultiSearchRequestBuilder prepareMultiSearch() {
return new MultiSearchRequestBuilder(this);
}
@Override
public ActionFuture<CountResponse> count(final CountRequest request) {
return execute(CountAction.INSTANCE, request);
}
@Override
public void count(final CountRequest request, final ActionListener<CountResponse> listener) {
execute(CountAction.INSTANCE, request, listener);
}
@Override
public CountRequestBuilder prepareCount(String... indices) {
return new CountRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<SuggestResponse> suggest(final SuggestRequest request) {
return execute(SuggestAction.INSTANCE, request);
}
@Override
public void suggest(final SuggestRequest request, final ActionListener<SuggestResponse> listener) {
execute(SuggestAction.INSTANCE, request, listener);
}
@Override
public SuggestRequestBuilder prepareSuggest(String... indices) {
return new SuggestRequestBuilder(this).setIndices(indices);
}
@Override
public ActionFuture<SearchResponse> moreLikeThis(final MoreLikeThisRequest request) {
return execute(MoreLikeThisAction.INSTANCE, request);
}
@Override
public void moreLikeThis(final MoreLikeThisRequest request, final ActionListener<SearchResponse> listener) {
execute(MoreLikeThisAction.INSTANCE, request, listener);
}
@Override
public MoreLikeThisRequestBuilder prepareMoreLikeThis(String index, String type, String id) {
return new MoreLikeThisRequestBuilder(this, index, type, id);
}
@Override
public ActionFuture<TermVectorResponse> termVector(final TermVectorRequest request) {
return execute(TermVectorAction.INSTANCE, request);
}
@Override
public void termVector(final TermVectorRequest request, final ActionListener<TermVectorResponse> listener) {
execute(TermVectorAction.INSTANCE, request, listener);
}
@Override
public TermVectorRequestBuilder prepareTermVector(String index, String type, String id) {
return new TermVectorRequestBuilder(this, index, type, id);
}
@Override
public ActionFuture<MultiTermVectorsResponse> multiTermVectors(final MultiTermVectorsRequest request) {
return execute(MultiTermVectorsAction.INSTANCE, request);
}
@Override
public void multiTermVectors(final MultiTermVectorsRequest request, final ActionListener<MultiTermVectorsResponse> listener) {
execute(MultiTermVectorsAction.INSTANCE, request, listener);
}
@Override
public MultiTermVectorsRequestBuilder prepareMultiTermVectors() {
return new MultiTermVectorsRequestBuilder(this);
}
@Override
public ActionFuture<PercolateResponse> percolate(final PercolateRequest request) {
return execute(PercolateAction.INSTANCE, request);
}
@Override
public void percolate(final PercolateRequest request, final ActionListener<PercolateResponse> listener) {
execute(PercolateAction.INSTANCE, request, listener);
}
@Override
public PercolateRequestBuilder preparePercolate() {
return new PercolateRequestBuilder(this);
}
@Override
public MultiPercolateRequestBuilder prepareMultiPercolate() {
return new MultiPercolateRequestBuilder(this);
}
@Override
public void multiPercolate(MultiPercolateRequest request, ActionListener<MultiPercolateResponse> listener) {
execute(MultiPercolateAction.INSTANCE, request, listener);
}
@Override
public ActionFuture<MultiPercolateResponse> multiPercolate(MultiPercolateRequest request) {
return execute(MultiPercolateAction.INSTANCE, request);
}
@Override
public ExplainRequestBuilder prepareExplain(String index, String type, String id) {
return new ExplainRequestBuilder(this, index, type, id);
}
@Override
public ActionFuture<ExplainResponse> explain(ExplainRequest request) {
return execute(ExplainAction.INSTANCE, request);
}
@Override
public void explain(ExplainRequest request, ActionListener<ExplainResponse> listener) {
execute(ExplainAction.INSTANCE, request, listener);
}
@Override
public void clearScroll(ClearScrollRequest request, ActionListener<ClearScrollResponse> listener) {
execute(ClearScrollAction.INSTANCE, request, listener);
}
@Override
public ActionFuture<ClearScrollResponse> clearScroll(ClearScrollRequest request) {
return execute(ClearScrollAction.INSTANCE, request);
}
@Override
public ClearScrollRequestBuilder prepareClearScroll() {
return new ClearScrollRequestBuilder(this);
}
}
| 1no label
|
src_main_java_org_elasticsearch_client_support_AbstractClient.java
|
858 |
public class TransportSearchDfsQueryAndFetchAction extends TransportSearchTypeAction {
@Inject
public TransportSearchDfsQueryAndFetchAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController) {
super(settings, threadPool, clusterService, searchService, searchPhaseController);
}
@Override
protected void doExecute(SearchRequest searchRequest, ActionListener<SearchResponse> listener) {
new AsyncAction(searchRequest, listener).start();
}
private class AsyncAction extends BaseAsyncAction<DfsSearchResult> {
private final AtomicArray<QueryFetchSearchResult> queryFetchResults;
private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) {
super(request, listener);
queryFetchResults = new AtomicArray<QueryFetchSearchResult>(firstResults.length());
}
@Override
protected String firstPhaseName() {
return "dfs";
}
@Override
protected void sendExecuteFirstPhase(DiscoveryNode node, ShardSearchRequest request, SearchServiceListener<DfsSearchResult> listener) {
searchService.sendExecuteDfs(node, request, listener);
}
@Override
protected void moveToSecondPhase() {
final AggregatedDfs dfs = searchPhaseController.aggregateDfs(firstResults);
final AtomicInteger counter = new AtomicInteger(firstResults.asList().size());
int localOperations = 0;
for (final AtomicArray.Entry<DfsSearchResult> entry : firstResults.asList()) {
DfsSearchResult dfsResult = entry.value;
DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
localOperations++;
} else {
QuerySearchRequest querySearchRequest = new QuerySearchRequest(request, dfsResult.id(), dfs);
executeSecondPhase(entry.index, dfsResult, counter, node, querySearchRequest);
}
}
if (localOperations > 0) {
if (request.operationThreading() == SearchOperationThreading.SINGLE_THREAD) {
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
for (final AtomicArray.Entry<DfsSearchResult> entry : firstResults.asList()) {
DfsSearchResult dfsResult = entry.value;
DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
QuerySearchRequest querySearchRequest = new QuerySearchRequest(request, dfsResult.id(), dfs);
executeSecondPhase(entry.index, dfsResult, counter, node, querySearchRequest);
}
}
}
});
} else {
boolean localAsync = request.operationThreading() == SearchOperationThreading.THREAD_PER_SHARD;
for (final AtomicArray.Entry<DfsSearchResult> entry : firstResults.asList()) {
final DfsSearchResult dfsResult = entry.value;
final DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
final QuerySearchRequest querySearchRequest = new QuerySearchRequest(request, dfsResult.id(), dfs);
try {
if (localAsync) {
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
executeSecondPhase(entry.index, dfsResult, counter, node, querySearchRequest);
}
});
} else {
executeSecondPhase(entry.index, dfsResult, counter, node, querySearchRequest);
}
} catch (Throwable t) {
onSecondPhaseFailure(t, querySearchRequest, entry.index, dfsResult, counter);
}
}
}
}
}
}
void executeSecondPhase(final int shardIndex, final DfsSearchResult dfsResult, final AtomicInteger counter, DiscoveryNode node, final QuerySearchRequest querySearchRequest) {
searchService.sendExecuteFetch(node, querySearchRequest, new SearchServiceListener<QueryFetchSearchResult>() {
@Override
public void onResult(QueryFetchSearchResult result) {
result.shardTarget(dfsResult.shardTarget());
queryFetchResults.set(shardIndex, result);
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
@Override
public void onFailure(Throwable t) {
onSecondPhaseFailure(t, querySearchRequest, shardIndex, dfsResult, counter);
}
});
}
void onSecondPhaseFailure(Throwable t, QuerySearchRequest querySearchRequest, int shardIndex, DfsSearchResult dfsResult, AtomicInteger counter) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] Failed to execute query phase", t, querySearchRequest.id());
}
this.addShardFailure(shardIndex, dfsResult.shardTarget(), t);
successulOps.decrementAndGet();
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
void finishHim() {
try {
innerFinishHim();
} catch (Throwable e) {
ReduceSearchPhaseException failure = new ReduceSearchPhaseException("query_fetch", "", e, buildShardFailures());
if (logger.isDebugEnabled()) {
logger.debug("failed to reduce search", failure);
}
listener.onFailure(failure);
} finally {
//
}
}
void innerFinishHim() throws Exception {
sortedShardList = searchPhaseController.sortDocs(queryFetchResults);
final InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, queryFetchResults, queryFetchResults);
String scrollId = null;
if (request.scroll() != null) {
scrollId = TransportSearchHelper.buildScrollId(request.searchType(), firstResults, null);
}
listener.onResponse(new SearchResponse(internalResponse, scrollId, expectedSuccessfulOps, successulOps.get(), buildTookInMillis(), buildShardFailures()));
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_search_type_TransportSearchDfsQueryAndFetchAction.java
|
156 |
static final class Sync extends AbstractQueuedLongSynchronizer {
private static final long serialVersionUID = 2540673546047039555L;
/**
* The number of times to spin in lock() and awaitAvailability().
*/
final int spins;
/**
* The number of reentrant holds on this lock. Uses a long for
* compatibility with other AbstractQueuedLongSynchronizer
* operations. Accessed only by lock holder.
*/
long holds;
Sync(int spins) { this.spins = spins; }
// overrides of AQLS methods
public final boolean isHeldExclusively() {
return (getState() & 1L) != 0L &&
getExclusiveOwnerThread() == Thread.currentThread();
}
public final boolean tryAcquire(long acquires) {
Thread current = Thread.currentThread();
long c = getState();
if ((c & 1L) == 0L) {
if (compareAndSetState(c, c + 1L)) {
holds = acquires;
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
holds += acquires;
return true;
}
return false;
}
public final boolean tryRelease(long releases) {
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
if ((holds -= releases) == 0L) {
setExclusiveOwnerThread(null);
setState(getState() + 1L);
return true;
}
return false;
}
public final long tryAcquireShared(long unused) {
return (((getState() & 1L) == 0L) ? 1L :
(getExclusiveOwnerThread() == Thread.currentThread()) ? 0L:
-1L);
}
public final boolean tryReleaseShared(long unused) {
return (getState() & 1L) == 0L;
}
public final Condition newCondition() {
throw new UnsupportedOperationException();
}
// Other methods in support of SequenceLock
final long getSequence() {
return getState();
}
final void lock() {
int k = spins;
while (!tryAcquire(1L)) {
if (k == 0) {
acquire(1L);
break;
}
--k;
}
}
final long awaitAvailability() {
long s;
while (((s = getState()) & 1L) != 0L &&
getExclusiveOwnerThread() != Thread.currentThread()) {
acquireShared(1L);
releaseShared(1L);
}
return s;
}
final long tryAwaitAvailability(long nanos)
throws InterruptedException, TimeoutException {
Thread current = Thread.currentThread();
for (;;) {
long s = getState();
if ((s & 1L) == 0L || getExclusiveOwnerThread() == current) {
releaseShared(1L);
return s;
}
if (!tryAcquireSharedNanos(1L, nanos))
throw new TimeoutException();
// since tryAcquireSharedNanos doesn't return seq
// retry with minimal wait time.
nanos = 1L;
}
}
final boolean isLocked() {
return (getState() & 1L) != 0L;
}
final Thread getOwner() {
return (getState() & 1L) == 0L ? null : getExclusiveOwnerThread();
}
final long getHoldCount() {
return isHeldExclusively() ? holds : 0;
}
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
holds = 0L;
setState(0L); // reset to unlocked state
}
}
| 0true
|
src_main_java_jsr166e_extra_SequenceLock.java
|
457 |
executor.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < operations; i++) {
map1.put("foo-" + i, "bar");
}
}
}, 60, EntryEventType.ADDED, operations, 0.75, map1, map2);
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_replicatedmap_ClientReplicatedMapTest.java
|
292 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name="BLC_DATA_DRVN_ENUM_VAL")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@AdminPresentationClass(friendlyName = "DataDrivenEnumerationValueImpl_friendyName")
public class DataDrivenEnumerationValueImpl implements DataDrivenEnumerationValue {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "DataDrivenEnumerationValueId")
@GenericGenerator(
name="DataDrivenEnumerationValueId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="DataDrivenEnumerationValueImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.common.enumeration.domain.DataDrivenEnumerationValueImpl")
}
)
@Column(name = "ENUM_VAL_ID")
protected Long id;
@ManyToOne(targetEntity = DataDrivenEnumerationImpl.class)
@JoinColumn(name = "ENUM_TYPE")
protected DataDrivenEnumeration type;
@Column(name = "ENUM_KEY")
@Index(name = "ENUM_VAL_KEY_INDEX", columnNames = {"ENUM_KEY"})
@AdminPresentation(friendlyName = "DataDrivenEnumerationValueImpl_Key", order = 1, gridOrder = 1, prominent = true)
protected String key;
@Column(name = "DISPLAY")
@AdminPresentation(friendlyName = "DataDrivenEnumerationValueImpl_Display", order = 2, gridOrder = 2, prominent = true)
protected String display;
@Column(name = "HIDDEN")
@Index(name = "HIDDEN_INDEX", columnNames = {"HIDDEN"})
@AdminPresentation(friendlyName = "DataDrivenEnumerationValueImpl_Hidden", order = 3, gridOrder = 3, prominent = true)
protected Boolean hidden = false;
@Override
public String getDisplay() {
return display;
}
@Override
public void setDisplay(String display) {
this.display = display;
}
@Override
public Boolean getHidden() {
if (hidden == null) {
return Boolean.FALSE;
} else {
return hidden;
}
}
@Override
public void setHidden(Boolean hidden) {
this.hidden = hidden;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getKey() {
return key;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override
public DataDrivenEnumeration getType() {
return type;
}
@Override
public void setType(DataDrivenEnumeration type) {
this.type = type;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_enumeration_domain_DataDrivenEnumerationValueImpl.java
|
841 |
searchServiceTransportAction.sendClearAllScrollContexts(node, request, new ActionListener<Boolean>() {
@Override
public void onResponse(Boolean success) {
onFreedContext();
}
@Override
public void onFailure(Throwable e) {
onFailedFreedContext(e, node);
}
});
| 1no label
|
src_main_java_org_elasticsearch_action_search_TransportClearScrollAction.java
|
1,514 |
public class PreferLocalPrimariesToRelocatingPrimariesTests extends ElasticsearchAllocationTestCase {
@Test
public void testPreferLocalPrimaryAllocationOverFiltered() {
int concurrentRecoveries = randomIntBetween(1, 10);
int primaryRecoveries = randomIntBetween(1, 10);
int numberOfShards = randomIntBetween(5, 20);
int totalNumberOfShards = numberOfShards * 2;
logger.info("create an allocation with [{}] initial primary recoveries and [{}] concurrent recoveries", primaryRecoveries, concurrentRecoveries);
AllocationService strategy = createAllocationService(settingsBuilder()
.put("cluster.routing.allocation.node_concurrent_recoveries", concurrentRecoveries)
.put("cluster.routing.allocation.node_initial_primaries_recoveries", primaryRecoveries)
.build());
logger.info("create 2 indices with [{}] no replicas, and wait till all are allocated", numberOfShards);
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test1").numberOfShards(numberOfShards).numberOfReplicas(0))
.put(IndexMetaData.builder("test2").numberOfShards(numberOfShards).numberOfReplicas(0))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test1"))
.addAsNew(metaData.index("test2"))
.build();
ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build();
logger.info("adding two nodes and performing rerouting till all are allocated");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder()
.put(newNode("node1", ImmutableMap.of("tag1", "value1")))
.put(newNode("node2", ImmutableMap.of("tag1", "value2")))).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
while (!clusterState.routingNodes().shardsWithState(INITIALIZING).isEmpty()) {
routingTable = strategy.applyStartedShards(clusterState, clusterState.routingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
}
logger.info("remove one of the nodes and apply filter to move everything from another node");
metaData = MetaData.builder()
.put(IndexMetaData.builder("test1").settings(settingsBuilder()
.put("index.number_of_shards", numberOfShards)
.put("index.number_of_replicas", 0)
.put("index.routing.allocation.exclude.tag1", "value2")
.build()))
.put(IndexMetaData.builder("test2").settings(settingsBuilder()
.put("index.number_of_shards", numberOfShards)
.put("index.number_of_replicas", 0)
.put("index.routing.allocation.exclude.tag1", "value2")
.build()))
.build();
clusterState = ClusterState.builder(clusterState).metaData(metaData).nodes(DiscoveryNodes.builder(clusterState.nodes()).remove("node1")).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logger.info("[{}] primaries should be still started but [{}] other primaries should be unassigned", numberOfShards, numberOfShards);
assertThat(clusterState.routingNodes().shardsWithState(STARTED).size(), equalTo(numberOfShards));
assertThat(clusterState.routingNodes().shardsWithState(INITIALIZING).size(), equalTo(0));
assertThat(clusterState.routingTable().shardsWithState(UNASSIGNED).size(), equalTo(numberOfShards));
logger.info("start node back up");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())
.put(newNode("node1", ImmutableMap.of("tag1", "value1")))).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
while (clusterState.routingNodes().shardsWithState(STARTED).size() < totalNumberOfShards) {
int localInitializations = 0;
int relocatingInitializations = 0;
for (MutableShardRouting routing : clusterState.routingNodes().shardsWithState(INITIALIZING)) {
if (routing.relocatingNodeId() == null) {
localInitializations++;
} else {
relocatingInitializations++;
}
}
int needToInitialize = totalNumberOfShards - clusterState.routingNodes().shardsWithState(STARTED).size() - clusterState.routingNodes().shardsWithState(RELOCATING).size();
logger.info("local initializations: [{}], relocating: [{}], need to initialize: {}", localInitializations, relocatingInitializations, needToInitialize);
assertThat(localInitializations, equalTo(Math.min(primaryRecoveries, needToInitialize)));
clusterState = startRandomInitializingShard(clusterState, strategy);
}
}
}
| 0true
|
src_test_java_org_elasticsearch_cluster_routing_allocation_PreferLocalPrimariesToRelocatingPrimariesTests.java
|
90 |
public interface Duration extends Comparable<Duration> {
/**
* Returns the length of this duration in the given {@link TimeUnit}.
*
* @param unit
* @return
*/
public long getLength(TimeUnit unit);
/**
* Whether this duration is of zero length.
* @return
*/
public boolean isZeroLength();
/**
* Returns the native unit used by this duration. The actual time length is specified in this unit of time.
* </p>
* @return
*/
public TimeUnit getNativeUnit();
/**
* Returns a new duration that equals the length of this duration minus the length of the given duration
* in the unit of this duration.
*
* @param subtrahend
* @return
*/
public Duration sub(Duration subtrahend);
/**
* Returns a new duration that equals the combined length of this and the given duration in the
* unit of this duration.
*
* @param addend
* @return
*/
public Duration add(Duration addend);
/**
* Multiplies the length of this duration by the given multiplier. The multiplier must be a non-negative number.
*
* @param multiplier
* @return
*/
public Duration multiply(double multiplier);
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Duration.java
|
574 |
ex.execute(new Runnable() {
public void run() {
factory.newHazelcastInstance(config);
nodeLatch.countDown();
}
});
| 0true
|
hazelcast_src_test_java_com_hazelcast_cluster_ClusterMembershipTest.java
|
95 |
public class ClientImpl implements Client {
private final String uuid;
private final InetSocketAddress socketAddress;
public ClientImpl(String uuid, InetSocketAddress socketAddress) {
this.uuid = uuid;
this.socketAddress = socketAddress;
}
@Override
public String getUuid() {
return uuid;
}
@Override
public InetSocketAddress getSocketAddress() {
return socketAddress;
}
@Override
public ClientType getClientType() {
return ClientType.JAVA;
}
}
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_ClientImpl.java
|
82 |
removeListenerActions.add(new Runnable() {
@Override
public void run() {
EventService eventService = clientEngine.getEventService();
eventService.deregisterListener(service, topic, id);
}
});
| 0true
|
hazelcast_src_main_java_com_hazelcast_client_ClientEndpoint.java
|
1,015 |
public abstract class InstanceShardOperationRequestBuilder<Request extends InstanceShardOperationRequest<Request>, Response extends ActionResponse, RequestBuilder extends InstanceShardOperationRequestBuilder<Request, Response, RequestBuilder>>
extends ActionRequestBuilder<Request, Response, RequestBuilder> {
protected InstanceShardOperationRequestBuilder(InternalGenericClient client, Request request) {
super(client, request);
}
@SuppressWarnings("unchecked")
public final RequestBuilder setIndex(String index) {
request.index(index);
return (RequestBuilder) this;
}
/**
* A timeout to wait if the index operation can't be performed immediately. Defaults to <tt>1m</tt>.
*/
@SuppressWarnings("unchecked")
public final RequestBuilder setTimeout(TimeValue timeout) {
request.timeout(timeout);
return (RequestBuilder) this;
}
/**
* A timeout to wait if the index operation can't be performed immediately. Defaults to <tt>1m</tt>.
*/
@SuppressWarnings("unchecked")
public final RequestBuilder setTimeout(String timeout) {
request.timeout(timeout);
return (RequestBuilder) this;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_single_instance_InstanceShardOperationRequestBuilder.java
|
546 |
public abstract class ORecordHookAbstract implements ORecordHook {
/**
* It's called just before to create the new iRecord.
*
* @param iiRecord
* The iRecord to create
* @return True if the iRecord has been modified and a new marshalling is required, otherwise false
*/
public RESULT onRecordBeforeCreate(final ORecord<?> iiRecord) {
return RESULT.RECORD_NOT_CHANGED;
}
/**
* It's called just after the iRecord is created.
*
* @param iiRecord
* The iRecord just created
*/
public void onRecordAfterCreate(final ORecord<?> iiRecord) {
}
public void onRecordCreateFailed(final ORecord<?> iiRecord) {
}
public void onRecordCreateReplicated(final ORecord<?> iiRecord) {
}
/**
* It's called just before to read the iRecord.
*
* @param iRecord
* The iRecord to read
* @return
*/
public RESULT onRecordBeforeRead(final ORecord<?> iRecord) {
return RESULT.RECORD_NOT_CHANGED;
}
/**
* It's called just after the iRecord is read.
*
* @param iiRecord
* The iRecord just read
*/
public void onRecordAfterRead(final ORecord<?> iiRecord) {
}
public void onRecordReadFailed(final ORecord<?> iiRecord) {
}
public void onRecordReadReplicated(final ORecord<?> iiRecord) {
}
/**
* It's called just before to update the iRecord.
*
* @param iiRecord
* The iRecord to update
* @return True if the iRecord has been modified and a new marshalling is required, otherwise false
*/
public RESULT onRecordBeforeUpdate(final ORecord<?> iiRecord) {
return RESULT.RECORD_NOT_CHANGED;
}
/**
* It's called just after the iRecord is updated.
*
* @param iiRecord
* The iRecord just updated
*/
public void onRecordAfterUpdate(final ORecord<?> iiRecord) {
}
public void onRecordUpdateFailed(final ORecord<?> iiRecord) {
}
public void onRecordUpdateReplicated(final ORecord<?> iiRecord) {
}
/**
* It's called just before to delete the iRecord.
*
* @param iiRecord
* The iRecord to delete
* @return True if the iRecord has been modified and a new marshalling is required, otherwise false
*/
public RESULT onRecordBeforeDelete(final ORecord<?> iiRecord) {
return RESULT.RECORD_NOT_CHANGED;
}
/**
* It's called just after the iRecord is deleted.
*
* @param iiRecord
* The iRecord just deleted
*/
public void onRecordAfterDelete(final ORecord<?> iiRecord) {
}
public void onRecordDeleteFailed(final ORecord<?> iiRecord) {
}
public void onRecordDeleteReplicated(final ORecord<?> iiRecord) {
}
public RESULT onRecordBeforeReplicaAdd(final ORecord<?> record) {
return RESULT.RECORD_NOT_CHANGED;
}
public void onRecordAfterReplicaAdd(final ORecord<?> record) {
}
public void onRecordReplicaAddFailed(final ORecord<?> record) {
}
public RESULT onRecordBeforeReplicaUpdate(final ORecord<?> record) {
return RESULT.RECORD_NOT_CHANGED;
}
public void onRecordAfterReplicaUpdate(final ORecord<?> record) {
}
public void onRecordReplicaUpdateFailed(final ORecord<?> record) {
}
public RESULT onRecordBeforeReplicaDelete(final ORecord<?> record) {
return RESULT.RECORD_NOT_CHANGED;
}
public void onRecordAfterReplicaDelete(final ORecord<?> record) {
}
public void onRecordReplicaDeleteFailed(final ORecord<?> record) {
}
public RESULT onTrigger(final TYPE iType, final ORecord<?> iRecord) {
switch (iType) {
case BEFORE_CREATE:
return onRecordBeforeCreate(iRecord);
case AFTER_CREATE:
onRecordAfterCreate(iRecord);
break;
case CREATE_FAILED:
onRecordCreateFailed(iRecord);
break;
case CREATE_REPLICATED:
onRecordCreateReplicated(iRecord);
break;
case BEFORE_READ:
return onRecordBeforeRead(iRecord);
case AFTER_READ:
onRecordAfterRead(iRecord);
break;
case READ_FAILED:
onRecordReadFailed(iRecord);
break;
case READ_REPLICATED:
onRecordReadReplicated(iRecord);
break;
case BEFORE_UPDATE:
return onRecordBeforeUpdate(iRecord);
case AFTER_UPDATE:
onRecordAfterUpdate(iRecord);
break;
case UPDATE_FAILED:
onRecordUpdateFailed(iRecord);
break;
case UPDATE_REPLICATED:
onRecordUpdateReplicated(iRecord);
break;
case BEFORE_DELETE:
return onRecordBeforeDelete(iRecord);
case AFTER_DELETE:
onRecordAfterDelete(iRecord);
break;
case DELETE_FAILED:
onRecordDeleteFailed(iRecord);
break;
case DELETE_REPLICATED:
onRecordDeleteReplicated(iRecord);
break;
case BEFORE_REPLICA_ADD:
return onRecordBeforeReplicaAdd(iRecord);
case AFTER_REPLICA_ADD:
onRecordAfterReplicaAdd(iRecord);
break;
case REPLICA_ADD_FAILED:
onRecordAfterReplicaAdd(iRecord);
break;
case BEFORE_REPLICA_UPDATE:
return onRecordBeforeReplicaUpdate(iRecord);
case AFTER_REPLICA_UPDATE:
onRecordAfterReplicaUpdate(iRecord);
break;
case REPLICA_UPDATE_FAILED:
onRecordReplicaUpdateFailed(iRecord);
break;
case BEFORE_REPLICA_DELETE:
return onRecordBeforeReplicaDelete(iRecord);
case AFTER_REPLICA_DELETE:
onRecordAfterReplicaDelete(iRecord);
break;
case REPLICA_DELETE_FAILED:
onRecordReplicaDeleteFailed(iRecord);
break;
}
return RESULT.RECORD_NOT_CHANGED;
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_hook_ORecordHookAbstract.java
|
123 |
@Service("blPageDefaultRuleProcessor")
public class PageDefaultRuleProcessor extends AbstractPageRuleProcessor {
private static final Log LOG = LogFactory.getLog(PageDefaultRuleProcessor.class);
/**
* Returns true if all of the rules associated with the passed in <code>Page</code>
* item match based on the passed in vars.
*
* Also returns true if no rules are present for the passed in item.
*
* @param sc - a structured content item to test
* @param vars - a map of objects used by the rule MVEL expressions
* @return the result of the rule checks
*/
public boolean checkForMatch(PageDTO page, Map<String, Object> vars) {
String ruleExpression = page.getRuleExpression();
if (ruleExpression != null) {
if (LOG.isTraceEnabled()) {
LOG.trace("Processing content rule for page with id " + page.getId() +". Value = " + ruleExpression);
}
boolean result = executeExpression(ruleExpression, vars);
if (! result) {
if (LOG.isDebugEnabled()) {
LOG.debug("Page failed to pass rule and will not be included for Page with id " + page.getId() +". Value = " + ruleExpression);
}
}
return result;
} else {
// If no rule found, then consider this a match.
return true;
}
}
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_service_PageDefaultRuleProcessor.java
|
143 |
static final class HashCode {
static final Random rng = new Random();
int code;
HashCode() {
int h = rng.nextInt(); // Avoid zero to allow xorShift rehash
code = (h == 0) ? 1 : h;
}
}
| 0true
|
src_main_java_jsr166e_Striped64.java
|
17 |
public interface BiAction<A,B> { void accept(A a, B b); }
| 0true
|
src_main_java_jsr166e_CompletableFuture.java
|
926 |
public abstract class BroadcastOperationRequest<T extends BroadcastOperationRequest> extends ActionRequest<T> {
protected String[] indices;
private BroadcastOperationThreading operationThreading = BroadcastOperationThreading.THREAD_PER_SHARD;
private IndicesOptions indicesOptions = IndicesOptions.strict();
protected BroadcastOperationRequest() {
}
protected BroadcastOperationRequest(String[] indices) {
this.indices = indices;
}
public String[] indices() {
return indices;
}
@SuppressWarnings("unchecked")
public final T indices(String... indices) {
this.indices = indices;
return (T) this;
}
@Override
public ActionRequestValidationException validate() {
return null;
}
/**
* Controls the operation threading model.
*/
public BroadcastOperationThreading operationThreading() {
return operationThreading;
}
/**
* Controls the operation threading model.
*/
@SuppressWarnings("unchecked")
public final T operationThreading(BroadcastOperationThreading operationThreading) {
this.operationThreading = operationThreading;
return (T) this;
}
/**
* Controls the operation threading model.
*/
public T operationThreading(String operationThreading) {
return operationThreading(BroadcastOperationThreading.fromString(operationThreading, this.operationThreading));
}
public IndicesOptions indicesOptions() {
return indicesOptions;
}
@SuppressWarnings("unchecked")
public final T indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = indicesOptions;
return (T) this;
}
protected void beforeStart() {
}
protected void beforeLocalFork() {
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeStringArrayNullable(indices);
out.writeByte(operationThreading.id());
indicesOptions.writeIndicesOptions(out);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
indices = in.readStringArray();
operationThreading = BroadcastOperationThreading.fromId(in.readByte());
indicesOptions = IndicesOptions.readIndicesOptions(in);
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_support_broadcast_BroadcastOperationRequest.java
|
2,799 |
public class Analysis {
public static Version parseAnalysisVersion(@IndexSettings Settings indexSettings, Settings settings, ESLogger logger) {
// check for explicit version on the specific analyzer component
String sVersion = settings.get("version");
if (sVersion != null) {
return Lucene.parseVersion(sVersion, Lucene.ANALYZER_VERSION, logger);
}
// check for explicit version on the index itself as default for all analysis components
sVersion = indexSettings.get("index.analysis.version");
if (sVersion != null) {
return Lucene.parseVersion(sVersion, Lucene.ANALYZER_VERSION, logger);
}
// resolve the analysis version based on the version the index was created with
return indexSettings.getAsVersion(IndexMetaData.SETTING_VERSION_CREATED, org.elasticsearch.Version.CURRENT).luceneVersion;
}
public static boolean isNoStopwords(Settings settings) {
String value = settings.get("stopwords");
return value != null && "_none_".equals(value);
}
public static CharArraySet parseStemExclusion(Settings settings, CharArraySet defaultStemExclusion, Version version) {
String value = settings.get("stem_exclusion");
if (value != null) {
if ("_none_".equals(value)) {
return CharArraySet.EMPTY_SET;
} else {
// LUCENE 4 UPGRADE: Should be settings.getAsBoolean("stem_exclusion_case", false)?
return new CharArraySet(version, Strings.commaDelimitedListToSet(value), false);
}
}
String[] stopWords = settings.getAsArray("stem_exclusion", null);
if (stopWords != null) {
// LUCENE 4 UPGRADE: Should be settings.getAsBoolean("stem_exclusion_case", false)?
return new CharArraySet(version, ImmutableList.of(stopWords), false);
} else {
return defaultStemExclusion;
}
}
public static final ImmutableMap<String, Set<?>> namedStopWords = MapBuilder.<String, Set<?>>newMapBuilder()
.put("_arabic_", ArabicAnalyzer.getDefaultStopSet())
.put("_armenian_", ArmenianAnalyzer.getDefaultStopSet())
.put("_basque_", BasqueAnalyzer.getDefaultStopSet())
.put("_brazilian_", BrazilianAnalyzer.getDefaultStopSet())
.put("_bulgarian_", BulgarianAnalyzer.getDefaultStopSet())
.put("_catalan_", CatalanAnalyzer.getDefaultStopSet())
.put("_czech_", CzechAnalyzer.getDefaultStopSet())
.put("_danish_", DanishAnalyzer.getDefaultStopSet())
.put("_dutch_", DutchAnalyzer.getDefaultStopSet())
.put("_english_", EnglishAnalyzer.getDefaultStopSet())
.put("_finnish_", FinnishAnalyzer.getDefaultStopSet())
.put("_french_", FrenchAnalyzer.getDefaultStopSet())
.put("_galician_", GalicianAnalyzer.getDefaultStopSet())
.put("_german_", GermanAnalyzer.getDefaultStopSet())
.put("_greek_", GreekAnalyzer.getDefaultStopSet())
.put("_hindi_", HindiAnalyzer.getDefaultStopSet())
.put("_hungarian_", HungarianAnalyzer.getDefaultStopSet())
.put("_indonesian_", IndonesianAnalyzer.getDefaultStopSet())
.put("_italian_", ItalianAnalyzer.getDefaultStopSet())
.put("_norwegian_", NorwegianAnalyzer.getDefaultStopSet())
.put("_persian_", PersianAnalyzer.getDefaultStopSet())
.put("_portuguese_", PortugueseAnalyzer.getDefaultStopSet())
.put("_romanian_", RomanianAnalyzer.getDefaultStopSet())
.put("_russian_", RussianAnalyzer.getDefaultStopSet())
.put("_spanish_", SpanishAnalyzer.getDefaultStopSet())
.put("_swedish_", SwedishAnalyzer.getDefaultStopSet())
.put("_turkish_", TurkishAnalyzer.getDefaultStopSet())
.immutableMap();
public static CharArraySet parseWords(Environment env, Settings settings, String name, CharArraySet defaultWords, ImmutableMap<String, Set<?>> namedWords, Version version, boolean ignoreCase) {
String value = settings.get(name);
if (value != null) {
if ("_none_".equals(value)) {
return CharArraySet.EMPTY_SET;
} else {
return resolveNamedWords(Strings.commaDelimitedListToSet(value), namedWords, version, ignoreCase);
}
}
List<String> pathLoadedWords = getWordList(env, settings, name);
if (pathLoadedWords != null) {
return resolveNamedWords(pathLoadedWords, namedWords, version, ignoreCase);
}
return defaultWords;
}
public static CharArraySet parseCommonWords(Environment env, Settings settings, CharArraySet defaultCommonWords, Version version, boolean ignoreCase) {
return parseWords(env, settings, "common_words", defaultCommonWords, namedStopWords, version, ignoreCase);
}
public static CharArraySet parseArticles(Environment env, Settings settings, Version version) {
return parseWords(env, settings, "articles", null, null, version, settings.getAsBoolean("articles_case", false));
}
public static CharArraySet parseStopWords(Environment env, Settings settings, CharArraySet defaultStopWords, Version version) {
return parseStopWords(env, settings, defaultStopWords, version, settings.getAsBoolean("stopwords_case", false));
}
public static CharArraySet parseStopWords(Environment env, Settings settings, CharArraySet defaultStopWords, Version version, boolean ignoreCase) {
return parseWords(env, settings, "stopwords", defaultStopWords, namedStopWords, version, ignoreCase);
}
private static CharArraySet resolveNamedWords(Collection<String> words, ImmutableMap<String, Set<?>> namedWords, Version version, boolean ignoreCase) {
if (namedWords == null) {
return new CharArraySet(version, words, ignoreCase);
}
CharArraySet setWords = new CharArraySet(version, words.size(), ignoreCase);
for (String word : words) {
if (namedWords.containsKey(word)) {
setWords.addAll(namedWords.get(word));
} else {
setWords.add(word);
}
}
return setWords;
}
public static CharArraySet getWordSet(Environment env, Settings settings, String settingsPrefix, Version version) {
List<String> wordList = getWordList(env, settings, settingsPrefix);
if (wordList == null) {
return null;
}
return new CharArraySet(version, wordList, settings.getAsBoolean(settingsPrefix + "_case", false));
}
/**
* Fetches a list of words from the specified settings file. The list should either be available at the key
* specified by settingsPrefix or in a file specified by settingsPrefix + _path.
*
* @throws org.elasticsearch.ElasticsearchIllegalArgumentException
* If the word list cannot be found at either key.
*/
public static List<String> getWordList(Environment env, Settings settings, String settingPrefix) {
String wordListPath = settings.get(settingPrefix + "_path", null);
if (wordListPath == null) {
String[] explicitWordList = settings.getAsArray(settingPrefix, null);
if (explicitWordList == null) {
return null;
} else {
return Arrays.asList(explicitWordList);
}
}
URL wordListFile = env.resolveConfig(wordListPath);
try {
return loadWordList(new InputStreamReader(wordListFile.openStream(), Charsets.UTF_8), "#");
} catch (IOException ioe) {
String message = String.format(Locale.ROOT, "IOException while reading %s_path: %s", settingPrefix, ioe.getMessage());
throw new ElasticsearchIllegalArgumentException(message);
}
}
public static List<String> loadWordList(Reader reader, String comment) throws IOException {
final List<String> result = new ArrayList<String>();
BufferedReader br = null;
try {
if (reader instanceof BufferedReader) {
br = (BufferedReader) reader;
} else {
br = new BufferedReader(reader);
}
String word = null;
while ((word = br.readLine()) != null) {
if (!Strings.hasText(word)) {
continue;
}
if (!word.startsWith(comment)) {
result.add(word.trim());
}
}
} finally {
if (br != null)
br.close();
}
return result;
}
/**
* @return null If no settings set for "settingsPrefix" then return <code>null</code>.
* @throws org.elasticsearch.ElasticsearchIllegalArgumentException
* If the Reader can not be instantiated.
*/
public static Reader getReaderFromFile(Environment env, Settings settings, String settingPrefix) {
String filePath = settings.get(settingPrefix, null);
if (filePath == null) {
return null;
}
URL fileUrl = env.resolveConfig(filePath);
Reader reader = null;
try {
reader = new InputStreamReader(fileUrl.openStream(), Charsets.UTF_8);
} catch (IOException ioe) {
String message = String.format(Locale.ROOT, "IOException while reading %s_path: %s", settingPrefix, ioe.getMessage());
throw new ElasticsearchIllegalArgumentException(message);
}
return reader;
}
/**
* Check whether the provided token stream is able to provide character
* terms.
* <p>Although most analyzers generate character terms (CharTermAttribute),
* some token only contain binary terms (BinaryTermAttribute,
* CharTermAttribute being a special type of BinaryTermAttribute), such as
* {@link NumericTokenStream} and unsuitable for highlighting and
* more-like-this queries which expect character terms.</p>
*/
public static boolean isCharacterTokenStream(TokenStream tokenStream) {
try {
tokenStream.addAttribute(CharTermAttribute.class);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Check whether {@link TokenStream}s generated with <code>analyzer</code>
* provide with character terms.
* @see #isCharacterTokenStream(TokenStream)
*/
public static boolean generatesCharacterTokenStream(Analyzer analyzer, String fieldName) throws IOException {
return isCharacterTokenStream(analyzer.tokenStream(fieldName, ""));
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_analysis_Analysis.java
|
1,079 |
public class UpdateHelper extends AbstractComponent {
private final IndicesService indicesService;
private final ScriptService scriptService;
@Inject
public UpdateHelper(Settings settings, IndicesService indicesService, ScriptService scriptService) {
super(settings);
this.indicesService = indicesService;
this.scriptService = scriptService;
}
/**
* Prepares an update request by converting it into an index or delete request or an update response (no action).
*/
public Result prepare(UpdateRequest request) {
IndexService indexService = indicesService.indexServiceSafe(request.index());
IndexShard indexShard = indexService.shardSafe(request.shardId());
return prepare(request, indexShard);
}
public Result prepare(UpdateRequest request, IndexShard indexShard) {
long getDate = System.currentTimeMillis();
final GetResult getResult = indexShard.getService().get(request.type(), request.id(),
new String[]{RoutingFieldMapper.NAME, ParentFieldMapper.NAME, TTLFieldMapper.NAME},
true, request.version(), request.versionType(), FetchSourceContext.FETCH_SOURCE);
if (!getResult.isExists()) {
if (request.upsertRequest() == null && !request.docAsUpsert()) {
throw new DocumentMissingException(new ShardId(request.index(), request.shardId()), request.type(), request.id());
}
IndexRequest indexRequest = request.docAsUpsert() ? request.doc() : request.upsertRequest();
indexRequest.index(request.index()).type(request.type()).id(request.id())
// it has to be a "create!"
.create(true)
.routing(request.routing())
.refresh(request.refresh())
.replicationType(request.replicationType()).consistencyLevel(request.consistencyLevel());
indexRequest.operationThreaded(false);
if (request.versionType() == VersionType.EXTERNAL) {
// in external versioning mode, we want to create the new document using the given version.
indexRequest.version(request.version()).versionType(VersionType.EXTERNAL);
}
return new Result(indexRequest, Operation.UPSERT, null, null);
}
long updateVersion = getResult.getVersion();
if (request.versionType() == VersionType.EXTERNAL) {
updateVersion = request.version(); // remember, match_any is excluded by the conflict test
}
if (getResult.internalSourceRef() == null) {
// no source, we can't do nothing, through a failure...
throw new DocumentSourceMissingException(new ShardId(request.index(), request.shardId()), request.type(), request.id());
}
Tuple<XContentType, Map<String, Object>> sourceAndContent = XContentHelper.convertToMap(getResult.internalSourceRef(), true);
String operation = null;
String timestamp = null;
Long ttl = null;
Object fetchedTTL = null;
final Map<String, Object> updatedSourceAsMap;
final XContentType updateSourceContentType = sourceAndContent.v1();
String routing = getResult.getFields().containsKey(RoutingFieldMapper.NAME) ? getResult.field(RoutingFieldMapper.NAME).getValue().toString() : null;
String parent = getResult.getFields().containsKey(ParentFieldMapper.NAME) ? getResult.field(ParentFieldMapper.NAME).getValue().toString() : null;
if (request.script() == null && request.doc() != null) {
IndexRequest indexRequest = request.doc();
updatedSourceAsMap = sourceAndContent.v2();
if (indexRequest.ttl() > 0) {
ttl = indexRequest.ttl();
}
timestamp = indexRequest.timestamp();
if (indexRequest.routing() != null) {
routing = indexRequest.routing();
}
if (indexRequest.parent() != null) {
parent = indexRequest.parent();
}
XContentHelper.update(updatedSourceAsMap, indexRequest.sourceAsMap());
} else {
Map<String, Object> ctx = new HashMap<String, Object>(2);
ctx.put("_source", sourceAndContent.v2());
try {
ExecutableScript script = scriptService.executable(request.scriptLang, request.script, request.scriptParams);
script.setNextVar("ctx", ctx);
script.run();
// we need to unwrap the ctx...
ctx = (Map<String, Object>) script.unwrap(ctx);
} catch (Exception e) {
throw new ElasticsearchIllegalArgumentException("failed to execute script", e);
}
operation = (String) ctx.get("op");
timestamp = (String) ctx.get("_timestamp");
fetchedTTL = ctx.get("_ttl");
if (fetchedTTL != null) {
if (fetchedTTL instanceof Number) {
ttl = ((Number) fetchedTTL).longValue();
} else {
ttl = TimeValue.parseTimeValue((String) fetchedTTL, null).millis();
}
}
updatedSourceAsMap = (Map<String, Object>) ctx.get("_source");
}
// apply script to update the source
// No TTL has been given in the update script so we keep previous TTL value if there is one
if (ttl == null) {
ttl = getResult.getFields().containsKey(TTLFieldMapper.NAME) ? (Long) getResult.field(TTLFieldMapper.NAME).getValue() : null;
if (ttl != null) {
ttl = ttl - (System.currentTimeMillis() - getDate); // It is an approximation of exact TTL value, could be improved
}
}
if (operation == null || "index".equals(operation)) {
final IndexRequest indexRequest = Requests.indexRequest(request.index()).type(request.type()).id(request.id()).routing(routing).parent(parent)
.source(updatedSourceAsMap, updateSourceContentType)
.version(updateVersion).versionType(request.versionType())
.replicationType(request.replicationType()).consistencyLevel(request.consistencyLevel())
.timestamp(timestamp).ttl(ttl)
.refresh(request.refresh());
indexRequest.operationThreaded(false);
return new Result(indexRequest, Operation.INDEX, updatedSourceAsMap, updateSourceContentType);
} else if ("delete".equals(operation)) {
DeleteRequest deleteRequest = Requests.deleteRequest(request.index()).type(request.type()).id(request.id()).routing(routing).parent(parent)
.version(updateVersion).versionType(request.versionType())
.replicationType(request.replicationType()).consistencyLevel(request.consistencyLevel());
deleteRequest.operationThreaded(false);
return new Result(deleteRequest, Operation.DELETE, updatedSourceAsMap, updateSourceContentType);
} else if ("none".equals(operation)) {
UpdateResponse update = new UpdateResponse(getResult.getIndex(), getResult.getType(), getResult.getId(), getResult.getVersion(), false);
update.setGetResult(extractGetResult(request, getResult.getVersion(), updatedSourceAsMap, updateSourceContentType, null));
return new Result(update, Operation.NONE, updatedSourceAsMap, updateSourceContentType);
} else {
logger.warn("Used update operation [{}] for script [{}], doing nothing...", operation, request.script);
UpdateResponse update = new UpdateResponse(getResult.getIndex(), getResult.getType(), getResult.getId(), getResult.getVersion(), false);
return new Result(update, Operation.NONE, updatedSourceAsMap, updateSourceContentType);
}
}
/**
* Extracts the fields from the updated document to be returned in a update response
*/
public GetResult extractGetResult(final UpdateRequest request, long version, final Map<String, Object> source, XContentType sourceContentType, @Nullable final BytesReference sourceAsBytes) {
if (request.fields() == null || request.fields().length == 0) {
return null;
}
boolean sourceRequested = false;
Map<String, GetField> fields = null;
if (request.fields() != null && request.fields().length > 0) {
SourceLookup sourceLookup = new SourceLookup();
sourceLookup.setNextSource(source);
for (String field : request.fields()) {
if (field.equals("_source")) {
sourceRequested = true;
continue;
}
Object value = sourceLookup.extractValue(field);
if (value != null) {
if (fields == null) {
fields = newHashMapWithExpectedSize(2);
}
GetField getField = fields.get(field);
if (getField == null) {
getField = new GetField(field, new ArrayList<Object>(2));
fields.put(field, getField);
}
getField.getValues().add(value);
}
}
}
// TODO when using delete/none, we can still return the source as bytes by generating it (using the sourceContentType)
return new GetResult(request.index(), request.type(), request.id(), version, true, sourceRequested ? sourceAsBytes : null, fields);
}
public static class Result {
private final Streamable action;
private final Operation operation;
private final Map<String, Object> updatedSourceAsMap;
private final XContentType updateSourceContentType;
public Result(Streamable action, Operation operation, Map<String, Object> updatedSourceAsMap, XContentType updateSourceContentType) {
this.action = action;
this.operation = operation;
this.updatedSourceAsMap = updatedSourceAsMap;
this.updateSourceContentType = updateSourceContentType;
}
@SuppressWarnings("unchecked")
public <T extends Streamable> T action() {
return (T) action;
}
public Operation operation() {
return operation;
}
public Map<String, Object> updatedSourceAsMap() {
return updatedSourceAsMap;
}
public XContentType updateSourceContentType() {
return updateSourceContentType;
}
}
public static enum Operation {
UPSERT,
INDEX,
DELETE,
NONE
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_update_UpdateHelper.java
|
548 |
public interface TypedClosure<K, V> {
public K getKey(V value);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_util_TypedClosure.java
|
114 |
public abstract class DefinitionGenerator {
abstract String generateShared(String indent, String delim);
abstract String generate(String indent, String delim);
abstract Set<Declaration> getImports();
abstract String getBrokenName();
abstract String getDescription();
abstract ProducedType getReturnType();
abstract LinkedHashMap<String, ProducedType> getParameters();
abstract Image getImage();
abstract Tree.CompilationUnit getRootNode();
abstract Node getNode();
static void appendParameters(LinkedHashMap<String,ProducedType> parameters,
StringBuffer buffer) {
if (parameters.isEmpty()) {
buffer.append("()");
}
else {
buffer.append("(");
for (Map.Entry<String,ProducedType> e: parameters.entrySet()) {
buffer.append(e.getValue().getProducedTypeName()).append(" ")
.append(e.getKey()).append(", ");
}
buffer.setLength(buffer.length()-2);
buffer.append(")");
}
}
static LinkedHashMap<String,ProducedType> getParametersFromPositionalArgs(Tree.PositionalArgumentList pal) {
LinkedHashMap<String,ProducedType> types = new LinkedHashMap<String,ProducedType>();
int i=0;
for (Tree.PositionalArgument pa: pal.getPositionalArguments()) {
if (pa instanceof Tree.ListedArgument) {
Tree.Expression e = ((Tree.ListedArgument) pa).getExpression();
ProducedType et = e.getTypeModel();
String name;
ProducedType t;
if (et == null) {
t = pa.getUnit().getAnythingDeclaration().getType();
name = "arg";
}
else {
t = pa.getUnit().denotableType(et);
if (e.getTerm() instanceof Tree.StaticMemberOrTypeExpression) {
String id = ((Tree.StaticMemberOrTypeExpression) e.getTerm())
.getIdentifier().getText();
name = Character.toLowerCase(id.charAt(0)) + id.substring(1);
}
else {
if (et.getDeclaration() instanceof ClassOrInterface ||
et.getDeclaration() instanceof TypeParameter) {
String tn = et.getDeclaration().getName();
name = Character.toLowerCase(tn.charAt(0)) + tn.substring(1);
}
else {
name = "arg";
}
}
}
if (types.containsKey(name)) {
name = name + ++i;
}
types.put(name, t);
}
}
return types;
}
static LinkedHashMap<String,ProducedType> getParametersFromNamedArgs(Tree.NamedArgumentList nal) {
LinkedHashMap<String,ProducedType> types = new LinkedHashMap<String,ProducedType>();
int i=0;
for (Tree.NamedArgument a: nal.getNamedArguments()) {
if (a instanceof Tree.SpecifiedArgument) {
Tree.SpecifiedArgument na = (Tree.SpecifiedArgument) a;
Tree.Expression e = na.getSpecifierExpression().getExpression();
String name = na.getIdentifier().getText();
ProducedType t;
if (e==null) {
t = a.getUnit().getAnythingDeclaration().getType();
}
else {
t = a.getUnit().denotableType(e.getTypeModel());
}
if (types.containsKey(name)) {
name = name + ++i;
}
types.put(name, t);
}
}
return types;
}
static void appendTypeParams(List<TypeParameter> typeParams,
StringBuilder typeParamDef, StringBuilder typeParamConstDef,
TypeParameter typeParam) {
if (typeParams.contains(typeParam)) {
return;
} else {
typeParams.add(typeParam);
}
if (typeParam.isContravariant()) {
typeParamDef.append("in ");
}
if (typeParam.isCovariant()) {
typeParamDef.append("out ");
}
typeParamDef.append(typeParam.getName());
if (typeParam.isDefaulted() && typeParam.getDefaultTypeArgument() != null) {
typeParamDef.append("=");
typeParamDef.append(typeParam.getDefaultTypeArgument().getProducedTypeName());
}
typeParamDef.append(",");
if (typeParam.isConstrained()) {
typeParamConstDef.append(" given ");
typeParamConstDef.append(typeParam.getName());
List<ProducedType> satisfiedTypes = typeParam.getSatisfiedTypes();
if (satisfiedTypes != null && !satisfiedTypes.isEmpty()) {
typeParamConstDef.append(" satisfies ");
boolean firstSatisfiedType = true;
for (ProducedType satisfiedType : satisfiedTypes) {
if (firstSatisfiedType) {
firstSatisfiedType = false;
} else {
typeParamConstDef.append("&");
}
typeParamConstDef.append(satisfiedType.getProducedTypeName());
}
}
List<ProducedType> caseTypes = typeParam.getCaseTypes();
if (caseTypes != null && !caseTypes.isEmpty()) {
typeParamConstDef.append(" of ");
boolean firstCaseType = true;
for (ProducedType caseType : caseTypes) {
if (firstCaseType) {
firstCaseType = false;
} else {
typeParamConstDef.append("|");
}
typeParamConstDef.append(caseType.getProducedTypeName());
}
}
if (typeParam.getParameterLists() != null) {
for (ParameterList paramList : typeParam.getParameterLists()) {
if (paramList != null && paramList.getParameters() != null) {
typeParamConstDef.append("(");
boolean firstParam = true;
for (Parameter param : paramList.getParameters()) {
if (firstParam) {
firstParam = false;
} else {
typeParamConstDef.append(",");
}
typeParamConstDef.append(param.getType().getProducedTypeName());
typeParamConstDef.append(" ");
typeParamConstDef.append(param.getName());
}
typeParamConstDef.append(")");
}
}
}
}
}
static void appendTypeParams(List<TypeParameter> typeParams,
StringBuilder typeParamDef, StringBuilder typeParamConstDef,
ProducedType pt) {
if (pt != null) {
if (pt.getDeclaration() instanceof UnionType) {
DefinitionGenerator.appendTypeParams(typeParams, typeParamDef, typeParamConstDef,
((UnionType) pt.getDeclaration()).getCaseTypes());
}
else if (pt.getDeclaration() instanceof IntersectionType) {
DefinitionGenerator.appendTypeParams(typeParams, typeParamDef, typeParamConstDef,
((IntersectionType) pt.getDeclaration()).getSatisfiedTypes());
}
else if (pt.getDeclaration() instanceof TypeParameter) {
appendTypeParams(typeParams, typeParamDef, typeParamConstDef,
(TypeParameter) pt.getDeclaration());
}
}
}
static void appendTypeParams(List<TypeParameter> typeParams, StringBuilder typeParamDef,
StringBuilder typeParamConstDef, Collection<ProducedType> parameterTypes) {
if (parameterTypes != null) {
for (ProducedType pt: parameterTypes) {
appendTypeParams(typeParams, typeParamDef, typeParamConstDef, pt);
}
}
}
static LinkedHashMap<String,ProducedType> getParameters(
FindArgumentsVisitor fav) {
if (fav.positionalArgs!=null) {
return getParametersFromPositionalArgs(fav.positionalArgs);
}
else if (fav.namedArgs!=null) {
return getParametersFromNamedArgs(fav.namedArgs);
}
else {
return null;
}
}
}
| 1no label
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_DefinitionGenerator.java
|
3,507 |
public class MapperService extends AbstractIndexComponent implements Iterable<DocumentMapper> {
public static final String DEFAULT_MAPPING = "_default_";
private static ObjectOpenHashSet<String> META_FIELDS = ObjectOpenHashSet.from(
"_uid", "_id", "_type", "_all", "_analyzer", "_boost", "_parent", "_routing", "_index",
"_size", "_timestamp", "_ttl"
);
private final AnalysisService analysisService;
private final IndexFieldDataService fieldDataService;
/**
* Will create types automatically if they do not exists in the mapping definition yet
*/
private final boolean dynamic;
private volatile String defaultMappingSource;
private volatile String defaultPercolatorMappingSource;
private volatile Map<String, DocumentMapper> mappers = ImmutableMap.of();
private final Object typeMutex = new Object();
private final Object mappersMutex = new Object();
private final FieldMappersLookup fieldMappers = new FieldMappersLookup();
private volatile ImmutableOpenMap<String, ObjectMappers> fullPathObjectMappers = ImmutableOpenMap.of();
private boolean hasNested = false; // updated dynamically to true when a nested object is added
private final DocumentMapperParser documentParser;
private final InternalFieldMapperListener fieldMapperListener = new InternalFieldMapperListener();
private final InternalObjectMapperListener objectMapperListener = new InternalObjectMapperListener();
private final SmartIndexNameSearchAnalyzer searchAnalyzer;
private final SmartIndexNameSearchQuoteAnalyzer searchQuoteAnalyzer;
private final List<DocumentTypeListener> typeListeners = new CopyOnWriteArrayList<DocumentTypeListener>();
@Inject
public MapperService(Index index, @IndexSettings Settings indexSettings, Environment environment, AnalysisService analysisService, IndexFieldDataService fieldDataService,
PostingsFormatService postingsFormatService, DocValuesFormatService docValuesFormatService, SimilarityLookupService similarityLookupService) {
super(index, indexSettings);
this.analysisService = analysisService;
this.fieldDataService = fieldDataService;
this.documentParser = new DocumentMapperParser(index, indexSettings, analysisService, postingsFormatService, docValuesFormatService, similarityLookupService);
this.searchAnalyzer = new SmartIndexNameSearchAnalyzer(analysisService.defaultSearchAnalyzer());
this.searchQuoteAnalyzer = new SmartIndexNameSearchQuoteAnalyzer(analysisService.defaultSearchQuoteAnalyzer());
this.dynamic = componentSettings.getAsBoolean("dynamic", true);
String defaultMappingLocation = componentSettings.get("default_mapping_location");
URL defaultMappingUrl;
if (defaultMappingLocation == null) {
try {
defaultMappingUrl = environment.resolveConfig("default-mapping.json");
} catch (FailedToResolveConfigException e) {
// not there, default to the built in one
defaultMappingUrl = indexSettings.getClassLoader().getResource("org/elasticsearch/index/mapper/default-mapping.json");
if (defaultMappingUrl == null) {
defaultMappingUrl = MapperService.class.getClassLoader().getResource("org/elasticsearch/index/mapper/default-mapping.json");
}
}
} else {
try {
defaultMappingUrl = environment.resolveConfig(defaultMappingLocation);
} catch (FailedToResolveConfigException e) {
// not there, default to the built in one
try {
defaultMappingUrl = new File(defaultMappingLocation).toURI().toURL();
} catch (MalformedURLException e1) {
throw new FailedToResolveConfigException("Failed to resolve dynamic mapping location [" + defaultMappingLocation + "]");
}
}
}
if (defaultMappingUrl == null) {
logger.info("failed to find default-mapping.json in the classpath, using the default template");
defaultMappingSource = "{\n" +
" \"_default_\":{\n" +
" }\n" +
"}";
} else {
try {
defaultMappingSource = Streams.copyToString(new InputStreamReader(defaultMappingUrl.openStream(), Charsets.UTF_8));
} catch (IOException e) {
throw new MapperException("Failed to load default mapping source from [" + defaultMappingLocation + "]", e);
}
}
String percolatorMappingLocation = componentSettings.get("default_percolator_mapping_location");
URL percolatorMappingUrl = null;
if (percolatorMappingLocation != null) {
try {
percolatorMappingUrl = environment.resolveConfig(percolatorMappingLocation);
} catch (FailedToResolveConfigException e) {
// not there, default to the built in one
try {
percolatorMappingUrl = new File(percolatorMappingLocation).toURI().toURL();
} catch (MalformedURLException e1) {
throw new FailedToResolveConfigException("Failed to resolve default percolator mapping location [" + percolatorMappingLocation + "]");
}
}
}
if (percolatorMappingUrl != null) {
try {
defaultPercolatorMappingSource = Streams.copyToString(new InputStreamReader(percolatorMappingUrl.openStream(), Charsets.UTF_8));
} catch (IOException e) {
throw new MapperException("Failed to load default percolator mapping source from [" + percolatorMappingUrl + "]", e);
}
} else {
defaultPercolatorMappingSource = "{\n" +
//" \"" + PercolatorService.TYPE_NAME + "\":{\n" +
" \"" + "_default_" + "\":{\n" +
" \"_id\" : {\"index\": \"not_analyzed\"}," +
" \"properties\" : {\n" +
" \"query\" : {\n" +
" \"type\" : \"object\",\n" +
" \"enabled\" : false\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
}
if (logger.isDebugEnabled()) {
logger.debug("using dynamic[{}], default mapping: default_mapping_location[{}], loaded_from[{}], default percolator mapping: location[{}], loaded_from[{}]", dynamic, defaultMappingLocation, defaultMappingUrl, percolatorMappingLocation, percolatorMappingUrl);
} else if (logger.isTraceEnabled()) {
logger.trace("using dynamic[{}], default mapping: default_mapping_location[{}], loaded_from[{}] and source[{}], default percolator mapping: location[{}], loaded_from[{}] and source[{}]", dynamic, defaultMappingLocation, defaultMappingUrl, defaultMappingSource, percolatorMappingLocation, percolatorMappingUrl, defaultPercolatorMappingSource);
}
}
public void close() {
for (DocumentMapper documentMapper : mappers.values()) {
documentMapper.close();
}
}
public boolean hasNested() {
return this.hasNested;
}
@Override
public UnmodifiableIterator<DocumentMapper> iterator() {
return Iterators.unmodifiableIterator(mappers.values().iterator());
}
public AnalysisService analysisService() {
return this.analysisService;
}
public DocumentMapperParser documentMapperParser() {
return this.documentParser;
}
public void addTypeListener(DocumentTypeListener listener) {
typeListeners.add(listener);
}
public void removeTypeListener(DocumentTypeListener listener) {
typeListeners.remove(listener);
}
public DocumentMapper merge(String type, CompressedString mappingSource, boolean applyDefault) {
if (DEFAULT_MAPPING.equals(type)) {
// verify we can parse it
DocumentMapper mapper = documentParser.parseCompressed(type, mappingSource);
// still add it as a document mapper so we have it registered and, for example, persisted back into
// the cluster meta data if needed, or checked for existence
synchronized (typeMutex) {
mappers = newMapBuilder(mappers).put(type, mapper).map();
}
try {
defaultMappingSource = mappingSource.string();
} catch (IOException e) {
throw new ElasticsearchGenerationException("failed to un-compress", e);
}
return mapper;
} else {
return merge(parse(type, mappingSource, applyDefault));
}
}
// never expose this to the outside world, we need to reparse the doc mapper so we get fresh
// instances of field mappers to properly remove existing doc mapper
private DocumentMapper merge(DocumentMapper mapper) {
synchronized (typeMutex) {
if (mapper.type().length() == 0) {
throw new InvalidTypeNameException("mapping type name is empty");
}
if (mapper.type().charAt(0) == '_') {
throw new InvalidTypeNameException("mapping type name [" + mapper.type() + "] can't start with '_'");
}
if (mapper.type().contains("#")) {
throw new InvalidTypeNameException("mapping type name [" + mapper.type() + "] should not include '#' in it");
}
if (mapper.type().contains(",")) {
throw new InvalidTypeNameException("mapping type name [" + mapper.type() + "] should not include ',' in it");
}
if (mapper.type().contains(".") && !PercolatorService.TYPE_NAME.equals(mapper.type())) {
logger.warn("Type [{}] contains a '.', it is recommended not to include it within a type name", mapper.type());
}
// we can add new field/object mappers while the old ones are there
// since we get new instances of those, and when we remove, we remove
// by instance equality
DocumentMapper oldMapper = mappers.get(mapper.type());
if (oldMapper != null) {
DocumentMapper.MergeResult result = oldMapper.merge(mapper, mergeFlags().simulate(false));
if (result.hasConflicts()) {
// TODO: What should we do???
if (logger.isDebugEnabled()) {
logger.debug("merging mapping for type [{}] resulted in conflicts: [{}]", mapper.type(), Arrays.toString(result.conflicts()));
}
}
fieldDataService.onMappingUpdate();
return oldMapper;
} else {
FieldMapperListener.Aggregator fieldMappersAgg = new FieldMapperListener.Aggregator();
mapper.traverse(fieldMappersAgg);
addFieldMappers(fieldMappersAgg.mappers);
mapper.addFieldMapperListener(fieldMapperListener, false);
ObjectMapperListener.Aggregator objectMappersAgg = new ObjectMapperListener.Aggregator();
mapper.traverse(objectMappersAgg);
addObjectMappers(objectMappersAgg.mappers.toArray(new ObjectMapper[objectMappersAgg.mappers.size()]));
mapper.addObjectMapperListener(objectMapperListener, false);
for (DocumentTypeListener typeListener : typeListeners) {
typeListener.beforeCreate(mapper);
}
mappers = newMapBuilder(mappers).put(mapper.type(), mapper).map();
return mapper;
}
}
}
private void addObjectMappers(ObjectMapper[] objectMappers) {
synchronized (mappersMutex) {
ImmutableOpenMap.Builder<String, ObjectMappers> fullPathObjectMappers = ImmutableOpenMap.builder(this.fullPathObjectMappers);
for (ObjectMapper objectMapper : objectMappers) {
ObjectMappers mappers = fullPathObjectMappers.get(objectMapper.fullPath());
if (mappers == null) {
mappers = new ObjectMappers(objectMapper);
} else {
mappers = mappers.concat(objectMapper);
}
fullPathObjectMappers.put(objectMapper.fullPath(), mappers);
// update the hasNested flag
if (objectMapper.nested().isNested()) {
hasNested = true;
}
}
this.fullPathObjectMappers = fullPathObjectMappers.build();
}
}
private void addFieldMappers(Iterable<FieldMapper> fieldMappers) {
synchronized (mappersMutex) {
this.fieldMappers.addNewMappers(fieldMappers);
}
}
public void remove(String type) {
synchronized (typeMutex) {
DocumentMapper docMapper = mappers.get(type);
if (docMapper == null) {
return;
}
docMapper.close();
mappers = newMapBuilder(mappers).remove(type).map();
removeObjectAndFieldMappers(docMapper);
for (DocumentTypeListener typeListener : typeListeners) {
typeListener.afterRemove(docMapper);
}
}
}
private void removeObjectAndFieldMappers(DocumentMapper docMapper) {
synchronized (mappersMutex) {
fieldMappers.removeMappers(docMapper.mappers());
ImmutableOpenMap.Builder<String, ObjectMappers> fullPathObjectMappers = ImmutableOpenMap.builder(this.fullPathObjectMappers);
for (ObjectMapper mapper : docMapper.objectMappers().values()) {
ObjectMappers mappers = fullPathObjectMappers.get(mapper.fullPath());
if (mappers != null) {
mappers = mappers.remove(mapper);
if (mappers.isEmpty()) {
fullPathObjectMappers.remove(mapper.fullPath());
} else {
fullPathObjectMappers.put(mapper.fullPath(), mappers);
}
}
}
this.fullPathObjectMappers = fullPathObjectMappers.build();
}
}
/**
* Just parses and returns the mapper without adding it, while still applying default mapping.
*/
public DocumentMapper parse(String mappingType, CompressedString mappingSource) throws MapperParsingException {
return parse(mappingType, mappingSource, true);
}
public DocumentMapper parse(String mappingType, CompressedString mappingSource, boolean applyDefault) throws MapperParsingException {
String defaultMappingSource;
if (PercolatorService.TYPE_NAME.equals(mappingType)) {
defaultMappingSource = this.defaultPercolatorMappingSource;
} else {
defaultMappingSource = this.defaultMappingSource;
}
return documentParser.parseCompressed(mappingType, mappingSource, applyDefault ? defaultMappingSource : null);
}
public boolean hasMapping(String mappingType) {
return mappers.containsKey(mappingType);
}
public Collection<String> types() {
return mappers.keySet();
}
public DocumentMapper documentMapper(String type) {
return mappers.get(type);
}
public DocumentMapper documentMapperWithAutoCreate(String type) {
DocumentMapper mapper = mappers.get(type);
if (mapper != null) {
return mapper;
}
if (!dynamic) {
throw new TypeMissingException(index, type, "trying to auto create mapping, but dynamic mapping is disabled");
}
// go ahead and dynamically create it
synchronized (typeMutex) {
mapper = mappers.get(type);
if (mapper != null) {
return mapper;
}
merge(type, null, true);
return mappers.get(type);
}
}
/**
* A filter for search. If a filter is required, will return it, otherwise, will return <tt>null</tt>.
*/
@Nullable
public Filter searchFilter(String... types) {
boolean filterPercolateType = hasMapping(PercolatorService.TYPE_NAME);
if (types != null && filterPercolateType) {
for (String type : types) {
if (PercolatorService.TYPE_NAME.equals(type)) {
filterPercolateType = false;
break;
}
}
}
Filter excludePercolatorType = null;
if (filterPercolateType) {
excludePercolatorType = new NotFilter(documentMapper(PercolatorService.TYPE_NAME).typeFilter());
}
if (types == null || types.length == 0) {
if (hasNested && filterPercolateType) {
return new AndFilter(ImmutableList.of(excludePercolatorType, NonNestedDocsFilter.INSTANCE));
} else if (hasNested) {
return NonNestedDocsFilter.INSTANCE;
} else if (filterPercolateType) {
return excludePercolatorType;
} else {
return null;
}
}
// if we filter by types, we don't need to filter by non nested docs
// since they have different types (starting with __)
if (types.length == 1) {
DocumentMapper docMapper = documentMapper(types[0]);
if (docMapper == null) {
return new TermFilter(new Term(types[0]));
}
return docMapper.typeFilter();
}
// see if we can use terms filter
boolean useTermsFilter = true;
for (String type : types) {
DocumentMapper docMapper = documentMapper(type);
if (docMapper == null) {
useTermsFilter = false;
break;
}
if (!docMapper.typeMapper().fieldType().indexed()) {
useTermsFilter = false;
break;
}
}
if (useTermsFilter) {
BytesRef[] typesBytes = new BytesRef[types.length];
for (int i = 0; i < typesBytes.length; i++) {
typesBytes[i] = new BytesRef(types[i]);
}
TermsFilter termsFilter = new TermsFilter(TypeFieldMapper.NAME, typesBytes);
if (filterPercolateType) {
return new AndFilter(ImmutableList.of(excludePercolatorType, termsFilter));
} else {
return termsFilter;
}
} else {
// Current bool filter requires that at least one should clause matches, even with a must clause.
XBooleanFilter bool = new XBooleanFilter();
for (String type : types) {
DocumentMapper docMapper = documentMapper(type);
if (docMapper == null) {
bool.add(new FilterClause(new TermFilter(new Term(TypeFieldMapper.NAME, type)), BooleanClause.Occur.SHOULD));
} else {
bool.add(new FilterClause(docMapper.typeFilter(), BooleanClause.Occur.SHOULD));
}
}
if (filterPercolateType) {
bool.add(excludePercolatorType, BooleanClause.Occur.MUST);
}
return bool;
}
}
/**
* Returns {@link FieldMappers} for all the {@link FieldMapper}s that are registered
* under the given name across all the different {@link DocumentMapper} types.
*
* @param name The name to return all the {@link FieldMappers} for across all {@link DocumentMapper}s.
* @return All the {@link FieldMappers} for across all {@link DocumentMapper}s
*/
public FieldMappers name(String name) {
return fieldMappers.name(name);
}
/**
* Returns {@link FieldMappers} for all the {@link FieldMapper}s that are registered
* under the given indexName across all the different {@link DocumentMapper} types.
*
* @param indexName The indexName to return all the {@link FieldMappers} for across all {@link DocumentMapper}s.
* @return All the {@link FieldMappers} across all {@link DocumentMapper}s for the given indexName.
*/
public FieldMappers indexName(String indexName) {
return fieldMappers.indexName(indexName);
}
/**
* Returns the {@link FieldMappers} of all the {@link FieldMapper}s that are
* registered under the give fullName across all the different {@link DocumentMapper} types.
*
* @param fullName The full name
* @return All teh {@link FieldMappers} across all the {@link DocumentMapper}s for the given fullName.
*/
public FieldMappers fullName(String fullName) {
return fieldMappers.fullName(fullName);
}
/**
* Returns objects mappers based on the full path of the object.
*/
public ObjectMappers objectMapper(String path) {
return fullPathObjectMappers.get(path);
}
/**
* Returns all the fields that match the given pattern, with an optional narrowing
* based on a list of types.
*/
public Set<String> simpleMatchToIndexNames(String pattern, @Nullable String[] types) {
if (types == null || types.length == 0) {
return simpleMatchToIndexNames(pattern);
}
if (types.length == 1 && types[0].equals("_all")) {
return simpleMatchToIndexNames(pattern);
}
if (!Regex.isSimpleMatchPattern(pattern)) {
return ImmutableSet.of(pattern);
}
Set<String> fields = Sets.newHashSet();
for (String type : types) {
DocumentMapper possibleDocMapper = mappers.get(type);
if (possibleDocMapper != null) {
for (String indexName : possibleDocMapper.mappers().simpleMatchToIndexNames(pattern)) {
fields.add(indexName);
}
}
}
return fields;
}
/**
* Returns all the fields that match the given pattern. If the pattern is prefixed with a type
* then the fields will be returned with a type prefix.
*/
public Set<String> simpleMatchToIndexNames(String pattern) {
if (!Regex.isSimpleMatchPattern(pattern)) {
return ImmutableSet.of(pattern);
}
int dotIndex = pattern.indexOf('.');
if (dotIndex != -1) {
String possibleType = pattern.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
Set<String> typedFields = Sets.newHashSet();
for (String indexName : possibleDocMapper.mappers().simpleMatchToIndexNames(pattern)) {
typedFields.add(possibleType + "." + indexName);
}
return typedFields;
}
}
return fieldMappers.simpleMatchToIndexNames(pattern);
}
public SmartNameObjectMapper smartNameObjectMapper(String smartName, @Nullable String[] types) {
if (types == null || types.length == 0) {
return smartNameObjectMapper(smartName);
}
if (types.length == 1 && types[0].equals("_all")) {
return smartNameObjectMapper(smartName);
}
for (String type : types) {
DocumentMapper possibleDocMapper = mappers.get(type);
if (possibleDocMapper != null) {
ObjectMapper mapper = possibleDocMapper.objectMappers().get(smartName);
if (mapper != null) {
return new SmartNameObjectMapper(mapper, possibleDocMapper);
}
}
}
// did not find one, see if its prefixed by type
int dotIndex = smartName.indexOf('.');
if (dotIndex != -1) {
String possibleType = smartName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
String possiblePath = smartName.substring(dotIndex + 1);
ObjectMapper mapper = possibleDocMapper.objectMappers().get(possiblePath);
if (mapper != null) {
return new SmartNameObjectMapper(mapper, possibleDocMapper);
}
}
}
// did not explicitly find one under the types provided, or prefixed by type...
return null;
}
public SmartNameObjectMapper smartNameObjectMapper(String smartName) {
int dotIndex = smartName.indexOf('.');
if (dotIndex != -1) {
String possibleType = smartName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
String possiblePath = smartName.substring(dotIndex + 1);
ObjectMapper mapper = possibleDocMapper.objectMappers().get(possiblePath);
if (mapper != null) {
return new SmartNameObjectMapper(mapper, possibleDocMapper);
}
}
}
ObjectMappers mappers = objectMapper(smartName);
if (mappers != null) {
return new SmartNameObjectMapper(mappers.mapper(), null);
}
return null;
}
/**
* Same as {@link #smartNameFieldMappers(String)} but returns the first field mapper for it. Returns
* <tt>null</tt> if there is none.
*/
public FieldMapper smartNameFieldMapper(String smartName) {
FieldMappers fieldMappers = smartNameFieldMappers(smartName);
if (fieldMappers != null) {
return fieldMappers.mapper();
}
return null;
}
public FieldMapper smartNameFieldMapper(String smartName, @Nullable String[] types) {
FieldMappers fieldMappers = smartNameFieldMappers(smartName, types);
if (fieldMappers != null) {
return fieldMappers.mapper();
}
return null;
}
public FieldMappers smartNameFieldMappers(String smartName, @Nullable String[] types) {
if (types == null || types.length == 0) {
return smartNameFieldMappers(smartName);
}
for (String type : types) {
DocumentMapper documentMapper = mappers.get(type);
// we found a mapper
if (documentMapper != null) {
// see if we find a field for it
FieldMappers mappers = documentMapper.mappers().smartName(smartName);
if (mappers != null) {
return mappers;
}
}
}
// did not find explicit field in the type provided, see if its prefixed with type
int dotIndex = smartName.indexOf('.');
if (dotIndex != -1) {
String possibleType = smartName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
String possibleName = smartName.substring(dotIndex + 1);
FieldMappers mappers = possibleDocMapper.mappers().smartName(possibleName);
if (mappers != null) {
return mappers;
}
}
}
// we did not find the field mapping in any of the types, so don't go and try to find
// it in other types...
return null;
}
/**
* Same as {@link #smartName(String)}, except it returns just the field mappers.
*/
public FieldMappers smartNameFieldMappers(String smartName) {
int dotIndex = smartName.indexOf('.');
if (dotIndex != -1) {
String possibleType = smartName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
String possibleName = smartName.substring(dotIndex + 1);
FieldMappers mappers = possibleDocMapper.mappers().smartName(possibleName);
if (mappers != null) {
return mappers;
}
}
}
FieldMappers mappers = fullName(smartName);
if (mappers != null) {
return mappers;
}
mappers = indexName(smartName);
if (mappers != null) {
return mappers;
}
return name(smartName);
}
public SmartNameFieldMappers smartName(String smartName, @Nullable String[] types) {
if (types == null || types.length == 0) {
return smartName(smartName);
}
if (types.length == 1 && types[0].equals("_all")) {
return smartName(smartName);
}
for (String type : types) {
DocumentMapper documentMapper = mappers.get(type);
// we found a mapper
if (documentMapper != null) {
// see if we find a field for it
FieldMappers mappers = documentMapper.mappers().smartName(smartName);
if (mappers != null) {
return new SmartNameFieldMappers(this, mappers, documentMapper, false);
}
}
}
// did not find explicit field in the type provided, see if its prefixed with type
int dotIndex = smartName.indexOf('.');
if (dotIndex != -1) {
String possibleType = smartName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
String possibleName = smartName.substring(dotIndex + 1);
FieldMappers mappers = possibleDocMapper.mappers().smartName(possibleName);
if (mappers != null) {
return new SmartNameFieldMappers(this, mappers, possibleDocMapper, true);
}
}
}
// we did not find the field mapping in any of the types, so don't go and try to find
// it in other types...
return null;
}
/**
* Returns smart field mappers based on a smart name. A smart name is one that can optioannly be prefixed
* with a type (and then a '.'). If it is, then the {@link MapperService.SmartNameFieldMappers}
* will have the doc mapper set.
* <p/>
* <p>It also (without the optional type prefix) try and find the {@link FieldMappers} for the specific
* name. It will first try to find it based on the full name (with the dots if its a compound name). If
* it is not found, will try and find it based on the indexName (which can be controlled in the mapping),
* and last, will try it based no the name itself.
* <p/>
* <p>If nothing is found, returns null.
*/
public SmartNameFieldMappers smartName(String smartName) {
int dotIndex = smartName.indexOf('.');
if (dotIndex != -1) {
String possibleType = smartName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
String possibleName = smartName.substring(dotIndex + 1);
FieldMappers mappers = possibleDocMapper.mappers().smartName(possibleName);
if (mappers != null) {
return new SmartNameFieldMappers(this, mappers, possibleDocMapper, true);
}
}
}
FieldMappers fieldMappers = fullName(smartName);
if (fieldMappers != null) {
return new SmartNameFieldMappers(this, fieldMappers, null, false);
}
fieldMappers = indexName(smartName);
if (fieldMappers != null) {
return new SmartNameFieldMappers(this, fieldMappers, null, false);
}
fieldMappers = name(smartName);
if (fieldMappers != null) {
return new SmartNameFieldMappers(this, fieldMappers, null, false);
}
return null;
}
public Analyzer searchAnalyzer() {
return this.searchAnalyzer;
}
public Analyzer searchQuoteAnalyzer() {
return this.searchQuoteAnalyzer;
}
public Analyzer fieldSearchAnalyzer(String field) {
return this.searchAnalyzer.getWrappedAnalyzer(field);
}
public Analyzer fieldSearchQuoteAnalyzer(String field) {
return this.searchQuoteAnalyzer.getWrappedAnalyzer(field);
}
/**
* Resolves the closest inherited {@link ObjectMapper} that is nested.
*/
public ObjectMapper resolveClosestNestedObjectMapper(String fieldName) {
int indexOf = fieldName.lastIndexOf('.');
if (indexOf == -1) {
return null;
} else {
do {
String objectPath = fieldName.substring(0, indexOf);
ObjectMappers objectMappers = objectMapper(objectPath);
if (objectMappers == null) {
return null;
}
if (objectMappers.hasNested()) {
for (ObjectMapper objectMapper : objectMappers) {
if (objectMapper.nested().isNested()) {
return objectMapper;
}
}
}
indexOf = objectPath.lastIndexOf('.');
} while (indexOf != -1);
}
return null;
}
/**
* @return Whether a field is a metadata field.
*/
public static boolean isMetadataField(String fieldName) {
return META_FIELDS.contains(fieldName);
}
public static class SmartNameObjectMapper {
private final ObjectMapper mapper;
private final DocumentMapper docMapper;
public SmartNameObjectMapper(ObjectMapper mapper, @Nullable DocumentMapper docMapper) {
this.mapper = mapper;
this.docMapper = docMapper;
}
public boolean hasMapper() {
return mapper != null;
}
public ObjectMapper mapper() {
return mapper;
}
public boolean hasDocMapper() {
return docMapper != null;
}
public DocumentMapper docMapper() {
return docMapper;
}
}
public static class SmartNameFieldMappers {
private final MapperService mapperService;
private final FieldMappers fieldMappers;
private final DocumentMapper docMapper;
private final boolean explicitTypeInName;
public SmartNameFieldMappers(MapperService mapperService, FieldMappers fieldMappers, @Nullable DocumentMapper docMapper, boolean explicitTypeInName) {
this.mapperService = mapperService;
this.fieldMappers = fieldMappers;
this.docMapper = docMapper;
this.explicitTypeInName = explicitTypeInName;
}
/**
* Has at least one mapper for the field.
*/
public boolean hasMapper() {
return !fieldMappers.isEmpty();
}
/**
* The first mapper for the smart named field.
*/
public FieldMapper mapper() {
return fieldMappers.mapper();
}
/**
* All the field mappers for the smart name field.
*/
public FieldMappers fieldMappers() {
return fieldMappers;
}
/**
* If the smart name was a typed field, with a type that we resolved, will return
* <tt>true</tt>.
*/
public boolean hasDocMapper() {
return docMapper != null;
}
/**
* If the smart name was a typed field, with a type that we resolved, will return
* the document mapper for it.
*/
public DocumentMapper docMapper() {
return docMapper;
}
/**
* Returns <tt>true</tt> if the type is explicitly specified in the name.
*/
public boolean explicitTypeInName() {
return this.explicitTypeInName;
}
public boolean explicitTypeInNameWithDocMapper() {
return explicitTypeInName && docMapper != null;
}
/**
* The best effort search analyzer associated with this field.
*/
public Analyzer searchAnalyzer() {
if (hasMapper()) {
Analyzer analyzer = mapper().searchAnalyzer();
if (analyzer != null) {
return analyzer;
}
}
if (docMapper != null && docMapper.searchAnalyzer() != null) {
return docMapper.searchAnalyzer();
}
return mapperService.searchAnalyzer();
}
public Analyzer searchQuoteAnalyzer() {
if (hasMapper()) {
Analyzer analyzer = mapper().searchQuoteAnalyzer();
if (analyzer != null) {
return analyzer;
}
}
if (docMapper != null && docMapper.searchQuotedAnalyzer() != null) {
return docMapper.searchQuotedAnalyzer();
}
return mapperService.searchQuoteAnalyzer();
}
}
final class SmartIndexNameSearchAnalyzer extends AnalyzerWrapper {
private final Analyzer defaultAnalyzer;
SmartIndexNameSearchAnalyzer(Analyzer defaultAnalyzer) {
this.defaultAnalyzer = defaultAnalyzer;
}
@Override
protected Analyzer getWrappedAnalyzer(String fieldName) {
int dotIndex = fieldName.indexOf('.');
if (dotIndex != -1) {
String possibleType = fieldName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
return possibleDocMapper.mappers().searchAnalyzer();
}
}
FieldMappers mappers = fieldMappers.fullName(fieldName);
if (mappers != null && mappers.mapper() != null && mappers.mapper().searchAnalyzer() != null) {
return mappers.mapper().searchAnalyzer();
}
mappers = fieldMappers.indexName(fieldName);
if (mappers != null && mappers.mapper() != null && mappers.mapper().searchAnalyzer() != null) {
return mappers.mapper().searchAnalyzer();
}
return defaultAnalyzer;
}
@Override
protected TokenStreamComponents wrapComponents(String fieldName, TokenStreamComponents components) {
return components;
}
}
final class SmartIndexNameSearchQuoteAnalyzer extends AnalyzerWrapper {
private final Analyzer defaultAnalyzer;
SmartIndexNameSearchQuoteAnalyzer(Analyzer defaultAnalyzer) {
this.defaultAnalyzer = defaultAnalyzer;
}
@Override
protected Analyzer getWrappedAnalyzer(String fieldName) {
int dotIndex = fieldName.indexOf('.');
if (dotIndex != -1) {
String possibleType = fieldName.substring(0, dotIndex);
DocumentMapper possibleDocMapper = mappers.get(possibleType);
if (possibleDocMapper != null) {
return possibleDocMapper.mappers().searchQuoteAnalyzer();
}
}
FieldMappers mappers = fieldMappers.fullName(fieldName);
if (mappers != null && mappers.mapper() != null && mappers.mapper().searchQuoteAnalyzer() != null) {
return mappers.mapper().searchQuoteAnalyzer();
}
mappers = fieldMappers.indexName(fieldName);
if (mappers != null && mappers.mapper() != null && mappers.mapper().searchQuoteAnalyzer() != null) {
return mappers.mapper().searchQuoteAnalyzer();
}
return defaultAnalyzer;
}
@Override
protected TokenStreamComponents wrapComponents(String fieldName, TokenStreamComponents components) {
return components;
}
}
class InternalFieldMapperListener extends FieldMapperListener {
@Override
public void fieldMapper(FieldMapper fieldMapper) {
addFieldMappers(Arrays.asList(fieldMapper));
}
@Override
public void fieldMappers(Iterable<FieldMapper> fieldMappers) {
addFieldMappers(fieldMappers);
}
}
class InternalObjectMapperListener extends ObjectMapperListener {
@Override
public void objectMapper(ObjectMapper objectMapper) {
addObjectMappers(new ObjectMapper[]{objectMapper});
}
@Override
public void objectMappers(ObjectMapper... objectMappers) {
addObjectMappers(objectMappers);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_mapper_MapperService.java
|
1,273 |
@SuppressWarnings("unchecked")
public class InternalTransportIndicesAdminClient extends AbstractIndicesAdminClient implements IndicesAdminClient {
private final TransportClientNodesService nodesService;
private final ThreadPool threadPool;
private final ImmutableMap<IndicesAction, TransportActionNodeProxy> actions;
@Inject
public InternalTransportIndicesAdminClient(Settings settings, TransportClientNodesService nodesService, TransportService transportService, ThreadPool threadPool,
Map<String, GenericAction> actions) {
this.nodesService = nodesService;
this.threadPool = threadPool;
MapBuilder<IndicesAction, TransportActionNodeProxy> actionsBuilder = new MapBuilder<IndicesAction, TransportActionNodeProxy>();
for (GenericAction action : actions.values()) {
if (action instanceof IndicesAction) {
actionsBuilder.put((IndicesAction) action, new TransportActionNodeProxy(settings, action, transportService));
}
}
this.actions = actionsBuilder.immutableMap();
}
@Override
public ThreadPool threadPool() {
return this.threadPool;
}
@SuppressWarnings("unchecked")
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> ActionFuture<Response> execute(final IndicesAction<Request, Response, RequestBuilder> action, final Request request) {
final TransportActionNodeProxy<Request, Response> proxy = actions.get(action);
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<Response>>() {
@Override
public ActionFuture<Response> doWithNode(DiscoveryNode node) throws ElasticsearchException {
return proxy.execute(node, request);
}
});
}
@SuppressWarnings("unchecked")
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void execute(final IndicesAction<Request, Response, RequestBuilder> action, final Request request, ActionListener<Response> listener) {
final TransportActionNodeProxy<Request, Response> proxy = actions.get(action);
nodesService.execute(new TransportClientNodesService.NodeListenerCallback<Response>() {
@Override
public void doWithNode(DiscoveryNode node, ActionListener<Response> listener) throws ElasticsearchException {
proxy.execute(node, request, listener);
}
}, listener);
}
}
| 1no label
|
src_main_java_org_elasticsearch_client_transport_support_InternalTransportIndicesAdminClient.java
|
168 |
private class SliceQueryRunner implements Runnable {
final KeySliceQuery kq;
final CountDownLatch doneSignal;
final AtomicInteger failureCount;
final Object[] resultArray;
final int resultPosition;
private SliceQueryRunner(KeySliceQuery kq, CountDownLatch doneSignal, AtomicInteger failureCount,
Object[] resultArray, int resultPosition) {
this.kq = kq;
this.doneSignal = doneSignal;
this.failureCount = failureCount;
this.resultArray = resultArray;
this.resultPosition = resultPosition;
}
@Override
public void run() {
try {
List<Entry> result;
result = edgeStoreQuery(kq);
resultArray[resultPosition] = result;
} catch (Exception e) {
failureCount.incrementAndGet();
log.warn("Individual query in multi-transaction failed: ", e);
} finally {
doneSignal.countDown();
}
}
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_BackendTransaction.java
|
5,129 |
public static class Builder {
private List<AggregatorFactory> factories = new ArrayList<AggregatorFactory>();
public Builder add(AggregatorFactory factory) {
factories.add(factory);
return this;
}
public AggregatorFactories build() {
if (factories.isEmpty()) {
return EMPTY;
}
return new AggregatorFactories(factories.toArray(new AggregatorFactory[factories.size()]));
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_AggregatorFactories.java
|
1,792 |
public class RestrictionType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, RestrictionType> TYPES = new LinkedHashMap<String, RestrictionType>();
public static final RestrictionType STRING_LIKE = new RestrictionType("STRING_LIKE", "STRING_LIKE");
public static final RestrictionType BOOLEAN = new RestrictionType("BOOLEAN", "BOOLEAN");
public static final RestrictionType CHARACTER = new RestrictionType("CHARACTER", "CHARACTER");
public static final RestrictionType DATE = new RestrictionType("DATE", "DATE");
public static final RestrictionType DECIMAL = new RestrictionType("DECIMAL", "DECIMAL");
public static final RestrictionType LONG = new RestrictionType("LONG", "LONG");
public static final RestrictionType COLLECTION_SIZE_EQUAL = new RestrictionType("COLLECTION_SIZE_EQUAL", "COLLECTION_SIZE_EQUAL");
public static final RestrictionType IS_NULL_LONG = new RestrictionType("IS_NULL_LONG", "IS_NULL_LONG");
public static final RestrictionType STRING_EQUAL = new RestrictionType("STRING_EQUAL", "STRING_EQUAL");
public static final RestrictionType LONG_EQUAL = new RestrictionType("LONG_EQUAL", "LONG_EQUAL");
public static RestrictionType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public RestrictionType() {
//do nothing
}
public RestrictionType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
public String getType() {
return type;
}
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)){
TYPES.put(type, this);
} else {
throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName());
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RestrictionType other = (RestrictionType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_criteria_RestrictionType.java
|
82 |
LESS_THAN_EQUAL {
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return Comparable.class.isAssignableFrom(clazz);
}
@Override
public boolean isValidCondition(Object condition) {
return condition!=null && condition instanceof Comparable;
}
@Override
public boolean evaluate(Object value, Object condition) {
Integer cmp = AttributeUtil.compare(value,condition);
return cmp!=null?cmp<=0:false;
}
@Override
public String toString() {
return "<=";
}
@Override
public TitanPredicate negate() {
return GREATER_THAN;
}
},
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java
|
1,464 |
public class OGraphFunctionFactory implements OSQLFunctionFactory {
private static final Map<String, Object> FUNCTIONS = new HashMap<String, Object>();
static {
FUNCTIONS.put(OSQLFunctionGremlin.NAME.toUpperCase(Locale.ENGLISH), OSQLFunctionGremlin.class);
FUNCTIONS.put(OSQLFunctionLabel.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionLabel());
FUNCTIONS.put(OSQLFunctionOut.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionOut());
FUNCTIONS.put(OSQLFunctionIn.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionIn());
FUNCTIONS.put(OSQLFunctionBoth.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionBoth());
FUNCTIONS.put(OSQLFunctionOutE.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionOutE());
FUNCTIONS.put(OSQLFunctionInE.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionInE());
FUNCTIONS.put(OSQLFunctionBothE.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionBothE());
FUNCTIONS.put(OSQLFunctionOutV.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionOutV());
FUNCTIONS.put(OSQLFunctionInV.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionInV());
FUNCTIONS.put(OSQLFunctionBothV.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionBothV());
FUNCTIONS.put(OSQLFunctionDijkstra.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionDijkstra());
FUNCTIONS.put(OSQLFunctionShortestPath.NAME.toUpperCase(Locale.ENGLISH), new OSQLFunctionShortestPath());
}
public Set<String> getFunctionNames() {
return FUNCTIONS.keySet();
}
public boolean hasFunction(final String name) {
return FUNCTIONS.containsKey(name);
}
public OSQLFunction createFunction(final String name) {
final Object obj = FUNCTIONS.get(name);
if (obj == null)
throw new OCommandExecutionException("Unknowned function name :" + name);
if (obj instanceof OSQLFunction)
return (OSQLFunction) obj;
else {
// it's a class
final Class<?> clazz = (Class<?>) obj;
try {
return (OSQLFunction) clazz.newInstance();
} catch (Exception e) {
throw new OCommandExecutionException("Error in creation of function " + name
+ "(). Probably there is not an empty constructor or the constructor generates errors", e);
}
}
}
}
| 1no label
|
graphdb_src_main_java_com_orientechnologies_orient_graph_sql_functions_OGraphFunctionFactory.java
|
281 |
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientSocketInterceptorTest {
@Before
@After
public void cleanup() throws Exception {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test(timeout = 120000)
public void testSuccessfulSocketInterceptor() {
Config config = new Config();
SocketInterceptorConfig socketInterceptorConfig = new SocketInterceptorConfig();
MySocketInterceptor mySocketInterceptor = new MySocketInterceptor(true);
socketInterceptorConfig.setImplementation(mySocketInterceptor).setEnabled(true);
config.getNetworkConfig().setSocketInterceptorConfig(socketInterceptorConfig);
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
assertEquals(2, h2.getCluster().getMembers().size());
assertEquals(2, h1.getCluster().getMembers().size());
ClientConfig clientConfig = new ClientConfig();
MySocketInterceptor myClientSocketInterceptor = new MySocketInterceptor(true);
clientConfig.getNetworkConfig().setSocketInterceptorConfig(new SocketInterceptorConfig().setEnabled(true)
.setImplementation(myClientSocketInterceptor));
HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
assertEquals(2, client.getCluster().getMembers().size());
assertEquals(3, mySocketInterceptor.getAcceptCallCount());
assertEquals(1, mySocketInterceptor.getConnectCallCount());
assertEquals(0, mySocketInterceptor.getAcceptFailureCount());
assertEquals(0, mySocketInterceptor.getConnectFailureCount());
assertTrue(myClientSocketInterceptor.getConnectCallCount() >= 2);
assertEquals(0, myClientSocketInterceptor.getAcceptCallCount());
assertEquals(0, myClientSocketInterceptor.getAcceptFailureCount());
assertEquals(0, myClientSocketInterceptor.getConnectFailureCount());
}
@Test(timeout = 120000)
public void testFailingSocketInterceptor() {
Config config = new Config();
SocketInterceptorConfig socketInterceptorConfig = new SocketInterceptorConfig();
MySocketInterceptor mySocketInterceptor = new MySocketInterceptor(true);
socketInterceptorConfig.setImplementation(mySocketInterceptor).setEnabled(true);
config.getNetworkConfig().setSocketInterceptorConfig(socketInterceptorConfig);
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
assertEquals(2, h2.getCluster().getMembers().size());
assertEquals(2, h1.getCluster().getMembers().size());
ClientConfig clientConfig = new ClientConfig();
MySocketInterceptor myClientSocketInterceptor = new MySocketInterceptor(false);
clientConfig.getNetworkConfig().setSocketInterceptorConfig(new SocketInterceptorConfig().setEnabled(true)
.setImplementation(myClientSocketInterceptor));
try {
HazelcastClient.newHazelcastClient(clientConfig);
fail("Client should not be able to connect!");
} catch (IllegalStateException e) {
assertTrue(mySocketInterceptor.getAcceptFailureCount() > 0);
assertTrue(myClientSocketInterceptor.getConnectFailureCount() > 0);
}
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_io_ClientSocketInterceptorTest.java
|
1,276 |
public interface AckedClusterStateUpdateTask extends TimeoutClusterStateUpdateTask {
/**
* Called to determine which nodes the acknowledgement is expected from
* @param discoveryNode a node
* @return true if the node is expected to send ack back, false otherwise
*/
boolean mustAck(DiscoveryNode discoveryNode);
/**
* Called once all the nodes have acknowledged the cluster state update request. Must be
* very lightweight execution, since it gets executed on the cluster service thread.
* @param t optional error that might have been thrown
*/
void onAllNodesAcked(@Nullable Throwable t);
/**
* Called once the acknowledgement timeout defined by
* {@link AckedClusterStateUpdateTask#ackTimeout()} has expired
*/
void onAckTimeout();
/**
* Acknowledgement timeout, maximum time interval to wait for acknowledgements
*/
TimeValue ackTimeout();
}
| 0true
|
src_main_java_org_elasticsearch_cluster_AckedClusterStateUpdateTask.java
|
742 |
public class ListGetRequest extends CollectionRequest {
int index = -1;
public ListGetRequest() {
}
public ListGetRequest(String name, int index) {
super(name);
this.index = index;
}
@Override
protected Operation prepareOperation() {
return new ListGetOperation(name, index);
}
@Override
public int getClassId() {
return CollectionPortableHook.LIST_GET;
}
public void write(PortableWriter writer) throws IOException {
super.write(writer);
writer.writeInt("i", index);
}
public void read(PortableReader reader) throws IOException {
super.read(reader);
index = reader.readInt("i");
}
@Override
public String getRequiredAction() {
return ActionConstants.ACTION_READ;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_client_ListGetRequest.java
|
1,327 |
public class SimpleClusterStateTests extends ElasticsearchIntegrationTest {
@Before
public void indexData() throws Exception {
index("foo", "bar", "1", XContentFactory.jsonBuilder().startObject().field("foo", "foo").endObject());
index("fuu", "buu", "1", XContentFactory.jsonBuilder().startObject().field("fuu", "fuu").endObject());
index("baz", "baz", "1", XContentFactory.jsonBuilder().startObject().field("baz", "baz").endObject());
refresh();
}
@Test
public void testRoutingTable() throws Exception {
ClusterStateResponse clusterStateResponseUnfiltered = client().admin().cluster().prepareState().clear().setRoutingTable(true).get();
assertThat(clusterStateResponseUnfiltered.getState().routingTable().hasIndex("foo"), is(true));
assertThat(clusterStateResponseUnfiltered.getState().routingTable().hasIndex("fuu"), is(true));
assertThat(clusterStateResponseUnfiltered.getState().routingTable().hasIndex("baz"), is(true));
assertThat(clusterStateResponseUnfiltered.getState().routingTable().hasIndex("non-existent"), is(false));
ClusterStateResponse clusterStateResponse = client().admin().cluster().prepareState().clear().get();
assertThat(clusterStateResponse.getState().routingTable().hasIndex("foo"), is(false));
assertThat(clusterStateResponse.getState().routingTable().hasIndex("fuu"), is(false));
assertThat(clusterStateResponse.getState().routingTable().hasIndex("baz"), is(false));
assertThat(clusterStateResponse.getState().routingTable().hasIndex("non-existent"), is(false));
}
@Test
public void testNodes() throws Exception {
ClusterStateResponse clusterStateResponse = client().admin().cluster().prepareState().clear().setNodes(true).get();
assertThat(clusterStateResponse.getState().nodes().nodes().size(), is(cluster().size()));
ClusterStateResponse clusterStateResponseFiltered = client().admin().cluster().prepareState().clear().get();
assertThat(clusterStateResponseFiltered.getState().nodes().nodes().size(), is(0));
}
@Test
public void testMetadata() throws Exception {
ClusterStateResponse clusterStateResponseUnfiltered = client().admin().cluster().prepareState().clear().setMetaData(true).get();
assertThat(clusterStateResponseUnfiltered.getState().metaData().indices().size(), is(3));
ClusterStateResponse clusterStateResponse = client().admin().cluster().prepareState().clear().get();
assertThat(clusterStateResponse.getState().metaData().indices().size(), is(0));
}
@Test
public void testIndexTemplates() throws Exception {
client().admin().indices().preparePutTemplate("foo_template")
.setTemplate("te*")
.setOrder(0)
.addMapping("type1", XContentFactory.jsonBuilder().startObject().startObject("type1").startObject("properties")
.startObject("field1").field("type", "string").field("store", "yes").endObject()
.startObject("field2").field("type", "string").field("store", "yes").field("index", "not_analyzed").endObject()
.endObject().endObject().endObject())
.get();
client().admin().indices().preparePutTemplate("fuu_template")
.setTemplate("test*")
.setOrder(1)
.addMapping("type1", XContentFactory.jsonBuilder().startObject().startObject("type1").startObject("properties")
.startObject("field2").field("type", "string").field("store", "no").endObject()
.endObject().endObject().endObject())
.get();
ClusterStateResponse clusterStateResponseUnfiltered = client().admin().cluster().prepareState().get();
assertThat(clusterStateResponseUnfiltered.getState().metaData().templates().size(), is(greaterThanOrEqualTo(2)));
ClusterStateResponse clusterStateResponse = client().admin().cluster().prepareState().clear().setMetaData(true).setIndexTemplates("foo_template").get();
assertThat(clusterStateResponse.getState().metaData().templates().size(), is(1));
}
@Test
public void testThatFilteringByIndexWorksForMetadataAndRoutingTable() throws Exception {
ClusterStateResponse clusterStateResponseFiltered = client().admin().cluster().prepareState().clear()
.setMetaData(true).setRoutingTable(true).setIndices("foo", "fuu", "non-existent").get();
// metadata
assertThat(clusterStateResponseFiltered.getState().metaData().indices().size(), is(2));
assertThat(clusterStateResponseFiltered.getState().metaData().indices(), CollectionAssertions.hasKey("foo"));
assertThat(clusterStateResponseFiltered.getState().metaData().indices(), CollectionAssertions.hasKey("fuu"));
// routing table
assertThat(clusterStateResponseFiltered.getState().routingTable().hasIndex("foo"), is(true));
assertThat(clusterStateResponseFiltered.getState().routingTable().hasIndex("fuu"), is(true));
assertThat(clusterStateResponseFiltered.getState().routingTable().hasIndex("baz"), is(false));
}
}
| 0true
|
src_test_java_org_elasticsearch_cluster_SimpleClusterStateTests.java
|
27 |
@Service("blCategoryFieldService")
public class CategoryFieldServiceImpl extends AbstractRuleBuilderFieldService {
@Override
public void init() {
fields.add(new FieldData.Builder()
.label("rule_categoryName")
.name("name")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_categoryId")
.name("id")
.operators("blcOperators_Numeric")
.options("[]")
.type(SupportedFieldType.ID)
.build());
fields.add(new FieldData.Builder()
.label("rule_categoryUrl")
.name("url")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
fields.add(new FieldData.Builder()
.label("rule_categoryLongDescription")
.name("longDescription")
.operators("blcOperators_Text")
.options("[]")
.type(SupportedFieldType.STRING)
.build());
}
@Override
public String getName() {
return RuleIdentifier.CATEGORY;
}
@Override
public String getDtoClassName() {
return "org.broadleafcommerce.core.catalog.domain.CategoryImpl";
}
}
| 0true
|
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_web_rulebuilder_service_CategoryFieldServiceImpl.java
|
2,544 |
public final class Address implements IdentifiedDataSerializable {
public static final int ID = 1;
private static final byte IPV4 = 4;
private static final byte IPV6 = 6;
private int port = -1;
private String host;
private byte type;
private String scopeId;
private boolean hostSet;
public Address() {
}
public Address(String host, int port) throws UnknownHostException {
this(host, InetAddress.getByName(host), port);
}
public Address(InetAddress inetAddress, int port) {
this(null, inetAddress, port);
hostSet = false;
}
public Address(InetSocketAddress inetSocketAddress) {
this(inetSocketAddress.getAddress(), inetSocketAddress.getPort());
}
public Address(String hostname, InetAddress inetAddress, int port) {
type = (inetAddress instanceof Inet4Address) ? IPV4 : IPV6;
String[] addressArgs = inetAddress.getHostAddress().split("\\%");
host = hostname != null ? hostname : addressArgs[0];
if (addressArgs.length == 2) {
scopeId = addressArgs[1];
}
this.port = port;
hostSet = !AddressUtil.isIpAddress(host);
}
public Address(Address address) {
this.host = address.host;
this.port = address.port;
this.type = address.type;
this.scopeId = address.scopeId;
this.hostSet = address.hostSet;
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(port);
out.write(type);
if (host != null) {
byte[] address = stringToBytes(host);
out.writeInt(address.length);
out.write(address);
} else {
out.writeInt(0);
}
}
public void readData(ObjectDataInput in) throws IOException {
port = in.readInt();
type = in.readByte();
int len = in.readInt();
if (len > 0) {
byte[] address = new byte[len];
in.readFully(address);
host = bytesToString(address);
}
}
public String getHost() {
return host;
}
@Override
public String toString() {
return "Address[" + getHost() + "]:" + port;
}
public int getPort() {
return port;
}
public InetAddress getInetAddress() throws UnknownHostException {
return InetAddress.getByName(getScopedHost());
}
public InetSocketAddress getInetSocketAddress() throws UnknownHostException {
return new InetSocketAddress(getInetAddress(), port);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Address)) {
return false;
}
final Address address = (Address) o;
return port == address.port && this.type == address.type && this.host.equals(address.host);
}
@Override
public int hashCode() {
int result = port;
result = 31 * result + host.hashCode();
return result;
}
public boolean isIPv4() {
return type == IPV4;
}
public boolean isIPv6() {
return type == IPV6;
}
public String getScopeId() {
return isIPv6() ? scopeId : null;
}
public void setScopeId(final String scopeId) {
if (isIPv6()) {
this.scopeId = scopeId;
}
}
public String getScopedHost() {
return (isIPv4() || hostSet || scopeId == null) ? getHost()
: getHost() + "%" + scopeId;
}
@Override
public int getFactoryId() {
return Data.FACTORY_ID;
}
@Override
public int getId() {
return ID;
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_nio_Address.java
|
1,591 |
public abstract class FieldMetadata implements Serializable {
private static final long serialVersionUID = 1L;
private String inheritedFromType;
private String[] availableToTypes;
private Boolean excluded;
private String friendlyName;
private String securityLevel;
private Integer order;
private String owningClassFriendlyName;
private String tab;
private Integer tabOrder;
//temporary fields
private Boolean childrenExcluded;
private String targetClass;
private String owningClass;
private String prefix;
private String fieldName;
private String showIfProperty;
private String currencyCodeField;
//Additional metadata not supported as first class
private Map<String, Object> additionalMetadata = new HashMap<String, Object>();
public String[] getAvailableToTypes() {
return availableToTypes;
}
public void setAvailableToTypes(String[] availableToTypes) {
Arrays.sort(availableToTypes);
this.availableToTypes = availableToTypes;
}
public String getInheritedFromType() {
return inheritedFromType;
}
public void setInheritedFromType(String inheritedFromType) {
this.inheritedFromType = inheritedFromType;
}
public Boolean getExcluded() {
return excluded;
}
public void setExcluded(Boolean excluded) {
this.excluded = excluded;
}
public Map<String, Object> getAdditionalMetadata() {
return additionalMetadata;
}
public void setAdditionalMetadata(Map<String, Object> additionalMetadata) {
this.additionalMetadata = additionalMetadata;
}
protected FieldMetadata populate(FieldMetadata metadata) {
metadata.inheritedFromType = inheritedFromType;
if (availableToTypes != null) {
metadata.availableToTypes = new String[availableToTypes.length];
System.arraycopy(availableToTypes, 0, metadata.availableToTypes, 0, availableToTypes.length);
}
metadata.excluded = excluded;
metadata.friendlyName = friendlyName;
metadata.owningClassFriendlyName = owningClassFriendlyName;
metadata.securityLevel = securityLevel;
metadata.order = order;
metadata.targetClass = targetClass;
metadata.owningClass = owningClass;
metadata.prefix = prefix;
metadata.childrenExcluded = childrenExcluded;
metadata.fieldName = fieldName;
metadata.showIfProperty = showIfProperty;
metadata.currencyCodeField = currencyCodeField;
for (Map.Entry<String, Object> entry : additionalMetadata.entrySet()) {
metadata.additionalMetadata.put(entry.getKey(), entry.getValue());
}
return metadata;
}
public String getShowIfProperty() {
return showIfProperty;
}
public void setShowIfProperty(String showIfProperty) {
this.showIfProperty = showIfProperty;
}
public String getCurrencyCodeField() {
return currencyCodeField;
}
public void setCurrencyCodeField(String currencyCodeField) {
this.currencyCodeField = currencyCodeField;
}
public String getFriendlyName() {
return friendlyName;
}
public void setFriendlyName(String friendlyName) {
this.friendlyName = friendlyName;
}
public String getSecurityLevel() {
return securityLevel;
}
public void setSecurityLevel(String securityLevel) {
this.securityLevel = securityLevel;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
public String getTargetClass() {
return targetClass;
}
public void setTargetClass(String targetClass) {
this.targetClass = targetClass;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getOwningClassFriendlyName() {
return owningClassFriendlyName;
}
public void setOwningClassFriendlyName(String owningClassFriendlyName) {
this.owningClassFriendlyName = owningClassFriendlyName;
}
public String getOwningClass() {
return owningClass;
}
public void setOwningClass(String owningClass) {
this.owningClass = owningClass;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public Boolean getChildrenExcluded() {
return childrenExcluded;
}
public void setChildrenExcluded(Boolean childrenExcluded) {
this.childrenExcluded = childrenExcluded;
}
public String getTab() {
return tab;
}
public void setTab(String tab) {
this.tab = tab;
}
public Integer getTabOrder() {
return tabOrder;
}
public void setTabOrder(Integer tabOrder) {
this.tabOrder = tabOrder;
}
public abstract FieldMetadata cloneFieldMetadata();
public abstract void accept(MetadataVisitor visitor);
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof FieldMetadata)) return false;
FieldMetadata that = (FieldMetadata) o;
if (additionalMetadata != null ? !additionalMetadata.equals(that.additionalMetadata) : that
.additionalMetadata != null)
return false;
if (!Arrays.equals(availableToTypes, that.availableToTypes)) return false;
if (childrenExcluded != null ? !childrenExcluded.equals(that.childrenExcluded) : that.childrenExcluded != null)
return false;
if (currencyCodeField != null ? !currencyCodeField.equals(that.currencyCodeField) : that.currencyCodeField !=
null)
return false;
if (excluded != null ? !excluded.equals(that.excluded) : that.excluded != null) return false;
if (fieldName != null ? !fieldName.equals(that.fieldName) : that.fieldName != null) return false;
if (friendlyName != null ? !friendlyName.equals(that.friendlyName) : that.friendlyName != null) return false;
if (inheritedFromType != null ? !inheritedFromType.equals(that.inheritedFromType) : that.inheritedFromType !=
null)
return false;
if (order != null ? !order.equals(that.order) : that.order != null) return false;
if (owningClass != null ? !owningClass.equals(that.owningClass) : that.owningClass != null) return false;
if (owningClassFriendlyName != null ? !owningClassFriendlyName.equals(that.owningClassFriendlyName) : that
.owningClassFriendlyName != null)
return false;
if (prefix != null ? !prefix.equals(that.prefix) : that.prefix != null) return false;
if (securityLevel != null ? !securityLevel.equals(that.securityLevel) : that.securityLevel != null)
return false;
if (showIfProperty != null ? !showIfProperty.equals(that.showIfProperty) : that.showIfProperty != null)
return false;
if (tab != null ? !tab.equals(that.tab) : that.tab != null) return false;
if (tabOrder != null ? !tabOrder.equals(that.tabOrder) : that.tabOrder != null) return false;
if (targetClass != null ? !targetClass.equals(that.targetClass) : that.targetClass != null) return false;
return true;
}
@Override
public int hashCode() {
int result = inheritedFromType != null ? inheritedFromType.hashCode() : 0;
result = 31 * result + (availableToTypes != null ? Arrays.hashCode(availableToTypes) : 0);
result = 31 * result + (excluded != null ? excluded.hashCode() : 0);
result = 31 * result + (friendlyName != null ? friendlyName.hashCode() : 0);
result = 31 * result + (securityLevel != null ? securityLevel.hashCode() : 0);
result = 31 * result + (order != null ? order.hashCode() : 0);
result = 31 * result + (owningClassFriendlyName != null ? owningClassFriendlyName.hashCode() : 0);
result = 31 * result + (tab != null ? tab.hashCode() : 0);
result = 31 * result + (tabOrder != null ? tabOrder.hashCode() : 0);
result = 31 * result + (childrenExcluded != null ? childrenExcluded.hashCode() : 0);
result = 31 * result + (targetClass != null ? targetClass.hashCode() : 0);
result = 31 * result + (owningClass != null ? owningClass.hashCode() : 0);
result = 31 * result + (prefix != null ? prefix.hashCode() : 0);
result = 31 * result + (fieldName != null ? fieldName.hashCode() : 0);
result = 31 * result + (showIfProperty != null ? showIfProperty.hashCode() : 0);
result = 31 * result + (currencyCodeField != null ? currencyCodeField.hashCode() : 0);
result = 31 * result + (additionalMetadata != null ? additionalMetadata.hashCode() : 0);
return result;
}
}
| 1no label
|
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_FieldMetadata.java
|
2,453 |
public class MultiMapService implements ManagedService, RemoteService,
MigrationAwareService, EventPublishingService<MultiMapEvent, EventListener>, TransactionalService {
public static final String SERVICE_NAME = "hz:impl:multiMapService";
private static final int STATS_MAP_INITIAL_CAPACITY = 1000;
private static final int REPLICA_ADDRESS_TRY_COUNT = 3;
private static final int REPLICA_ADDRESS_SLEEP_WAIT_MILLIS = 1000;
private final NodeEngine nodeEngine;
private final MultiMapPartitionContainer[] partitionContainers;
private final ConcurrentMap<String, LocalMultiMapStatsImpl> statsMap
= new ConcurrentHashMap<String, LocalMultiMapStatsImpl>(STATS_MAP_INITIAL_CAPACITY);
private final ConstructorFunction<String, LocalMultiMapStatsImpl> localMultiMapStatsConstructorFunction
= new ConstructorFunction<String, LocalMultiMapStatsImpl>() {
public LocalMultiMapStatsImpl createNew(String key) {
return new LocalMultiMapStatsImpl();
}
};
public MultiMapService(NodeEngine nodeEngine) {
this.nodeEngine = nodeEngine;
int partitionCount = nodeEngine.getPartitionService().getPartitionCount();
partitionContainers = new MultiMapPartitionContainer[partitionCount];
}
public void init(final NodeEngine nodeEngine, Properties properties) {
int partitionCount = nodeEngine.getPartitionService().getPartitionCount();
for (int partition = 0; partition < partitionCount; partition++) {
partitionContainers[partition] = new MultiMapPartitionContainer(this, partition);
}
final LockService lockService = nodeEngine.getSharedService(LockService.SERVICE_NAME);
if (lockService != null) {
lockService.registerLockStoreConstructor(SERVICE_NAME, new ConstructorFunction<ObjectNamespace, LockStoreInfo>() {
public LockStoreInfo createNew(final ObjectNamespace key) {
String name = key.getObjectName();
final MultiMapConfig multiMapConfig = nodeEngine.getConfig().findMultiMapConfig(name);
return new LockStoreInfo() {
public int getBackupCount() {
return multiMapConfig.getSyncBackupCount();
}
public int getAsyncBackupCount() {
return multiMapConfig.getAsyncBackupCount();
}
};
}
});
}
}
public void reset() {
for (MultiMapPartitionContainer container : partitionContainers) {
if (container != null) {
container.destroy();
}
}
}
public void shutdown(boolean terminate) {
reset();
for (int i = 0; i < partitionContainers.length; i++) {
partitionContainers[i] = null;
}
}
public MultiMapContainer getOrCreateCollectionContainer(int partitionId, String name) {
return partitionContainers[partitionId].getOrCreateMultiMapContainer(name);
}
public MultiMapPartitionContainer getPartitionContainer(int partitionId) {
return partitionContainers[partitionId];
}
public DistributedObject createDistributedObject(String name) {
return new ObjectMultiMapProxy(this, nodeEngine, name);
}
public void destroyDistributedObject(String name) {
for (MultiMapPartitionContainer container : partitionContainers) {
if (container != null) {
container.destroyCollection(name);
}
}
nodeEngine.getEventService().deregisterAllListeners(SERVICE_NAME, name);
}
public Set<Data> localKeySet(String name) {
Set<Data> keySet = new HashSet<Data>();
ClusterServiceImpl clusterService = (ClusterServiceImpl) nodeEngine.getClusterService();
Address thisAddress = clusterService.getThisAddress();
for (int i = 0; i < nodeEngine.getPartitionService().getPartitionCount(); i++) {
InternalPartition partition = nodeEngine.getPartitionService().getPartition(i);
MultiMapPartitionContainer partitionContainer = getPartitionContainer(i);
MultiMapContainer multiMapContainer = partitionContainer.getCollectionContainer(name);
if (multiMapContainer == null) {
continue;
}
if (thisAddress.equals(partition.getOwnerOrNull())) {
keySet.addAll(multiMapContainer.keySet());
}
}
getLocalMultiMapStatsImpl(name).incrementOtherOperations();
return keySet;
}
public SerializationService getSerializationService() {
return nodeEngine.getSerializationService();
}
public NodeEngine getNodeEngine() {
return nodeEngine;
}
public String addListener(String name, EventListener listener, Data key, boolean includeValue, boolean local) {
EventService eventService = nodeEngine.getEventService();
EventRegistration registration;
final MultiMapEventFilter filter = new MultiMapEventFilter(includeValue, key);
if (local) {
registration = eventService.registerLocalListener(SERVICE_NAME, name, filter, listener);
} else {
registration = eventService.registerListener(SERVICE_NAME, name, filter, listener);
}
return registration.getId();
}
public boolean removeListener(String name, String registrationId) {
EventService eventService = nodeEngine.getEventService();
return eventService.deregisterListener(SERVICE_NAME, name, registrationId);
}
public void dispatchEvent(MultiMapEvent event, EventListener listener) {
EntryListener entryListener = (EntryListener) listener;
EntryEvent entryEvent = new EntryEvent(event.getName(), nodeEngine.getClusterService().getMember(event.getCaller()),
event.getEventType().getType(), nodeEngine.toObject(event.getKey()), nodeEngine.toObject(event.getValue()));
if (event.getEventType().equals(EntryEventType.ADDED)) {
entryListener.entryAdded(entryEvent);
} else if (event.getEventType().equals(EntryEventType.REMOVED)) {
entryListener.entryRemoved(entryEvent);
}
getLocalMultiMapStatsImpl(event.getName()).incrementReceivedEvents();
}
public void beforeMigration(PartitionMigrationEvent partitionMigrationEvent) {
}
public Operation prepareReplicationOperation(PartitionReplicationEvent event) {
int replicaIndex = event.getReplicaIndex();
final MultiMapPartitionContainer partitionContainer = partitionContainers[event.getPartitionId()];
if (partitionContainer == null) {
return null;
}
Map<String, Map> map = new HashMap<String, Map>(partitionContainer.containerMap.size());
for (Map.Entry<String, MultiMapContainer> entry : partitionContainer.containerMap.entrySet()) {
String name = entry.getKey();
MultiMapContainer container = entry.getValue();
if (container.config.getTotalBackupCount() < replicaIndex) {
continue;
}
map.put(name, container.multiMapWrappers);
}
if (map.isEmpty()) {
return null;
}
return new MultiMapMigrationOperation(map);
}
public void insertMigratedData(int partitionId, Map<String, Map> map) {
for (Map.Entry<String, Map> entry : map.entrySet()) {
String name = entry.getKey();
MultiMapContainer container = getOrCreateCollectionContainer(partitionId, name);
Map<Data, MultiMapWrapper> collections = entry.getValue();
container.multiMapWrappers.putAll(collections);
}
}
private void clearMigrationData(int partitionId) {
final MultiMapPartitionContainer partitionContainer = partitionContainers[partitionId];
if (partitionContainer != null) {
partitionContainer.containerMap.clear();
}
}
public void commitMigration(PartitionMigrationEvent event) {
if (event.getMigrationEndpoint() == MigrationEndpoint.SOURCE) {
clearMigrationData(event.getPartitionId());
}
}
public void rollbackMigration(PartitionMigrationEvent event) {
clearMigrationData(event.getPartitionId());
}
public void clearPartitionReplica(int partitionId) {
clearMigrationData(partitionId);
}
public LocalMapStats createStats(String name) {
LocalMultiMapStatsImpl stats = getLocalMultiMapStatsImpl(name);
long ownedEntryCount = 0;
long backupEntryCount = 0;
long hits = 0;
long lockedEntryCount = 0;
ClusterServiceImpl clusterService = (ClusterServiceImpl) nodeEngine.getClusterService();
Address thisAddress = clusterService.getThisAddress();
for (int i = 0; i < nodeEngine.getPartitionService().getPartitionCount(); i++) {
InternalPartition partition = nodeEngine.getPartitionService().getPartition(i);
MultiMapPartitionContainer partitionContainer = getPartitionContainer(i);
MultiMapContainer multiMapContainer = partitionContainer.getCollectionContainer(name);
if (multiMapContainer == null) {
continue;
}
Address owner = partition.getOwnerOrNull();
if (owner != null) {
if (owner.equals(thisAddress)) {
lockedEntryCount += multiMapContainer.getLockedCount();
for (MultiMapWrapper wrapper : multiMapContainer.multiMapWrappers.values()) {
hits += wrapper.getHits();
ownedEntryCount += wrapper.getCollection(false).size();
}
} else {
int backupCount = multiMapContainer.config.getTotalBackupCount();
for (int j = 1; j <= backupCount; j++) {
Address replicaAddress = partition.getReplicaAddress(j);
int memberSize = nodeEngine.getClusterService().getMembers().size();
int tryCount = REPLICA_ADDRESS_TRY_COUNT;
// wait if the partition table is not updated yet
while (memberSize > backupCount && replicaAddress == null && tryCount-- > 0) {
try {
Thread.sleep(REPLICA_ADDRESS_SLEEP_WAIT_MILLIS);
} catch (InterruptedException e) {
throw ExceptionUtil.rethrow(e);
}
replicaAddress = partition.getReplicaAddress(j);
}
if (replicaAddress != null && replicaAddress.equals(thisAddress)) {
for (MultiMapWrapper wrapper : multiMapContainer.multiMapWrappers.values()) {
backupEntryCount += wrapper.getCollection(false).size();
}
}
}
}
}
}
stats.setOwnedEntryCount(ownedEntryCount);
stats.setBackupEntryCount(backupEntryCount);
stats.setHits(hits);
stats.setLockedEntryCount(lockedEntryCount);
return stats;
}
public LocalMultiMapStatsImpl getLocalMultiMapStatsImpl(String name) {
return ConcurrencyUtil.getOrPutIfAbsent(statsMap, name, localMultiMapStatsConstructorFunction);
}
public <T extends TransactionalObject> T createTransactionalObject(String name, TransactionSupport transaction) {
return (T) new TransactionalMultiMapProxy(nodeEngine, this, name, transaction);
}
public void rollbackTransaction(String transactionId) {
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_multimap_MultiMapService.java
|
696 |
constructors[LIST_SET] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new ListSetRequest();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java
|
1,150 |
public class OSQLMethodNormalize extends OAbstractSQLMethod {
public static final String NAME = "normalize";
public OSQLMethodNormalize() {
super(NAME, 0, 2);
}
@Override
public Object execute(OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iMethodParams) {
if (ioResult != null) {
final Normalizer.Form form = iMethodParams != null && iMethodParams.length > 0 ? Normalizer.Form
.valueOf(OStringSerializerHelper.getStringContent(iMethodParams[0].toString())) : Normalizer.Form.NFD;
String normalized = Normalizer.normalize(ioResult.toString(), form);
if (iMethodParams != null && iMethodParams.length > 1) {
normalized = normalized.replaceAll(OStringSerializerHelper.getStringContent(iMethodParams[0].toString()), "");
} else {
normalized = normalized.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}
ioResult = normalized;
}
return ioResult;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodNormalize.java
|
6,371 |
public class ConnectTransportException extends ActionTransportException {
private final DiscoveryNode node;
public ConnectTransportException(DiscoveryNode node, String msg) {
this(node, msg, null, null);
}
public ConnectTransportException(DiscoveryNode node, String msg, String action) {
this(node, msg, action, null);
}
public ConnectTransportException(DiscoveryNode node, String msg, Throwable cause) {
this(node, msg, null, cause);
}
public ConnectTransportException(DiscoveryNode node, String msg, String action, Throwable cause) {
super(node.name(), node.address(), action, msg, cause);
this.node = node;
}
public DiscoveryNode node() {
return node;
}
}
| 1no label
|
src_main_java_org_elasticsearch_transport_ConnectTransportException.java
|
68 |
static final class MapEntry<K,V> implements Map.Entry<K,V> {
final K key; // non-null
V val; // non-null
final ConcurrentHashMapV8<K,V> map;
MapEntry(K key, V val, ConcurrentHashMapV8<K,V> map) {
this.key = key;
this.val = val;
this.map = map;
}
public K getKey() { return key; }
public V getValue() { return val; }
public int hashCode() { return key.hashCode() ^ val.hashCode(); }
public String toString() { return key + "=" + val; }
public boolean equals(Object o) {
Object k, v; Map.Entry<?,?> e;
return ((o instanceof Map.Entry) &&
(k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
(v = e.getValue()) != null &&
(k == key || k.equals(key)) &&
(v == val || v.equals(val)));
}
/**
* Sets our entry's value and writes through to the map. The
* value to return is somewhat arbitrary here. Since we do not
* necessarily track asynchronous changes, the most recent
* "previous" value could be different from what we return (or
* could even have been removed, in which case the put will
* re-establish). We do not and cannot guarantee more.
*/
public V setValue(V value) {
if (value == null) throw new NullPointerException();
V v = val;
val = value;
map.put(key, value);
return v;
}
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
229 |
assertTrueEventually(new AssertTask() {
public void run() throws Exception {
assertEquals(1, map.size());
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceExecuteTest.java
|
368 |
public class GetRepositoriesAction extends ClusterAction<GetRepositoriesRequest, GetRepositoriesResponse, GetRepositoriesRequestBuilder> {
public static final GetRepositoriesAction INSTANCE = new GetRepositoriesAction();
public static final String NAME = "cluster/repository/get";
private GetRepositoriesAction() {
super(NAME);
}
@Override
public GetRepositoriesResponse newResponse() {
return new GetRepositoriesResponse();
}
@Override
public GetRepositoriesRequestBuilder newRequestBuilder(ClusterAdminClient client) {
return new GetRepositoriesRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_repositories_get_GetRepositoriesAction.java
|
6,421 |
targetTransport.threadPool().generic().execute(new Runnable() {
@Override
public void run() {
targetTransport.messageReceived(data, action, sourceTransport, version, null);
}
});
| 1no label
|
src_main_java_org_elasticsearch_transport_local_LocalTransportChannel.java
|
807 |
execute(request, new ActionListener<MultiPercolateResponse>() {
@Override
public void onResponse(MultiPercolateResponse response) {
try {
channel.sendResponse(response);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send error response for action [mpercolate] and request [" + request + "]", e1);
}
}
});
| 0true
|
src_main_java_org_elasticsearch_action_percolate_TransportMultiPercolateAction.java
|
194 |
public class ProxyFactoryConfig {
private String service;
private String className;
public ProxyFactoryConfig() {
}
public ProxyFactoryConfig(String className, String service) {
this.className = className;
this.service = service;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_config_ProxyFactoryConfig.java
|
43 |
@Component("blPageItemCriteriaCustomPersistenceHandler")
public class PageItemCriteriaCustomPersistenceHandler extends CustomPersistenceHandlerAdapter {
private final Log LOG = LogFactory.getLog(PageItemCriteriaCustomPersistenceHandler.class);
@Override
public Boolean canHandleAdd(PersistencePackage persistencePackage) {
String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
return PageItemCriteria.class.getName().equals(ceilingEntityFullyQualifiedClassname);
}
@Override
public Boolean canHandleRemove(PersistencePackage persistencePackage) {
return canHandleAdd(persistencePackage);
}
@Override
public Boolean canHandleUpdate(PersistencePackage persistencePackage) {
return canHandleAdd(persistencePackage);
}
protected void removeHtmlEncoding(Entity entity) {
Property prop = entity.findProperty("orderItemMatchRule");
if (prop != null && prop.getValue() != null) {
//antisamy XSS protection encodes the values in the MVEL
//reverse this behavior
prop.setValue(prop.getRawValue());
}
}
@Override
public Entity add(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
Entity entity = persistencePackage.getEntity();
removeHtmlEncoding(entity);
try {
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
PageItemCriteria adminInstance = (PageItemCriteria) Class.forName(entity.getType()[0]).newInstance();
Map<String, FieldMetadata> adminProperties = helper.getSimpleMergedProperties(PageItemCriteria.class.getName(), persistencePerspective);
adminInstance = (PageItemCriteria) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);
if (adminInstance.getPage().getLockedFlag()) {
throw new IllegalArgumentException("Unable to update a locked record");
}
adminInstance = (PageItemCriteria) dynamicEntityDao.merge(adminInstance);
Entity adminEntity = helper.getRecord(adminProperties, adminInstance, null, null);
return adminEntity;
} catch (Exception e) {
throw new ServiceException("Unable to add entity for " + entity.getType()[0], e);
}
}
@Override
public Entity update(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
Entity entity = persistencePackage.getEntity();
removeHtmlEncoding(entity);
try {
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
Map<String, FieldMetadata> adminProperties = helper.getSimpleMergedProperties(PageItemCriteria.class.getName(), persistencePerspective);
Object primaryKey = helper.getPrimaryKey(entity, adminProperties);
PageItemCriteria adminInstance = (PageItemCriteria) dynamicEntityDao.retrieve(Class.forName(entity.getType()[0]), primaryKey);
if (adminInstance.getPage().getLockedFlag()) {
/*
This may be an attempt to delete a target item criteria off an otherwise un-edited, production StructuredContent instance
*/
CriteriaBuilder criteriaBuilder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder();
CriteriaQuery<Page> query = criteriaBuilder.createQuery(Page.class);
Root<PageImpl> root = query.from(PageImpl.class);
query.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("archivedFlag"), Boolean.FALSE), criteriaBuilder.equal(root.get("originalPageId"), adminInstance.getPage().getId())));
query.select(root);
TypedQuery<Page> scQuery = dynamicEntityDao.getStandardEntityManager().createQuery(query);
try {
checkCriteria: {
Page myContent = scQuery.getSingleResult();
for (PageItemCriteria itemCriteria : myContent.getQualifyingItemCriteria()) {
if (itemCriteria.getMatchRule().equals(adminInstance.getMatchRule()) && itemCriteria.getQuantity().equals(adminInstance.getQuantity())) {
//manually set the values - otherwise unwanted properties will be set
itemCriteria.setMatchRule(entity.findProperty("orderItemMatchRule").getValue());
itemCriteria.setQuantity(Integer.parseInt(entity.findProperty("quantity").getValue()));
adminInstance = itemCriteria;
break checkCriteria;
}
}
throw new RuntimeException("Unable to find an item criteria to update");
}
} catch (Exception e) {
throw new IllegalArgumentException("Unable to update a locked record");
}
} else {
adminInstance = (PageItemCriteria) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);
}
adminInstance = (PageItemCriteria) dynamicEntityDao.merge(adminInstance);
Entity adminEntity = helper.getRecord(adminProperties, adminInstance, null, null);
return adminEntity;
} catch (Exception e) {
throw new ServiceException("Unable to update entity for " + entity.getType()[0], e);
}
}
@Override
public void remove(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
Entity entity = persistencePackage.getEntity();
try {
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
Map<String, FieldMetadata> adminProperties = helper.getSimpleMergedProperties(PageItemCriteria.class.getName(), persistencePerspective);
Object primaryKey = helper.getPrimaryKey(entity, adminProperties);
PageItemCriteria adminInstance = (PageItemCriteria) dynamicEntityDao.retrieve(Class.forName(entity.getType()[0]), primaryKey);
if (adminInstance.getPage().getLockedFlag()) {
/*
This may be an attempt to delete a target item criteria off an otherwise un-edited, production StructuredContent instance
*/
CriteriaBuilder criteriaBuilder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder();
CriteriaQuery<Page> query = criteriaBuilder.createQuery(Page.class);
Root<PageImpl> root = query.from(PageImpl.class);
query.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("archivedFlag"), Boolean.FALSE), criteriaBuilder.equal(root.get("originalPageId"), adminInstance.getPage().getId())));
query.select(root);
TypedQuery<Page> scQuery = dynamicEntityDao.getStandardEntityManager().createQuery(query);
try {
Page myContent = scQuery.getSingleResult();
for (PageItemCriteria itemCriteria : myContent.getQualifyingItemCriteria()) {
if (itemCriteria.getMatchRule().equals(adminInstance.getMatchRule()) && itemCriteria.getQuantity().equals(adminInstance.getQuantity())) {
myContent.getQualifyingItemCriteria().remove(itemCriteria);
return;
}
}
throw new RuntimeException("Unable to find an item criteria to delete");
} catch (Exception e) {
throw new IllegalArgumentException("Unable to update a locked record");
}
}
dynamicEntityDao.remove(adminInstance);
} catch (Exception e) {
throw new ServiceException("Unable to remove entity for " + entity.getType()[0], e);
}
}
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_admin_server_handler_PageItemCriteriaCustomPersistenceHandler.java
|
6,018 |
public final class Correction {
public static final Correction[] EMPTY = new Correction[0];
public double score;
public final Candidate[] candidates;
public Correction(double score, Candidate[] candidates) {
this.score = score;
this.candidates = candidates;
}
@Override
public String toString() {
return "Correction [score=" + score + ", candidates=" + Arrays.toString(candidates) + "]";
}
public BytesRef join(BytesRef separator) {
return join(separator, null, null);
}
public BytesRef join(BytesRef separator, BytesRef preTag, BytesRef postTag) {
return join(separator, new BytesRef(), preTag, postTag);
}
public BytesRef join(BytesRef separator, BytesRef result, BytesRef preTag, BytesRef postTag) {
BytesRef[] toJoin = new BytesRef[this.candidates.length];
int len = separator.length * this.candidates.length - 1;
for (int i = 0; i < toJoin.length; i++) {
Candidate candidate = candidates[i];
if (preTag == null || candidate.userInput) {
toJoin[i] = candidate.term;
} else {
final int maxLen = preTag.length + postTag.length + candidate.term.length;
final BytesRef highlighted = new BytesRef(maxLen);// just allocate once
if (i == 0 || candidates[i-1].userInput) {
highlighted.append(preTag);
}
highlighted.append(candidate.term);
if (toJoin.length == i + 1 || candidates[i+1].userInput) {
highlighted.append(postTag);
}
toJoin[i] = highlighted;
}
len += toJoin[i].length;
}
result.offset = 0;
result.grow(len);
return SuggestUtils.joinPreAllocated(separator, result, toJoin);
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_suggest_phrase_Correction.java
|
53 |
@SuppressWarnings("serial")
static final class ForEachEntryTask<K,V>
extends BulkTask<K,V,Void> {
final Action<? super Entry<K,V>> action;
ForEachEntryTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
Action<? super Entry<K,V>> action) {
super(p, b, i, f, t);
this.action = action;
}
public final void compute() {
final Action<? super Entry<K,V>> action;
if ((action = this.action) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
new ForEachEntryTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
action).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
action.apply(p);
propagateCompletion();
}
}
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
278 |
public interface OCommandResultListener {
/**
* This method is called for each result.
*
* @param iRecord
* Current record
* @return True to continue the query, otherwise false
*/
public boolean result(Object iRecord);
/**
* Called at the end of processing. This is useful to clean-up local attributes.
*/
public void end();
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_command_OCommandResultListener.java
|
2,154 |
public class TxnLockAndGetOperation extends LockAwareOperation {
private VersionedValue response;
private String ownerUuid;
public TxnLockAndGetOperation() {
}
public TxnLockAndGetOperation(String name, Data dataKey, long timeout, long ttl, String ownerUuid) {
super(name, dataKey, ttl);
this.ownerUuid = ownerUuid;
setWaitTimeout(timeout);
}
@Override
public void run() throws Exception {
if (!recordStore.txnLock(getKey(), ownerUuid, getThreadId(), ttl)) {
throw new TransactionException("Transaction couldn't obtain lock.");
}
Record record = recordStore.getRecord(dataKey);
Data value = record == null ? null : mapService.toData(record.getValue());
response = new VersionedValue(value, record == null ? 0 : record.getVersion());
}
public boolean shouldWait() {
return !recordStore.canAcquireLock(dataKey, ownerUuid, getThreadId());
}
@Override
public void onWaitExpire() {
final ResponseHandler responseHandler = getResponseHandler();
responseHandler.sendResponse(null);
}
@Override
public Object getResponse() {
return response;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeUTF(ownerUuid);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
ownerUuid = in.readUTF();
}
@Override
public String toString() {
return "TxnLockAndGetOperation{" +
"timeout=" + getWaitTimeout() +
", thread=" + getThreadId() +
'}';
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_map_tx_TxnLockAndGetOperation.java
|
339 |
public class NodeReplace extends NodeReplaceInsert {
@Override
protected boolean checkNode(List<Node> usedNodes, Node[] primaryNodes, Node node) {
if (replaceNode(primaryNodes, node, usedNodes)) {
return true;
}
//check if this same node already exists
if (exactNodeExists(primaryNodes, node, usedNodes)) {
return true;
}
return false;
}
protected boolean replaceNode(Node[] primaryNodes, Node testNode, List<Node> usedNodes) {
boolean foundItem = false;
for (int j=0;j<primaryNodes.length;j++){
if (primaryNodes[j].getNodeName().equals(testNode.getNodeName())) {
Node newNode = primaryNodes[j].getOwnerDocument().importNode(testNode.cloneNode(true), true);
primaryNodes[j].getParentNode().replaceChild(newNode, primaryNodes[j]);
usedNodes.add(testNode);
foundItem = true;
}
}
return foundItem;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_handlers_NodeReplace.java
|
289 |
public interface ListenableActionFuture<T> extends ActionFuture<T> {
/**
* Add an action listener to be invoked when a response has received.
*/
void addListener(final ActionListener<T> listener);
/**
* Add an action listener (runnable) to be invoked when a response has received.
*/
void addListener(final Runnable listener);
}
| 0true
|
src_main_java_org_elasticsearch_action_ListenableActionFuture.java
|
6,302 |
public class MockDirectoryHelper {
public static final String RANDOM_IO_EXCEPTION_RATE = "index.store.mock.random.io_exception_rate";
public static final String RANDOM_IO_EXCEPTION_RATE_ON_OPEN = "index.store.mock.random.io_exception_rate_on_open";
public static final String RANDOM_THROTTLE = "index.store.mock.random.throttle";
public static final String CHECK_INDEX_ON_CLOSE = "index.store.mock.check_index_on_close";
public static final String RANDOM_PREVENT_DOUBLE_WRITE = "index.store.mock.random.prevent_double_write";
public static final String RANDOM_NO_DELETE_OPEN_FILE = "index.store.mock.random.no_delete_open_file";
public static final String RANDOM_FAIL_ON_CLOSE= "index.store.mock.random.fail_on_close";
public static final Set<ElasticsearchMockDirectoryWrapper> wrappers = ConcurrentCollections.newConcurrentSet();
private final Random random;
private final double randomIOExceptionRate;
private final double randomIOExceptionRateOnOpen;
private final Throttling throttle;
private final boolean checkIndexOnClose;
private final Settings indexSettings;
private final ShardId shardId;
private final boolean preventDoubleWrite;
private final boolean noDeleteOpenFile;
private final ESLogger logger;
private final boolean failOnClose;
public MockDirectoryHelper(ShardId shardId, Settings indexSettings, ESLogger logger) {
final long seed = indexSettings.getAsLong(ElasticsearchIntegrationTest.INDEX_SEED_SETTING, 0l);
random = new Random(seed);
randomIOExceptionRate = indexSettings.getAsDouble(RANDOM_IO_EXCEPTION_RATE, 0.0d);
randomIOExceptionRateOnOpen = indexSettings.getAsDouble(RANDOM_IO_EXCEPTION_RATE_ON_OPEN, 0.0d);
preventDoubleWrite = indexSettings.getAsBoolean(RANDOM_PREVENT_DOUBLE_WRITE, true); // true is default in MDW
noDeleteOpenFile = indexSettings.getAsBoolean(RANDOM_NO_DELETE_OPEN_FILE, random.nextBoolean()); // true is default in MDW
random.nextInt(shardId.getId() + 1); // some randomness per shard
throttle = Throttling.valueOf(indexSettings.get(RANDOM_THROTTLE, random.nextDouble() < 0.1 ? "SOMETIMES" : "NEVER"));
checkIndexOnClose = indexSettings.getAsBoolean(CHECK_INDEX_ON_CLOSE, false);// we can't do this by default since it might close the index input that we still read from in a pending fetch phase.
failOnClose = indexSettings.getAsBoolean(RANDOM_FAIL_ON_CLOSE, false);
if (logger.isDebugEnabled()) {
logger.debug("Using MockDirWrapper with seed [{}] throttle: [{}] checkIndexOnClose: [{}]", SeedUtils.formatSeed(seed),
throttle, checkIndexOnClose);
}
this.indexSettings = indexSettings;
this.shardId = shardId;
this.logger = logger;
}
public Directory wrap(Directory dir) {
final ElasticsearchMockDirectoryWrapper w = new ElasticsearchMockDirectoryWrapper(random, dir, logger, failOnClose);
w.setRandomIOExceptionRate(randomIOExceptionRate);
w.setRandomIOExceptionRateOnOpen(randomIOExceptionRateOnOpen);
w.setThrottling(throttle);
w.setCheckIndexOnClose(checkIndexOnClose);
w.setPreventDoubleWrite(preventDoubleWrite);
w.setNoDeleteOpenFile(noDeleteOpenFile);
wrappers.add(w);
return w;
}
public Directory[] wrapAllInplace(Directory[] dirs) {
for (int i = 0; i < dirs.length; i++) {
dirs[i] = wrap(dirs[i]);
}
return dirs;
}
public FsDirectoryService randomDirectorService(IndexStore indexStore) {
if ((Constants.WINDOWS || Constants.SUN_OS) && Constants.JRE_IS_64BIT && MMapDirectory.UNMAP_SUPPORTED) {
return new MmapFsDirectoryService(shardId, indexSettings, indexStore);
} else if (Constants.WINDOWS) {
return new SimpleFsDirectoryService(shardId, indexSettings, indexStore);
}
switch (random.nextInt(3)) {
case 1:
return new MmapFsDirectoryService(shardId, indexSettings, indexStore);
case 0:
return new SimpleFsDirectoryService(shardId, indexSettings, indexStore);
default:
return new NioFsDirectoryService(shardId, indexSettings, indexStore);
}
}
public DirectoryService randomRamDirectoryService() {
return new RamDirectoryService(shardId, indexSettings);
}
public static final class ElasticsearchMockDirectoryWrapper extends MockDirectoryWrapper {
private final ESLogger logger;
private final boolean failOnClose;
public ElasticsearchMockDirectoryWrapper(Random random, Directory delegate, ESLogger logger, boolean failOnClose) {
super(random, delegate);
this.logger = logger;
this.failOnClose = failOnClose;
}
@Override
public void close() throws IOException {
try {
super.close();
} catch (RuntimeException ex) {
if (failOnClose) {
throw ex;
}
// we catch the exception on close to properly close shards even if there are open files
// the test framework will call closeWithRuntimeException after the test exits to fail
// on unclosed files.
logger.debug("MockDirectoryWrapper#close() threw exception", ex);
}
}
public void closeWithRuntimeException() throws IOException {
super.close(); // force fail if open files etc. called in tear down of ElasticsearchIntegrationTest
}
}
}
| 1no label
|
src_test_java_org_elasticsearch_test_store_MockDirectoryHelper.java
|
328 |
public class MergeManagerSetupException extends Exception {
private static final long serialVersionUID = 1L;
public MergeManagerSetupException() {
super();
}
public MergeManagerSetupException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public MergeManagerSetupException(String arg0) {
super(arg0);
}
public MergeManagerSetupException(Throwable arg0) {
super(arg0);
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_exceptions_MergeManagerSetupException.java
|
1,524 |
public class RoutingNodesIntegrityTests extends ElasticsearchAllocationTestCase {
private final ESLogger logger = Loggers.getLogger(IndexBalanceTests.class);
@Test
public void testBalanceAllNodesStarted() {
AllocationService strategy = createAllocationService(settingsBuilder()
.put("cluster.routing.allocation.node_concurrent_recoveries", 10)
.put("cluster.routing.allocation.node_initial_primaries_recoveries", 10)
.put("cluster.routing.allocation.allow_rebalance", "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1).build());
logger.info("Building initial routing table");
MetaData metaData = MetaData.builder().put(IndexMetaData.builder("test").numberOfShards(3).numberOfReplicas(1))
.put(IndexMetaData.builder("test1").numberOfShards(3).numberOfReplicas(1)).build();
RoutingTable routingTable = RoutingTable.builder().addAsNew(metaData.index("test")).addAsNew(metaData.index("test1")).build();
ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build();
RoutingNodes routingNodes = clusterState.routingNodes();
logger.info("Adding three node and performing rerouting");
clusterState = ClusterState.builder(clusterState)
.nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2")).put(newNode("node3"))).build();
routingNodes = clusterState.routingNodes();
assertThat(assertShardStats(routingNodes), equalTo(true));
// all shards are unassigned. so no inactive shards or primaries.
assertThat(routingNodes.hasInactiveShards(), equalTo(false));
assertThat(routingNodes.hasInactivePrimaries(), equalTo(false));
assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(true));
RoutingTable prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(assertShardStats(routingNodes), equalTo(true));
assertThat(routingNodes.hasInactiveShards(), equalTo(true));
assertThat(routingNodes.hasInactivePrimaries(), equalTo(true));
assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false));
logger.info("Another round of rebalancing");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
logger.info("Reroute, nothing should change");
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
logger.info("Start the more shards");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(assertShardStats(routingNodes), equalTo(true));
assertThat(routingNodes.hasInactiveShards(), equalTo(false));
assertThat(routingNodes.hasInactivePrimaries(), equalTo(false));
assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false));
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
}
@Test
public void testBalanceIncrementallyStartNodes() {
AllocationService strategy = createAllocationService(settingsBuilder()
.put("cluster.routing.allocation.node_concurrent_recoveries", 10)
.put("cluster.routing.allocation.node_initial_primaries_recoveries", 10)
.put("cluster.routing.allocation.allow_rebalance", "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1).build());
logger.info("Building initial routing table");
MetaData metaData = MetaData.builder().put(IndexMetaData.builder("test").numberOfShards(3).numberOfReplicas(1))
.put(IndexMetaData.builder("test1").numberOfShards(3).numberOfReplicas(1)).build();
RoutingTable routingTable = RoutingTable.builder().addAsNew(metaData.index("test")).addAsNew(metaData.index("test1")).build();
ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build();
logger.info("Adding one node and performing rerouting");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1"))).build();
RoutingTable prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logger.info("Add another node and perform rerouting, nothing will happen since primary not started");
clusterState = ClusterState.builder(clusterState)
.nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node2"))).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logger.info("Start the primary shard");
RoutingNodes routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logger.info("Reroute, nothing should change");
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
logger.info("Start the backup shard");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
logger.info("Add another node and perform rerouting, nothing will happen since primary not started");
clusterState = ClusterState.builder(clusterState)
.nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node3"))).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logger.info("Reroute, nothing should change");
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
logger.info("Start the backup shard");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test").shards().size(), equalTo(3));
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(prevRoutingTable != routingTable, equalTo(true));
assertThat(routingTable.index("test1").shards().size(), equalTo(3));
assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node1").shardsWithState("test", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node2").shardsWithState("test", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node3").shardsWithState("test", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node1").shardsWithState("test1", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node2").shardsWithState("test1", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node3").shardsWithState("test1", STARTED).size(), equalTo(2));
}
@Test
public void testBalanceAllNodesStartedAddIndex() {
AllocationService strategy = createAllocationService(settingsBuilder()
.put("cluster.routing.allocation.node_concurrent_recoveries", 1)
.put("cluster.routing.allocation.node_initial_primaries_recoveries", 3)
.put("cluster.routing.allocation.allow_rebalance", "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1).build());
logger.info("Building initial routing table");
MetaData metaData = MetaData.builder().put(IndexMetaData.builder("test").numberOfShards(3).numberOfReplicas(1)).build();
RoutingTable routingTable = RoutingTable.builder().addAsNew(metaData.index("test")).build();
ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build();
logger.info("Adding three node and performing rerouting");
clusterState = ClusterState.builder(clusterState)
.nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2")).put(newNode("node3"))).build();
RoutingNodes routingNodes = clusterState.routingNodes();
assertThat(assertShardStats(routingNodes), equalTo(true));
assertThat(routingNodes.hasInactiveShards(), equalTo(false));
assertThat(routingNodes.hasInactivePrimaries(), equalTo(false));
assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(true));
RoutingTable prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(assertShardStats(routingNodes), equalTo(true));
assertThat(routingNodes.hasInactiveShards(), equalTo(true));
assertThat(routingNodes.hasInactivePrimaries(), equalTo(true));
assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false));
logger.info("Another round of rebalancing");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(prevRoutingTable == routingTable, equalTo(true));
routingNodes = clusterState.routingNodes();
assertThat(routingNodes.node("node1").numberOfShardsWithState(INITIALIZING), equalTo(1));
assertThat(routingNodes.node("node2").numberOfShardsWithState(INITIALIZING), equalTo(1));
assertThat(routingNodes.node("node3").numberOfShardsWithState(INITIALIZING), equalTo(1));
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(assertShardStats(routingNodes), equalTo(true));
assertThat(routingNodes.hasInactiveShards(), equalTo(true));
assertThat(routingNodes.hasInactivePrimaries(), equalTo(false));
assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false));
assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(1));
assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(1));
assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(1));
logger.info("Reroute, nothing should change");
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
assertThat(prevRoutingTable == routingTable, equalTo(true));
logger.info("Start the more shards");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(assertShardStats(routingNodes), equalTo(true));
assertThat(routingNodes.hasInactiveShards(), equalTo(false));
assertThat(routingNodes.hasInactivePrimaries(), equalTo(false));
assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false));
assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(2));
assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(2));
assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(2));
assertThat(routingNodes.node("node1").shardsWithState("test", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node2").shardsWithState("test", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node3").shardsWithState("test", STARTED).size(), equalTo(2));
logger.info("Add new index 3 shards 1 replica");
prevRoutingTable = routingTable;
metaData = MetaData.builder(metaData)
.put(IndexMetaData.builder("test1").settings(ImmutableSettings.settingsBuilder()
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 3)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)
))
.build();
routingTable = RoutingTable.builder(routingTable)
.addAsNew(metaData.index("test1"))
.build();
clusterState = ClusterState.builder(clusterState).metaData(metaData).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(assertShardStats(routingNodes), equalTo(true));
assertThat(routingNodes.hasInactiveShards(), equalTo(false));
assertThat(routingNodes.hasInactivePrimaries(), equalTo(false));
assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(true));
assertThat(routingTable.index("test1").shards().size(), equalTo(3));
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logger.info("Reroute, assign");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())).build();
prevRoutingTable = routingTable;
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(assertShardStats(routingNodes), equalTo(true));
assertThat(routingNodes.hasInactiveShards(), equalTo(true));
assertThat(routingNodes.hasInactivePrimaries(), equalTo(true));
assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false));
assertThat(prevRoutingTable == routingTable, equalTo(true));
logger.info("Reroute, start the primaries");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(assertShardStats(routingNodes), equalTo(true));
assertThat(routingNodes.hasInactiveShards(), equalTo(true));
assertThat(routingNodes.hasInactivePrimaries(), equalTo(false));
assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false));
logger.info("Reroute, start the replicas");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(assertShardStats(routingNodes), equalTo(true));
assertThat(routingNodes.hasInactiveShards(), equalTo(false));
assertThat(routingNodes.hasInactivePrimaries(), equalTo(false));
assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false));
assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(4));
assertThat(routingNodes.node("node1").shardsWithState("test1", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node2").shardsWithState("test1", STARTED).size(), equalTo(2));
assertThat(routingNodes.node("node3").shardsWithState("test1", STARTED).size(), equalTo(2));
logger.info("kill one node");
IndexShardRoutingTable indexShardRoutingTable = routingTable.index("test").shard(0);
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).remove(indexShardRoutingTable.primaryShard().currentNodeId())).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(assertShardStats(routingNodes), equalTo(true));
assertThat(routingNodes.hasInactiveShards(), equalTo(true));
// replica got promoted to primary
assertThat(routingNodes.hasInactivePrimaries(), equalTo(false));
assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false));
logger.info("Start Recovering shards round 1");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(assertShardStats(routingNodes), equalTo(true));
assertThat(routingNodes.hasInactiveShards(), equalTo(true));
assertThat(routingNodes.hasInactivePrimaries(), equalTo(false));
assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false));
logger.info("Start Recovering shards round 2");
routingNodes = clusterState.routingNodes();
prevRoutingTable = routingTable;
routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
routingNodes = clusterState.routingNodes();
assertThat(assertShardStats(routingNodes), equalTo(true));
assertThat(routingNodes.hasInactiveShards(), equalTo(false));
assertThat(routingNodes.hasInactivePrimaries(), equalTo(false));
assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false));
}
private boolean assertShardStats(RoutingNodes routingNodes) {
return RoutingNodes.assertShardStats(routingNodes);
}
}
| 0true
|
src_test_java_org_elasticsearch_cluster_routing_allocation_RoutingNodesIntegrityTests.java
|
1,772 |
public abstract class BasePolygonBuilder<E extends BasePolygonBuilder<E>> extends ShapeBuilder {
public static final GeoShapeType TYPE = GeoShapeType.POLYGON;
// Linear ring defining the shell of the polygon
protected Ring<E> shell;
// List of linear rings defining the holes of the polygon
protected final ArrayList<BaseLineStringBuilder<?>> holes = new ArrayList<BaseLineStringBuilder<?>>();
@SuppressWarnings("unchecked")
private E thisRef() {
return (E)this;
}
public E point(double longitude, double latitude) {
shell.point(longitude, latitude);
return thisRef();
}
/**
* Add a point to the shell of the polygon
* @param coordinate coordinate of the new point
* @return this
*/
public E point(Coordinate coordinate) {
shell.point(coordinate);
return thisRef();
}
/**
* Add a array of points to the shell of the polygon
* @param coordinates coordinates of the new points to add
* @return this
*/
public E points(Coordinate...coordinates) {
shell.points(coordinates);
return thisRef();
}
/**
* Add a new hole to the polygon
* @param hole linear ring defining the hole
* @return this
*/
public E hole(BaseLineStringBuilder<?> hole) {
holes.add(hole);
return thisRef();
}
/**
* build new hole to the polygon
* @param hole linear ring defining the hole
* @return this
*/
public Ring<E> hole() {
Ring<E> hole = new Ring<E>(thisRef());
this.holes.add(hole);
return hole;
}
/**
* Close the shell of the polygon
* @return parent
*/
public ShapeBuilder close() {
return shell.close();
}
/**
* The coordinates setup by the builder will be assembled to a polygon. The result will consist of
* a set of polygons. Each of these components holds a list of linestrings defining the polygon: the
* first set of coordinates will be used as the shell of the polygon. The others are defined to holes
* within the polygon.
* This Method also wraps the polygons at the dateline. In order to this fact the result may
* contains more polygons and less holes than defined in the builder it self.
*
* @return coordinates of the polygon
*/
public Coordinate[][][] coordinates() {
int numEdges = shell.points.size()-1; // Last point is repeated
for (int i = 0; i < holes.size(); i++) {
numEdges += holes.get(i).points.size()-1;
}
Edge[] edges = new Edge[numEdges];
Edge[] holeComponents = new Edge[holes.size()];
int offset = createEdges(0, true, shell, edges, 0);
for (int i = 0; i < holes.size(); i++) {
int length = createEdges(i+1, false, this.holes.get(i), edges, offset);
holeComponents[i] = edges[offset];
offset += length;
}
int numHoles = holeComponents.length;
numHoles = merge(edges, 0, intersections(+DATELINE, edges), holeComponents, numHoles);
numHoles = merge(edges, 0, intersections(-DATELINE, edges), holeComponents, numHoles);
return compose(edges, holeComponents, numHoles);
}
@Override
public Shape build() {
Geometry geometry = buildGeometry(FACTORY, wrapdateline);
return new JtsGeometry(geometry, SPATIAL_CONTEXT, !wrapdateline);
}
protected XContentBuilder coordinatesArray(XContentBuilder builder, Params params) throws IOException {
shell.coordinatesToXcontent(builder, true);
for(BaseLineStringBuilder<?> hole : holes) {
hole.coordinatesToXcontent(builder, true);
}
return builder;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(FIELD_TYPE, TYPE.shapename);
builder.startArray(FIELD_COORDINATES);
coordinatesArray(builder, params);
builder.endArray();
builder.endObject();
return builder;
}
public Geometry buildGeometry(GeometryFactory factory, boolean fixDateline) {
if(fixDateline) {
Coordinate[][][] polygons = coordinates();
return polygons.length == 1
? polygon(factory, polygons[0])
: multipolygon(factory, polygons);
} else {
return toPolygon(factory);
}
}
public Polygon toPolygon() {
return toPolygon(FACTORY);
}
protected Polygon toPolygon(GeometryFactory factory) {
final LinearRing shell = linearRing(factory, this.shell.points);
final LinearRing[] holes = new LinearRing[this.holes.size()];
Iterator<BaseLineStringBuilder<?>> iterator = this.holes.iterator();
for (int i = 0; iterator.hasNext(); i++) {
holes[i] = linearRing(factory, iterator.next().points);
}
return factory.createPolygon(shell, holes);
}
protected static LinearRing linearRing(GeometryFactory factory, ArrayList<Coordinate> coordinates) {
return factory.createLinearRing(coordinates.toArray(new Coordinate[coordinates.size()]));
}
@Override
public GeoShapeType type() {
return TYPE;
}
protected static Polygon polygon(GeometryFactory factory, Coordinate[][] polygon) {
LinearRing shell = factory.createLinearRing(polygon[0]);
LinearRing[] holes;
if(polygon.length > 1) {
holes = new LinearRing[polygon.length-1];
for (int i = 0; i < holes.length; i++) {
holes[i] = factory.createLinearRing(polygon[i+1]);
}
} else {
holes = null;
}
return factory.createPolygon(shell, holes);
}
/**
* Create a Multipolygon from a set of coordinates. Each primary array contains a polygon which
* in turn contains an array of linestrings. These line Strings are represented as an array of
* coordinates. The first linestring will be the shell of the polygon the others define holes
* within the polygon.
*
* @param factory {@link GeometryFactory} to use
* @param polygons definition of polygons
* @return a new Multipolygon
*/
protected static MultiPolygon multipolygon(GeometryFactory factory, Coordinate[][][] polygons) {
Polygon[] polygonSet = new Polygon[polygons.length];
for (int i = 0; i < polygonSet.length; i++) {
polygonSet[i] = polygon(factory, polygons[i]);
}
return factory.createMultiPolygon(polygonSet);
}
/**
* This method sets the component id of all edges in a ring to a given id and shifts the
* coordinates of this component according to the dateline
*
* @param edge An arbitrary edge of the component
* @param id id to apply to the component
* @param edges a list of edges to which all edges of the component will be added (could be <code>null</code>)
* @return number of edges that belong to this component
*/
private static int component(final Edge edge, final int id, final ArrayList<Edge> edges) {
// find a coordinate that is not part of the dateline
Edge any = edge;
while(any.coordinate.x == +DATELINE || any.coordinate.x == -DATELINE) {
if((any = any.next) == edge) {
break;
}
}
double shift = any.coordinate.x > DATELINE ? DATELINE : (any.coordinate.x < -DATELINE ? -DATELINE : 0);
if (debugEnabled()) {
LOGGER.debug("shift: {[]}", shift);
}
// run along the border of the component, collect the
// edges, shift them according to the dateline and
// update the component id
int length = 0;
Edge current = edge;
do {
current.coordinate = shift(current.coordinate, shift);
current.component = id;
if(edges != null) {
edges.add(current);
}
length++;
} while((current = current.next) != edge);
return length;
}
/**
* Compute all coordinates of a component
* @param component an arbitrary edge of the component
* @param coordinates Array of coordinates to write the result to
* @return the coordinates parameter
*/
private static Coordinate[] coordinates(Edge component, Coordinate[] coordinates) {
for (int i = 0; i < coordinates.length; i++) {
coordinates[i] = (component = component.next).coordinate;
}
return coordinates;
}
private static Coordinate[][][] buildCoordinates(ArrayList<ArrayList<Coordinate[]>> components) {
Coordinate[][][] result = new Coordinate[components.size()][][];
for (int i = 0; i < result.length; i++) {
ArrayList<Coordinate[]> component = components.get(i);
result[i] = component.toArray(new Coordinate[component.size()][]);
}
if(debugEnabled()) {
for (int i = 0; i < result.length; i++) {
LOGGER.debug("Component {[]}:", i);
for (int j = 0; j < result[i].length; j++) {
LOGGER.debug("\t" + Arrays.toString(result[i][j]));
}
}
}
return result;
}
private static final Coordinate[][] EMPTY = new Coordinate[0][];
private static Coordinate[][] holes(Edge[] holes, int numHoles) {
if (numHoles == 0) {
return EMPTY;
}
final Coordinate[][] points = new Coordinate[numHoles][];
for (int i = 0; i < numHoles; i++) {
int length = component(holes[i], -(i+1), null); // mark as visited by inverting the sign
points[i] = coordinates(holes[i], new Coordinate[length+1]);
}
return points;
}
private static Edge[] edges(Edge[] edges, int numHoles, ArrayList<ArrayList<Coordinate[]>> components) {
ArrayList<Edge> mainEdges = new ArrayList<Edge>(edges.length);
for (int i = 0; i < edges.length; i++) {
if (edges[i].component >= 0) {
int length = component(edges[i], -(components.size()+numHoles+1), mainEdges);
ArrayList<Coordinate[]> component = new ArrayList<Coordinate[]>();
component.add(coordinates(edges[i], new Coordinate[length+1]));
components.add(component);
}
}
return mainEdges.toArray(new Edge[mainEdges.size()]);
}
private static Coordinate[][][] compose(Edge[] edges, Edge[] holes, int numHoles) {
final ArrayList<ArrayList<Coordinate[]>> components = new ArrayList<ArrayList<Coordinate[]>>();
assign(holes, holes(holes, numHoles), numHoles, edges(edges, numHoles, components), components);
return buildCoordinates(components);
}
private static void assign(Edge[] holes, Coordinate[][] points, int numHoles, Edge[] edges, ArrayList<ArrayList<Coordinate[]>> components) {
// Assign Hole to related components
// To find the new component the hole belongs to all intersections of the
// polygon edges with a vertical line are calculated. This vertical line
// is an arbitrary point of the hole. The polygon edge next to this point
// is part of the polygon the hole belongs to.
if (debugEnabled()) {
LOGGER.debug("Holes: " + Arrays.toString(holes));
}
for (int i = 0; i < numHoles; i++) {
final Edge current = holes[i];
final int intersections = intersections(current.coordinate.x, edges);
final int pos = Arrays.binarySearch(edges, 0, intersections, current, INTERSECTION_ORDER);
assert pos < 0 : "illegal state: two edges cross the datum at the same position";
final int index = -(pos+2);
final int component = -edges[index].component - numHoles - 1;
if(debugEnabled()) {
LOGGER.debug("\tposition ("+index+") of edge "+current+": " + edges[index]);
LOGGER.debug("\tComponent: " + component);
LOGGER.debug("\tHole intersections ("+current.coordinate.x+"): " + Arrays.toString(edges));
}
components.get(component).add(points[i]);
}
}
private static int merge(Edge[] intersections, int offset, int length, Edge[] holes, int numHoles) {
// Intersections appear pairwise. On the first edge the inner of
// of the polygon is entered. On the second edge the outer face
// is entered. Other kinds of intersections are discard by the
// intersection function
for (int i = 0; i < length; i += 2) {
Edge e1 = intersections[offset + i + 0];
Edge e2 = intersections[offset + i + 1];
// If two segments are connected maybe a hole must be deleted
// Since Edges of components appear pairwise we need to check
// the second edge only (the first edge is either polygon or
// already handled)
if (e2.component > 0) {
//TODO: Check if we could save the set null step
numHoles--;
holes[e2.component-1] = holes[numHoles];
holes[numHoles] = null;
}
connect(e1, e2);
}
return numHoles;
}
private static void connect(Edge in, Edge out) {
assert in != null && out != null;
assert in != out;
// Connecting two Edges by inserting the point at
// dateline intersection and connect these by adding
// two edges between this points. One per direction
if(in.intersect != in.next.coordinate) {
// NOTE: the order of the object creation is crucial here! Don't change it!
// first edge has no point on dateline
Edge e1 = new Edge(in.intersect, in.next);
if(out.intersect != out.next.coordinate) {
// second edge has no point on dateline
Edge e2 = new Edge(out.intersect, out.next);
in.next = new Edge(in.intersect, e2, in.intersect);
} else {
// second edge intersects with dateline
in.next = new Edge(in.intersect, out.next, in.intersect);
}
out.next = new Edge(out.intersect, e1, out.intersect);
} else {
// first edge intersects with dateline
Edge e2 = new Edge(out.intersect, in.next, out.intersect);
if(out.intersect != out.next.coordinate) {
// second edge has no point on dateline
Edge e1 = new Edge(out.intersect, out.next);
in.next = new Edge(in.intersect, e1, in.intersect);
} else {
// second edge intersects with dateline
in.next = new Edge(in.intersect, out.next, in.intersect);
}
out.next = e2;
}
}
private static int createEdges(int component, boolean direction, BaseLineStringBuilder<?> line, Edge[] edges, int offset) {
Coordinate[] points = line.coordinates(false); // last point is repeated
Edge.ring(component, direction, points, 0, edges, offset, points.length-1);
return points.length-1;
}
public static class Ring<P extends ShapeBuilder> extends BaseLineStringBuilder<Ring<P>> {
private final P parent;
protected Ring(P parent) {
this(parent, new ArrayList<Coordinate>());
}
protected Ring(P parent, ArrayList<Coordinate> points) {
super(points);
this.parent = parent;
}
public P close() {
Coordinate start = points.get(0);
Coordinate end = points.get(points.size()-1);
if(start.x != end.x || start.y != end.y) {
points.add(start);
}
return parent;
}
@Override
public GeoShapeType type() {
return null;
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_common_geo_builders_BasePolygonBuilder.java
|
494 |
public class GenericResponse {
private List<String> errorCodes = new ArrayList<String>();
/**
* Returns true if
* @return
*/
public boolean getHasErrors() {
return errorCodes.size() > 0;
}
public List<String> getErrorCodesList() {
return errorCodes;
}
public void addErrorCode(String errorCode) {
if (errorCode != null) {
errorCodes.add(errorCode);
}
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_service_GenericResponse.java
|
149 |
public class ReadMostlyVector<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
private static final long serialVersionUID = 8673264195747942595L;
/*
* This class exists mainly as a vehicle to exercise various
* constructions using SequenceLocks. Read-only methods
* take one of a few forms:
*
* Short methods,including get(index), continually retry obtaining
* a snapshot of array, count, and element, using sequence number
* to validate.
*
* Methods that are potentially O(n) (or worse) try once in
* read-only mode, and then lock. When in read-only mode, they
* validate only at the end of an array scan unless the element is
* actually used (for example, as an argument of method equals).
*
* We rely on some invariants that are always true, even for field
* reads in read-only mode that have not yet been validated:
* - array != null
* - count >= 0
*/
/**
* The maximum size of array to allocate.
* See CopyOnWriteArrayList for explanation.
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
// fields are non-private to simplify nested class access
Object[] array;
final StampedLock lock;
int count;
final int capacityIncrement;
/**
* Creates an empty vector with the given initial capacity and
* capacity increment.
*
* @param initialCapacity the initial capacity of the underlying array
* @param capacityIncrement if non-zero, the number to
* add when resizing to accommodate additional elements.
* If zero, the array size is doubled when resized.
*
* @throws IllegalArgumentException if initial capacity is negative
*/
public ReadMostlyVector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.array = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
this.lock = new StampedLock();
}
/**
* Creates an empty vector with the given initial capacity.
*
* @param initialCapacity the initial capacity of the underlying array
* @throws IllegalArgumentException if initial capacity is negative
*/
public ReadMostlyVector(int initialCapacity) {
this(initialCapacity, 0);
}
/**
* Creates an empty vector.
*/
public ReadMostlyVector() {
this.capacityIncrement = 0;
this.lock = new StampedLock();
}
/**
* Creates a vector containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection of initially held elements
* @throws NullPointerException if the specified collection is null
*/
public ReadMostlyVector(Collection<? extends E> c) {
Object[] elements = c.toArray();
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elements.getClass() != Object[].class)
elements = Arrays.copyOf(elements, elements.length, Object[].class);
this.array = elements;
this.count = elements.length;
this.capacityIncrement = 0;
this.lock = new StampedLock();
}
// internal constructor for clone
ReadMostlyVector(Object[] array, int count, int capacityIncrement) {
this.array = array;
this.count = count;
this.capacityIncrement = capacityIncrement;
this.lock = new StampedLock();
}
static final int INITIAL_CAP = 16;
// For explanation, see CopyOnWriteArrayList
final Object[] grow(int minCapacity) {
Object[] items;
int newCapacity;
if ((items = array) == null)
newCapacity = INITIAL_CAP;
else {
int oldCapacity = array.length;
newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
}
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
else if (minCapacity > MAX_ARRAY_SIZE)
newCapacity = Integer.MAX_VALUE;
else
newCapacity = MAX_ARRAY_SIZE;
}
return array = ((items == null) ?
new Object[newCapacity] :
Arrays.copyOf(items, newCapacity));
}
/*
* Internal versions of most base functionality, wrapped
* in different ways from public methods from this class
* as well as sublist and iterator classes.
*/
static int findFirstIndex(Object[] items, Object x, int index, int fence) {
int len;
if (items != null && (len = items.length) > 0) {
int start = (index < 0) ? 0 : index;
int bound = (fence < len) ? fence : len;
for (int i = start; i < bound; ++i) {
Object e = items[i];
if ((x == null) ? e == null : x.equals(e))
return i;
}
}
return -1;
}
static int findLastIndex(Object[] items, Object x, int index, int origin) {
int len;
if (items != null && (len = items.length) > 0) {
int last = (index < len) ? index : len - 1;
int start = (origin < 0) ? 0 : origin;
for (int i = last; i >= start; --i) {
Object e = items[i];
if ((x == null) ? e == null : x.equals(e))
return i;
}
}
return -1;
}
final void rawAdd(E e) {
int n = count;
Object[] items = array;
if (items == null || n >= items.length)
items = grow(n + 1);
items[n] = e;
count = n + 1;
}
final void rawAddAt(int index, E e) {
int n = count;
Object[] items = array;
if (index > n)
throw new ArrayIndexOutOfBoundsException(index);
if (items == null || n >= items.length)
items = grow(n + 1);
if (index < n)
System.arraycopy(items, index, items, index + 1, n - index);
items[index] = e;
count = n + 1;
}
final boolean rawAddAllAt(int index, Object[] elements) {
int n = count;
Object[] items = array;
if (index < 0 || index > n)
throw new ArrayIndexOutOfBoundsException(index);
int len = elements.length;
if (len == 0)
return false;
int newCount = n + len;
if (items == null || newCount >= items.length)
items = grow(newCount);
int mv = n - index;
if (mv > 0)
System.arraycopy(items, index, items, index + len, mv);
System.arraycopy(elements, 0, items, index, len);
count = newCount;
return true;
}
final boolean rawRemoveAt(int index) {
int n = count - 1;
Object[] items = array;
if (items == null || index < 0 || index > n)
return false;
int mv = n - index;
if (mv > 0)
System.arraycopy(items, index + 1, items, index, mv);
items[n] = null;
count = n;
return true;
}
/**
* Internal version of removeAll for lists and sublists. In this
* and other similar methods below, the bound argument is, if
* non-negative, the purported upper bound of a list/sublist, or
* is left negative if the bound should be determined via count
* field under lock.
*/
final boolean lockedRemoveAll(Collection<?> c, int origin, int bound) {
boolean removed = false;
final StampedLock lock = this.lock;
long stamp = lock.writeLock();
try {
int n = count;
int fence = bound < 0 || bound > n ? n : bound;
if (origin >= 0 && origin < fence) {
for (Object x : c) {
while (rawRemoveAt(findFirstIndex(array, x, origin, fence)))
removed = true;
}
}
} finally {
lock.unlockWrite(stamp);
}
return removed;
}
final boolean lockedRetainAll(Collection<?> c, int origin, int bound) {
final StampedLock lock = this.lock;
boolean removed = false;
if (c != this) {
long stamp = lock.writeLock();
try {
Object[] items;
int i, n;
if ((items = array) != null && (n = count) > 0 &&
n < items.length && (i = origin) >= 0) {
int fence = bound < 0 || bound > n ? n : bound;
while (i < fence) {
if (c.contains(items[i]))
++i;
else {
--fence;
int mv = --n - i;
if (mv > 0)
System.arraycopy(items, i + 1, items, i, mv);
}
}
if (count != n) {
count = n;
removed = true;
}
}
} finally {
lock.unlockWrite(stamp);
}
}
return removed;
}
final void internalClear(int origin, int bound) {
Object[] items;
int n, len;
if ((items = array) != null && (len = items.length) > 0) {
if (origin < 0)
origin = 0;
if ((n = count) > len)
n = len;
int fence = bound < 0 || bound > n ? n : bound;
int removed = fence - origin;
int newCount = n - removed;
int mv = n - (origin + removed);
if (mv > 0)
System.arraycopy(items, origin + removed, items, origin, mv);
for (int i = n; i < newCount; ++i)
items[i] = null;
count = newCount;
}
}
final boolean internalContainsAll(Collection<?> c, int origin, int bound) {
Object[] items;
int n, len;
if ((items = array) != null && (len = items.length) > 0) {
if (origin < 0)
origin = 0;
if ((n = count) > len)
n = len;
int fence = bound < 0 || bound > n ? n : bound;
for (Object e : c) {
if (findFirstIndex(items, e, origin, fence) < 0)
return false;
}
}
else if (!c.isEmpty())
return false;
return true;
}
final boolean internalEquals(List<?> list, int origin, int bound) {
Object[] items;
int n, len;
if ((items = array) != null && (len = items.length) > 0) {
if (origin < 0)
origin = 0;
if ((n = count) > len)
n = len;
int fence = bound < 0 || bound > n ? n : bound;
Iterator<?> it = list.iterator();
for (int i = origin; i < fence; ++i) {
if (!it.hasNext())
return false;
Object y = it.next();
Object x = items[i];
if (x != y && (x == null || !x.equals(y)))
return false;
}
if (it.hasNext())
return false;
}
else if (!list.isEmpty())
return false;
return true;
}
final int internalHashCode(int origin, int bound) {
int hash = 1;
Object[] items;
int n, len;
if ((items = array) != null && (len = items.length) > 0) {
if (origin < 0)
origin = 0;
if ((n = count) > len)
n = len;
int fence = bound < 0 || bound > n ? n : bound;
for (int i = origin; i < fence; ++i) {
Object e = items[i];
hash = 31*hash + (e == null ? 0 : e.hashCode());
}
}
return hash;
}
final String internalToString(int origin, int bound) {
Object[] items;
int n, len;
if ((items = array) != null && (len = items.length) > 0) {
if ((n = count) > len)
n = len;
int fence = bound < 0 || bound > n ? n : bound;
int i = (origin < 0) ? 0 : origin;
if (i != fence) {
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
Object e = items[i];
sb.append((e == this) ? "(this Collection)" : e.toString());
if (++i < fence)
sb.append(',').append(' ');
else
return sb.append(']').toString();
}
}
}
return "[]";
}
final Object[] internalToArray(int origin, int bound) {
Object[] items;
int n, len;
if ((items = array) != null && (len = items.length) > 0) {
if (origin < 0)
origin = 0;
if ((n = count) > len)
n = len;
int fence = bound < 0 || bound > n ? n : bound;
int i = (origin < 0) ? 0 : origin;
if (i != fence)
return Arrays.copyOfRange(items, i, fence, Object[].class);
}
return new Object[0];
}
@SuppressWarnings("unchecked")
final <T> T[] internalToArray(T[] a, int origin, int bound) {
int alen = a.length;
Object[] items;
int n, len;
if ((items = array) != null && (len = items.length) > 0) {
if (origin < 0)
origin = 0;
if ((n = count) > len)
n = len;
int fence = bound < 0 || bound > n ? n : bound;
int i = (origin < 0) ? 0 : origin;
int rlen = fence - origin;
if (rlen > 0) {
if (alen >= rlen) {
System.arraycopy(items, 0, a, origin, rlen);
if (alen > rlen)
a[rlen] = null;
return a;
}
return (T[]) Arrays.copyOfRange(items, i, fence, a.getClass());
}
}
if (alen > 0)
a[0] = null;
return a;
}
// public List methods
public boolean add(E e) {
final StampedLock lock = this.lock;
long stamp = lock.writeLock();
try {
rawAdd(e);
} finally {
lock.unlockWrite(stamp);
}
return true;
}
public void add(int index, E element) {
final StampedLock lock = this.lock;
long stamp = lock.writeLock();
try {
rawAddAt(index, element);
} finally {
lock.unlockWrite(stamp);
}
}
public boolean addAll(Collection<? extends E> c) {
Object[] elements = c.toArray();
int len = elements.length;
if (len == 0)
return false;
final StampedLock lock = this.lock;
long stamp = lock.writeLock();
try {
Object[] items = array;
int n = count;
int newCount = n + len;
if (items == null || newCount >= items.length)
items = grow(newCount);
System.arraycopy(elements, 0, items, n, len);
count = newCount;
} finally {
lock.unlockWrite(stamp);
}
return true;
}
public boolean addAll(int index, Collection<? extends E> c) {
Object[] elements = c.toArray();
boolean ret;
final StampedLock lock = this.lock;
long stamp = lock.writeLock();
try {
ret = rawAddAllAt(index, elements);
} finally {
lock.unlockWrite(stamp);
}
return ret;
}
public void clear() {
final StampedLock lock = this.lock;
long stamp = lock.writeLock();
try {
int n = count;
Object[] items = array;
if (items != null) {
for (int i = 0; i < n; i++)
items[i] = null;
}
count = 0;
} finally {
lock.unlockWrite(stamp);
}
}
public boolean contains(Object o) {
return indexOf(o, 0) >= 0;
}
public boolean containsAll(Collection<?> c) {
boolean ret;
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
ret = internalContainsAll(c, 0, -1);
} finally {
lock.unlockRead(stamp);
}
return ret;
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
return internalEquals((List<?>)o, 0, -1);
} finally {
lock.unlockRead(stamp);
}
}
public E get(int index) {
final StampedLock lock = this.lock;
long stamp = lock.tryOptimisticRead();
Object[] items;
if (index >= 0 && (items = array) != null &&
index < count && index < items.length) {
@SuppressWarnings("unchecked") E e = (E)items[index];
if (lock.validate(stamp))
return e;
}
return lockedGet(index);
}
@SuppressWarnings("unchecked") private E lockedGet(int index) {
boolean oobe = false;
E e = null;
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
Object[] items;
if ((items = array) != null && index < items.length &&
index < count && index >= 0)
e = (E)items[index];
else
oobe = true;
} finally {
lock.unlockRead(stamp);
}
if (oobe)
throw new ArrayIndexOutOfBoundsException(index);
return e;
}
public int hashCode() {
int h;
final StampedLock lock = this.lock;
long s = lock.readLock();
try {
h = internalHashCode(0, -1);
} finally {
lock.unlockRead(s);
}
return h;
}
public int indexOf(Object o) {
int idx;
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
idx = findFirstIndex(array, o, 0, count);
} finally {
lock.unlockRead(stamp);
}
return idx;
}
public boolean isEmpty() {
final StampedLock lock = this.lock;
long stamp = lock.tryOptimisticRead();
return count == 0; // no need for validation
}
public Iterator<E> iterator() {
return new Itr<E>(this, 0);
}
public int lastIndexOf(Object o) {
int idx;
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
idx = findLastIndex(array, o, count - 1, 0);
} finally {
lock.unlockRead(stamp);
}
return idx;
}
public ListIterator<E> listIterator() {
return new Itr<E>(this, 0);
}
public ListIterator<E> listIterator(int index) {
return new Itr<E>(this, index);
}
@SuppressWarnings("unchecked") public E remove(int index) {
E oldValue = null;
boolean oobe = false;
final StampedLock lock = this.lock;
long stamp = lock.writeLock();
try {
if (index < 0 || index >= count)
oobe = true;
else {
oldValue = (E) array[index];
rawRemoveAt(index);
}
} finally {
lock.unlockWrite(stamp);
}
if (oobe)
throw new ArrayIndexOutOfBoundsException(index);
return oldValue;
}
public boolean remove(Object o) {
final StampedLock lock = this.lock;
long stamp = lock.writeLock();
try {
return rawRemoveAt(findFirstIndex(array, o, 0, count));
} finally {
lock.unlockWrite(stamp);
}
}
public boolean removeAll(Collection<?> c) {
return lockedRemoveAll(c, 0, -1);
}
public boolean retainAll(Collection<?> c) {
return lockedRetainAll(c, 0, -1);
}
@SuppressWarnings("unchecked") public E set(int index, E element) {
E oldValue = null;
boolean oobe = false;
final StampedLock lock = this.lock;
long stamp = lock.writeLock();
try {
Object[] items = array;
if (items == null || index < 0 || index >= count)
oobe = true;
else {
oldValue = (E) items[index];
items[index] = element;
}
} finally {
lock.unlockWrite(stamp);
}
if (oobe)
throw new ArrayIndexOutOfBoundsException(index);
return oldValue;
}
public int size() {
final StampedLock lock = this.lock;
long stamp = lock.tryOptimisticRead();
return count; // no need for validation
}
private int lockedSize() {
int n;
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
n = count;
} finally {
lock.unlockRead(stamp);
}
return n;
}
public List<E> subList(int fromIndex, int toIndex) {
int ssize = toIndex - fromIndex;
if (ssize >= 0 && fromIndex >= 0) {
ReadMostlyVectorSublist<E> ret = null;
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
if (toIndex <= count)
ret = new ReadMostlyVectorSublist<E>(this, fromIndex, ssize);
} finally {
lock.unlockRead(stamp);
}
if (ret != null)
return ret;
}
throw new ArrayIndexOutOfBoundsException(fromIndex < 0 ? fromIndex : toIndex);
}
public Object[] toArray() {
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
return internalToArray(0, -1);
} finally {
lock.unlockRead(stamp);
}
}
public <T> T[] toArray(T[] a) {
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
return internalToArray(a, 0, -1);
} finally {
lock.unlockRead(stamp);
}
}
public String toString() {
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
return internalToString(0, -1);
} finally {
lock.unlockRead(stamp);
}
}
// ReadMostlyVector-only methods
/**
* Appends the element, if not present.
*
* @param e element to be added to this list, if absent
* @return {@code true} if the element was added
*/
public boolean addIfAbsent(E e) {
boolean ret;
final StampedLock lock = this.lock;
long stamp = lock.writeLock();
try {
if (findFirstIndex(array, e, 0, count) < 0) {
rawAdd(e);
ret = true;
}
else
ret = false;
} finally {
lock.unlockWrite(stamp);
}
return ret;
}
/**
* Appends all of the elements in the specified collection that
* are not already contained in this list, to the end of
* this list, in the order that they are returned by the
* specified collection's iterator.
*
* @param c collection containing elements to be added to this list
* @return the number of elements added
* @throws NullPointerException if the specified collection is null
* @see #addIfAbsent(Object)
*/
public int addAllAbsent(Collection<? extends E> c) {
int added = 0;
Object[] cs = c.toArray();
int clen = cs.length;
if (clen != 0) {
long stamp = lock.writeLock();
try {
for (int i = 0; i < clen; ++i) {
@SuppressWarnings("unchecked")
E e = (E) cs[i];
if (findFirstIndex(array, e, 0, count) < 0) {
rawAdd(e);
++added;
}
}
} finally {
lock.unlockWrite(stamp);
}
}
return added;
}
/**
* Returns an iterator operating over a snapshot copy of the
* elements of this collection created upon construction of the
* iterator. The iterator does <em>NOT</em> support the
* {@code remove} method.
*
* @return an iterator over the elements in this list in proper sequence
*/
public Iterator<E> snapshotIterator() {
return new SnapshotIterator<E>(this);
}
static final class SnapshotIterator<E> implements Iterator<E> {
private final Object[] items;
private int cursor;
SnapshotIterator(ReadMostlyVector<E> v) { items = v.toArray(); }
public boolean hasNext() { return cursor < items.length; }
@SuppressWarnings("unchecked") public E next() {
if (cursor < items.length)
return (E) items[cursor++];
throw new NoSuchElementException();
}
public void remove() { throw new UnsupportedOperationException() ; }
}
/** Interface describing a void action of one argument */
public interface Action<A> { void apply(A a); }
public void forEachReadOnly(Action<E> action) {
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
Object[] items;
int len, n;
if ((items = array) != null && (len = items.length) > 0 &&
(n = count) <= len) {
for (int i = 0; i < n; ++i) {
@SuppressWarnings("unchecked") E e = (E)items[i];
action.apply(e);
}
}
} finally {
lock.unlockRead(stamp);
}
}
// Vector-only methods
/** See {@link Vector#firstElement} */
public E firstElement() {
final StampedLock lock = this.lock;
long stamp = lock.tryOptimisticRead();
Object[] items;
if ((items = array) != null && count > 0 && items.length > 0) {
@SuppressWarnings("unchecked") E e = (E)items[0];
if (lock.validate(stamp))
return e;
}
return lockedFirstElement();
}
@SuppressWarnings("unchecked") private E lockedFirstElement() {
Object e = null;
boolean oobe = false;
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
Object[] items = array;
if (items != null && count > 0 && items.length > 0)
e = items[0];
else
oobe = true;
} finally {
lock.unlockRead(stamp);
}
if (oobe)
throw new NoSuchElementException();
return (E) e;
}
/** See {@link Vector#lastElement} */
public E lastElement() {
final StampedLock lock = this.lock;
long stamp = lock.tryOptimisticRead();
Object[] items;
int i;
if ((items = array) != null && (i = count - 1) >= 0 &&
i < items.length) {
@SuppressWarnings("unchecked") E e = (E)items[i];
if (lock.validate(stamp))
return e;
}
return lockedLastElement();
}
@SuppressWarnings("unchecked") private E lockedLastElement() {
Object e = null;
boolean oobe = false;
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
Object[] items = array;
int i = count - 1;
if (items != null && i >= 0 && i < items.length)
e = items[i];
else
oobe = true;
} finally {
lock.unlockRead(stamp);
}
if (oobe)
throw new NoSuchElementException();
return (E) e;
}
/** See {@link Vector#indexOf(Object, int)} */
public int indexOf(Object o, int index) {
if (index < 0)
throw new ArrayIndexOutOfBoundsException(index);
int idx;
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
idx = findFirstIndex(array, o, index, count);
} finally {
lock.unlockRead(stamp);
}
return idx;
}
/** See {@link Vector#lastIndexOf(Object, int)} */
public int lastIndexOf(Object o, int index) {
boolean oobe = false;
int idx = -1;
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
if (index < count)
idx = findLastIndex(array, o, index, 0);
else
oobe = true;
} finally {
lock.unlockRead(stamp);
}
if (oobe)
throw new ArrayIndexOutOfBoundsException(index);
return idx;
}
/** See {@link Vector#setSize} */
public void setSize(int newSize) {
if (newSize < 0)
throw new ArrayIndexOutOfBoundsException(newSize);
final StampedLock lock = this.lock;
long stamp = lock.writeLock();
try {
Object[] items;
int n = count;
if (newSize > n)
grow(newSize);
else if ((items = array) != null) {
for (int i = newSize ; i < n ; i++)
items[i] = null;
}
count = newSize;
} finally {
lock.unlockWrite(stamp);
}
}
/** See {@link Vector#copyInto} */
public void copyInto(Object[] anArray) {
final StampedLock lock = this.lock;
long stamp = lock.writeLock();
try {
Object[] items;
if ((items = array) != null)
System.arraycopy(items, 0, anArray, 0, count);
} finally {
lock.unlockWrite(stamp);
}
}
/** See {@link Vector#trimToSize} */
public void trimToSize() {
final StampedLock lock = this.lock;
long stamp = lock.writeLock();
try {
Object[] items = array;
int n = count;
if (items != null && n < items.length)
array = Arrays.copyOf(items, n);
} finally {
lock.unlockWrite(stamp);
}
}
/** See {@link Vector#ensureCapacity} */
public void ensureCapacity(int minCapacity) {
if (minCapacity > 0) {
final StampedLock lock = this.lock;
long stamp = lock.writeLock();
try {
Object[] items = array;
int cap = (items == null) ? 0 : items.length;
if (minCapacity - cap > 0)
grow(minCapacity);
} finally {
lock.unlockWrite(stamp);
}
}
}
/** See {@link Vector#elements} */
public Enumeration<E> elements() {
return new Itr<E>(this, 0);
}
/** See {@link Vector#capacity} */
public int capacity() {
return array.length;
}
/** See {@link Vector#elementAt} */
public E elementAt(int index) {
return get(index);
}
/** See {@link Vector#setElementAt} */
public void setElementAt(E obj, int index) {
set(index, obj);
}
/** See {@link Vector#removeElementAt} */
public void removeElementAt(int index) {
remove(index);
}
/** See {@link Vector#insertElementAt} */
public void insertElementAt(E obj, int index) {
add(index, obj);
}
/** See {@link Vector#addElement} */
public void addElement(E obj) {
add(obj);
}
/** See {@link Vector#removeElement} */
public boolean removeElement(Object obj) {
return remove(obj);
}
/** See {@link Vector#removeAllElements} */
public void removeAllElements() {
clear();
}
// other methods
public ReadMostlyVector<E> clone() {
Object[] a = null;
int n;
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
Object[] items = array;
if (items == null)
n = 0;
else {
int len = items.length;
if ((n = count) > len)
n = len;
a = Arrays.copyOf(items, n);
}
} finally {
lock.unlockRead(stamp);
}
return new ReadMostlyVector<E>(a, n, capacityIncrement);
}
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
final StampedLock lock = this.lock;
long stamp = lock.readLock();
try {
s.defaultWriteObject();
} finally {
lock.unlockRead(stamp);
}
}
static final class Itr<E> implements ListIterator<E>, Enumeration<E> {
final StampedLock lock;
final ReadMostlyVector<E> list;
Object[] items;
long seq;
int cursor;
int fence;
int lastRet;
Itr(ReadMostlyVector<E> list, int index) {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
this.list = list;
this.lock = lock;
this.items = list.array;
this.fence = list.count;
this.cursor = index;
this.lastRet = -1;
} finally {
this.seq = lock.tryConvertToOptimisticRead(stamp);
}
if (index < 0 || index > fence)
throw new ArrayIndexOutOfBoundsException(index);
}
public boolean hasPrevious() {
return cursor > 0;
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
public boolean hasNext() {
return cursor < fence;
}
public E next() {
int i = cursor;
Object[] es = items;
if (es == null || i < 0 || i >= fence || i >= es.length)
throw new NoSuchElementException();
@SuppressWarnings("unchecked") E e = (E)es[i];
lastRet = i;
cursor = i + 1;
if (!lock.validate(seq))
throw new ConcurrentModificationException();
return e;
}
public E previous() {
int i = cursor - 1;
Object[] es = items;
if (es == null || i < 0 || i >= fence || i >= es.length)
throw new NoSuchElementException();
@SuppressWarnings("unchecked") E e = (E)es[i];
lastRet = i;
cursor = i;
if (!lock.validate(seq))
throw new ConcurrentModificationException();
return e;
}
public void remove() {
int i = lastRet;
if (i < 0)
throw new IllegalStateException();
if ((seq = lock.tryConvertToWriteLock(seq)) == 0)
throw new ConcurrentModificationException();
try {
list.rawRemoveAt(i);
fence = list.count;
cursor = i;
lastRet = -1;
} finally {
seq = lock.tryConvertToOptimisticRead(seq);
}
}
public void set(E e) {
int i = lastRet;
Object[] es = items;
if (es == null || i < 0 | i >= fence)
throw new IllegalStateException();
if ((seq = lock.tryConvertToWriteLock(seq)) == 0)
throw new ConcurrentModificationException();
try {
es[i] = e;
} finally {
seq = lock.tryConvertToOptimisticRead(seq);
}
}
public void add(E e) {
int i = cursor;
if (i < 0)
throw new IllegalStateException();
if ((seq = lock.tryConvertToWriteLock(seq)) == 0)
throw new ConcurrentModificationException();
try {
list.rawAddAt(i, e);
items = list.array;
fence = list.count;
cursor = i + 1;
lastRet = -1;
} finally {
seq = lock.tryConvertToOptimisticRead(seq);
}
}
public boolean hasMoreElements() { return hasNext(); }
public E nextElement() { return next(); }
}
static final class ReadMostlyVectorSublist<E>
implements List<E>, RandomAccess, java.io.Serializable {
private static final long serialVersionUID = 3041673470172026059L;
final ReadMostlyVector<E> list;
final int offset;
volatile int size;
ReadMostlyVectorSublist(ReadMostlyVector<E> list,
int offset, int size) {
this.list = list;
this.offset = offset;
this.size = size;
}
private void rangeCheck(int index) {
if (index < 0 || index >= size)
throw new ArrayIndexOutOfBoundsException(index);
}
public boolean add(E element) {
final StampedLock lock = list.lock;
long stamp = lock.writeLock();
try {
int c = size;
list.rawAddAt(c + offset, element);
size = c + 1;
} finally {
lock.unlockWrite(stamp);
}
return true;
}
public void add(int index, E element) {
final StampedLock lock = list.lock;
long stamp = lock.writeLock();
try {
if (index < 0 || index > size)
throw new ArrayIndexOutOfBoundsException(index);
list.rawAddAt(index + offset, element);
++size;
} finally {
lock.unlockWrite(stamp);
}
}
public boolean addAll(Collection<? extends E> c) {
Object[] elements = c.toArray();
final StampedLock lock = list.lock;
long stamp = lock.writeLock();
try {
int s = size;
int pc = list.count;
list.rawAddAllAt(offset + s, elements);
int added = list.count - pc;
size = s + added;
return added != 0;
} finally {
lock.unlockWrite(stamp);
}
}
public boolean addAll(int index, Collection<? extends E> c) {
Object[] elements = c.toArray();
final StampedLock lock = list.lock;
long stamp = lock.writeLock();
try {
int s = size;
if (index < 0 || index > s)
throw new ArrayIndexOutOfBoundsException(index);
int pc = list.count;
list.rawAddAllAt(index + offset, elements);
int added = list.count - pc;
size = s + added;
return added != 0;
} finally {
lock.unlockWrite(stamp);
}
}
public void clear() {
final StampedLock lock = list.lock;
long stamp = lock.writeLock();
try {
list.internalClear(offset, offset + size);
size = 0;
} finally {
lock.unlockWrite(stamp);
}
}
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public boolean containsAll(Collection<?> c) {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
return list.internalContainsAll(c, offset, offset + size);
} finally {
lock.unlockRead(stamp);
}
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
return list.internalEquals((List<?>)(o), offset, offset + size);
} finally {
lock.unlockRead(stamp);
}
}
public E get(int index) {
if (index < 0 || index >= size)
throw new ArrayIndexOutOfBoundsException(index);
return list.get(index + offset);
}
public int hashCode() {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
return list.internalHashCode(offset, offset + size);
} finally {
lock.unlockRead(stamp);
}
}
public int indexOf(Object o) {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
int idx = findFirstIndex(list.array, o, offset, offset + size);
return idx < 0 ? -1 : idx - offset;
} finally {
lock.unlockRead(stamp);
}
}
public boolean isEmpty() {
return size() == 0;
}
public Iterator<E> iterator() {
return new SubItr<E>(this, offset);
}
public int lastIndexOf(Object o) {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
int idx = findLastIndex(list.array, o, offset + size - 1, offset);
return idx < 0 ? -1 : idx - offset;
} finally {
lock.unlockRead(stamp);
}
}
public ListIterator<E> listIterator() {
return new SubItr<E>(this, offset);
}
public ListIterator<E> listIterator(int index) {
return new SubItr<E>(this, index + offset);
}
public E remove(int index) {
final StampedLock lock = list.lock;
long stamp = lock.writeLock();
try {
Object[] items = list.array;
int i = index + offset;
if (items == null || index < 0 || index >= size || i >= items.length)
throw new ArrayIndexOutOfBoundsException(index);
@SuppressWarnings("unchecked") E result = (E)items[i];
list.rawRemoveAt(i);
size--;
return result;
} finally {
lock.unlockWrite(stamp);
}
}
public boolean remove(Object o) {
final StampedLock lock = list.lock;
long stamp = lock.writeLock();
try {
if (list.rawRemoveAt(findFirstIndex(list.array, o, offset,
offset + size))) {
--size;
return true;
}
else
return false;
} finally {
lock.unlockWrite(stamp);
}
}
public boolean removeAll(Collection<?> c) {
return list.lockedRemoveAll(c, offset, offset + size);
}
public boolean retainAll(Collection<?> c) {
return list.lockedRetainAll(c, offset, offset + size);
}
public E set(int index, E element) {
if (index < 0 || index >= size)
throw new ArrayIndexOutOfBoundsException(index);
return list.set(index+offset, element);
}
public int size() {
return size;
}
public List<E> subList(int fromIndex, int toIndex) {
int c = size;
int ssize = toIndex - fromIndex;
if (fromIndex < 0)
throw new ArrayIndexOutOfBoundsException(fromIndex);
if (toIndex > c || ssize < 0)
throw new ArrayIndexOutOfBoundsException(toIndex);
return new ReadMostlyVectorSublist<E>(list, offset+fromIndex, ssize);
}
public Object[] toArray() {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
return list.internalToArray(offset, offset + size);
} finally {
lock.unlockRead(stamp);
}
}
public <T> T[] toArray(T[] a) {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
return list.internalToArray(a, offset, offset + size);
} finally {
lock.unlockRead(stamp);
}
}
public String toString() {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
return list.internalToString(offset, offset + size);
} finally {
lock.unlockRead(stamp);
}
}
}
static final class SubItr<E> implements ListIterator<E> {
final ReadMostlyVectorSublist<E> sublist;
final ReadMostlyVector<E> list;
final StampedLock lock;
Object[] items;
long seq;
int cursor;
int origin;
int fence;
int lastRet;
SubItr(ReadMostlyVectorSublist<E> sublist, int index) {
final StampedLock lock = sublist.list.lock;
long stamp = lock.readLock();
try {
this.sublist = sublist;
this.list = sublist.list;
this.lock = lock;
this.cursor = index;
this.origin = sublist.offset;
this.fence = origin + sublist.size;
this.lastRet = -1;
} finally {
this.seq = lock.tryConvertToOptimisticRead(stamp);
}
if (index < 0 || cursor > fence)
throw new ArrayIndexOutOfBoundsException(index);
}
public int nextIndex() {
return cursor - origin;
}
public int previousIndex() {
return cursor - origin - 1;
}
public boolean hasNext() {
return cursor < fence;
}
public boolean hasPrevious() {
return cursor > origin;
}
public E next() {
int i = cursor;
Object[] es = items;
if (es == null || i < origin || i >= fence || i >= es.length)
throw new NoSuchElementException();
@SuppressWarnings("unchecked") E e = (E)es[i];
lastRet = i;
cursor = i + 1;
if (!lock.validate(seq))
throw new ConcurrentModificationException();
return e;
}
public E previous() {
int i = cursor - 1;
Object[] es = items;
if (es == null || i < 0 || i >= fence || i >= es.length)
throw new NoSuchElementException();
@SuppressWarnings("unchecked") E e = (E)es[i];
lastRet = i;
cursor = i;
if (!lock.validate(seq))
throw new ConcurrentModificationException();
return e;
}
public void remove() {
int i = lastRet;
if (i < 0)
throw new IllegalStateException();
if ((seq = lock.tryConvertToWriteLock(seq)) == 0)
throw new ConcurrentModificationException();
try {
list.rawRemoveAt(i);
fence = origin + sublist.size;
cursor = i;
lastRet = -1;
} finally {
seq = lock.tryConvertToOptimisticRead(seq);
}
}
public void set(E e) {
int i = lastRet;
if (i < origin || i >= fence)
throw new IllegalStateException();
if ((seq = lock.tryConvertToWriteLock(seq)) == 0)
throw new ConcurrentModificationException();
try {
list.set(i, e);
} finally {
seq = lock.tryConvertToOptimisticRead(seq);
}
}
public void add(E e) {
int i = cursor;
if (i < origin || i >= fence)
throw new IllegalStateException();
if ((seq = lock.tryConvertToWriteLock(seq)) == 0)
throw new ConcurrentModificationException();
try {
list.rawAddAt(i, e);
items = list.array;
fence = origin + sublist.size;
cursor = i + 1;
lastRet = -1;
} finally {
seq = lock.tryConvertToOptimisticRead(seq);
}
}
}
}
| 0true
|
src_main_java_jsr166e_extra_ReadMostlyVector.java
|
4,444 |
public static class FieldDataWeigher implements Weigher<Key, AtomicFieldData> {
@Override
public int weigh(Key key, AtomicFieldData fieldData) {
int weight = (int) Math.min(fieldData.getMemorySizeInBytes(), Integer.MAX_VALUE);
return weight == 0 ? 1 : weight;
}
}
| 1no label
|
src_main_java_org_elasticsearch_indices_fielddata_cache_IndicesFieldDataCache.java
|
193 |
@Embeddable
public class Auditable implements Serializable {
private static final long serialVersionUID = 1L;
@Column(name = "DATE_CREATED", updatable = false)
@Temporal(TemporalType.TIMESTAMP)
@AdminPresentation(friendlyName = "Auditable_Date_Created", order = 1000,
tab = Presentation.Tab.Name.Audit, tabOrder = Presentation.Tab.Order.Audit,
group = "Auditable_Audit", groupOrder = 1000,
readOnly = true)
protected Date dateCreated;
@Column(name = "CREATED_BY", updatable = false)
@AdminPresentation(friendlyName = "Auditable_Created_By", order = 2000,
tab = Presentation.Tab.Name.Audit, tabOrder = Presentation.Tab.Order.Audit,
group = "Auditable_Audit",
readOnly = true)
protected Long createdBy;
@Column(name = "DATE_UPDATED")
@Temporal(TemporalType.TIMESTAMP)
@AdminPresentation(friendlyName = "Auditable_Date_Updated", order = 3000,
tab = Presentation.Tab.Name.Audit, tabOrder = Presentation.Tab.Order.Audit,
group = "Auditable_Audit",
readOnly = true)
protected Date dateUpdated;
@Column(name = "UPDATED_BY")
@AdminPresentation(friendlyName = "Auditable_Updated_By", order = 4000,
tab = Presentation.Tab.Name.Audit, tabOrder = Presentation.Tab.Order.Audit,
group = "Auditable_Audit",
readOnly = true)
protected Long updatedBy;
public Date getDateCreated() {
return dateCreated;
}
public Long getCreatedBy() {
return createdBy;
}
public Date getDateUpdated() {
return dateUpdated;
}
public Long getUpdatedBy() {
return updatedBy;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
public void setDateUpdated(Date dateUpdated) {
this.dateUpdated = dateUpdated;
}
public void setUpdatedBy(Long updatedBy) {
this.updatedBy = updatedBy;
}
public static class Presentation {
public static class Tab {
public static class Name {
public static final String Audit = "Auditable_Tab";
}
public static class Order {
public static final int Audit = 99000;
}
}
public static class Group {
public static class Name {
public static final String Audit = "Auditable_Audit";
}
public static class Order {
public static final int Audit = 1000;
}
}
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_audit_Auditable.java
|
1,013 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_GIFTWRAP_ORDER_ITEM")
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements")
@AdminPresentationClass(friendlyName = "GiftWrapOrderItemImpl_giftWrapOrderItem")
public class GiftWrapOrderItemImpl extends DiscreteOrderItemImpl implements GiftWrapOrderItem {
private static final long serialVersionUID = 1L;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "giftWrapOrderItem", targetEntity = OrderItemImpl.class,
cascade = {CascadeType.MERGE, CascadeType.PERSIST})
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements")
@AdminPresentationCollection(friendlyName="OrderItemImpl_Price_Details",
tab = OrderItemImpl.Presentation.Tab.Name.Advanced, tabOrder = OrderItemImpl.Presentation.Tab.Order.Advanced)
protected List<OrderItem> wrappedItems = new ArrayList<OrderItem>();
public List<OrderItem> getWrappedItems() {
return wrappedItems;
}
public void setWrappedItems(List<OrderItem> wrappedItems) {
this.wrappedItems = wrappedItems;
}
@Override
public OrderItem clone() {
GiftWrapOrderItem orderItem = (GiftWrapOrderItem) super.clone();
if (wrappedItems != null) orderItem.getWrappedItems().addAll(wrappedItems);
return orderItem;
}
@Override
public int hashCode() {
final int prime = super.hashCode();
int result = super.hashCode();
result = prime * result + ((wrappedItems == null) ? 0 : wrappedItems.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
GiftWrapOrderItemImpl other = (GiftWrapOrderItemImpl) obj;
if (!super.equals(obj)) {
return false;
}
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (wrappedItems == null) {
if (other.wrappedItems != null)
return false;
} else if (!wrappedItems.equals(other.wrappedItems))
return false;
return true;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_GiftWrapOrderItemImpl.java
|
480 |
public class ProtoSecureChannelProcessor extends SecureChannelProcessor {
@Override
public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException, ServletException {
Assert.isTrue((invocation != null) && (config != null), "Nulls cannot be provided");
for (ConfigAttribute attribute : config) {
if (supports(attribute)) {
if (invocation.getHttpRequest().getHeader("X-Forwarded-Proto") != null
&& "https".equalsIgnoreCase(invocation.getHttpRequest().getHeader("X-Forwarded-Proto"))) {
return;
} else if (invocation.getHttpRequest().isSecure()) {
return;
} else {
getEntryPoint().commence(invocation.getRequest(), invocation.getResponse());
}
}
}
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_security_channel_ProtoSecureChannelProcessor.java
|
375 |
public class ODatabaseFlat extends ODatabaseRecordTx {
public ODatabaseFlat(String iURL) {
super(iURL, ORecordFlat.RECORD_TYPE);
}
@SuppressWarnings("unchecked")
@Override
public ORecordIteratorCluster<ORecordFlat> browseCluster(final String iClusterName) {
return super.browseCluster(iClusterName, ORecordFlat.class);
}
@Override
public ORecordIteratorCluster<ORecordFlat> browseCluster(String iClusterName, OClusterPosition startClusterPosition,
OClusterPosition endClusterPosition, boolean loadTombstones) {
return super.browseCluster(iClusterName, ORecordFlat.class, startClusterPosition, endClusterPosition, loadTombstones);
}
@SuppressWarnings("unchecked")
@Override
public ORecordFlat newInstance() {
return new ORecordFlat();
}
@Override
public ODatabaseRecord commit() {
try {
return super.commit();
} finally {
getTransaction().close();
}
}
@Override
public ODatabaseRecord rollback() {
try {
return super.rollback();
} finally {
getTransaction().close();
}
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_db_record_ODatabaseFlat.java
|
4 |
@Component("blCategoryCustomPersistenceHandler")
public class CategoryCustomPersistenceHandler extends CustomPersistenceHandlerAdapter {
private static final Log LOG = LogFactory.getLog(CategoryCustomPersistenceHandler.class);
@Override
public Boolean canHandleAdd(PersistencePackage persistencePackage) {
String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
String[] customCriteria = persistencePackage.getCustomCriteria();
return !ArrayUtils.isEmpty(customCriteria) && "addNewCategory".equals(customCriteria[0]) && Category.class.getName().equals(ceilingEntityFullyQualifiedClassname);
}
@Override
public Entity add(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {
Entity entity = persistencePackage.getEntity();
try {
PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
Category adminInstance = (Category) Class.forName(entity.getType()[0]).newInstance();
Map<String, FieldMetadata> adminProperties = helper.getSimpleMergedProperties(Category.class.getName(), persistencePerspective);
adminInstance = (Category) helper.createPopulatedInstance(adminInstance, entity, adminProperties, false);
CategoryXref categoryXref = new CategoryXrefImpl();
categoryXref.setCategory(adminInstance.getDefaultParentCategory());
categoryXref.setSubCategory(adminInstance);
if (adminInstance.getDefaultParentCategory() != null && !adminInstance.getAllParentCategoryXrefs().contains(categoryXref)) {
adminInstance.getAllParentCategoryXrefs().add(categoryXref);
}
adminInstance = (Category) dynamicEntityDao.merge(adminInstance);
return helper.getRecord(adminProperties, adminInstance, null, null);
} catch (Exception e) {
throw new ServiceException("Unable to add entity for " + entity.getType()[0], e);
}
}
protected Map<String, FieldMetadata> getMergedProperties(Class<?> ceilingEntityFullyQualifiedClass, DynamicEntityDao dynamicEntityDao, Boolean populateManyToOneFields, String[] includeManyToOneFields, String[] excludeManyToOneFields, String configurationKey) throws ClassNotFoundException, SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, NoSuchFieldException {
Class<?>[] entities = dynamicEntityDao.getAllPolymorphicEntitiesFromCeiling(ceilingEntityFullyQualifiedClass);
return dynamicEntityDao.getMergedProperties(
ceilingEntityFullyQualifiedClass.getName(),
entities,
null,
new String[]{},
new ForeignKey[]{},
MergedPropertyType.PRIMARY,
populateManyToOneFields,
includeManyToOneFields,
excludeManyToOneFields,
configurationKey,
""
);
}
}
| 0true
|
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_server_service_handler_CategoryCustomPersistenceHandler.java
|
158 |
private final Function<String, Locker> ASTYANAX_RECIPE_LOCKER_CREATOR = new Function<String, Locker>() {
@Override
public Locker apply(String lockerName) {
String expectedManagerName = "com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager";
String actualManagerName = storeManager.getClass().getCanonicalName();
// Require AstyanaxStoreManager
Preconditions.checkArgument(expectedManagerName.equals(actualManagerName),
"Astyanax Recipe locker is only supported with the Astyanax storage backend (configured:"
+ actualManagerName + " != required:" + expectedManagerName + ")");
try {
Class<?> c = storeManager.getClass();
Method method = c.getMethod("openLocker", String.class);
Object o = method.invoke(storeManager, lockerName);
return (Locker) o;
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Could not find method when configuring locking with Astyanax Recipes");
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Could not access method when configuring locking with Astyanax Recipes", e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException("Could not invoke method when configuring locking with Astyanax Recipes", e);
}
}
};
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_Backend.java
|
583 |
public class PaymentHostException extends PaymentException {
private static final long serialVersionUID = 1L;
public PaymentHostException() {
super();
}
public PaymentHostException(String message, Throwable cause) {
super(message, cause);
}
public PaymentHostException(String message) {
super(message);
}
public PaymentHostException(Throwable cause) {
super(cause);
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_vendor_service_exception_PaymentHostException.java
|
742 |
public class ProductOptionValidationType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, ProductOptionValidationType> TYPES = new LinkedHashMap<String, ProductOptionValidationType>();
public static final ProductOptionValidationType REGEX = new ProductOptionValidationType("REGEX", "Regular Expression");
public static ProductOptionValidationType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public ProductOptionValidationType() {
//do nothing
}
public ProductOptionValidationType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
@Override
public String getType() {
return type;
}
@Override
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProductOptionValidationType other = (ProductOptionValidationType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_service_type_ProductOptionValidationType.java
|
2,608 |
= new ConstructorFunction<Address, ConnectionMonitor>() {
public ConnectionMonitor createNew(Address endpoint) {
return new ConnectionMonitor(TcpIpConnectionManager.this, endpoint);
}
};
| 1no label
|
hazelcast_src_main_java_com_hazelcast_nio_TcpIpConnectionManager.java
|
1,004 |
public abstract class TransportSingleCustomOperationAction<Request extends SingleCustomOperationRequest, Response extends ActionResponse> extends TransportAction<Request, Response> {
protected final ClusterService clusterService;
protected final TransportService transportService;
final String transportAction;
final String transportShardAction;
final String executor;
protected TransportSingleCustomOperationAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService) {
super(settings, threadPool);
this.clusterService = clusterService;
this.transportService = transportService;
this.transportAction = transportAction();
this.transportShardAction = transportAction() + "/s";
this.executor = executor();
transportService.registerHandler(transportAction, new TransportHandler());
transportService.registerHandler(transportShardAction, new ShardTransportHandler());
}
@Override
protected void doExecute(Request request, ActionListener<Response> listener) {
new AsyncSingleAction(request, listener).start();
}
protected abstract String transportAction();
protected abstract String executor();
/**
* Can return null to execute on this local node.
*/
protected abstract ShardsIterator shards(ClusterState state, Request request);
protected abstract Response shardOperation(Request request, int shardId) throws ElasticsearchException;
protected abstract Request newRequest();
protected abstract Response newResponse();
protected abstract ClusterBlockException checkGlobalBlock(ClusterState state, Request request);
protected abstract ClusterBlockException checkRequestBlock(ClusterState state, Request request);
private class AsyncSingleAction {
private final ActionListener<Response> listener;
private final ShardsIterator shardsIt;
private final Request request;
private final DiscoveryNodes nodes;
private AsyncSingleAction(Request request, ActionListener<Response> listener) {
this.request = request;
this.listener = listener;
ClusterState clusterState = clusterService.state();
nodes = clusterState.nodes();
ClusterBlockException blockException = checkGlobalBlock(clusterState, request);
if (blockException != null) {
throw blockException;
}
blockException = checkRequestBlock(clusterState, request);
if (blockException != null) {
throw blockException;
}
this.shardsIt = shards(clusterState, request);
}
public void start() {
performFirst();
}
private void onFailure(ShardRouting shardRouting, Throwable e) {
if (logger.isTraceEnabled() && e != null) {
logger.trace(shardRouting.shortSummary() + ": Failed to execute [" + request + "]", e);
}
perform(e);
}
/**
* First get should try and use a shard that exists on a local node for better performance
*/
private void performFirst() {
if (shardsIt == null) {
// just execute it on the local node
if (request.operationThreaded()) {
request.beforeLocalFork();
threadPool.executor(executor()).execute(new Runnable() {
@Override
public void run() {
try {
Response response = shardOperation(request, -1);
listener.onResponse(response);
} catch (Throwable e) {
onFailure(null, e);
}
}
});
return;
} else {
try {
final Response response = shardOperation(request, -1);
listener.onResponse(response);
return;
} catch (Throwable e) {
onFailure(null, e);
}
}
return;
}
if (request.preferLocalShard()) {
boolean foundLocal = false;
ShardRouting shardX;
while ((shardX = shardsIt.nextOrNull()) != null) {
final ShardRouting shard = shardX;
if (shard.currentNodeId().equals(nodes.localNodeId())) {
foundLocal = true;
if (request.operationThreaded()) {
request.beforeLocalFork();
threadPool.executor(executor()).execute(new Runnable() {
@Override
public void run() {
try {
Response response = shardOperation(request, shard.id());
listener.onResponse(response);
} catch (Throwable e) {
shardsIt.reset();
onFailure(shard, e);
}
}
});
return;
} else {
try {
final Response response = shardOperation(request, shard.id());
listener.onResponse(response);
return;
} catch (Throwable e) {
shardsIt.reset();
onFailure(shard, e);
}
}
}
}
if (!foundLocal) {
// no local node get, go remote
shardsIt.reset();
perform(null);
}
} else {
perform(null);
}
}
private void perform(final Throwable lastException) {
final ShardRouting shard = shardsIt == null ? null : shardsIt.nextOrNull();
if (shard == null) {
Throwable failure = lastException;
if (failure == null) {
failure = new NoShardAvailableActionException(null, "No shard available for [" + request + "]");
} else {
if (logger.isDebugEnabled()) {
logger.debug("failed to execute [" + request + "]", failure);
}
}
listener.onFailure(failure);
} else {
if (shard.currentNodeId().equals(nodes.localNodeId())) {
// we don't prefer local shard, so try and do it here
if (!request.preferLocalShard()) {
try {
if (request.operationThreaded()) {
request.beforeLocalFork();
threadPool.executor(executor).execute(new Runnable() {
@Override
public void run() {
try {
Response response = shardOperation(request, shard.id());
listener.onResponse(response);
} catch (Throwable e) {
onFailure(shard, e);
}
}
});
} else {
final Response response = shardOperation(request, shard.id());
listener.onResponse(response);
}
} catch (Throwable e) {
onFailure(shard, e);
}
} else {
perform(lastException);
}
} else {
DiscoveryNode node = nodes.get(shard.currentNodeId());
transportService.sendRequest(node, transportShardAction, new ShardSingleOperationRequest(request, shard.id()), new BaseTransportResponseHandler<Response>() {
@Override
public Response newInstance() {
return newResponse();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void handleResponse(final Response response) {
listener.onResponse(response);
}
@Override
public void handleException(TransportException exp) {
onFailure(shard, exp);
}
});
}
}
}
}
private class TransportHandler extends BaseTransportRequestHandler<Request> {
@Override
public Request newInstance() {
return newRequest();
}
@Override
public void messageReceived(Request request, final TransportChannel channel) throws Exception {
// no need to have a threaded listener since we just send back a response
request.listenerThreaded(false);
// if we have a local operation, execute it on a thread since we don't spawn
request.operationThreaded(true);
execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response result) {
try {
channel.sendResponse(result);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send response for get", e1);
}
}
});
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
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);
}
}
protected class ShardSingleOperationRequest extends TransportRequest {
private Request request;
private int shardId;
ShardSingleOperationRequest() {
}
public ShardSingleOperationRequest(Request request, int shardId) {
super(request);
this.request = request;
this.shardId = shardId;
}
public Request request() {
return request;
}
public int shardId() {
return shardId;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
request = newRequest();
request.readFrom(in);
shardId = in.readVInt();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
request.writeTo(out);
out.writeVInt(shardId);
}
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_single_custom_TransportSingleCustomOperationAction.java
|
379 |
public class ClusterRerouteAction extends ClusterAction<ClusterRerouteRequest, ClusterRerouteResponse, ClusterRerouteRequestBuilder> {
public static final ClusterRerouteAction INSTANCE = new ClusterRerouteAction();
public static final String NAME = "cluster/reroute";
private ClusterRerouteAction() {
super(NAME);
}
@Override
public ClusterRerouteResponse newResponse() {
return new ClusterRerouteResponse();
}
@Override
public ClusterRerouteRequestBuilder newRequestBuilder(ClusterAdminClient client) {
return new ClusterRerouteRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_reroute_ClusterRerouteAction.java
|
368 |
public class DynamicTranslationProvider {
/**
* If translations are enabled, this method will look for a translation for the specified field. If translations are
* disabled or if this particular field did not have a translation, it will return back the defaultValue.
*
* @param obj
* @param field
* @param defaultValue
* @return the translated value
*/
public static String getValue(Object obj, String field, final String defaultValue) {
String valueToReturn = defaultValue;
if (TranslationConsiderationContext.hasTranslation()) {
TranslationService translationService = TranslationConsiderationContext.getTranslationService();
Locale locale = BroadleafRequestContext.getBroadleafRequestContext().getJavaLocale();
String translatedValue = translationService.getTranslatedValue(obj, field, locale);
if (StringUtils.isNotBlank(translatedValue)) {
valueToReturn = translatedValue;
}
}
return valueToReturn;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_i18n_service_DynamicTranslationProvider.java
|
587 |
public interface PaymentResponse extends Serializable {
public boolean isErrorDetected();
public void setErrorDetected(boolean isErrorDetected);
public String getErrorCode();
public void setErrorCode(String errorCode);
public String getErrorText();
public void setErrorText(String errorText);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_vendor_service_message_PaymentResponse.java
|
435 |
static final class Fields {
static final XContentBuilderString SHARDS = new XContentBuilderString("shards");
static final XContentBuilderString TOTAL = new XContentBuilderString("total");
static final XContentBuilderString PRIMARIES = new XContentBuilderString("primaries");
static final XContentBuilderString REPLICATION = new XContentBuilderString("replication");
static final XContentBuilderString MIN = new XContentBuilderString("min");
static final XContentBuilderString MAX = new XContentBuilderString("max");
static final XContentBuilderString AVG = new XContentBuilderString("avg");
static final XContentBuilderString INDEX = new XContentBuilderString("index");
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsIndices.java
|
1,208 |
longIntMap = build(type, limit, smartSize, availableProcessors, new Recycler.C<LongIntOpenHashMap>() {
@Override
public LongIntOpenHashMap newInstance(int sizing) {
return new LongIntOpenHashMap(size(sizing));
}
@Override
public void clear(LongIntOpenHashMap value) {
value.clear();
}
});
| 0true
|
src_main_java_org_elasticsearch_cache_recycler_CacheRecycler.java
|
4,922 |
public class RestMultiGetAction extends BaseRestHandler {
private final boolean allowExplicitIndex;
@Inject
public RestMultiGetAction(Settings settings, Client client, RestController controller) {
super(settings, client);
controller.registerHandler(GET, "/_mget", this);
controller.registerHandler(POST, "/_mget", this);
controller.registerHandler(GET, "/{index}/_mget", this);
controller.registerHandler(POST, "/{index}/_mget", this);
controller.registerHandler(GET, "/{index}/{type}/_mget", this);
controller.registerHandler(POST, "/{index}/{type}/_mget", this);
this.allowExplicitIndex = settings.getAsBoolean("rest.action.multi.allow_explicit_index", true);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
MultiGetRequest multiGetRequest = new MultiGetRequest();
multiGetRequest.listenerThreaded(false);
multiGetRequest.refresh(request.paramAsBoolean("refresh", multiGetRequest.refresh()));
multiGetRequest.preference(request.param("preference"));
multiGetRequest.realtime(request.paramAsBoolean("realtime", null));
String[] sFields = null;
String sField = request.param("fields");
if (sField != null) {
sFields = Strings.splitStringByCommaToArray(sField);
}
FetchSourceContext defaultFetchSource = FetchSourceContext.parseFromRestRequest(request);
try {
multiGetRequest.add(request.param("index"), request.param("type"), sFields, defaultFetchSource, request.param("routing"), RestActions.getRestContent(request), allowExplicitIndex);
} catch (Exception e) {
try {
XContentBuilder builder = restContentBuilder(request);
channel.sendResponse(new XContentRestResponse(request, BAD_REQUEST, builder.startObject().field("error", e.getMessage()).endObject()));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
return;
}
client.multiGet(multiGetRequest, new ActionListener<MultiGetResponse>() {
@Override
public void onResponse(MultiGetResponse response) {
try {
XContentBuilder builder = restContentBuilder(request);
response.toXContent(builder, request);
channel.sendResponse(new XContentRestResponse(request, OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new XContentThrowableRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
}
}
| 1no label
|
src_main_java_org_elasticsearch_rest_action_get_RestMultiGetAction.java
|
2,080 |
public class PartitionWideEntryOperation extends AbstractMapOperation
implements BackupAwareOperation, PartitionAwareOperation {
private static final EntryEventType __NO_NEED_TO_FIRE_EVENT = null;
EntryProcessor entryProcessor;
MapEntrySet response;
public PartitionWideEntryOperation(String name, EntryProcessor entryProcessor) {
super(name);
this.entryProcessor = entryProcessor;
}
public PartitionWideEntryOperation() {
}
public void innerBeforeRun() {
final ManagedContext managedContext = getNodeEngine().getSerializationService().getManagedContext();
managedContext.initialize(entryProcessor);
}
public void run() {
response = new MapEntrySet();
MapEntrySimple entry;
final RecordStore recordStore = mapService.getRecordStore(getPartitionId(), name);
final LocalMapStatsImpl mapStats = mapService.getLocalMapStatsImpl(name);
final Map<Data, Record> records = recordStore.getReadonlyRecordMap();
for (final Map.Entry<Data, Record> recordEntry : records.entrySet()) {
final long start = System.currentTimeMillis();
final Data dataKey = recordEntry.getKey();
final Record record = recordEntry.getValue();
final Object valueBeforeProcess = record.getValue();
final Object valueBeforeProcessObject = mapService.toObject(valueBeforeProcess);
Object objectKey = mapService.toObject(record.getKey());
if (getPredicate() != null) {
final SerializationService ss = getNodeEngine().getSerializationService();
QueryEntry queryEntry = new QueryEntry(ss, dataKey, objectKey, valueBeforeProcessObject);
if (!getPredicate().apply(queryEntry)) {
continue;
}
}
entry = new MapEntrySimple(objectKey, valueBeforeProcessObject);
final Object result = entryProcessor.process(entry);
final Object valueAfterProcess = entry.getValue();
Data dataValue = null;
if (result != null) {
dataValue = mapService.toData(result);
response.add(new AbstractMap.SimpleImmutableEntry<Data, Data>(dataKey, dataValue));
}
EntryEventType eventType;
if (valueAfterProcess == null) {
recordStore.remove(dataKey);
mapStats.incrementRemoves(getLatencyFrom(start));
eventType = EntryEventType.REMOVED;
} else {
if (valueBeforeProcessObject == null) {
mapStats.incrementPuts(getLatencyFrom(start));
eventType = EntryEventType.ADDED;
}
// take this case as a read so no need to fire an event.
else if (!entry.isModified()) {
mapStats.incrementGets(getLatencyFrom(start));
eventType = __NO_NEED_TO_FIRE_EVENT;
} else {
mapStats.incrementPuts(getLatencyFrom(start));
eventType = EntryEventType.UPDATED;
}
// todo if this is a read only operation, record access operations should be done.
if (eventType != __NO_NEED_TO_FIRE_EVENT) {
recordStore.put(new AbstractMap.SimpleImmutableEntry<Data, Object>(dataKey, valueAfterProcess));
}
}
if (eventType != __NO_NEED_TO_FIRE_EVENT) {
final Data oldValue = mapService.toData(valueBeforeProcess);
final Data value = mapService.toData(valueAfterProcess);
mapService.publishEvent(getCallerAddress(), name, eventType, dataKey, oldValue, value);
if (mapService.isNearCacheAndInvalidationEnabled(name)) {
mapService.invalidateAllNearCaches(name, dataKey);
}
if (mapContainer.getWanReplicationPublisher() != null && mapContainer.getWanMergePolicy() != null) {
if (EntryEventType.REMOVED.equals(eventType)) {
mapService.publishWanReplicationRemove(name, dataKey, Clock.currentTimeMillis());
} else {
Record r = recordStore.getRecord(dataKey);
final SimpleEntryView entryView = mapService.createSimpleEntryView(dataKey, dataValue, r);
mapService.publishWanReplicationUpdate(name, entryView);
}
}
}
}
}
@Override
public boolean returnsResponse() {
return true;
}
@Override
public Object getResponse() {
return response;
}
protected Predicate getPredicate() {
return null;
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
entryProcessor = in.readObject();
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeObject(entryProcessor);
}
@Override
public String toString() {
return "PartitionWideEntryOperation{}";
}
public boolean shouldBackup() {
return entryProcessor.getBackupProcessor() != null;
}
public int getSyncBackupCount() {
return 0;
}
public int getAsyncBackupCount() {
return mapContainer.getTotalBackupCount();
}
@Override
public Operation getBackupOperation() {
EntryBackupProcessor backupProcessor = entryProcessor.getBackupProcessor();
return backupProcessor != null ? new PartitionWideEntryBackupOperation(name, backupProcessor) : null;
}
private long getLatencyFrom(long begin) {
return Clock.currentTimeMillis() - begin;
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_map_operation_PartitionWideEntryOperation.java
|
93 |
interface ClientExceptionConverter {
Object convert(Throwable t);
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_client_ClientExceptionConverter.java
|
324 |
public class MergeXmlConfigResource {
private static final Log LOG = LogFactory.getLog(MergeXmlConfigResource.class);
public Resource getMergedConfigResource(ResourceInputStream[] sources) throws BeansException {
Resource configResource = null;
ResourceInputStream merged = null;
try {
merged = merge(sources);
//read the final stream into a byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
boolean eof = false;
while (!eof) {
int temp = merged.read();
if (temp == -1) {
eof = true;
} else {
baos.write(temp);
}
}
configResource = new ByteArrayResource(baos.toByteArray());
if (LOG.isDebugEnabled()) {
LOG.debug("Merged config: \n" + serialize(configResource));
}
} catch (MergeException e) {
throw new FatalBeanException("Unable to merge source and patch locations", e);
} catch (MergeManagerSetupException e) {
throw new FatalBeanException("Unable to merge source and patch locations", e);
} catch (IOException e) {
throw new FatalBeanException("Unable to merge source and patch locations", e);
} finally {
if (merged != null) {
try{ merged.close(); } catch (Throwable e) {
LOG.error("Unable to merge source and patch locations", e);
}
}
}
return configResource;
}
protected ResourceInputStream merge(ResourceInputStream[] sources) throws MergeException, MergeManagerSetupException {
if (sources.length == 1) return sources[0];
ResourceInputStream response = null;
ResourceInputStream[] pair = new ResourceInputStream[2];
pair[0] = sources[0];
for (int j=1;j<sources.length;j++){
pair[1] = sources[j];
response = mergeItems(pair[0], pair[1]);
try{
pair[0].close();
} catch (Throwable e) {
LOG.error("Unable to merge source and patch locations", e);
}
try{
pair[1].close();
} catch (Throwable e) {
LOG.error("Unable to merge source and patch locations", e);
}
pair[0] = response;
}
return response;
}
protected ResourceInputStream mergeItems(ResourceInputStream sourceLocationFirst, ResourceInputStream sourceLocationSecond) throws MergeException, MergeManagerSetupException {
ResourceInputStream response = new MergeManager().merge(sourceLocationFirst, sourceLocationSecond);
return response;
}
public String serialize(Resource resource) {
String response = "";
try {
response = serialize(resource.getInputStream());
} catch (IOException e) {
LOG.error("Unable to merge source and patch locations", e);
}
return response;
}
public String serialize(InputStream in) {
InputStreamReader reader = null;
int temp;
StringBuilder item = new StringBuilder();
boolean eof = false;
try {
reader = new InputStreamReader(in);
while (!eof) {
temp = reader.read();
if (temp == -1) {
eof = true;
} else {
item.append((char) temp);
}
}
} catch (IOException e) {
LOG.error("Unable to merge source and patch locations", e);
} finally {
if (reader != null) {
try{ reader.close(); } catch (Throwable e) {
LOG.error("Unable to merge source and patch locations", e);
}
}
}
return item.toString();
}
protected byte[] buildArrayFromStream(InputStream source) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
boolean eof = false;
try{
while (!eof) {
int temp = source.read();
if (temp == -1) {
eof = true;
} else {
baos.write(temp);
}
}
} finally {
try{ source.close(); } catch (Throwable e) {
LOG.error("Unable to merge source and patch locations", e);
}
}
return baos.toByteArray();
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_MergeXmlConfigResource.java
|
338 |
static class Deal implements Serializable {
Integer id;
Deal(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java
|
1,420 |
public class TitanHBaseRecordReader extends RecordReader<NullWritable, FaunusVertex> {
private TableRecordReader reader;
private TitanHBaseHadoopGraph graph;
private FaunusVertexQueryFilter vertexQuery;
private Configuration configuration;
private FaunusVertex vertex;
private final byte[] edgestoreFamilyBytes;
public TitanHBaseRecordReader(final TitanHBaseHadoopGraph graph, final FaunusVertexQueryFilter vertexQuery, final TableRecordReader reader, final byte[] edgestoreFamilyBytes) {
this.graph = graph;
this.vertexQuery = vertexQuery;
this.reader = reader;
this.edgestoreFamilyBytes = edgestoreFamilyBytes;
}
@Override
public void initialize(final InputSplit inputSplit, final TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
reader.initialize(inputSplit, taskAttemptContext);
configuration = ModifiableHadoopConfiguration.of(DEFAULT_COMPAT.getContextConfiguration(taskAttemptContext));
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
while (reader.nextKeyValue()) {
final FaunusVertex temp = graph.readHadoopVertex(
configuration,
reader.getCurrentKey().copyBytes(),
reader.getCurrentValue().getMap().get(edgestoreFamilyBytes));
if (null != temp) {
vertex = temp;
vertexQuery.filterRelationsOf(vertex);
return true;
}
}
return false;
}
@Override
public NullWritable getCurrentKey() throws IOException, InterruptedException {
return NullWritable.get();
}
@Override
public FaunusVertex getCurrentValue() throws IOException, InterruptedException {
return this.vertex;
}
@Override
public void close() throws IOException {
this.graph.close();
this.reader.close();
}
@Override
public float getProgress() {
return this.reader.getProgress();
}
}
| 1no label
|
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_formats_hbase_TitanHBaseRecordReader.java
|
5,807 |
private static class CustomWeightedSpanTermExtractor extends WeightedSpanTermExtractor {
public CustomWeightedSpanTermExtractor() {
super();
}
public CustomWeightedSpanTermExtractor(String defaultField) {
super(defaultField);
}
@Override
protected void extractUnknownQuery(Query query,
Map<String, WeightedSpanTerm> terms) throws IOException {
if (query instanceof FunctionScoreQuery) {
query = ((FunctionScoreQuery) query).getSubQuery();
extract(query, terms);
} else if (query instanceof FiltersFunctionScoreQuery) {
query = ((FiltersFunctionScoreQuery) query).getSubQuery();
extract(query, terms);
} else if (query instanceof XFilteredQuery) {
query = ((XFilteredQuery) query).getQuery();
extract(query, terms);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_highlight_CustomQueryScorer.java
|
465 |
public interface SimpleRule extends Serializable {
/**
* The rule in the form of an MVEL expression
*
* @return the rule as an MVEL string
*/
@Nonnull
public String getMatchRule();
/**
* Sets the match rule used to test this item.
*
* @param matchRule the rule as an MVEL string
*/
public void setMatchRule(@Nonnull String matchRule);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_rule_SimpleRule.java
|
707 |
constructors[TXN_SET_SIZE] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new TxnSetSizeRequest();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java
|
201 |
public abstract class ClientAbstractIOSelector extends Thread implements IOSelector {
private static final int TIMEOUT = 3;
protected final ILogger logger;
protected final Queue<Runnable> selectorQueue = new ConcurrentLinkedQueue<Runnable>();
protected final int waitTime;
protected final Selector selector;
protected boolean live = true;
private final CountDownLatch shutdownLatch = new CountDownLatch(1);
protected ClientAbstractIOSelector(ThreadGroup threadGroup, String threadName) {
super(threadGroup, threadName);
this.logger = Logger.getLogger(getClass().getName());
this.waitTime = 5000;
Selector selectorTemp = null;
try {
selectorTemp = Selector.open();
} catch (final IOException e) {
handleSelectorException(e);
}
this.selector = selectorTemp;
}
public Selector getSelector() {
return selector;
}
public void addTask(Runnable runnable) {
selectorQueue.add(runnable);
}
public void wakeup() {
selector.wakeup();
}
public void shutdown() {
selectorQueue.clear();
try {
addTask(new Runnable() {
public void run() {
live = false;
shutdownLatch.countDown();
}
});
interrupt();
} catch (Throwable ignored) {
}
}
public void awaitShutdown() {
try {
shutdownLatch.await(TIMEOUT, TimeUnit.SECONDS);
} catch (InterruptedException ignored) {
}
}
private void processSelectionQueue() {
while (live) {
final Runnable runnable = selectorQueue.poll();
if (runnable == null) {
return;
}
runnable.run();
}
}
public final void run() {
try {
//noinspection WhileLoopSpinsOnField
while (live) {
processSelectionQueue();
if (!live || isInterrupted()) {
if (logger.isFinestEnabled()) {
logger.finest(getName() + " is interrupted!");
}
live = false;
return;
}
int selectedKeyCount;
try {
selectedKeyCount = selector.select(waitTime);
} catch (Throwable e) {
logger.warning(e.toString());
continue;
}
if (selectedKeyCount == 0) {
continue;
}
final Set<SelectionKey> setSelectedKeys = selector.selectedKeys();
final Iterator<SelectionKey> it = setSelectedKeys.iterator();
while (it.hasNext()) {
final SelectionKey sk = it.next();
try {
it.remove();
handleSelectionKey(sk);
} catch (Throwable e) {
handleSelectorException(e);
}
}
}
} catch (Throwable e) {
logger.warning("Unhandled exception in " + getName(), e);
} finally {
try {
if (logger.isFinestEnabled()) {
logger.finest("Closing selector " + getName());
}
selector.close();
} catch (final Exception ignored) {
}
}
}
protected abstract void handleSelectionKey(SelectionKey sk);
private void handleSelectorException(final Throwable e) {
String msg = "Selector exception at " + getName() + ", cause= " + e.toString();
logger.warning(msg, e);
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientAbstractIOSelector.java
|
5,400 |
@SuppressWarnings({"unchecked", "ForLoopReplaceableByForEach"})
public class AggregationContext implements ReaderContextAware, ScorerAware {
private final SearchContext searchContext;
private ObjectObjectOpenHashMap<String, FieldDataSource>[] perDepthFieldDataSources = new ObjectObjectOpenHashMap[4];
private List<ReaderContextAware> readerAwares = new ArrayList<ReaderContextAware>();
private List<ScorerAware> scorerAwares = new ArrayList<ScorerAware>();
private AtomicReaderContext reader;
private Scorer scorer;
public AggregationContext(SearchContext searchContext) {
this.searchContext = searchContext;
}
public SearchContext searchContext() {
return searchContext;
}
public CacheRecycler cacheRecycler() {
return searchContext.cacheRecycler();
}
public PageCacheRecycler pageCacheRecycler() {
return searchContext.pageCacheRecycler();
}
public AtomicReaderContext currentReader() {
return reader;
}
public Scorer currentScorer() {
return scorer;
}
public void setNextReader(AtomicReaderContext reader) {
this.reader = reader;
for (ReaderContextAware aware : readerAwares) {
aware.setNextReader(reader);
}
}
public void setScorer(Scorer scorer) {
this.scorer = scorer;
for (ScorerAware scorerAware : scorerAwares) {
scorerAware.setScorer(scorer);
}
}
/** Get a value source given its configuration and the depth of the aggregator in the aggregation tree. */
public <VS extends ValuesSource> VS valuesSource(ValuesSourceConfig<VS> config, int depth) {
assert config.valid() : "value source config is invalid - must have either a field context or a script or marked as unmapped";
assert !config.unmapped : "value source should not be created for unmapped fields";
if (perDepthFieldDataSources.length <= depth) {
perDepthFieldDataSources = Arrays.copyOf(perDepthFieldDataSources, ArrayUtil.oversize(1 + depth, RamUsageEstimator.NUM_BYTES_OBJECT_REF));
}
if (perDepthFieldDataSources[depth] == null) {
perDepthFieldDataSources[depth] = new ObjectObjectOpenHashMap<String, FieldDataSource>();
}
final ObjectObjectOpenHashMap<String, FieldDataSource> fieldDataSources = perDepthFieldDataSources[depth];
if (config.fieldContext == null) {
if (NumericValuesSource.class.isAssignableFrom(config.valueSourceType)) {
return (VS) numericScript(config);
}
if (BytesValuesSource.class.isAssignableFrom(config.valueSourceType)) {
return (VS) bytesScript(config);
}
throw new AggregationExecutionException("value source of type [" + config.valueSourceType.getSimpleName() + "] is not supported by scripts");
}
if (NumericValuesSource.class.isAssignableFrom(config.valueSourceType)) {
return (VS) numericField(fieldDataSources, config);
}
if (GeoPointValuesSource.class.isAssignableFrom(config.valueSourceType)) {
return (VS) geoPointField(fieldDataSources, config);
}
// falling back to bytes values
return (VS) bytesField(fieldDataSources, config);
}
private NumericValuesSource numericScript(ValuesSourceConfig<?> config) {
setScorerIfNeeded(config.script);
setReaderIfNeeded(config.script);
scorerAwares.add(config.script);
readerAwares.add(config.script);
FieldDataSource.Numeric source = new FieldDataSource.Numeric.Script(config.script, config.scriptValueType);
if (config.ensureUnique || config.ensureSorted) {
source = new FieldDataSource.Numeric.SortedAndUnique(source);
readerAwares.add((ReaderContextAware) source);
}
return new NumericValuesSource(source, config.formatter(), config.parser());
}
private NumericValuesSource numericField(ObjectObjectOpenHashMap<String, FieldDataSource> fieldDataSources, ValuesSourceConfig<?> config) {
FieldDataSource.Numeric dataSource = (FieldDataSource.Numeric) fieldDataSources.get(config.fieldContext.field());
if (dataSource == null) {
FieldDataSource.MetaData metaData = FieldDataSource.MetaData.load(config.fieldContext.indexFieldData(), searchContext);
dataSource = new FieldDataSource.Numeric.FieldData((IndexNumericFieldData<?>) config.fieldContext.indexFieldData(), metaData);
setReaderIfNeeded((ReaderContextAware) dataSource);
readerAwares.add((ReaderContextAware) dataSource);
fieldDataSources.put(config.fieldContext.field(), dataSource);
}
if (config.script != null) {
setScorerIfNeeded(config.script);
setReaderIfNeeded(config.script);
scorerAwares.add(config.script);
readerAwares.add(config.script);
dataSource = new FieldDataSource.Numeric.WithScript(dataSource, config.script);
if (config.ensureUnique || config.ensureSorted) {
dataSource = new FieldDataSource.Numeric.SortedAndUnique(dataSource);
readerAwares.add((ReaderContextAware) dataSource);
}
}
if (config.needsHashes) {
dataSource.setNeedsHashes(true);
}
return new NumericValuesSource(dataSource, config.formatter(), config.parser());
}
private ValuesSource bytesField(ObjectObjectOpenHashMap<String, FieldDataSource> fieldDataSources, ValuesSourceConfig<?> config) {
FieldDataSource dataSource = fieldDataSources.get(config.fieldContext.field());
if (dataSource == null) {
final IndexFieldData<?> indexFieldData = config.fieldContext.indexFieldData();
FieldDataSource.MetaData metaData = FieldDataSource.MetaData.load(config.fieldContext.indexFieldData(), searchContext);
if (indexFieldData instanceof IndexFieldData.WithOrdinals) {
dataSource = new FieldDataSource.Bytes.WithOrdinals.FieldData((IndexFieldData.WithOrdinals) indexFieldData, metaData);
} else {
dataSource = new FieldDataSource.Bytes.FieldData(indexFieldData, metaData);
}
setReaderIfNeeded((ReaderContextAware) dataSource);
readerAwares.add((ReaderContextAware) dataSource);
fieldDataSources.put(config.fieldContext.field(), dataSource);
}
if (config.script != null) {
setScorerIfNeeded(config.script);
setReaderIfNeeded(config.script);
scorerAwares.add(config.script);
readerAwares.add(config.script);
dataSource = new FieldDataSource.WithScript(dataSource, config.script);
}
// Even in case we wrap field data, we might still need to wrap for sorting, because the wrapped field data might be
// eg. a numeric field data that doesn't sort according to the byte order. However field data values are unique so no
// need to wrap for uniqueness
if ((config.ensureUnique && !dataSource.metaData().uniqueness().unique()) || config.ensureSorted) {
dataSource = new FieldDataSource.Bytes.SortedAndUnique(dataSource);
readerAwares.add((ReaderContextAware) dataSource);
}
if (config.needsHashes) { // the data source needs hash if at least one consumer needs hashes
dataSource.setNeedsHashes(true);
}
if (dataSource instanceof FieldDataSource.Bytes.WithOrdinals) {
return new BytesValuesSource.WithOrdinals((FieldDataSource.Bytes.WithOrdinals) dataSource);
} else {
return new BytesValuesSource(dataSource);
}
}
private BytesValuesSource bytesScript(ValuesSourceConfig<?> config) {
setScorerIfNeeded(config.script);
setReaderIfNeeded(config.script);
scorerAwares.add(config.script);
readerAwares.add(config.script);
FieldDataSource.Bytes source = new FieldDataSource.Bytes.Script(config.script);
if (config.ensureUnique || config.ensureSorted) {
source = new FieldDataSource.Bytes.SortedAndUnique(source);
readerAwares.add((ReaderContextAware) source);
}
return new BytesValuesSource(source);
}
private GeoPointValuesSource geoPointField(ObjectObjectOpenHashMap<String, FieldDataSource> fieldDataSources, ValuesSourceConfig<?> config) {
FieldDataSource.GeoPoint dataSource = (FieldDataSource.GeoPoint) fieldDataSources.get(config.fieldContext.field());
if (dataSource == null) {
FieldDataSource.MetaData metaData = FieldDataSource.MetaData.load(config.fieldContext.indexFieldData(), searchContext);
dataSource = new FieldDataSource.GeoPoint((IndexGeoPointFieldData<?>) config.fieldContext.indexFieldData(), metaData);
setReaderIfNeeded(dataSource);
readerAwares.add(dataSource);
fieldDataSources.put(config.fieldContext.field(), dataSource);
}
if (config.needsHashes) {
dataSource.setNeedsHashes(true);
}
return new GeoPointValuesSource(dataSource);
}
public void registerReaderContextAware(ReaderContextAware readerContextAware) {
setReaderIfNeeded(readerContextAware);
readerAwares.add(readerContextAware);
}
public void registerScorerAware(ScorerAware scorerAware) {
setScorerIfNeeded(scorerAware);
scorerAwares.add(scorerAware);
}
private void setReaderIfNeeded(ReaderContextAware readerAware) {
if (reader != null) {
readerAware.setNextReader(reader);
}
}
private void setScorerIfNeeded(ScorerAware scorerAware) {
if (scorer != null) {
scorerAware.setScorer(scorer);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_aggregations_support_AggregationContext.java
|
419 |
public final class ClientMapProxy<K, V> extends ClientProxy implements IMap<K, V> {
private final String name;
private volatile ClientNearCache<Data> nearCache;
private final AtomicBoolean nearCacheInitialized = new AtomicBoolean();
public ClientMapProxy(String instanceName, String serviceName, String name) {
super(instanceName, serviceName, name);
this.name = name;
}
@Override
public boolean containsKey(Object key) {
initNearCache();
final Data keyData = toData(key);
if (nearCache != null) {
Object cached = nearCache.get(keyData);
if (cached != null) {
if (cached.equals(ClientNearCache.NULL_OBJECT)) {
return false;
}
return true;
}
}
MapContainsKeyRequest request = new MapContainsKeyRequest(name, keyData);
Boolean result = invoke(request, keyData);
return result;
}
@Override
public boolean containsValue(Object value) {
Data valueData = toData(value);
MapContainsValueRequest request = new MapContainsValueRequest(name, valueData);
Boolean result = invoke(request);
return result;
}
@Override
public V get(Object key) {
initNearCache();
final Data keyData = toData(key);
if (nearCache != null) {
Object cached = nearCache.get(keyData);
if (cached != null) {
if (cached.equals(ClientNearCache.NULL_OBJECT)) {
return null;
}
return (V) cached;
}
}
MapGetRequest request = new MapGetRequest(name, keyData);
final V result = invoke(request, keyData);
if (nearCache != null) {
nearCache.put(keyData, result);
}
return result;
}
@Override
public V put(K key, V value) {
return put(key, value, -1, null);
}
@Override
public V remove(Object key) {
final Data keyData = toData(key);
invalidateNearCache(keyData);
MapRemoveRequest request = new MapRemoveRequest(name, keyData, ThreadUtil.getThreadId());
return invoke(request, keyData);
}
@Override
public boolean remove(Object key, Object value) {
final Data keyData = toData(key);
final Data valueData = toData(value);
invalidateNearCache(keyData);
MapRemoveIfSameRequest request = new MapRemoveIfSameRequest(name, keyData, valueData, ThreadUtil.getThreadId());
Boolean result = invoke(request, keyData);
return result;
}
@Override
public void delete(Object key) {
final Data keyData = toData(key);
invalidateNearCache(keyData);
MapDeleteRequest request = new MapDeleteRequest(name, keyData, ThreadUtil.getThreadId());
invoke(request, keyData);
}
@Override
public void flush() {
MapFlushRequest request = new MapFlushRequest(name);
invoke(request);
}
@Override
public Future<V> getAsync(final K key) {
initNearCache();
final Data keyData = toData(key);
if (nearCache != null) {
Object cached = nearCache.get(keyData);
if (cached != null && !ClientNearCache.NULL_OBJECT.equals(cached)) {
return new CompletedFuture(getContext().getSerializationService(),
cached, getContext().getExecutionService().getAsyncExecutor());
}
}
final MapGetRequest request = new MapGetRequest(name, keyData);
try {
final ICompletableFuture future = getContext().getInvocationService().invokeOnKeyOwner(request, keyData);
final DelegatingFuture<V> delegatingFuture = new DelegatingFuture<V>(future, getContext().getSerializationService());
delegatingFuture.andThen(new ExecutionCallback<V>() {
@Override
public void onResponse(V response) {
if (nearCache != null) {
nearCache.put(keyData, response);
}
}
@Override
public void onFailure(Throwable t) {
}
});
return delegatingFuture;
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
@Override
public Future<V> putAsync(final K key, final V value) {
return putAsync(key, value, -1, null);
}
@Override
public Future<V> putAsync(final K key, final V value, final long ttl, final TimeUnit timeunit) {
final Data keyData = toData(key);
final Data valueData = toData(value);
invalidateNearCache(keyData);
MapPutRequest request = new MapPutRequest(name, keyData, valueData,
ThreadUtil.getThreadId(), getTimeInMillis(ttl, timeunit));
try {
final ICompletableFuture future = getContext().getInvocationService().invokeOnKeyOwner(request, keyData);
return new DelegatingFuture<V>(future, getContext().getSerializationService());
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
@Override
public Future<V> removeAsync(final K key) {
final Data keyData = toData(key);
invalidateNearCache(keyData);
MapRemoveRequest request = new MapRemoveRequest(name, keyData, ThreadUtil.getThreadId());
try {
final ICompletableFuture future = getContext().getInvocationService().invokeOnKeyOwner(request, keyData);
return new DelegatingFuture<V>(future, getContext().getSerializationService());
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
@Override
public boolean tryRemove(K key, long timeout, TimeUnit timeunit) {
final Data keyData = toData(key);
invalidateNearCache(keyData);
MapTryRemoveRequest request = new MapTryRemoveRequest(name, keyData,
ThreadUtil.getThreadId(), timeunit.toMillis(timeout));
Boolean result = invoke(request, keyData);
return result;
}
@Override
public boolean tryPut(K key, V value, long timeout, TimeUnit timeunit) {
final Data keyData = toData(key);
final Data valueData = toData(value);
invalidateNearCache(keyData);
MapTryPutRequest request = new MapTryPutRequest(name, keyData, valueData,
ThreadUtil.getThreadId(), timeunit.toMillis(timeout));
Boolean result = invoke(request, keyData);
return result;
}
@Override
public V put(K key, V value, long ttl, TimeUnit timeunit) {
final Data keyData = toData(key);
final Data valueData = toData(value);
invalidateNearCache(keyData);
MapPutRequest request = new MapPutRequest(name, keyData, valueData,
ThreadUtil.getThreadId(), getTimeInMillis(ttl, timeunit));
return invoke(request, keyData);
}
@Override
public void putTransient(K key, V value, long ttl, TimeUnit timeunit) {
final Data keyData = toData(key);
final Data valueData = toData(value);
invalidateNearCache(keyData);
MapPutTransientRequest request = new MapPutTransientRequest(name, keyData, valueData,
ThreadUtil.getThreadId(), getTimeInMillis(ttl, timeunit));
invoke(request);
}
@Override
public V putIfAbsent(K key, V value) {
return putIfAbsent(key, value, -1, null);
}
@Override
public V putIfAbsent(K key, V value, long ttl, TimeUnit timeunit) {
final Data keyData = toData(key);
final Data valueData = toData(value);
invalidateNearCache(keyData);
MapPutIfAbsentRequest request = new MapPutIfAbsentRequest(name, keyData, valueData,
ThreadUtil.getThreadId(), getTimeInMillis(ttl, timeunit));
return invoke(request, keyData);
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
final Data keyData = toData(key);
final Data oldValueData = toData(oldValue);
final Data newValueData = toData(newValue);
invalidateNearCache(keyData);
MapReplaceIfSameRequest request = new MapReplaceIfSameRequest(name, keyData, oldValueData, newValueData,
ThreadUtil.getThreadId());
Boolean result = invoke(request, keyData);
return result;
}
@Override
public V replace(K key, V value) {
final Data keyData = toData(key);
final Data valueData = toData(value);
invalidateNearCache(keyData);
MapReplaceRequest request = new MapReplaceRequest(name, keyData, valueData,
ThreadUtil.getThreadId());
return invoke(request, keyData);
}
@Override
public void set(K key, V value, long ttl, TimeUnit timeunit) {
final Data keyData = toData(key);
final Data valueData = toData(value);
invalidateNearCache(keyData);
MapSetRequest request = new MapSetRequest(name, keyData, valueData,
ThreadUtil.getThreadId(), getTimeInMillis(ttl, timeunit));
invoke(request, keyData);
}
@Override
public void lock(K key) {
final Data keyData = toData(key);
MapLockRequest request = new MapLockRequest(name, keyData, ThreadUtil.getThreadId());
invoke(request, keyData);
}
@Override
public void lock(K key, long leaseTime, TimeUnit timeUnit) {
final Data keyData = toData(key);
MapLockRequest request = new MapLockRequest(name, keyData,
ThreadUtil.getThreadId(), getTimeInMillis(leaseTime, timeUnit), -1);
invoke(request, keyData);
}
@Override
public boolean isLocked(K key) {
final Data keyData = toData(key);
MapIsLockedRequest request = new MapIsLockedRequest(name, keyData);
Boolean result = invoke(request, keyData);
return result;
}
@Override
public boolean tryLock(K key) {
try {
return tryLock(key, 0, null);
} catch (InterruptedException e) {
return false;
}
}
@Override
public boolean tryLock(K key, long time, TimeUnit timeunit) throws InterruptedException {
final Data keyData = toData(key);
MapLockRequest request = new MapLockRequest(name, keyData,
ThreadUtil.getThreadId(), Long.MAX_VALUE, getTimeInMillis(time, timeunit));
Boolean result = invoke(request, keyData);
return result;
}
@Override
public void unlock(K key) {
final Data keyData = toData(key);
MapUnlockRequest request = new MapUnlockRequest(name, keyData, ThreadUtil.getThreadId(), false);
invoke(request, keyData);
}
@Override
public void forceUnlock(K key) {
final Data keyData = toData(key);
MapUnlockRequest request = new MapUnlockRequest(name, keyData, ThreadUtil.getThreadId(), true);
invoke(request, keyData);
}
@Override
public String addLocalEntryListener(EntryListener<K, V> listener) {
throw new UnsupportedOperationException("Locality is ambiguous for client!!!");
}
@Override
public String addLocalEntryListener(EntryListener<K, V> listener,
Predicate<K, V> predicate, boolean includeValue) {
throw new UnsupportedOperationException("Locality is ambiguous for client!!!");
}
@Override
public String addLocalEntryListener(EntryListener<K, V> listener,
Predicate<K, V> predicate, K key, boolean includeValue) {
throw new UnsupportedOperationException("Locality is ambiguous for client!!!");
}
public String addInterceptor(MapInterceptor interceptor) {
MapAddInterceptorRequest request = new MapAddInterceptorRequest(name, interceptor);
return invoke(request);
}
@Override
public void removeInterceptor(String id) {
MapRemoveInterceptorRequest request = new MapRemoveInterceptorRequest(name, id);
invoke(request);
}
@Override
public String addEntryListener(EntryListener<K, V> listener, boolean includeValue) {
MapAddEntryListenerRequest request = new MapAddEntryListenerRequest(name, includeValue);
EventHandler<PortableEntryEvent> handler = createHandler(listener, includeValue);
return listen(request, handler);
}
@Override
public boolean removeEntryListener(String id) {
final MapRemoveEntryListenerRequest request = new MapRemoveEntryListenerRequest(name, id);
return stopListening(request, id);
}
@Override
public String addEntryListener(EntryListener<K, V> listener, K key, boolean includeValue) {
final Data keyData = toData(key);
MapAddEntryListenerRequest request = new MapAddEntryListenerRequest(name, keyData, includeValue);
EventHandler<PortableEntryEvent> handler = createHandler(listener, includeValue);
return listen(request, keyData, handler);
}
@Override
public String addEntryListener(EntryListener<K, V> listener, Predicate<K, V> predicate, K key, boolean includeValue) {
final Data keyData = toData(key);
MapAddEntryListenerRequest request = new MapAddEntryListenerRequest(name, keyData, includeValue, predicate);
EventHandler<PortableEntryEvent> handler = createHandler(listener, includeValue);
return listen(request, keyData, handler);
}
@Override
public String addEntryListener(EntryListener<K, V> listener, Predicate<K, V> predicate, boolean includeValue) {
MapAddEntryListenerRequest request = new MapAddEntryListenerRequest(name, null, includeValue, predicate);
EventHandler<PortableEntryEvent> handler = createHandler(listener, includeValue);
return listen(request, null, handler);
}
@Override
public EntryView<K, V> getEntryView(K key) {
final Data keyData = toData(key);
MapGetEntryViewRequest request = new MapGetEntryViewRequest(name, keyData);
SimpleEntryView entryView = invoke(request, keyData);
if (entryView == null) {
return null;
}
final Data value = (Data) entryView.getValue();
entryView.setKey(key);
entryView.setValue(toObject(value));
//TODO putCache
return entryView;
}
@Override
public boolean evict(K key) {
final Data keyData = toData(key);
MapEvictRequest request = new MapEvictRequest(name, keyData, ThreadUtil.getThreadId());
Boolean result = invoke(request);
return result;
}
@Override
public Set<K> keySet() {
MapKeySetRequest request = new MapKeySetRequest(name);
MapKeySet mapKeySet = invoke(request);
Set<Data> keySetData = mapKeySet.getKeySet();
Set<K> keySet = new HashSet<K>(keySetData.size());
for (Data data : keySetData) {
final K key = toObject(data);
keySet.add(key);
}
return keySet;
}
@Override
public Map<K, V> getAll(Set<K> keys) {
initNearCache();
Set<Data> keySet = new HashSet(keys.size());
Map<K, V> result = new HashMap<K, V>();
for (Object key : keys) {
keySet.add(toData(key));
}
if (nearCache != null) {
final Iterator<Data> iterator = keySet.iterator();
while (iterator.hasNext()) {
Data key = iterator.next();
Object cached = nearCache.get(key);
if (cached != null && !ClientNearCache.NULL_OBJECT.equals(cached)) {
result.put((K) toObject(key), (V) cached);
iterator.remove();
}
}
}
if (keys.isEmpty()) {
return result;
}
MapGetAllRequest request = new MapGetAllRequest(name, keySet);
MapEntrySet mapEntrySet = invoke(request);
Set<Entry<Data, Data>> entrySet = mapEntrySet.getEntrySet();
for (Entry<Data, Data> dataEntry : entrySet) {
final V value = (V) toObject(dataEntry.getValue());
final K key = (K) toObject(dataEntry.getKey());
result.put(key, value);
if (nearCache != null) {
nearCache.put(dataEntry.getKey(), value);
}
}
return result;
}
@Override
public Collection<V> values() {
MapValuesRequest request = new MapValuesRequest(name);
MapValueCollection mapValueCollection = invoke(request);
Collection<Data> collectionData = mapValueCollection.getValues();
Collection<V> collection = new ArrayList<V>(collectionData.size());
for (Data data : collectionData) {
final V value = toObject(data);
collection.add(value);
}
return collection;
}
@Override
public Set<Entry<K, V>> entrySet() {
MapEntrySetRequest request = new MapEntrySetRequest(name);
MapEntrySet result = invoke(request);
Set<Entry<K, V>> entrySet = new HashSet<Entry<K, V>>();
Set<Entry<Data, Data>> entries = result.getEntrySet();
for (Entry<Data, Data> dataEntry : entries) {
Data keyData = dataEntry.getKey();
Data valueData = dataEntry.getValue();
K key = toObject(keyData);
V value = toObject(valueData);
entrySet.add(new AbstractMap.SimpleEntry<K, V>(key, value));
}
return entrySet;
}
@Override
public Set<K> keySet(Predicate predicate) {
PagingPredicate pagingPredicate = null;
if (predicate instanceof PagingPredicate) {
pagingPredicate = (PagingPredicate) predicate;
pagingPredicate.setIterationType(IterationType.KEY);
if (pagingPredicate.getPage() > 0 && pagingPredicate.getAnchor() == null) {
pagingPredicate.previousPage();
keySet(pagingPredicate);
pagingPredicate.nextPage();
}
}
MapQueryRequest request = new MapQueryRequest(name, predicate, IterationType.KEY);
QueryResultSet result = invoke(request);
if (pagingPredicate == null) {
final HashSet<K> keySet = new HashSet<K>();
for (Object o : result) {
final K key = toObject(o);
keySet.add(key);
}
return keySet;
}
final Comparator<Entry> comparator = SortingUtil.newComparator(pagingPredicate.getComparator(), IterationType.KEY);
final SortedQueryResultSet sortedResult = new SortedQueryResultSet(comparator, IterationType.KEY,
pagingPredicate.getPageSize());
final Iterator<Entry> iterator = result.rawIterator();
while (iterator.hasNext()) {
final Entry entry = iterator.next();
final K key = toObject(entry.getKey());
final V value = toObject(entry.getValue());
sortedResult.add(new AbstractMap.SimpleImmutableEntry<K, V>(key, value));
}
PagingPredicateAccessor.setPagingPredicateAnchor(pagingPredicate, sortedResult.last());
return (Set<K>) sortedResult;
}
@Override
public Set<Entry<K, V>> entrySet(Predicate predicate) {
PagingPredicate pagingPredicate = null;
if (predicate instanceof PagingPredicate) {
pagingPredicate = (PagingPredicate) predicate;
pagingPredicate.setIterationType(IterationType.ENTRY);
if (pagingPredicate.getPage() > 0 && pagingPredicate.getAnchor() == null) {
pagingPredicate.previousPage();
entrySet(pagingPredicate);
pagingPredicate.nextPage();
}
}
MapQueryRequest request = new MapQueryRequest(name, predicate, IterationType.ENTRY);
QueryResultSet result = invoke(request);
Set entrySet;
if (pagingPredicate == null) {
entrySet = new HashSet<Entry<K, V>>(result.size());
} else {
entrySet = new SortedQueryResultSet(pagingPredicate.getComparator(), IterationType.ENTRY,
pagingPredicate.getPageSize());
}
for (Object data : result) {
AbstractMap.SimpleImmutableEntry<Data, Data> dataEntry = (AbstractMap.SimpleImmutableEntry<Data, Data>) data;
K key = toObject(dataEntry.getKey());
V value = toObject(dataEntry.getValue());
entrySet.add(new AbstractMap.SimpleEntry<K, V>(key, value));
}
if (pagingPredicate != null) {
PagingPredicateAccessor.setPagingPredicateAnchor(pagingPredicate, ((SortedQueryResultSet) entrySet).last());
}
return entrySet;
}
@Override
public Collection<V> values(Predicate predicate) {
PagingPredicate pagingPredicate = null;
if (predicate instanceof PagingPredicate) {
pagingPredicate = (PagingPredicate) predicate;
pagingPredicate.setIterationType(IterationType.VALUE);
if (pagingPredicate.getPage() > 0 && pagingPredicate.getAnchor() == null) {
pagingPredicate.previousPage();
values(pagingPredicate);
pagingPredicate.nextPage();
}
}
MapQueryRequest request = new MapQueryRequest(name, predicate, IterationType.VALUE);
QueryResultSet result = invoke(request);
if (pagingPredicate == null) {
final ArrayList<V> values = new ArrayList<V>(result.size());
for (Object data : result) {
V value = toObject(data);
values.add(value);
}
return values;
}
List<Entry<Object, V>> valueEntryList = new ArrayList<Entry<Object, V>>(result.size());
final Iterator<Entry> iterator = result.rawIterator();
while (iterator.hasNext()) {
final Entry entry = iterator.next();
K key = toObject(entry.getKey());
V value = toObject(entry.getValue());
valueEntryList.add(new AbstractMap.SimpleImmutableEntry<Object, V>(key, value));
}
Collections.sort(valueEntryList, SortingUtil.newComparator(pagingPredicate.getComparator(), IterationType.VALUE));
if (valueEntryList.size() > pagingPredicate.getPageSize()) {
valueEntryList = valueEntryList.subList(0, pagingPredicate.getPageSize());
}
Entry anchor = null;
if (valueEntryList.size() != 0) {
anchor = valueEntryList.get(valueEntryList.size() - 1);
}
PagingPredicateAccessor.setPagingPredicateAnchor(pagingPredicate, anchor);
final ArrayList<V> values = new ArrayList<V>(valueEntryList.size());
for (Entry<Object, V> objectVEntry : valueEntryList) {
values.add(objectVEntry.getValue());
}
return values;
}
@Override
public Set<K> localKeySet() {
throw new UnsupportedOperationException("Locality is ambiguous for client!!!");
}
@Override
public Set<K> localKeySet(Predicate predicate) {
throw new UnsupportedOperationException("Locality is ambiguous for client!!!");
}
@Override
public void addIndex(String attribute, boolean ordered) {
MapAddIndexRequest request = new MapAddIndexRequest(name, attribute, ordered);
invoke(request);
}
@Override
public LocalMapStats getLocalMapStats() {
initNearCache();
LocalMapStatsImpl localMapStats = new LocalMapStatsImpl();
if (nearCache != null) {
localMapStats.setNearCacheStats(nearCache.getNearCacheStats());
}
return localMapStats;
}
@Override
public Object executeOnKey(K key, EntryProcessor entryProcessor) {
final Data keyData = toData(key);
MapExecuteOnKeyRequest request = new MapExecuteOnKeyRequest(name, entryProcessor, keyData);
return invoke(request, keyData);
}
public void submitToKey(K key, EntryProcessor entryProcessor, final ExecutionCallback callback) {
final Data keyData = toData(key);
final MapExecuteOnKeyRequest request = new MapExecuteOnKeyRequest(name, entryProcessor, keyData);
try {
final ClientCallFuture future = (ClientCallFuture) getContext().getInvocationService().
invokeOnKeyOwner(request, keyData);
future.andThen(callback);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
public Future submitToKey(K key, EntryProcessor entryProcessor) {
final Data keyData = toData(key);
final MapExecuteOnKeyRequest request = new MapExecuteOnKeyRequest(name, entryProcessor, keyData);
try {
final ICompletableFuture future = getContext().getInvocationService().invokeOnKeyOwner(request, keyData);
return new DelegatingFuture(future, getContext().getSerializationService());
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
@Override
public Map<K, Object> executeOnEntries(EntryProcessor entryProcessor) {
MapExecuteOnAllKeysRequest request = new MapExecuteOnAllKeysRequest(name, entryProcessor);
MapEntrySet entrySet = invoke(request);
Map<K, Object> result = new HashMap<K, Object>();
for (Entry<Data, Data> dataEntry : entrySet.getEntrySet()) {
final Data keyData = dataEntry.getKey();
final Data valueData = dataEntry.getValue();
K key = toObject(keyData);
result.put(key, toObject(valueData));
}
return result;
}
@Override
public Map<K, Object> executeOnEntries(EntryProcessor entryProcessor, Predicate predicate) {
MapExecuteWithPredicateRequest request = new MapExecuteWithPredicateRequest(name, entryProcessor, predicate);
MapEntrySet entrySet = invoke(request);
Map<K, Object> result = new HashMap<K, Object>();
for (Entry<Data, Data> dataEntry : entrySet.getEntrySet()) {
final Data keyData = dataEntry.getKey();
final Data valueData = dataEntry.getValue();
K key = toObject(keyData);
result.put(key, toObject(valueData));
}
return result;
}
@Override
public Map<K, Object> executeOnKeys(Set<K> keys, EntryProcessor entryProcessor) {
Set<Data> dataKeys = new HashSet<Data>(keys.size());
for (K key : keys) {
dataKeys.add(toData(key));
}
MapExecuteOnKeysRequest request = new MapExecuteOnKeysRequest(name, entryProcessor, dataKeys);
MapEntrySet entrySet = invoke(request);
Map<K, Object> result = new HashMap<K, Object>();
for (Entry<Data, Data> dataEntry : entrySet.getEntrySet()) {
final Data keyData = dataEntry.getKey();
final Data valueData = dataEntry.getValue();
K key = toObject(keyData);
result.put(key, toObject(valueData));
}
return result;
}
@Override
public void set(K key, V value) {
set(key, value, -1, null);
}
@Override
public int size() {
MapSizeRequest request = new MapSizeRequest(name);
Integer result = invoke(request);
return result;
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
MapEntrySet entrySet = new MapEntrySet();
for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
final Data keyData = toData(entry.getKey());
invalidateNearCache(keyData);
entrySet.add(new AbstractMap.SimpleImmutableEntry<Data, Data>(keyData, toData(entry.getValue())));
}
MapPutAllRequest request = new MapPutAllRequest(name, entrySet);
invoke(request);
}
@Override
public void clear() {
MapClearRequest request = new MapClearRequest(name);
invoke(request);
}
@Override
protected void onDestroy() {
destroyNearCache();
}
private void destroyNearCache() {
if (nearCache != null) {
nearCache.destroy();
}
}
@Override
protected void onShutdown() {
destroyNearCache();
}
protected long getTimeInMillis(final long time, final TimeUnit timeunit) {
return timeunit != null ? timeunit.toMillis(time) : time;
}
private EventHandler<PortableEntryEvent> createHandler(final EntryListener<K, V> listener, final boolean includeValue) {
return new EventHandler<PortableEntryEvent>() {
public void handle(PortableEntryEvent event) {
V value = null;
V oldValue = null;
if (includeValue) {
value = toObject(event.getValue());
oldValue = toObject(event.getOldValue());
}
K key = toObject(event.getKey());
Member member = getContext().getClusterService().getMember(event.getUuid());
EntryEvent<K, V> entryEvent = new EntryEvent<K, V>(name, member,
event.getEventType().getType(), key, oldValue, value);
switch (event.getEventType()) {
case ADDED:
listener.entryAdded(entryEvent);
break;
case REMOVED:
listener.entryRemoved(entryEvent);
break;
case UPDATED:
listener.entryUpdated(entryEvent);
break;
case EVICTED:
listener.entryEvicted(entryEvent);
break;
default:
throw new IllegalArgumentException("Not a known event type " + event.getEventType());
}
}
@Override
public void onListenerRegister() {
}
};
}
private void invalidateNearCache(Data key) {
if (nearCache != null) {
nearCache.invalidate(key);
}
}
private void initNearCache() {
if (nearCacheInitialized.compareAndSet(false, true)) {
final NearCacheConfig nearCacheConfig = getContext().getClientConfig().getNearCacheConfig(name);
if (nearCacheConfig == null) {
return;
}
ClientNearCache<Data> nearCacheInternal = new ClientNearCache<Data>(
name, ClientNearCacheType.Map, getContext(), nearCacheConfig);
nearCache = nearCacheInternal;
}
}
@Override
public String toString() {
return "IMap{" + "name='" + getName() + '\'' + '}';
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientMapProxy.java
|
1,072 |
indexAction.execute(upsertRequest, new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse response) {
UpdateResponse update = new UpdateResponse(response.getIndex(), response.getType(), response.getId(), response.getVersion(), response.isCreated());
if (request.fields() != null && request.fields().length > 0) {
Tuple<XContentType, Map<String, Object>> sourceAndContent = XContentHelper.convertToMap(upsertSourceBytes, true);
update.setGetResult(updateHelper.extractGetResult(request, response.getVersion(), sourceAndContent.v2(), sourceAndContent.v1(), upsertSourceBytes));
} else {
update.setGetResult(null);
}
listener.onResponse(update);
}
@Override
public void onFailure(Throwable e) {
e = ExceptionsHelper.unwrapCause(e);
if (e instanceof VersionConflictEngineException || e instanceof DocumentAlreadyExistsException) {
if (retryCount < request.retryOnConflict()) {
threadPool.executor(executor()).execute(new Runnable() {
@Override
public void run() {
shardOperation(request, listener, retryCount + 1);
}
});
return;
}
}
listener.onFailure(e);
}
});
| 1no label
|
src_main_java_org_elasticsearch_action_update_TransportUpdateAction.java
|
402 |
public class OomeOnClientAuthenticationMain {
private OomeOnClientAuthenticationMain() {
}
public static void main(String[] args) {
HazelcastInstance hz = Hazelcast.newHazelcastInstance();
ClientConfig clientConfig = new ClientConfig();
clientConfig.getGroupConfig().setPassword("foo");
clientConfig.getNetworkConfig().setConnectionAttemptLimit(0);
for (int k = 0; k < 1000000; k++) {
System.out.println("At:" + k);
try {
HazelcastClient.newHazelcastClient(clientConfig);
} catch (IllegalStateException e) {
}
}
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_oome_OomeOnClientAuthenticationMain.java
|
548 |
public class GetFieldMappingsAction extends IndicesAction<GetFieldMappingsRequest, GetFieldMappingsResponse, GetFieldMappingsRequestBuilder> {
public static final GetFieldMappingsAction INSTANCE = new GetFieldMappingsAction();
public static final String NAME = "mappings/fields/get";
private GetFieldMappingsAction() {
super(NAME);
}
@Override
public GetFieldMappingsRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new GetFieldMappingsRequestBuilder((InternalGenericClient) client);
}
@Override
public GetFieldMappingsResponse newResponse() {
return new GetFieldMappingsResponse();
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_mapping_get_GetFieldMappingsAction.java
|
88 |
public class Decimal extends AbstractDecimal {
public static final int DECIMALS = 3;
public static final Decimal MIN_VALUE = new Decimal(minDoubleValue(DECIMALS));
public static final Decimal MAX_VALUE = new Decimal(maxDoubleValue(DECIMALS));
private Decimal() {}
public Decimal(double value) {
super(value, DECIMALS);
}
private Decimal(long format) {
super(format, DECIMALS);
}
public static class DecimalSerializer extends AbstractDecimalSerializer<Decimal> {
public DecimalSerializer() {
super(DECIMALS, Decimal.class);
}
@Override
protected Decimal construct(long format, int decimals) {
assert decimals==DECIMALS;
return new Decimal(format);
}
}
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Decimal.java
|
1,071 |
public class MaxSizeConfig {
private MaxSizeConfigReadOnly readOnly;
private int size = MapConfig.DEFAULT_MAX_SIZE;
private MaxSizePolicy maxSizePolicy = MaxSizePolicy.PER_NODE;
public MaxSizeConfig() {
}
public MaxSizeConfig(int size, MaxSizePolicy maxSizePolicy) {
this.size = size;
this.maxSizePolicy = maxSizePolicy;
}
public MaxSizeConfig(MaxSizeConfig config) {
this.size = config.size;
this.maxSizePolicy = config.maxSizePolicy;
}
public enum MaxSizePolicy {
PER_NODE, PER_PARTITION, USED_HEAP_PERCENTAGE, USED_HEAP_SIZE
}
public MaxSizeConfigReadOnly getAsReadOnly() {
if (readOnly == null) {
readOnly = new MaxSizeConfigReadOnly(this);
}
return readOnly;
}
public int getSize() {
return size;
}
public MaxSizeConfig setSize(int size) {
if (size <= 0) {
size = Integer.MAX_VALUE;
}
this.size = size;
return this;
}
public MaxSizePolicy getMaxSizePolicy() {
return maxSizePolicy;
}
public MaxSizeConfig setMaxSizePolicy(MaxSizePolicy maxSizePolicy) {
this.maxSizePolicy = maxSizePolicy;
return this;
}
@Override
public String toString() {
return "MaxSizeConfig{" +
"maxSizePolicy='" + maxSizePolicy + '\'' +
", size=" + size +
'}';
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_config_MaxSizeConfig.java
|
1,696 |
public class BytesArray implements BytesReference {
public static final BytesArray EMPTY = new BytesArray(BytesRef.EMPTY_BYTES, 0, 0);
private byte[] bytes;
private int offset;
private int length;
public BytesArray(String bytes) {
BytesRef bytesRef = new BytesRef();
UnicodeUtil.UTF16toUTF8(bytes, 0, bytes.length(), bytesRef);
this.bytes = bytesRef.bytes;
this.offset = bytesRef.offset;
this.length = bytesRef.length;
}
public BytesArray(BytesRef bytesRef) {
this(bytesRef, false);
}
public BytesArray(BytesRef bytesRef, boolean deepCopy) {
if (deepCopy) {
BytesRef copy = BytesRef.deepCopyOf(bytesRef);
bytes = copy.bytes;
offset = copy.offset;
length = copy.length;
} else {
bytes = bytesRef.bytes;
offset = bytesRef.offset;
length = bytesRef.length;
}
}
public BytesArray(byte[] bytes) {
this.bytes = bytes;
this.offset = 0;
this.length = bytes.length;
}
public BytesArray(byte[] bytes, int offset, int length) {
this.bytes = bytes;
this.offset = offset;
this.length = length;
}
@Override
public byte get(int index) {
return bytes[offset + index];
}
@Override
public int length() {
return length;
}
@Override
public BytesReference slice(int from, int length) {
if (from < 0 || (from + length) > this.length) {
throw new ElasticsearchIllegalArgumentException("can't slice a buffer with length [" + this.length + "], with slice parameters from [" + from + "], length [" + length + "]");
}
return new BytesArray(bytes, offset + from, length);
}
@Override
public StreamInput streamInput() {
return new BytesStreamInput(bytes, offset, length, false);
}
@Override
public void writeTo(OutputStream os) throws IOException {
os.write(bytes, offset, length);
}
@Override
public byte[] toBytes() {
if (offset == 0 && bytes.length == length) {
return bytes;
}
return Arrays.copyOfRange(bytes, offset, offset + length);
}
@Override
public BytesArray toBytesArray() {
return this;
}
@Override
public BytesArray copyBytesArray() {
return new BytesArray(Arrays.copyOfRange(bytes, offset, offset + length));
}
@Override
public ChannelBuffer toChannelBuffer() {
return ChannelBuffers.wrappedBuffer(bytes, offset, length);
}
@Override
public boolean hasArray() {
return true;
}
@Override
public byte[] array() {
return bytes;
}
@Override
public int arrayOffset() {
return offset;
}
@Override
public String toUtf8() {
if (length == 0) {
return "";
}
return new String(bytes, offset, length, Charsets.UTF_8);
}
@Override
public BytesRef toBytesRef() {
return new BytesRef(bytes, offset, length);
}
@Override
public BytesRef copyBytesRef() {
return new BytesRef(Arrays.copyOfRange(bytes, offset, offset + length));
}
@Override
public int hashCode() {
return Helper.bytesHashCode(this);
}
@Override
public boolean equals(Object obj) {
return Helper.bytesEqual(this, (BytesReference) obj);
}
}
| 1no label
|
src_main_java_org_elasticsearch_common_bytes_BytesArray.java
|
1,317 |
public interface LocalNodeMasterListener {
/**
* Called when local node is elected to be the master
*/
void onMaster();
/**
* Called when the local node used to be the master, a new master was elected and it's no longer the local node.
*/
void offMaster();
/**
* The name of the executor that the implementation of the callbacks of this lister should be executed on. The thread
* that is responsible for managing instances of this lister is the same thread handling the cluster state events. If
* the work done is the callbacks above is inexpensive, this value may be {@link org.elasticsearch.threadpool.ThreadPool.Names#SAME SAME}
* (indicating that the callbaks will run on the same thread as the cluster state events are fired with). On the other hand,
* if the logic in the callbacks are heavier and take longer to process (or perhaps involve blocking due to IO operations),
* prefer to execute them on a separte more appropriate executor (eg. {@link org.elasticsearch.threadpool.ThreadPool.Names#GENERIC GENERIC}
* or {@link org.elasticsearch.threadpool.ThreadPool.Names#MANAGEMENT MANAGEMENT}).
*
* @return The name of the executor that will run the callbacks of this listener.
*/
String executorName();
}
| 0true
|
src_main_java_org_elasticsearch_cluster_LocalNodeMasterListener.java
|
510 |
public class StressThread extends TestThread {
@Override
public void doRun() throws Exception {
while (!isStopped()) {
int key = random.nextInt(MAP_SIZE);
int value = map.get(key);
assertEquals("The value for the key was not consistent", key, value);
}
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_stress_MapStableReadStressTest.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.