Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
300
private final RecordChanges<Long, Collection<DynamicRecord>, SchemaRule> schemaRuleChanges = new RecordChanges<>(new RecordChanges.Loader<Long, Collection<DynamicRecord>, SchemaRule>() { @Override public Collection<DynamicRecord> newUnused(Long key, SchemaRule additionalData) { return getSchemaStore().allocateFrom(additionalData); } @Override public Collection<DynamicRecord> load(Long key, SchemaRule additionalData) { return getSchemaStore().getRecords( key ); } @Override public void ensureHeavy(Collection<DynamicRecord> dynamicRecords) { SchemaStore schemaStore = getSchemaStore(); for ( DynamicRecord record : dynamicRecords) { schemaStore.ensureHeavy(record); } } @Override public Collection<DynamicRecord> clone(Collection<DynamicRecord> dynamicRecords) { Collection<DynamicRecord> list = new ArrayList<>( dynamicRecords.size() ); for ( DynamicRecord record : dynamicRecords) { list.add( record.clone() ); } return list; } }, true);
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreTransaction.java
910
public class TransportSuggestAction extends TransportBroadcastOperationAction<SuggestRequest, SuggestResponse, ShardSuggestRequest, ShardSuggestResponse> { private final IndicesService indicesService; private final SuggestPhase suggestPhase; @Inject public TransportSuggestAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, IndicesService indicesService, SuggestPhase suggestPhase) { super(settings, threadPool, clusterService, transportService); this.indicesService = indicesService; this.suggestPhase = suggestPhase; } @Override protected String executor() { return ThreadPool.Names.SUGGEST; } @Override protected String transportAction() { return SuggestAction.NAME; } @Override protected SuggestRequest newRequest() { return new SuggestRequest(); } @Override protected ShardSuggestRequest newShardRequest() { return new ShardSuggestRequest(); } @Override protected ShardSuggestRequest newShardRequest(ShardRouting shard, SuggestRequest request) { return new ShardSuggestRequest(shard.index(), shard.id(), request); } @Override protected ShardSuggestResponse newShardResponse() { return new ShardSuggestResponse(); } @Override protected GroupShardsIterator shards(ClusterState clusterState, SuggestRequest request, String[] concreteIndices) { Map<String, Set<String>> routingMap = clusterState.metaData().resolveSearchRouting(request.routing(), request.indices()); return clusterService.operationRouting().searchShards(clusterState, request.indices(), concreteIndices, routingMap, request.preference()); } @Override protected ClusterBlockException checkGlobalBlock(ClusterState state, SuggestRequest request) { return state.blocks().globalBlockedException(ClusterBlockLevel.READ); } @Override protected ClusterBlockException checkRequestBlock(ClusterState state, SuggestRequest countRequest, String[] concreteIndices) { return state.blocks().indicesBlockedException(ClusterBlockLevel.READ, concreteIndices); } @Override protected SuggestResponse newResponse(SuggestRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) { int successfulShards = 0; int failedShards = 0; final Map<String, List<Suggest.Suggestion>> groupedSuggestions = new HashMap<String, List<Suggest.Suggestion>>(); List<ShardOperationFailedException> shardFailures = null; for (int i = 0; i < shardsResponses.length(); i++) { Object shardResponse = shardsResponses.get(i); if (shardResponse == null) { // simply ignore non active shards } else if (shardResponse instanceof BroadcastShardOperationFailedException) { failedShards++; if (shardFailures == null) { shardFailures = newArrayList(); } shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse)); } else { Suggest suggest = ((ShardSuggestResponse) shardResponse).getSuggest(); Suggest.group(groupedSuggestions, suggest); successfulShards++; } } return new SuggestResponse(new Suggest(Suggest.reduce(groupedSuggestions)), shardsResponses.length(), successfulShards, failedShards, shardFailures); } @Override protected ShardSuggestResponse shardOperation(ShardSuggestRequest request) throws ElasticsearchException { IndexService indexService = indicesService.indexServiceSafe(request.index()); IndexShard indexShard = indexService.shardSafe(request.shardId()); final Engine.Searcher searcher = indexShard.acquireSearcher("suggest"); XContentParser parser = null; try { BytesReference suggest = request.suggest(); if (suggest != null && suggest.length() > 0) { parser = XContentFactory.xContent(suggest).createParser(suggest); if (parser.nextToken() != XContentParser.Token.START_OBJECT) { throw new ElasticsearchIllegalArgumentException("suggest content missing"); } final SuggestionSearchContext context = suggestPhase.parseElement().parseInternal(parser, indexService.mapperService(), request.index(), request.shardId()); final Suggest result = suggestPhase.execute(context, searcher.reader()); return new ShardSuggestResponse(request.index(), request.shardId(), result); } return new ShardSuggestResponse(request.index(), request.shardId(), new Suggest()); } catch (Throwable ex) { throw new ElasticsearchException("failed to execute suggest", ex); } finally { searcher.release(); if (parser != null) { parser.close(); } } } }
1no label
src_main_java_org_elasticsearch_action_suggest_TransportSuggestAction.java
2,871
public class HunspellTokenFilterFactoryTests extends ElasticsearchTestCase { @Test public void testDedup() throws IOException { Settings settings = settingsBuilder() .put("path.conf", getResource("/indices/analyze/conf_dir")) .put("index.analysis.filter.en_US.type", "hunspell") .put("index.analysis.filter.en_US.locale", "en_US") .build(); AnalysisService analysisService = AnalysisTestsHelper.createAnalysisServiceFromSettings(settings); TokenFilterFactory tokenFilter = analysisService.tokenFilter("en_US"); assertThat(tokenFilter, instanceOf(HunspellTokenFilterFactory.class)); HunspellTokenFilterFactory hunspellTokenFilter = (HunspellTokenFilterFactory) tokenFilter; assertThat(hunspellTokenFilter.dedup(), is(true)); settings = settingsBuilder() .put("path.conf", getResource("/indices/analyze/conf_dir")) .put("index.analysis.filter.en_US.type", "hunspell") .put("index.analysis.filter.en_US.dedup", false) .put("index.analysis.filter.en_US.locale", "en_US") .build(); analysisService = AnalysisTestsHelper.createAnalysisServiceFromSettings(settings); tokenFilter = analysisService.tokenFilter("en_US"); assertThat(tokenFilter, instanceOf(HunspellTokenFilterFactory.class)); hunspellTokenFilter = (HunspellTokenFilterFactory) tokenFilter; assertThat(hunspellTokenFilter.dedup(), is(false)); } @Test public void testDefaultRecursionLevel() throws IOException { Settings settings = settingsBuilder() .put("path.conf", getResource("/indices/analyze/conf_dir")) .put("index.analysis.filter.en_US.type", "hunspell") .put("index.analysis.filter.en_US.locale", "en_US") .build(); AnalysisService analysisService = AnalysisTestsHelper.createAnalysisServiceFromSettings(settings); TokenFilterFactory tokenFilter = analysisService.tokenFilter("en_US"); assertThat(tokenFilter, instanceOf(HunspellTokenFilterFactory.class)); HunspellTokenFilterFactory hunspellTokenFilter = (HunspellTokenFilterFactory) tokenFilter; assertThat(hunspellTokenFilter.recursionLevel(), is(2)); } @Test public void testCustomRecursionLevel() throws IOException { Settings settings = settingsBuilder() .put("path.conf", getResource("/indices/analyze/conf_dir")) .put("index.analysis.filter.en_US.type", "hunspell") .put("index.analysis.filter.en_US.recursion_level", 0) .put("index.analysis.filter.en_US.locale", "en_US") .build(); AnalysisService analysisService = AnalysisTestsHelper.createAnalysisServiceFromSettings(settings); TokenFilterFactory tokenFilter = analysisService.tokenFilter("en_US"); assertThat(tokenFilter, instanceOf(HunspellTokenFilterFactory.class)); HunspellTokenFilterFactory hunspellTokenFilter = (HunspellTokenFilterFactory) tokenFilter; assertThat(hunspellTokenFilter.recursionLevel(), is(0)); } @Test(expected = ProvisionException.class) public void negativeRecursionLevelShouldFail() throws IOException { Settings settings = settingsBuilder() .put("path.conf", getResource("/indices/analyze/conf_dir")) .put("index.analysis.filter.en_US.type", "hunspell") .put("index.analysis.filter.en_US.recursion_level", -1) .put("index.analysis.filter.en_US.locale", "en_US") .build(); AnalysisTestsHelper.createAnalysisServiceFromSettings(settings); } }
0true
src_test_java_org_elasticsearch_index_analysis_HunspellTokenFilterFactoryTests.java
179
public class XidImpl implements Xid { interface Seed { long nextRandomLong(); long nextSequenceId(); } public static final Seed DEFAULT_SEED = new Seed() { private long nextSequenceId = 0; private final Random r = new Random(); @Override public synchronized long nextSequenceId() { return nextSequenceId++; } @Override public long nextRandomLong() { return r.nextLong(); } }; // Neo4j ('N' 'E' 'O') format identifier private static final int FORMAT_ID = 0x4E454E31; private static final byte INSTANCE_ID[] = new byte[] { 'N', 'E', 'O', 'K', 'E', 'R', 'N', 'L', '\0' }; // INSTANCE_ID + millitime(long) + seqnumber(long) private final byte globalId[]; // branchId assumes Xid.MAXBQUALSIZE >= 4 private final byte branchId[]; /** * Generates a new global id byte[] for use as one part that makes up a Xid. A global id is made up of: * - INSTANCE_ID: fixed number of bytes and content * - 8b: current time millis * - 8b: sequence id, incremented for each new generated global id * - 4b: local id, an id fixed for and local to the instance generating this global id * * resourceId.length = 4, unique for each XAResource * @param localId * @return */ public static byte[] getNewGlobalId( Seed seed, int localId ) { byte globalId[] = Arrays.copyOf( INSTANCE_ID, INSTANCE_ID.length + 20 ); wrap( globalId, INSTANCE_ID.length, 20 ) .putLong( seed.nextRandomLong() ) .putLong( seed.nextSequenceId() ) .putInt( localId ); return globalId; } static boolean isThisTm( byte globalId[] ) { if ( globalId.length < INSTANCE_ID.length ) { return false; } for ( int i = 0; i < INSTANCE_ID.length; i++ ) { if ( globalId[i] != INSTANCE_ID[i] ) { return false; } } return true; } public XidImpl( byte globalId[], byte resourceId[] ) { if ( globalId.length > Xid.MAXGTRIDSIZE ) { throw new IllegalArgumentException( "GlobalId length to long: " + globalId.length + ". Max is " + Xid.MAXGTRIDSIZE ); } if ( resourceId.length > Xid.MAXBQUALSIZE ) { throw new IllegalArgumentException( "BranchId (resource id) to long, " + resourceId.length ); } this.globalId = globalId; this.branchId = resourceId; } @Override public byte[] getGlobalTransactionId() { return globalId.clone(); } @Override public byte[] getBranchQualifier() { return branchId.clone(); } @Override public int getFormatId() { return FORMAT_ID; } @Override public boolean equals( Object o ) { if ( !(o instanceof Xid) ) { return false; } return Arrays.equals( globalId, ((Xid) o).getGlobalTransactionId() ) && Arrays.equals( branchId, ((Xid) o).getBranchQualifier() ); } private volatile int hashCode = 0; @Override public int hashCode() { if ( hashCode == 0 ) { int calcHash = 0; for ( int i = 0; i < 3 && i < globalId.length; i++ ) { calcHash += globalId[globalId.length - i - 1] << i * 8; } if ( branchId.length > 0 ) { calcHash += branchId[0] << 3 * 8; } hashCode = 3217 * calcHash; } return hashCode; } @Override public String toString() { StringBuffer buf = new StringBuffer( "GlobalId[" ); int baseLength = INSTANCE_ID.length + 8 + 8; if ( globalId.length == baseLength || globalId.length == baseLength+4 ) { for ( int i = 0; i < INSTANCE_ID.length - 1; i++ ) { buf.append( (char) globalId[i] ); } ByteBuffer byteBuf = ByteBuffer.wrap( globalId ); byteBuf.position( INSTANCE_ID.length ); long time = byteBuf.getLong(); long sequence = byteBuf.getLong(); buf.append( '|' ); buf.append( time ); buf.append( '|' ); buf.append( sequence ); /* MP 2013-11-27: 4b added to the globalId, consisting of the serverId value. This if-statement * keeps things backwards compatible and nice. */ if ( byteBuf.hasRemaining() ) { buf.append( '|' ).append( byteBuf.getInt() ); } } else { buf.append( "UNKNOWN_ID" ); } buf.append( "], BranchId[ " ); for ( int i = 0; i < branchId.length; i++ ) { buf.append( branchId[i] + " " ); } buf.append( "]" ); return buf.toString(); } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_XidImpl.java
173
.build(new CacheLoader<String,URLProcessor>() { public URLProcessor load(String key) throws IOException, ServletException { if (LOG.isDebugEnabled()) { LOG.debug("Loading URL processor into Cache"); } return determineURLProcessor(key); } });
1no label
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_web_BroadleafProcessURLFilter.java
5,461
public class SearchSourceBuilder implements ToXContent { /** * A static factory method to construct a new search source. */ public static SearchSourceBuilder searchSource() { return new SearchSourceBuilder(); } /** * A static factory method to construct new search highlights. */ public static HighlightBuilder highlight() { return new HighlightBuilder(); } private QueryBuilder queryBuilder; private BytesReference queryBinary; private FilterBuilder postFilterBuilder; private BytesReference filterBinary; private int from = -1; private int size = -1; private Boolean explain; private Boolean version; private List<SortBuilder> sorts; private boolean trackScores = false; private Float minScore; private long timeoutInMillis = -1; private List<String> fieldNames; private List<String> fieldDataFields; private List<ScriptField> scriptFields; private List<PartialField> partialFields; private FetchSourceContext fetchSourceContext; private List<FacetBuilder> facets; private BytesReference facetsBinary; private List<AbstractAggregationBuilder> aggregations; private BytesReference aggregationsBinary; private HighlightBuilder highlightBuilder; private SuggestBuilder suggestBuilder; private List<RescoreBuilder> rescoreBuilders; private Integer defaultRescoreWindowSize; private ObjectFloatOpenHashMap<String> indexBoost = null; private String[] stats; /** * Constructs a new search source builder. */ public SearchSourceBuilder() { } /** * Constructs a new search source builder with a search query. * * @see org.elasticsearch.index.query.QueryBuilders */ public SearchSourceBuilder query(QueryBuilder query) { this.queryBuilder = query; return this; } /** * Constructs a new search source builder with a raw search query. */ public SearchSourceBuilder query(byte[] queryBinary) { return query(queryBinary, 0, queryBinary.length); } /** * Constructs a new search source builder with a raw search query. */ public SearchSourceBuilder query(byte[] queryBinary, int queryBinaryOffset, int queryBinaryLength) { return query(new BytesArray(queryBinary, queryBinaryOffset, queryBinaryLength)); } /** * Constructs a new search source builder with a raw search query. */ public SearchSourceBuilder query(BytesReference queryBinary) { this.queryBinary = queryBinary; return this; } /** * Constructs a new search source builder with a raw search query. */ public SearchSourceBuilder query(String queryString) { return query(queryString.getBytes(Charsets.UTF_8)); } /** * Constructs a new search source builder with a query from a builder. */ public SearchSourceBuilder query(XContentBuilder query) { return query(query.bytes()); } /** * Constructs a new search source builder with a query from a map. */ public SearchSourceBuilder query(Map query) { try { XContentBuilder builder = XContentFactory.contentBuilder(Requests.CONTENT_TYPE); builder.map(query); return query(builder); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + query + "]", e); } } /** * Sets a filter that will be executed after the query has been executed and only has affect on the search hits * (not aggregations or facets). This filter is always executed as last filtering mechanism. */ public SearchSourceBuilder postFilter(FilterBuilder postFilter) { this.postFilterBuilder = postFilter; return this; } /** * Sets a filter on the query executed that only applies to the search query * (and not facets for example). */ public SearchSourceBuilder postFilter(String postFilterString) { return postFilter(postFilterString.getBytes(Charsets.UTF_8)); } /** * Sets a filter on the query executed that only applies to the search query * (and not facets for example). */ public SearchSourceBuilder postFilter(byte[] postFilter) { return postFilter(postFilter, 0, postFilter.length); } /** * Sets a filter on the query executed that only applies to the search query * (and not facets for example). */ public SearchSourceBuilder postFilter(byte[] postFilterBinary, int postFilterBinaryOffset, int postFilterBinaryLength) { return postFilter(new BytesArray(postFilterBinary, postFilterBinaryOffset, postFilterBinaryLength)); } /** * Sets a filter on the query executed that only applies to the search query * (and not facets for example). */ public SearchSourceBuilder postFilter(BytesReference postFilterBinary) { this.filterBinary = postFilterBinary; return this; } /** * Constructs a new search source builder with a query from a builder. */ public SearchSourceBuilder postFilter(XContentBuilder postFilter) { return postFilter(postFilter.bytes()); } /** * Constructs a new search source builder with a query from a map. */ public SearchSourceBuilder postFilter(Map postFilter) { try { XContentBuilder builder = XContentFactory.contentBuilder(Requests.CONTENT_TYPE); builder.map(postFilter); return postFilter(builder); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + postFilter + "]", e); } } /** * From index to start the search from. Defaults to <tt>0</tt>. */ public SearchSourceBuilder from(int from) { this.from = from; return this; } /** * The number of search hits to return. Defaults to <tt>10</tt>. */ public SearchSourceBuilder size(int size) { this.size = size; return this; } /** * Sets the minimum score below which docs will be filtered out. */ public SearchSourceBuilder minScore(float minScore) { this.minScore = minScore; return this; } /** * Should each {@link org.elasticsearch.search.SearchHit} be returned with an * explanation of the hit (ranking). */ public SearchSourceBuilder explain(Boolean explain) { this.explain = explain; return this; } /** * Should each {@link org.elasticsearch.search.SearchHit} be returned with a version * associated with it. */ public SearchSourceBuilder version(Boolean version) { this.version = version; return this; } /** * An optional timeout to control how long search is allowed to take. */ public SearchSourceBuilder timeout(TimeValue timeout) { this.timeoutInMillis = timeout.millis(); return this; } /** * An optional timeout to control how long search is allowed to take. */ public SearchSourceBuilder timeout(String timeout) { this.timeoutInMillis = TimeValue.parseTimeValue(timeout, null).millis(); return this; } /** * Adds a sort against the given field name and the sort ordering. * * @param name The name of the field * @param order The sort ordering */ public SearchSourceBuilder sort(String name, SortOrder order) { return sort(SortBuilders.fieldSort(name).order(order)); } /** * Add a sort against the given field name. * * @param name The name of the field to sort by */ public SearchSourceBuilder sort(String name) { return sort(SortBuilders.fieldSort(name)); } /** * Adds a sort builder. */ public SearchSourceBuilder sort(SortBuilder sort) { if (sorts == null) { sorts = Lists.newArrayList(); } sorts.add(sort); return this; } /** * Applies when sorting, and controls if scores will be tracked as well. Defaults to * <tt>false</tt>. */ public SearchSourceBuilder trackScores(boolean trackScores) { this.trackScores = trackScores; return this; } /** * Add a facet to perform as part of the search. */ public SearchSourceBuilder facet(FacetBuilder facet) { if (facets == null) { facets = Lists.newArrayList(); } facets.add(facet); return this; } /** * Sets a raw (xcontent / json) facets. */ public SearchSourceBuilder facets(byte[] facetsBinary) { return facets(facetsBinary, 0, facetsBinary.length); } /** * Sets a raw (xcontent / json) facets. */ public SearchSourceBuilder facets(byte[] facetsBinary, int facetBinaryOffset, int facetBinaryLength) { return facets(new BytesArray(facetsBinary, facetBinaryOffset, facetBinaryLength)); } /** * Sets a raw (xcontent / json) facets. */ public SearchSourceBuilder facets(BytesReference facetsBinary) { this.facetsBinary = facetsBinary; return this; } /** * Sets a raw (xcontent / json) facets. */ public SearchSourceBuilder facets(XContentBuilder facets) { return facets(facets.bytes()); } /** * Sets a raw (xcontent / json) facets. */ public SearchSourceBuilder facets(Map facets) { try { XContentBuilder builder = XContentFactory.contentBuilder(Requests.CONTENT_TYPE); builder.map(facets); return facets(builder); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + facets + "]", e); } } /** * Add an get to perform as part of the search. */ public SearchSourceBuilder aggregation(AbstractAggregationBuilder aggregation) { if (aggregations == null) { aggregations = Lists.newArrayList(); } aggregations.add(aggregation); return this; } /** * Sets a raw (xcontent / json) addAggregation. */ public SearchSourceBuilder aggregations(byte[] aggregationsBinary) { return aggregations(aggregationsBinary, 0, aggregationsBinary.length); } /** * Sets a raw (xcontent / json) addAggregation. */ public SearchSourceBuilder aggregations(byte[] aggregationsBinary, int aggregationsBinaryOffset, int aggregationsBinaryLength) { return aggregations(new BytesArray(aggregationsBinary, aggregationsBinaryOffset, aggregationsBinaryLength)); } /** * Sets a raw (xcontent / json) addAggregation. */ public SearchSourceBuilder aggregations(BytesReference aggregationsBinary) { this.aggregationsBinary = aggregationsBinary; return this; } /** * Sets a raw (xcontent / json) addAggregation. */ public SearchSourceBuilder aggregations(XContentBuilder facets) { return aggregations(facets.bytes()); } /** * Set the rescore window size for rescores that don't specify their window. * @param defaultRescoreWindowSize * @return */ public SearchSourceBuilder defaultRescoreWindowSize(int defaultRescoreWindowSize) { this.defaultRescoreWindowSize = defaultRescoreWindowSize; return this; } /** * Sets a raw (xcontent / json) addAggregation. */ public SearchSourceBuilder aggregations(Map aggregations) { try { XContentBuilder builder = XContentFactory.contentBuilder(Requests.CONTENT_TYPE); builder.map(aggregations); return aggregations(builder); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + aggregations + "]", e); } } public HighlightBuilder highlighter() { if (highlightBuilder == null) { highlightBuilder = new HighlightBuilder(); } return highlightBuilder; } /** * Adds highlight to perform as part of the search. */ public SearchSourceBuilder highlight(HighlightBuilder highlightBuilder) { this.highlightBuilder = highlightBuilder; return this; } public SuggestBuilder suggest() { if (suggestBuilder == null) { suggestBuilder = new SuggestBuilder("suggest"); } return suggestBuilder; } public SearchSourceBuilder addRescorer(RescoreBuilder rescoreBuilder) { if (rescoreBuilders == null) { rescoreBuilders = new ArrayList<RescoreBuilder>(); } rescoreBuilders.add(rescoreBuilder); return this; } public SearchSourceBuilder clearRescorers() { rescoreBuilders = null; return this; } /** * Indicates whether the response should contain the stored _source for every hit * * @param fetch * @return */ public SearchSourceBuilder fetchSource(boolean fetch) { if (this.fetchSourceContext == null) { this.fetchSourceContext = new FetchSourceContext(fetch); } else { this.fetchSourceContext.fetchSource(fetch); } return this; } /** * Indicate that _source should be returned with every hit, with an "include" and/or "exclude" set which can include simple wildcard * elements. * * @param include An optional include (optionally wildcarded) pattern to filter the returned _source * @param exclude An optional exclude (optionally wildcarded) pattern to filter the returned _source */ public SearchSourceBuilder fetchSource(@Nullable String include, @Nullable String exclude) { return fetchSource(include == null ? Strings.EMPTY_ARRAY : new String[]{include}, include == null ? Strings.EMPTY_ARRAY : new String[]{exclude}); } /** * Indicate that _source should be returned with every hit, with an "include" and/or "exclude" set which can include simple wildcard * elements. * * @param includes An optional list of include (optionally wildcarded) pattern to filter the returned _source * @param excludes An optional list of exclude (optionally wildcarded) pattern to filter the returned _source */ public SearchSourceBuilder fetchSource(@Nullable String[] includes, @Nullable String[] excludes) { fetchSourceContext = new FetchSourceContext(includes, excludes); return this; } /** * Indicate how the _source should be fetched. */ public SearchSourceBuilder fetchSource(@Nullable FetchSourceContext fetchSourceContext) { this.fetchSourceContext = fetchSourceContext; return this; } /** * Sets no fields to be loaded, resulting in only id and type to be returned per field. */ public SearchSourceBuilder noFields() { this.fieldNames = ImmutableList.of(); return this; } /** * Sets the fields to load and return as part of the search request. If none are specified, * the source of the document will be returned. */ public SearchSourceBuilder fields(List<String> fields) { this.fieldNames = fields; return this; } /** * Adds the fields to load and return as part of the search request. If none are specified, * the source of the document will be returned. */ public SearchSourceBuilder fields(String... fields) { if (fieldNames == null) { fieldNames = new ArrayList<String>(); } for (String field : fields) { fieldNames.add(field); } return this; } /** * Adds a field to load and return (note, it must be stored) as part of the search request. * If none are specified, the source of the document will be return. */ public SearchSourceBuilder field(String name) { if (fieldNames == null) { fieldNames = new ArrayList<String>(); } fieldNames.add(name); return this; } /** * Adds a field to load from the field data cache and return as part of the search request. */ public SearchSourceBuilder fieldDataField(String name) { if (fieldDataFields == null) { fieldDataFields = new ArrayList<String>(); } fieldDataFields.add(name); return this; } /** * Adds a script field under the given name with the provided script. * * @param name The name of the field * @param script The script */ public SearchSourceBuilder scriptField(String name, String script) { return scriptField(name, null, script, null); } /** * Adds a script field. * * @param name The name of the field * @param script The script to execute * @param params The script parameters */ public SearchSourceBuilder scriptField(String name, String script, Map<String, Object> params) { return scriptField(name, null, script, params); } /** * Adds a script field. * * @param name The name of the field * @param lang The language of the script * @param script The script to execute * @param params The script parameters (can be <tt>null</tt>) */ public SearchSourceBuilder scriptField(String name, String lang, String script, Map<String, Object> params) { if (scriptFields == null) { scriptFields = Lists.newArrayList(); } scriptFields.add(new ScriptField(name, lang, script, params)); return this; } /** * Adds a partial field based on _source, with an "include" and/or "exclude" set which can include simple wildcard * elements. * * @deprecated since 1.0.0 * use {@link SearchSourceBuilder#fetchSource(String, String)} instead * * @param name The name of the field * @param include An optional include (optionally wildcarded) pattern from _source * @param exclude An optional exclude (optionally wildcarded) pattern from _source */ @Deprecated public SearchSourceBuilder partialField(String name, @Nullable String include, @Nullable String exclude) { if (partialFields == null) { partialFields = Lists.newArrayList(); } partialFields.add(new PartialField(name, include, exclude)); return this; } /** * Adds a partial field based on _source, with an "includes" and/or "excludes set which can include simple wildcard * elements. * * @deprecated since 1.0.0 * use {@link SearchSourceBuilder#fetchSource(String[], String[])} instead * * @param name The name of the field * @param includes An optional list of includes (optionally wildcarded) patterns from _source * @param excludes An optional list of excludes (optionally wildcarded) patterns from _source */ @Deprecated public SearchSourceBuilder partialField(String name, @Nullable String[] includes, @Nullable String[] excludes) { if (partialFields == null) { partialFields = Lists.newArrayList(); } partialFields.add(new PartialField(name, includes, excludes)); return this; } /** * Sets the boost a specific index will receive when the query is executeed against it. * * @param index The index to apply the boost against * @param indexBoost The boost to apply to the index */ public SearchSourceBuilder indexBoost(String index, float indexBoost) { if (this.indexBoost == null) { this.indexBoost = new ObjectFloatOpenHashMap<String>(); } this.indexBoost.put(index, indexBoost); return this; } /** * The stats groups this request will be aggregated under. */ public SearchSourceBuilder stats(String... statsGroups) { this.stats = statsGroups; return this; } @Override public String toString() { try { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON).prettyPrint(); toXContent(builder, ToXContent.EMPTY_PARAMS); return builder.string(); } catch (Exception e) { return "{ \"error\" : \"" + e.getMessage() + "\"}"; } } public BytesReference buildAsBytes() throws SearchSourceBuilderException { return buildAsBytes(Requests.CONTENT_TYPE); } public BytesReference buildAsBytes(XContentType contentType) throws SearchSourceBuilderException { try { XContentBuilder builder = XContentFactory.contentBuilder(contentType); toXContent(builder, ToXContent.EMPTY_PARAMS); return builder.bytes(); } catch (Exception e) { throw new SearchSourceBuilderException("Failed to build search source", e); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); if (from != -1) { builder.field("from", from); } if (size != -1) { builder.field("size", size); } if (timeoutInMillis != -1) { builder.field("timeout", timeoutInMillis); } if (queryBuilder != null) { builder.field("query"); queryBuilder.toXContent(builder, params); } if (queryBinary != null) { if (XContentFactory.xContentType(queryBinary) == builder.contentType()) { builder.rawField("query", queryBinary); } else { builder.field("query_binary", queryBinary); } } if (postFilterBuilder != null) { builder.field("post_filter"); postFilterBuilder.toXContent(builder, params); } if (filterBinary != null) { if (XContentFactory.xContentType(filterBinary) == builder.contentType()) { builder.rawField("filter", filterBinary); } else { builder.field("filter_binary", filterBinary); } } if (minScore != null) { builder.field("min_score", minScore); } if (version != null) { builder.field("version", version); } if (explain != null) { builder.field("explain", explain); } if (fetchSourceContext != null) { if (!fetchSourceContext.fetchSource()) { builder.field("_source", false); } else { builder.startObject("_source"); builder.array("includes", fetchSourceContext.includes()); builder.array("excludes", fetchSourceContext.excludes()); builder.endObject(); } } if (fieldNames != null) { if (fieldNames.size() == 1) { builder.field("fields", fieldNames.get(0)); } else { builder.startArray("fields"); for (String fieldName : fieldNames) { builder.value(fieldName); } builder.endArray(); } } if (fieldDataFields != null) { builder.startArray("fielddata_fields"); for (String fieldName : fieldDataFields) { builder.value(fieldName); } builder.endArray(); } if (partialFields != null) { builder.startObject("partial_fields"); for (PartialField partialField : partialFields) { builder.startObject(partialField.name()); if (partialField.includes() != null) { if (partialField.includes().length == 1) { builder.field("include", partialField.includes()[0]); } else { builder.field("include", partialField.includes()); } } if (partialField.excludes() != null) { if (partialField.excludes().length == 1) { builder.field("exclude", partialField.excludes()[0]); } else { builder.field("exclude", partialField.excludes()); } } builder.endObject(); } builder.endObject(); } if (scriptFields != null) { builder.startObject("script_fields"); for (ScriptField scriptField : scriptFields) { builder.startObject(scriptField.fieldName()); builder.field("script", scriptField.script()); if (scriptField.lang() != null) { builder.field("lang", scriptField.lang()); } if (scriptField.params() != null) { builder.field("params"); builder.map(scriptField.params()); } builder.endObject(); } builder.endObject(); } if (sorts != null) { builder.startArray("sort"); for (SortBuilder sort : sorts) { builder.startObject(); sort.toXContent(builder, params); builder.endObject(); } builder.endArray(); } if (trackScores) { builder.field("track_scores", trackScores); } if (indexBoost != null) { builder.startObject("indices_boost"); final boolean[] states = indexBoost.allocated; final Object[] keys = indexBoost.keys; final float[] values = indexBoost.values; for (int i = 0; i < states.length; i++) { if (states[i]) { builder.field((String) keys[i], values[i]); } } builder.endObject(); } if (facets != null) { builder.field("facets"); builder.startObject(); for (FacetBuilder facet : facets) { facet.toXContent(builder, params); } builder.endObject(); } if (facetsBinary != null) { if (XContentFactory.xContentType(facetsBinary) == builder.contentType()) { builder.rawField("facets", facetsBinary); } else { builder.field("facets_binary", facetsBinary); } } if (aggregations != null) { builder.field("aggregations"); builder.startObject(); for (AbstractAggregationBuilder aggregation : aggregations) { aggregation.toXContent(builder, params); } builder.endObject(); } if (aggregationsBinary != null) { if (XContentFactory.xContentType(aggregationsBinary) == builder.contentType()) { builder.rawField("aggregations", aggregationsBinary); } else { builder.field("aggregations_binary", aggregationsBinary); } } if (highlightBuilder != null) { highlightBuilder.toXContent(builder, params); } if (suggestBuilder != null) { suggestBuilder.toXContent(builder, params); } if (rescoreBuilders != null) { // Strip empty rescoreBuilders from the request Iterator<RescoreBuilder> itr = rescoreBuilders.iterator(); while (itr.hasNext()) { if (itr.next().isEmpty()) { itr.remove(); } } // Now build the request taking care to skip empty lists and only send the object form // if there is just one builder. if (rescoreBuilders.size() == 1) { builder.startObject("rescore"); rescoreBuilders.get(0).toXContent(builder, params); if (rescoreBuilders.get(0).windowSize() == null && defaultRescoreWindowSize != null) { builder.field("window_size", defaultRescoreWindowSize); } builder.endObject(); } else if (!rescoreBuilders.isEmpty()) { builder.startArray("rescore"); for (RescoreBuilder rescoreBuilder : rescoreBuilders) { builder.startObject(); rescoreBuilder.toXContent(builder, params); if (rescoreBuilder.windowSize() == null && defaultRescoreWindowSize != null) { builder.field("window_size", defaultRescoreWindowSize); } builder.endObject(); } builder.endArray(); } } if (stats != null) { builder.startArray("stats"); for (String stat : stats) { builder.value(stat); } builder.endArray(); } builder.endObject(); return builder; } private static class ScriptField { private final String fieldName; private final String script; private final String lang; private final Map<String, Object> params; private ScriptField(String fieldName, String lang, String script, Map<String, Object> params) { this.fieldName = fieldName; this.lang = lang; this.script = script; this.params = params; } public String fieldName() { return fieldName; } public String script() { return script; } public String lang() { return this.lang; } public Map<String, Object> params() { return params; } } private static class PartialField { private final String name; private final String[] includes; private final String[] excludes; private PartialField(String name, String[] includes, String[] excludes) { this.name = name; this.includes = includes; this.excludes = excludes; } private PartialField(String name, String include, String exclude) { this.name = name; this.includes = include == null ? null : new String[]{include}; this.excludes = exclude == null ? null : new String[]{exclude}; } public String name() { return name; } public String[] includes() { return includes; } public String[] excludes() { return excludes; } } }
1no label
src_main_java_org_elasticsearch_search_builder_SearchSourceBuilder.java
111
public abstract class OListenerManger<L> { private final Collection<L> listeners; private final OLock lock; public OListenerManger() { this(new HashSet<L>(8), new ONoLock()); } public OListenerManger(final OLock iLock) { listeners = new HashSet<L>(8); lock = iLock; } public OListenerManger(final Collection<L> iListeners, final OLock iLock) { listeners = iListeners; lock = iLock; } public void registerListener(final L iListener) { if (iListener != null) { lock.lock(); try { listeners.add(iListener); } finally { lock.unlock(); } } } public void unregisterListener(final L iListener) { if (iListener != null) { lock.lock(); try { listeners.remove(iListener); } finally { lock.unlock(); } } } public void resetListeners() { lock.lock(); try { listeners.clear(); } finally { lock.unlock(); } } public Iterable<L> browseListeners() { return listeners; } @SuppressWarnings("unchecked") public Iterable<L> getListenersCopy() { lock.lock(); try { return (Iterable<L>) new HashSet<Object>(listeners); } finally { lock.unlock(); } } public OLock getLock() { return lock; } }
0true
commons_src_main_java_com_orientechnologies_common_listener_OListenerManger.java
95
public class RagManager implements Visitor<LineLogger, RuntimeException> { // if a runtime exception is thrown from any method it means that the // RWLock class hasn't kept the contract to the RagManager // The contract is: // o When a transaction gets a lock on a resource and both the readCount and // writeCount for that transaction on the resource was 0 // RagManager.lockAcquired( resource ) must be invoked // o When a tx releases a lock on a resource and both the readCount and // writeCount for that transaction on the resource goes down to zero // RagManager.lockReleased( resource ) must be invoked // o After invoke to the checkWaitOn( resource ) method that didn't result // in a DeadlockDetectedException the transaction must wait // o When the transaction wakes up from waiting on a resource the // stopWaitOn( resource ) method must be invoked private final Map<Object,List<Transaction>> resourceMap = new HashMap<Object,List<Transaction>>(); private final ArrayMap<Transaction,Object> waitingTxMap = new ArrayMap<Transaction,Object>( (byte)5, false, true ); private final AtomicInteger deadlockCount = new AtomicInteger(); long getDeadlockCount() { return deadlockCount.longValue(); } synchronized void lockAcquired( Object resource, Transaction tx ) { List<Transaction> lockingTxList = resourceMap.get( resource ); if ( lockingTxList != null ) { assert !lockingTxList.contains( tx ); lockingTxList.add( tx ); } else { lockingTxList = new LinkedList<Transaction>(); lockingTxList.add( tx ); resourceMap.put( resource, lockingTxList ); } } synchronized void lockReleased( Object resource, Transaction tx ) { List<Transaction> lockingTxList = resourceMap.get( resource ); if ( lockingTxList == null ) { throw new LockException( resource + " not found in resource map" ); } if ( !lockingTxList.remove( tx ) ) { throw new LockException( tx + "not found in locking tx list" ); } if ( lockingTxList.size() == 0 ) { resourceMap.remove( resource ); } } synchronized void stopWaitOn( Object resource, Transaction tx ) { if ( waitingTxMap.remove( tx ) == null ) { throw new LockException( tx + " not waiting on " + resource ); } } // after invoke the transaction must wait on the resource synchronized void checkWaitOn( Object resource, Transaction tx ) throws DeadlockDetectedException { List<Transaction> lockingTxList = resourceMap.get( resource ); if ( lockingTxList == null ) { throw new LockException( "Illegal resource[" + resource + "], not found in map" ); } if ( waitingTxMap.get( tx ) != null ) { throw new LockException( tx + " already waiting for resource" ); } Iterator<Transaction> itr = lockingTxList.iterator(); List<Transaction> checkedTransactions = new LinkedList<Transaction>(); Stack<Object> graphStack = new Stack<Object>(); // has resource,transaction interleaved graphStack.push( resource ); while ( itr.hasNext() ) { Transaction lockingTx = itr.next(); // the if statement bellow is valid because: // t1 -> r1 -> t1 (can happened with RW locks) is ok but, // t1 -> r1 -> t1&t2 where t2 -> r1 is a deadlock // think like this, we have two transactions and one resource // o t1 takes read lock on r1 // o t2 takes read lock on r1 // o t1 wanna take write lock on r1 but has to wait for t2 // to release the read lock ( t1->r1->(t1&t2), ok not deadlock yet // o t2 wanna take write lock on r1 but has to wait for t1 // to release read lock.... // DEADLOCK t1->r1->(t1&t2) and t2->r1->(t1&t2) ===> // t1->r1->t2->r1->t1, t2->r1->t1->r1->t2 etc... // to allow the first three steps above we check if lockingTx == // waitingTx on first level. // because of this special case we have to keep track on the // already "checked" tx since it is (now) legal for one type of // circular reference to exist (t1->r1->t1) otherwise we may // traverse t1->r1->t2->r1->t2->r1->t2... until SOE // ... KISS to you too if ( lockingTx.equals( tx ) ) { continue; } graphStack.push( lockingTx ); checkWaitOnRecursive( lockingTx, tx, checkedTransactions, graphStack ); graphStack.pop(); } // ok no deadlock, we can wait on resource waitingTxMap.put( tx, resource ); } private synchronized void checkWaitOnRecursive( Transaction lockingTx, Transaction waitingTx, List<Transaction> checkedTransactions, Stack<Object> graphStack ) throws DeadlockDetectedException { if ( lockingTx.equals( waitingTx ) ) { StringBuffer circle = null; Object resource; do { lockingTx = (Transaction) graphStack.pop(); resource = graphStack.pop(); if ( circle == null ) { circle = new StringBuffer(); circle.append( lockingTx ).append( " <-[:HELD_BY]- " ).append( resource ); } else { circle.append( " <-[:WAITING_FOR]- " ).append( lockingTx ).append( " <-[:HELD_BY]- " ).append( resource ); } } while ( !graphStack.isEmpty() ); deadlockCount.incrementAndGet(); throw new DeadlockDetectedException( waitingTx + " can't wait on resource " + resource + " since => " + circle ); } checkedTransactions.add( lockingTx ); Object resource = waitingTxMap.get( lockingTx ); if ( resource != null ) { graphStack.push( resource ); // if the resource doesn't exist in resorceMap that means all the // locks on the resource has been released // it is possible when this tx was in RWLock.acquire and // saw it had to wait for the lock the scheduler changes to some // other tx that will release the locks on the resource and // remove it from the map // this is ok since current tx or any other tx will wake // in the synchronized block and will be forced to do the deadlock // check once more if lock cannot be acquired List<Transaction> lockingTxList = resourceMap.get( resource ); if ( lockingTxList != null ) { for ( Transaction aLockingTxList : lockingTxList ) { lockingTx = aLockingTxList; // so we don't if ( !checkedTransactions.contains( lockingTx ) ) { graphStack.push( lockingTx ); checkWaitOnRecursive( lockingTx, waitingTx, checkedTransactions, graphStack ); graphStack.pop(); } } } graphStack.pop(); } } @Override public synchronized boolean visit( LineLogger logger ) { logger.logLine( "Waiting list: " ); Iterator<Transaction> transactions = waitingTxMap.keySet().iterator(); if ( !transactions.hasNext() ) { logger.logLine( "No transactions waiting on resources" ); } else { logger.logLine( "" ); // new line } while ( transactions.hasNext() ) { Transaction tx = transactions.next(); logger.logLine( "" + tx + "->" + waitingTxMap.get( tx ) ); } logger.logLine( "Resource lock list: " ); Iterator<?> resources = resourceMap.keySet().iterator(); if ( !resources.hasNext() ) { logger.logLine( "No locked resources found" ); } else { logger.logLine( "" ); } while ( resources.hasNext() ) { Object resource = resources.next(); logger.logLine( "" + resource + "->" ); Iterator<Transaction> itr = resourceMap.get( resource ).iterator(); if ( !itr.hasNext() ) { logger.logLine( " Error empty list found" ); } while ( itr.hasNext() ) { logger.logLine( "" + itr.next() ); if ( itr.hasNext() ) { logger.logLine( "," ); } else { logger.logLine( "" ); } } } return true; } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_RagManager.java
39
Runnable r = new Runnable() { @Override public void run() { try { for (Entry<String, Map<Long, Map<String, String>>> feedData : groupData[dataIndex].entrySet()) { PartitionTimestamps timeStamp = null; try { timeStamp = putData(null, feedData.getKey(), databases[dataIndex], timeUnit, feedData.getValue()); } catch (BufferFullException e) { bufferFull.compareAndSet(false, true); } if (timeStamp == null) { break; } else { timestamps.put(feedData.getKey(), timeStamp); } } } finally { latch.countDown(); } } };
0true
timeSequenceFeedAggregator_src_main_java_gov_nasa_arc_mct_buffer_disk_internal_PartitionFastDiskBuffer.java
1,207
public class OClusterEntryIterator implements Iterator<OPhysicalPosition> { private final OCluster cluster; private final OClusterPosition max; private final OClusterPosition min; private OPhysicalPosition[] positionsToProcess; private int positionsIndex; public OClusterEntryIterator(final OCluster iCluster) { cluster = iCluster; try { min = cluster.getFirstPosition(); max = cluster.getLastPosition(); } catch (IOException ioe) { throw new IllegalStateException("Exception during iterator creation", ioe); } positionsToProcess = null; positionsIndex = -1; } public boolean hasNext() { if (OClusterPosition.INVALID_POSITION.compareTo(min) == 0) return false; if (positionsToProcess == null) return true; return positionsToProcess.length != 0; } public OPhysicalPosition next() { try { if (positionsIndex == -1) { positionsToProcess = cluster.ceilingPositions(new OPhysicalPosition(min)); positionsIndex = 0; } if (positionsToProcess.length == 0) throw new NoSuchElementException(); final OPhysicalPosition result = positionsToProcess[positionsIndex]; positionsIndex++; if (positionsIndex >= positionsToProcess.length) { positionsToProcess = cluster.higherPositions(positionsToProcess[positionsToProcess.length - 1]); positionsIndex = 0; } return result; } catch (IOException e) { throw new ODatabaseException("Cannot read next record of cluster.", e); } } public void remove() { throw new UnsupportedOperationException("remove"); } }
0true
core_src_main_java_com_orientechnologies_orient_core_storage_OClusterEntryIterator.java
661
return new Iterator<V>() { private final OSBTreeMapEntryIterator<Object, V> entryIterator = new OSBTreeMapEntryIterator<Object, V>(sbTree); @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public V next() { return entryIterator.next().getValue(); } @Override public void remove() { entryIterator.remove(); } };
0true
core_src_main_java_com_orientechnologies_orient_core_index_engine_OSBTreeIndexEngine.java
1,357
final ExecutionCallback callback = new ExecutionCallback() { public void onResponse(Object response) { if ((Boolean) response) count.incrementAndGet(); latch.countDown(); } public void onFailure(Throwable t) { } };
0true
hazelcast_src_test_java_com_hazelcast_executor_ExecutorServiceTest.java
4,126
public class ShardSearchService extends AbstractIndexShardComponent { private final ShardSlowLogSearchService slowLogSearchService; private final StatsHolder totalStats = new StatsHolder(); private final CounterMetric openContexts = new CounterMetric(); private volatile Map<String, StatsHolder> groupsStats = ImmutableMap.of(); @Inject public ShardSearchService(ShardId shardId, @IndexSettings Settings indexSettings, ShardSlowLogSearchService slowLogSearchService) { super(shardId, indexSettings); this.slowLogSearchService = slowLogSearchService; } /** * Returns the stats, including group specific stats. If the groups are null/0 length, then nothing * is returned for them. If they are set, then only groups provided will be returned, or * <tt>_all</tt> for all groups. */ public SearchStats stats(String... groups) { SearchStats.Stats total = totalStats.stats(); Map<String, SearchStats.Stats> groupsSt = null; if (groups != null && groups.length > 0) { if (groups.length == 1 && groups[0].equals("_all")) { groupsSt = new HashMap<String, SearchStats.Stats>(groupsStats.size()); for (Map.Entry<String, StatsHolder> entry : groupsStats.entrySet()) { groupsSt.put(entry.getKey(), entry.getValue().stats()); } } else { groupsSt = new HashMap<String, SearchStats.Stats>(groups.length); for (String group : groups) { StatsHolder statsHolder = groupsStats.get(group); if (statsHolder != null) { groupsSt.put(group, statsHolder.stats()); } } } } return new SearchStats(total, openContexts.count(), groupsSt); } public void onPreQueryPhase(SearchContext searchContext) { totalStats.queryCurrent.inc(); if (searchContext.groupStats() != null) { for (int i = 0; i < searchContext.groupStats().size(); i++) { groupStats(searchContext.groupStats().get(i)).queryCurrent.inc(); } } } public void onFailedQueryPhase(SearchContext searchContext) { totalStats.queryCurrent.dec(); if (searchContext.groupStats() != null) { for (int i = 0; i < searchContext.groupStats().size(); i++) { groupStats(searchContext.groupStats().get(i)).queryCurrent.dec(); } } } public void onQueryPhase(SearchContext searchContext, long tookInNanos) { totalStats.queryMetric.inc(tookInNanos); totalStats.queryCurrent.dec(); if (searchContext.groupStats() != null) { for (int i = 0; i < searchContext.groupStats().size(); i++) { StatsHolder statsHolder = groupStats(searchContext.groupStats().get(i)); statsHolder.queryMetric.inc(tookInNanos); statsHolder.queryCurrent.dec(); } } slowLogSearchService.onQueryPhase(searchContext, tookInNanos); } public void onPreFetchPhase(SearchContext searchContext) { totalStats.fetchCurrent.inc(); if (searchContext.groupStats() != null) { for (int i = 0; i < searchContext.groupStats().size(); i++) { groupStats(searchContext.groupStats().get(i)).fetchCurrent.inc(); } } } public void onFailedFetchPhase(SearchContext searchContext) { totalStats.fetchCurrent.dec(); if (searchContext.groupStats() != null) { for (int i = 0; i < searchContext.groupStats().size(); i++) { groupStats(searchContext.groupStats().get(i)).fetchCurrent.dec(); } } } public void onFetchPhase(SearchContext searchContext, long tookInNanos) { totalStats.fetchMetric.inc(tookInNanos); totalStats.fetchCurrent.dec(); if (searchContext.groupStats() != null) { for (int i = 0; i < searchContext.groupStats().size(); i++) { StatsHolder statsHolder = groupStats(searchContext.groupStats().get(i)); statsHolder.fetchMetric.inc(tookInNanos); statsHolder.fetchCurrent.dec(); } } slowLogSearchService.onFetchPhase(searchContext, tookInNanos); } public void clear() { totalStats.clear(); synchronized (this) { if (!groupsStats.isEmpty()) { MapBuilder<String, StatsHolder> typesStatsBuilder = MapBuilder.newMapBuilder(); for (Map.Entry<String, StatsHolder> typeStats : groupsStats.entrySet()) { if (typeStats.getValue().totalCurrent() > 0) { typeStats.getValue().clear(); typesStatsBuilder.put(typeStats.getKey(), typeStats.getValue()); } } groupsStats = typesStatsBuilder.immutableMap(); } } } private StatsHolder groupStats(String group) { StatsHolder stats = groupsStats.get(group); if (stats == null) { synchronized (this) { stats = groupsStats.get(group); if (stats == null) { stats = new StatsHolder(); groupsStats = MapBuilder.newMapBuilder(groupsStats).put(group, stats).immutableMap(); } } } return stats; } public void onNewContext(SearchContext context) { openContexts.inc(); } public void onFreeContext(SearchContext context) { openContexts.dec(); } static class StatsHolder { public final MeanMetric queryMetric = new MeanMetric(); public final MeanMetric fetchMetric = new MeanMetric(); public final CounterMetric queryCurrent = new CounterMetric(); public final CounterMetric fetchCurrent = new CounterMetric(); public SearchStats.Stats stats() { return new SearchStats.Stats( queryMetric.count(), TimeUnit.NANOSECONDS.toMillis(queryMetric.sum()), queryCurrent.count(), fetchMetric.count(), TimeUnit.NANOSECONDS.toMillis(fetchMetric.sum()), fetchCurrent.count()); } public long totalCurrent() { return queryCurrent.count() + fetchCurrent.count(); } public void clear() { queryMetric.clear(); fetchMetric.clear(); } } }
1no label
src_main_java_org_elasticsearch_index_search_stats_ShardSearchService.java
444
public class KCVSUtil { private static final Logger log = LoggerFactory.getLogger(KeyColumnValueStore.class); /** * Retrieves the value for the specified column and key under the given transaction * from the store if such exists, otherwise returns NULL * * @param store Store * @param key Key * @param column Column * @param txh Transaction * @return Value for key and column or NULL if such does not exist */ public static StaticBuffer get(KeyColumnValueStore store, StaticBuffer key, StaticBuffer column, StoreTransaction txh) throws BackendException { KeySliceQuery query = new KeySliceQuery(key, column, BufferUtil.nextBiggerBuffer(column)).setLimit(2); List<Entry> result = store.getSlice(query, txh); if (result.size() > 1) log.warn("GET query returned more than 1 result: store {} | key {} | column {}", new Object[]{store.getName(), key, column}); if (result.isEmpty()) return null; else return result.get(0).getValueAs(StaticBuffer.STATIC_FACTORY); } /** * If the store supports unordered scans, then call {#link * {@link KeyColumnValueStore#getKeys(SliceQuery, StoreTransaction)}. The * {@code SliceQuery} bounds are a binary all-zeros with an all-ones buffer. * The limit is 1. * <p> * If the store supports ordered scans, then call {#link * {@link KeyColumnValueStore#getKeys(KeyRangeQuery, StoreTransaction)}. The * key and columns slice bounds are the same as those described above. The * column limit is 1. * * @param store the store to query * @param features the store's features * @param keyLength length of the zero/one buffers that form the key limits * @param sliceLength length of the zero/one buffers that form the col limits * @param txh transaction to use with getKeys * @return keys returned by the store.getKeys call * @throws com.thinkaurelius.titan.diskstorage.BackendException unexpected failure */ public static KeyIterator getKeys(KeyColumnValueStore store, StoreFeatures features, int keyLength, int sliceLength, StoreTransaction txh) throws BackendException { SliceQuery slice = new SliceQuery(BufferUtil.zeroBuffer(sliceLength), BufferUtil.oneBuffer(sliceLength)).setLimit(1); if (features.hasUnorderedScan()) { return store.getKeys(slice, txh); } else if (features.hasOrderedScan()) { return store.getKeys(new KeyRangeQuery(BufferUtil.zeroBuffer(keyLength), BufferUtil.oneBuffer(keyLength), slice), txh); } else throw new UnsupportedOperationException("Scan not supported by this store"); } /** * Returns true if the specified key-column pair exists in the store. * * @param store Store * @param key Key * @param column Column * @param txh Transaction * @return TRUE, if key has at least one column-value pair, else FALSE */ public static boolean containsKeyColumn(KeyColumnValueStore store, StaticBuffer key, StaticBuffer column, StoreTransaction txh) throws BackendException { return get(store, key, column, txh) != null; } private static final StaticBuffer START = BufferUtil.zeroBuffer(8), END = BufferUtil.oneBuffer(32); public static boolean containsKey(KeyColumnValueStore store, StaticBuffer key, StoreTransaction txh) throws BackendException { return containsKey(store,key,32,txh); } public static boolean containsKey(KeyColumnValueStore store, StaticBuffer key, int maxColumnLength, StoreTransaction txh) throws BackendException { StaticBuffer start = START, end = END; if (maxColumnLength>32) { end = BufferUtil.oneBuffer(maxColumnLength); } return !store.getSlice(new KeySliceQuery(key, START, END).setLimit(1),txh).isEmpty(); } public static boolean matches(SliceQuery query, StaticBuffer column) { return query.getSliceStart().compareTo(column)<=0 && query.getSliceEnd().compareTo(column)>0; } public static boolean matches(KeyRangeQuery query, StaticBuffer key, StaticBuffer column) { return matches(query,column) && query.getKeyStart().compareTo(key)<=0 && query.getKeyEnd().compareTo(key)>0; } public static Map<StaticBuffer,EntryList> emptyResults(List<StaticBuffer> keys) { Map<StaticBuffer,EntryList> result = new HashMap<StaticBuffer, EntryList>(keys.size()); for (StaticBuffer key : keys) { result.put(key,EntryList.EMPTY_LIST); } return result; } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_KCVSUtil.java
869
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() { @Override public void run() { executeFetch(entry.index, queryResult.shardTarget(), counter, fetchSearchRequest, node); } });
0true
src_main_java_org_elasticsearch_action_search_type_TransportSearchDfsQueryThenFetchAction.java
2,101
public class OutputStreamStreamOutput extends StreamOutput { private final OutputStream out; public OutputStreamStreamOutput(OutputStream out) { this.out = out; } @Override public void writeByte(byte b) throws IOException { out.write(b); } @Override public void writeBytes(byte[] b, int offset, int length) throws IOException { out.write(b, offset, length); } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { out.close(); } @Override public void reset() throws IOException { throw new UnsupportedOperationException(); } }
0true
src_main_java_org_elasticsearch_common_io_stream_OutputStreamStreamOutput.java
455
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
238
public interface OCache { /** * All operations running at cache initialization stage */ void startup(); /** * All operations running at cache destruction stage */ void shutdown(); /** * Tell whether cache is enabled * * @return {@code true} if cache enabled at call time, otherwise - {@code false} */ boolean isEnabled(); /** * Enable cache * * @return {@code true} - if enabled, {@code false} - otherwise (already enabled) */ boolean enable(); /** * Disable cache. None of record management methods will cause effect on cache in disabled state. * Only cache info methods available at that state. * * @return {@code true} - if disabled, {@code false} - otherwise (already disabled) */ boolean disable(); /** * Look up for record in cache by it's identifier * * @param id unique identifier of record * @return record stored in cache if any, otherwise - {@code null} */ ORecordInternal<?> get(ORID id); /** * Push record to cache. Identifier of record used as access key * * @param record record that should be cached * @return previous version of record */ ORecordInternal<?> put(ORecordInternal<?> record); /** * Remove record with specified identifier * * @param id unique identifier of record * @return record stored in cache if any, otherwise - {@code null} */ ORecordInternal<?> remove(ORID id); /** * Remove all records from cache */ void clear(); /** * Total number of stored records * * @return non-negative number */ int size(); /** * Maximum number of items cache should keep * * @return non-negative number */ int limit(); /** * Keys of all stored in cache records * * @return keys of records */ Collection<ORID> keys(); /** * Lock the item with given id, even if item does not exist all read/update * operations for given item should be locked. * * @param id Item to lock. */ void lock(ORID id); /** * Unlock item. * * @param id item to unlock; */ void unlock(ORID id); }
0true
core_src_main_java_com_orientechnologies_orient_core_cache_OCache.java
14
static final class AsyncRun extends Async { final Runnable fn; final CompletableFuture<Void> dst; AsyncRun(Runnable fn, CompletableFuture<Void> dst) { this.fn = fn; this.dst = dst; } public final boolean exec() { CompletableFuture<Void> d; Throwable ex; if ((d = this.dst) != null && d.result == null) { try { fn.run(); ex = null; } catch (Throwable rex) { ex = rex; } d.internalComplete(null, ex); } return true; } private static final long serialVersionUID = 5232453952276885070L; }
0true
src_main_java_jsr166e_CompletableFuture.java
426
public class ClusterStateAction extends ClusterAction<ClusterStateRequest, ClusterStateResponse, ClusterStateRequestBuilder> { public static final ClusterStateAction INSTANCE = new ClusterStateAction(); public static final String NAME = "cluster/state"; private ClusterStateAction() { super(NAME); } @Override public ClusterStateResponse newResponse() { return new ClusterStateResponse(); } @Override public ClusterStateRequestBuilder newRequestBuilder(ClusterAdminClient client) { return new ClusterStateRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_state_ClusterStateAction.java
723
createIndexAction.execute(new CreateIndexRequest(request.index()).cause("auto(delete api)").masterNodeTimeout(request.timeout()), new ActionListener<CreateIndexResponse>() { @Override public void onResponse(CreateIndexResponse result) { innerExecute(request, listener); } @Override public void onFailure(Throwable e) { if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) { // we have the index, do it innerExecute(request, listener); } else { listener.onFailure(e); } } });
0true
src_main_java_org_elasticsearch_action_delete_TransportDeleteAction.java
773
public abstract class OLazyWrapperIterator<T> implements Iterator<T>, Iterable<T>, OResettable, OSizeable { protected final Iterator<?> iterator; protected T nextElement; protected final int size; // -1 = UNKNOWN public OLazyWrapperIterator(final Iterator<?> iterator) { this.iterator = iterator; this.size = -1; } public OLazyWrapperIterator(final Iterator<?> iterator, final int iSize) { this.iterator = iterator; this.size = iSize; } public abstract boolean filter(T iObject); public abstract T createWrapper(Object iObject); @Override public Iterator<T> iterator() { reset(); return this; } public int size() { if (size > -1) return size; if (iterator instanceof OSizeable) return ((OSizeable) iterator).size(); return 0; } @Override public void reset() { if (iterator instanceof OResettable) // RESET IT FOR MULTIPLE ITERATIONS ((OResettable) iterator).reset(); nextElement = null; } @Override public boolean hasNext() { while (nextElement == null && iterator.hasNext()) { nextElement = createWrapper(iterator.next()); if (nextElement != null && !filter(nextElement)) nextElement = null; } return nextElement != null; } @Override public T next() { if (hasNext()) try { return nextElement; } finally { nextElement = null; } throw new NoSuchElementException(); } @Override public void remove() { iterator.remove(); } }
0true
core_src_main_java_com_orientechnologies_orient_core_iterator_OLazyWrapperIterator.java
1,003
public interface FulfillmentGroupItem extends Serializable { public Long getId(); public void setId(Long id); public FulfillmentGroup getFulfillmentGroup(); public void setFulfillmentGroup(FulfillmentGroup fulfillmentGroup); public OrderItem getOrderItem(); public void setOrderItem(OrderItem orderItem); public int getQuantity(); public void setQuantity(int quantity); public Money getRetailPrice(); public Money getSalePrice(); /** * @deprecated Use {@link #getTotalItemAmount()} or {@link #getTotalItemTaxableAmount()} */ public Money getPrice(); public Money getTotalItemAmount(); public void setTotalItemAmount(Money amount); public Money getProratedOrderAdjustmentAmount(); public void setProratedOrderAdjustmentAmount(Money amount); public Money getTotalItemTaxableAmount(); public void setTotalItemTaxableAmount(Money amount); public FulfillmentGroupStatusType getStatus(); public void setStatus(FulfillmentGroupStatusType status); public void removeAssociations(); public FulfillmentGroupItem clone(); /** * Gets a list of TaxDetail objects, which are taxes that apply directly to this item. * The amount in each TaxDetail takes into account the quantity of this item * * @return a list of taxes that apply to this item */ public List<TaxDetail> getTaxes(); /** * Sets the list of TaxDetail objects, which are taxes that apply directly to this item. * The amount in each TaxDetail must take into account the quantity of this item * * @param taxes the list of taxes on this item */ public void setTaxes(List<TaxDetail> taxes); /** * Gets the total tax for this item, which is the sum of all taxes for this item. * This total is calculated in the TotalActivity stage of the pricing workflow. * * @return the total tax for this item */ public Money getTotalTax(); /** * Sets the total tax for this item, which is the sum of all taxes for this item. * This total should only be set during the TotalActivity stage of the pricing workflow. * * @param totalTax the total tax for this item */ public void setTotalTax(Money totalTax); /** * Returns true if this item has pro-rated order adjustments. * @return */ boolean getHasProratedOrderAdjustments(); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_FulfillmentGroupItem.java
5,836
public class SourceSimpleFragmentsBuilder extends SimpleFragmentsBuilder { private final SearchContext searchContext; public SourceSimpleFragmentsBuilder(FieldMapper<?> mapper, SearchContext searchContext, String[] preTags, String[] postTags, BoundaryScanner boundaryScanner) { super(mapper, preTags, postTags, boundaryScanner); this.searchContext = searchContext; } public static final Field[] EMPTY_FIELDS = new Field[0]; @Override protected Field[] getFields(IndexReader reader, int docId, String fieldName) throws IOException { // we know its low level reader, and matching docId, since that's how we call the highlighter with SearchLookup lookup = searchContext.lookup(); lookup.setNextReader((AtomicReaderContext) reader.getContext()); lookup.setNextDocId(docId); List<Object> values = lookup.source().extractRawValues(mapper.names().sourcePath()); if (values.isEmpty()) { return EMPTY_FIELDS; } Field[] fields = new Field[values.size()]; for (int i = 0; i < values.size(); i++) { fields[i] = new Field(mapper.names().indexName(), values.get(i).toString(), TextField.TYPE_NOT_STORED); } return fields; } }
1no label
src_main_java_org_elasticsearch_search_highlight_vectorhighlight_SourceSimpleFragmentsBuilder.java
5,966
public final class SuggestUtils { public static Comparator<SuggestWord> LUCENE_FREQUENCY = new SuggestWordFrequencyComparator(); public static Comparator<SuggestWord> SCORE_COMPARATOR = SuggestWordQueue.DEFAULT_COMPARATOR; private SuggestUtils() { // utils!! } public static DirectSpellChecker getDirectSpellChecker(DirectSpellcheckerSettings suggestion) { DirectSpellChecker directSpellChecker = new DirectSpellChecker(); directSpellChecker.setAccuracy(suggestion.accuracy()); Comparator<SuggestWord> comparator; switch (suggestion.sort()) { case SCORE: comparator = SCORE_COMPARATOR; break; case FREQUENCY: comparator = LUCENE_FREQUENCY; break; default: throw new ElasticsearchIllegalArgumentException("Illegal suggest sort: " + suggestion.sort()); } directSpellChecker.setComparator(comparator); directSpellChecker.setDistance(suggestion.stringDistance()); directSpellChecker.setMaxEdits(suggestion.maxEdits()); directSpellChecker.setMaxInspections(suggestion.maxInspections()); directSpellChecker.setMaxQueryFrequency(suggestion.maxTermFreq()); directSpellChecker.setMinPrefix(suggestion.prefixLength()); directSpellChecker.setMinQueryLength(suggestion.minWordLength()); directSpellChecker.setThresholdFrequency(suggestion.minDocFreq()); directSpellChecker.setLowerCaseTerms(false); return directSpellChecker; } public static BytesRef join(BytesRef separator, BytesRef result, BytesRef... toJoin) { int len = separator.length * toJoin.length - 1; for (BytesRef br : toJoin) { len += br.length; } result.grow(len); return joinPreAllocated(separator, result, toJoin); } public static BytesRef joinPreAllocated(BytesRef separator, BytesRef result, BytesRef... toJoin) { result.length = 0; result.offset = 0; for (int i = 0; i < toJoin.length - 1; i++) { BytesRef br = toJoin[i]; System.arraycopy(br.bytes, br.offset, result.bytes, result.offset, br.length); result.offset += br.length; System.arraycopy(separator.bytes, separator.offset, result.bytes, result.offset, separator.length); result.offset += separator.length; } final BytesRef br = toJoin[toJoin.length-1]; System.arraycopy(br.bytes, br.offset, result.bytes, result.offset, br.length); result.length = result.offset + br.length; result.offset = 0; return result; } public static abstract class TokenConsumer { protected CharTermAttribute charTermAttr; protected PositionIncrementAttribute posIncAttr; protected OffsetAttribute offsetAttr; public void reset(TokenStream stream) { charTermAttr = stream.addAttribute(CharTermAttribute.class); posIncAttr = stream.addAttribute(PositionIncrementAttribute.class); offsetAttr = stream.addAttribute(OffsetAttribute.class); } protected BytesRef fillBytesRef(BytesRef spare) { spare.offset = 0; spare.length = spare.bytes.length; char[] source = charTermAttr.buffer(); UnicodeUtil.UTF16toUTF8(source, 0, charTermAttr.length(), spare); return spare; } public abstract void nextToken() throws IOException; public void end() {} } public static int analyze(Analyzer analyzer, BytesRef toAnalyze, String field, TokenConsumer consumer, CharsRef spare) throws IOException { UnicodeUtil.UTF8toUTF16(toAnalyze, spare); return analyze(analyzer, spare, field, consumer); } public static int analyze(Analyzer analyzer, CharsRef toAnalyze, String field, TokenConsumer consumer) throws IOException { TokenStream ts = analyzer.tokenStream( field, new FastCharArrayReader(toAnalyze.chars, toAnalyze.offset, toAnalyze.length) ); return analyze(ts, consumer); } public static int analyze(TokenStream stream, TokenConsumer consumer) throws IOException { stream.reset(); consumer.reset(stream); int numTokens = 0; while (stream.incrementToken()) { consumer.nextToken(); numTokens++; } consumer.end(); stream.close(); return numTokens; } public static SuggestMode resolveSuggestMode(String suggestMode) { suggestMode = suggestMode.toLowerCase(Locale.US); if ("missing".equals(suggestMode)) { return SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX; } else if ("popular".equals(suggestMode)) { return SuggestMode.SUGGEST_MORE_POPULAR; } else if ("always".equals(suggestMode)) { return SuggestMode.SUGGEST_ALWAYS; } else { throw new ElasticsearchIllegalArgumentException("Illegal suggest mode " + suggestMode); } } public static Suggest.Suggestion.Sort resolveSort(String sortVal) { if ("score".equals(sortVal)) { return Suggest.Suggestion.Sort.SCORE; } else if ("frequency".equals(sortVal)) { return Suggest.Suggestion.Sort.FREQUENCY; } else { throw new ElasticsearchIllegalArgumentException("Illegal suggest sort " + sortVal); } } public static StringDistance resolveDistance(String distanceVal) { if ("internal".equals(distanceVal)) { return DirectSpellChecker.INTERNAL_LEVENSHTEIN; } else if ("damerau_levenshtein".equals(distanceVal) || "damerauLevenshtein".equals(distanceVal)) { return new LuceneLevenshteinDistance(); } else if ("levenstein".equals(distanceVal)) { return new LevensteinDistance(); //TODO Jaro and Winkler are 2 people - so apply same naming logic as damerau_levenshtein } else if ("jarowinkler".equals(distanceVal)) { return new JaroWinklerDistance(); } else if ("ngram".equals(distanceVal)) { return new NGramDistance(); } else { throw new ElasticsearchIllegalArgumentException("Illegal distance option " + distanceVal); } } public static class Fields { public static final ParseField STRING_DISTANCE = new ParseField("string_distance"); public static final ParseField SUGGEST_MODE = new ParseField("suggest_mode"); public static final ParseField MAX_EDITS = new ParseField("max_edits"); public static final ParseField MAX_INSPECTIONS = new ParseField("max_inspections"); // TODO some of these constants are the same as MLT constants and // could be moved to a shared class for maintaining consistency across // the platform public static final ParseField MAX_TERM_FREQ = new ParseField("max_term_freq"); public static final ParseField PREFIX_LENGTH = new ParseField("prefix_length", "prefix_len"); public static final ParseField MIN_WORD_LENGTH = new ParseField("min_word_length", "min_word_len"); public static final ParseField MIN_DOC_FREQ = new ParseField("min_doc_freq"); public static final ParseField SHARD_SIZE = new ParseField("shard_size"); } public static boolean parseDirectSpellcheckerSettings(XContentParser parser, String fieldName, DirectSpellcheckerSettings suggestion) throws IOException { if ("accuracy".equals(fieldName)) { suggestion.accuracy(parser.floatValue()); } else if (Fields.SUGGEST_MODE.match(fieldName)) { suggestion.suggestMode(SuggestUtils.resolveSuggestMode(parser.text())); } else if ("sort".equals(fieldName)) { suggestion.sort(SuggestUtils.resolveSort(parser.text())); } else if (Fields.STRING_DISTANCE.match(fieldName)) { suggestion.stringDistance(SuggestUtils.resolveDistance(parser.text())); } else if (Fields.MAX_EDITS.match(fieldName)) { suggestion.maxEdits(parser.intValue()); if (suggestion.maxEdits() < 1 || suggestion.maxEdits() > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE) { throw new ElasticsearchIllegalArgumentException("Illegal max_edits value " + suggestion.maxEdits()); } } else if (Fields.MAX_INSPECTIONS.match(fieldName)) { suggestion.maxInspections(parser.intValue()); } else if (Fields.MAX_TERM_FREQ.match(fieldName)) { suggestion.maxTermFreq(parser.floatValue()); } else if (Fields.PREFIX_LENGTH.match(fieldName)) { suggestion.prefixLength(parser.intValue()); } else if (Fields.MIN_WORD_LENGTH.match(fieldName)) { suggestion.minQueryLength(parser.intValue()); } else if (Fields.MIN_DOC_FREQ.match(fieldName)) { suggestion.minDocFreq(parser.floatValue()); } else { return false; } return true; } public static boolean parseSuggestContext(XContentParser parser, MapperService mapperService, String fieldName, SuggestionSearchContext.SuggestionContext suggestion) throws IOException { if ("analyzer".equals(fieldName)) { String analyzerName = parser.text(); Analyzer analyzer = mapperService.analysisService().analyzer(analyzerName); if (analyzer == null) { throw new ElasticsearchIllegalArgumentException("Analyzer [" + analyzerName + "] doesn't exists"); } suggestion.setAnalyzer(analyzer); } else if ("field".equals(fieldName)) { suggestion.setField(parser.text()); } else if ("size".equals(fieldName)) { suggestion.setSize(parser.intValue()); } else if (Fields.SHARD_SIZE.match(fieldName)) { suggestion.setShardSize(parser.intValue()); } else { return false; } return true; } public static void verifySuggestion(MapperService mapperService, BytesRef globalText, SuggestionContext suggestion) { // Verify options and set defaults if (suggestion.getField() == null) { throw new ElasticsearchIllegalArgumentException("The required field option is missing"); } if (suggestion.getText() == null) { if (globalText == null) { throw new ElasticsearchIllegalArgumentException("The required text option is missing"); } suggestion.setText(globalText); } if (suggestion.getAnalyzer() == null) { suggestion.setAnalyzer(mapperService.searchAnalyzer()); } if (suggestion.getShardSize() == -1) { suggestion.setShardSize(Math.max(suggestion.getSize(), 5)); } } public static ShingleTokenFilterFactory.Factory getShingleFilterFactory(Analyzer analyzer) { if (analyzer instanceof NamedAnalyzer) { analyzer = ((NamedAnalyzer)analyzer).analyzer(); } if (analyzer instanceof CustomAnalyzer) { final CustomAnalyzer a = (CustomAnalyzer) analyzer; final TokenFilterFactory[] tokenFilters = a.tokenFilters(); for (TokenFilterFactory tokenFilterFactory : tokenFilters) { if (tokenFilterFactory instanceof ShingleTokenFilterFactory) { return ((ShingleTokenFilterFactory)tokenFilterFactory).getInnerFactory(); } else if (tokenFilterFactory instanceof ShingleTokenFilterFactory.Factory) { return (ShingleTokenFilterFactory.Factory) tokenFilterFactory; } } } return null; } }
1no label
src_main_java_org_elasticsearch_search_suggest_SuggestUtils.java
853
public interface OfferServiceExtensionHandler extends ExtensionHandler { public ExtensionResultStatusType applyAdditionalFilters(List<Offer> offers); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_OfferServiceExtensionHandler.java
290
filterText.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.keyCode == 0x0D || e.keyCode == SWT.KEYPAD_CR) // Enter key go(); if (e.keyCode == SWT.ARROW_DOWN) list.getTable().setFocus(); if (e.keyCode == SWT.ARROW_UP) list.getTable().setFocus(); if (e.character == 0x1B) // ESC dispose(); } public void keyReleased(KeyEvent e) { // do nothing } });
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_RecentFilesPopup.java
1,612
public class MetadataVisitorAdapter implements MetadataVisitor, Serializable { @Override public void visit(AdornedTargetCollectionMetadata metadata) { throw new IllegalArgumentException("Not supported in this context"); } @Override public void visit(BasicFieldMetadata metadata) { throw new IllegalArgumentException("Not supported in this context"); } @Override public void visit(BasicCollectionMetadata metadata) { throw new IllegalArgumentException("Not supported in this context"); } @Override public void visit(MapMetadata metadata) { throw new IllegalArgumentException("Not supported in this context"); } }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_visitor_MetadataVisitorAdapter.java
2,464
timer.schedule(new Runnable() { @Override public void run() { boolean removed = getQueue().remove(fCommand); if (removed) { timeoutCallback.run(); } } }, timeout.nanos(), TimeUnit.NANOSECONDS);
0true
src_main_java_org_elasticsearch_common_util_concurrent_PrioritizedEsThreadPoolExecutor.java
1,461
public class GroupShardsIterator implements Iterable<ShardIterator> { private final Collection<ShardIterator> iterators; public GroupShardsIterator(Collection<ShardIterator> iterators) { this.iterators = iterators; } /** * Returns the total number of shards within all groups * @return total number of shards */ public int totalSize() { int size = 0; for (ShardIterator shard : iterators) { size += shard.size(); } return size; } /** * Returns the total number of shards plus the number of empty groups * @return number of shards and empty groups */ public int totalSizeWith1ForEmpty() { int size = 0; for (ShardIterator shard : iterators) { int sizeActive = shard.size(); if (sizeActive == 0) { size += 1; } else { size += sizeActive; } } return size; } /** * Return the number of groups * @return number of groups */ public int size() { return iterators.size(); } /** * Return all group iterators * @return */ public Collection<ShardIterator> iterators() { return iterators; } @Override public Iterator<ShardIterator> iterator() { return iterators.iterator(); } }
0true
src_main_java_org_elasticsearch_cluster_routing_GroupShardsIterator.java
944
new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } lock.destroy(); } }).start();
0true
hazelcast_src_test_java_com_hazelcast_concurrent_lock_LockTest.java
217
public class ThreadLocalManager { private static final Log LOG = LogFactory.getLog(ThreadLocalManager.class); private static final ThreadLocal<ThreadLocalManager> THREAD_LOCAL_MANAGER = new ThreadLocal<ThreadLocalManager>() { @Override protected ThreadLocalManager initialValue() { return new ThreadLocalManager(); } }; protected Map<Long, ThreadLocal> threadLocals = new LinkedHashMap<Long, ThreadLocal>(); public static void addThreadLocal(ThreadLocal threadLocal) { Long position; synchronized (threadLock) { count++; position = count; } THREAD_LOCAL_MANAGER.get().threadLocals.put(position, threadLocal); } public static <T> ThreadLocal<T> createThreadLocal(final Class<T> type) { return createThreadLocal(type, true); } public static <T> ThreadLocal<T> createThreadLocal(final Class<T> type, final boolean createInitialValue) { ThreadLocal<T> response = new ThreadLocal<T>() { @Override protected T initialValue() { addThreadLocal(this); if (!createInitialValue) { return null; } try { return type.newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } @Override public void set(T value) { super.get(); super.set(value); } }; return response; } public static void remove() { for (Map.Entry<Long, ThreadLocal> entry : THREAD_LOCAL_MANAGER.get().threadLocals.entrySet()) { if (LOG.isDebugEnabled()) { LOG.debug("Removing ThreadLocal #" + entry.getKey() + " from request thread."); } entry.getValue().remove(); } THREAD_LOCAL_MANAGER.get().threadLocals.clear(); THREAD_LOCAL_MANAGER.remove(); } private static Long count = 0L; private static final Object threadLock = new Object(); }
0true
common_src_main_java_org_broadleafcommerce_common_classloader_release_ThreadLocalManager.java
2,850
public class DanishAnalyzerProvider extends AbstractIndexAnalyzerProvider<DanishAnalyzer> { private final DanishAnalyzer analyzer; @Inject public DanishAnalyzerProvider(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); analyzer = new DanishAnalyzer(version, Analysis.parseStopWords(env, settings, DanishAnalyzer.getDefaultStopSet(), version), Analysis.parseStemExclusion(settings, CharArraySet.EMPTY_SET, version)); } @Override public DanishAnalyzer get() { return this.analyzer; } }
0true
src_main_java_org_elasticsearch_index_analysis_DanishAnalyzerProvider.java
353
private class NodeShutdownRequestHandler extends BaseTransportRequestHandler<NodeShutdownRequest> { static final String ACTION = "/cluster/nodes/shutdown/node"; @Override public NodeShutdownRequest newInstance() { return new NodeShutdownRequest(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void messageReceived(final NodeShutdownRequest request, TransportChannel channel) throws Exception { if (disabled) { throw new ElasticsearchIllegalStateException("Shutdown is disabled"); } logger.info("shutting down in [{}]", delay); Thread t = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(delay.millis()); } catch (InterruptedException e) { // ignore } if (!request.exit) { logger.info("initiating requested shutdown (no exit)..."); try { node.close(); } catch (Exception e) { logger.warn("Failed to shutdown", e); } return; } boolean shutdownWithWrapper = false; if (System.getProperty("elasticsearch-service") != null) { try { Class wrapperManager = settings.getClassLoader().loadClass("org.tanukisoftware.wrapper.WrapperManager"); logger.info("initiating requested shutdown (using service)"); wrapperManager.getMethod("stopAndReturn", int.class).invoke(null, 0); shutdownWithWrapper = true; } catch (Throwable e) { logger.error("failed to initial shutdown on service wrapper", e); } } if (!shutdownWithWrapper) { logger.info("initiating requested shutdown..."); try { node.close(); } catch (Exception e) { logger.warn("Failed to shutdown", e); } finally { // make sure we initiate the shutdown hooks, so the Bootstrap#main thread will exit System.exit(0); } } } }); t.start(); channel.sendResponse(TransportResponse.Empty.INSTANCE); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_shutdown_TransportNodesShutdownAction.java
23
public class ControlStructureCompletions { }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ControlStructureCompletions.java
746
public class TransportExplainAction extends TransportShardSingleOperationAction<ExplainRequest, ExplainResponse> { private final IndicesService indicesService; private final ScriptService scriptService; private final CacheRecycler cacheRecycler; private final PageCacheRecycler pageCacheRecycler; @Inject public TransportExplainAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, IndicesService indicesService, ScriptService scriptService, CacheRecycler cacheRecycler, PageCacheRecycler pageCacheRecycler) { super(settings, threadPool, clusterService, transportService); this.indicesService = indicesService; this.scriptService = scriptService; this.cacheRecycler = cacheRecycler; this.pageCacheRecycler = pageCacheRecycler; } @Override protected void doExecute(ExplainRequest request, ActionListener<ExplainResponse> listener) { request.nowInMillis = System.currentTimeMillis(); super.doExecute(request, listener); } protected String transportAction() { return ExplainAction.NAME; } protected String executor() { return ThreadPool.Names.GET; // Or use Names.SEARCH? } @Override protected void resolveRequest(ClusterState state, ExplainRequest request) { String concreteIndex = state.metaData().concreteIndex(request.index()); request.filteringAlias(state.metaData().filteringAliases(concreteIndex, request.index())); request.index(state.metaData().concreteIndex(request.index())); // Fail fast on the node that received the request. if (request.routing() == null && state.getMetaData().routingRequired(request.index(), request.type())) { throw new RoutingMissingException(request.index(), request.type(), request.id()); } } protected ExplainResponse shardOperation(ExplainRequest request, int shardId) throws ElasticsearchException { IndexService indexService = indicesService.indexService(request.index()); IndexShard indexShard = indexService.shardSafe(shardId); Term uidTerm = new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(request.type(), request.id())); Engine.GetResult result = indexShard.get(new Engine.Get(false, uidTerm)); if (!result.exists()) { return new ExplainResponse(false); } SearchContext context = new DefaultSearchContext( 0, new ShardSearchRequest().types(new String[]{request.type()}) .filteringAliases(request.filteringAlias()) .nowInMillis(request.nowInMillis), null, result.searcher(), indexService, indexShard, scriptService, cacheRecycler, pageCacheRecycler ); SearchContext.setCurrent(context); try { context.parsedQuery(indexService.queryParserService().parseQuery(request.source())); context.preProcess(); int topLevelDocId = result.docIdAndVersion().docId + result.docIdAndVersion().context.docBase; Explanation explanation = context.searcher().explain(context.query(), topLevelDocId); for (RescoreSearchContext ctx : context.rescore()) { Rescorer rescorer = ctx.rescorer(); explanation = rescorer.explain(topLevelDocId, context, ctx, explanation); } if (request.fields() != null || (request.fetchSourceContext() != null && request.fetchSourceContext().fetchSource())) { // Advantage is that we're not opening a second searcher to retrieve the _source. Also // because we are working in the same searcher in engineGetResult we can be sure that a // doc isn't deleted between the initial get and this call. GetResult getResult = indexShard.getService().get(result, request.id(), request.type(), request.fields(), request.fetchSourceContext()); return new ExplainResponse(true, explanation, getResult); } else { return new ExplainResponse(true, explanation); } } catch (IOException e) { throw new ElasticsearchException("Could not explain", e); } finally { context.release(); SearchContext.removeCurrent(); } } protected ExplainRequest newRequest() { return new ExplainRequest(); } protected ExplainResponse newResponse() { return new ExplainResponse(); } protected ClusterBlockException checkGlobalBlock(ClusterState state, ExplainRequest request) { return state.blocks().globalBlockedException(ClusterBlockLevel.READ); } protected ClusterBlockException checkRequestBlock(ClusterState state, ExplainRequest request) { return state.blocks().indexBlockedException(ClusterBlockLevel.READ, request.index()); } protected ShardIterator shards(ClusterState state, ExplainRequest request) throws ElasticsearchException { return clusterService.operationRouting().getShards( clusterService.state(), request.index(), request.type(), request.id(), request.routing(), request.preference() ); } }
1no label
src_main_java_org_elasticsearch_action_explain_TransportExplainAction.java
1,281
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_REVIEW_DETAIL") public class ReviewDetailImpl implements ReviewDetail { @Id @GeneratedValue(generator = "ReviewDetailId") @GenericGenerator( name="ReviewDetailId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="ReviewDetailImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.rating.domain.ReviewDetailImpl") } ) @Column(name = "REVIEW_DETAIL_ID") private Long id; @ManyToOne(targetEntity = CustomerImpl.class, optional = false) @JoinColumn(name = "CUSTOMER_ID") @Index(name="REVIEWDETAIL_CUSTOMER_INDEX", columnNames={"CUSTOMER_ID"}) protected Customer customer; @Column(name = "REVIEW_SUBMITTED_DATE", nullable = false) protected Date reivewSubmittedDate; @Column(name = "REVIEW_TEXT", nullable = false) protected String reviewText; @Column(name = "REVIEW_STATUS", nullable = false) @Index(name="REVIEWDETAIL_STATUS_INDEX", columnNames={"REVIEW_STATUS"}) protected String reviewStatus; @Column(name = "HELPFUL_COUNT", nullable = false) protected Integer helpfulCount; @Column(name = "NOT_HELPFUL_COUNT", nullable = false) protected Integer notHelpfulCount; @ManyToOne(optional = false, targetEntity = RatingSummaryImpl.class) @JoinColumn(name = "RATING_SUMMARY_ID") @Index(name="REVIEWDETAIL_SUMMARY_INDEX", columnNames={"RATING_SUMMARY_ID"}) protected RatingSummary ratingSummary; @OneToMany(mappedBy = "reviewDetail", targetEntity = ReviewFeedbackImpl.class, cascade = {CascadeType.ALL}) protected List<ReviewFeedback> reviewFeedback; @OneToOne(targetEntity = RatingDetailImpl.class) @JoinColumn(name = "RATING_DETAIL_ID") @Index(name="REVIEWDETAIL_RATING_INDEX", columnNames={"RATING_DETAIL_ID"}) protected RatingDetail ratingDetail; public ReviewDetailImpl() {} public ReviewDetailImpl(Customer customer, Date reivewSubmittedDate, RatingDetail ratingDetail, String reviewText, RatingSummary ratingSummary) { super(); this.customer = customer; this.reivewSubmittedDate = reivewSubmittedDate; this.reviewText = reviewText; this.ratingSummary = ratingSummary; this.reviewFeedback = new ArrayList<ReviewFeedback>(); this.helpfulCount = Integer.valueOf(0); this.notHelpfulCount = Integer.valueOf(0); this.reviewStatus = ReviewStatusType.PENDING.getType(); this.ratingDetail = ratingDetail; } @Override public Date getReviewSubmittedDate() { return reivewSubmittedDate; } @Override public Long getId() { return id; } @Override public String getReviewText() { return reviewText; } @Override public void setReviewText(String reviewText) { this.reviewText = reviewText; } @Override public ReviewStatusType getStatus() { return new ReviewStatusType(reviewStatus); } @Override public Customer getCustomer() { return customer; } @Override public Integer helpfulCount() { return helpfulCount; } @Override public Integer notHelpfulCount() { return notHelpfulCount; } @Override public RatingSummary getRatingSummary() { return ratingSummary; } @Override public RatingDetail getRatingDetail() { return ratingDetail; } @Override public List<ReviewFeedback> getReviewFeedback() { return reviewFeedback == null ? new ArrayList<ReviewFeedback>() : reviewFeedback; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_rating_domain_ReviewDetailImpl.java
122
public enum ConsistencyModifier { /** * Uses the default consistency model guaranteed by the enclosing transaction against the configured * storage backend. * </p> * What this means exactly, depends on the configuration of the storage backend as well as the (optional) configuration * of the enclosing transaction. */ DEFAULT, /** * Locks will be explicitly acquired to guarantee consistency if the storage backend supports locks. * </p> * The exact consistency guarantees depend on the configured lock implementation. * </p> * Note, that locking may be ignored under certain transaction configurations. */ LOCK, /** * Causes Titan to delete and add a new edge/property instead of overwriting an existing one, hence avoiding potential * concurrent write conflicts. This only applies to multi-edges and list-properties. * </p> * Note, that this potentially impacts how the data should be read. */ FORK; }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_schema_ConsistencyModifier.java
1,886
class Reflection { /** * A placeholder. This enables us to continue processing and gather more * errors but blows up if you actually try to use it. */ static class InvalidConstructor { InvalidConstructor() { throw new AssertionError(); } } @SuppressWarnings("unchecked") static <T> Constructor<T> invalidConstructor() { try { return (Constructor<T>) InvalidConstructor.class.getDeclaredConstructor(); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } }
0true
src_main_java_org_elasticsearch_common_inject_Reflection.java
3,057
public class PreBuiltPostingsFormatProvider implements PostingsFormatProvider { public static final class Factory implements PostingsFormatProvider.Factory { private final PreBuiltPostingsFormatProvider provider; public Factory(PostingsFormat postingsFormat) { this(postingsFormat.getName(), postingsFormat); } public Factory(String name, PostingsFormat postingsFormat) { this.provider = new PreBuiltPostingsFormatProvider(name, postingsFormat); } public PostingsFormatProvider get() { return provider; } @Override public PostingsFormatProvider create(String name, Settings settings) { return provider; } public String name() { return provider.name(); } } private final String name; private final PostingsFormat postingsFormat; public PreBuiltPostingsFormatProvider(PostingsFormat postingsFormat) { this(postingsFormat.getName(), postingsFormat); } public PreBuiltPostingsFormatProvider(String name, PostingsFormat postingsFormat) { if (postingsFormat == null) { throw new IllegalArgumentException("PostingsFormat must not be null"); } this.name = name; this.postingsFormat = postingsFormat; } @Override public String name() { return name; } @Override public PostingsFormat get() { return postingsFormat; } }
0true
src_main_java_org_elasticsearch_index_codec_postingsformat_PreBuiltPostingsFormatProvider.java
544
flushAction.execute(Requests.flushRequest(request.indices()), new ActionListener<FlushResponse>() { @Override public void onResponse(FlushResponse flushResponse) { // get all types that need to be deleted. ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> result = clusterService.state().metaData().findMappings( request.indices(), request.types() ); // create OrFilter with type filters within to account for different types BoolFilterBuilder filterBuilder = new BoolFilterBuilder(); Set<String> types = new HashSet<String>(); for (ObjectObjectCursor<String, ImmutableOpenMap<String, MappingMetaData>> typesMeta : result) { for (ObjectObjectCursor<String, MappingMetaData> type : typesMeta.value) { filterBuilder.should(new TypeFilterBuilder(type.key)); types.add(type.key); } } if (types.size() == 0) { throw new TypeMissingException(new Index("_all"), request.types(), "No index has the type."); } request.types(types.toArray(new String[types.size()])); QuerySourceBuilder querySourceBuilder = new QuerySourceBuilder() .setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), filterBuilder)); deleteByQueryAction.execute(Requests.deleteByQueryRequest(request.indices()).source(querySourceBuilder), new ActionListener<DeleteByQueryResponse>() { @Override public void onResponse(DeleteByQueryResponse deleteByQueryResponse) { refreshAction.execute(Requests.refreshRequest(request.indices()), new ActionListener<RefreshResponse>() { @Override public void onResponse(RefreshResponse refreshResponse) { removeMapping(); } @Override public void onFailure(Throwable e) { removeMapping(); } protected void removeMapping() { DeleteMappingClusterStateUpdateRequest clusterStateUpdateRequest = new DeleteMappingClusterStateUpdateRequest() .indices(request.indices()).types(request.types()) .ackTimeout(request.timeout()) .masterNodeTimeout(request.masterNodeTimeout()); metaDataMappingService.removeMapping(clusterStateUpdateRequest, new ClusterStateUpdateListener() { @Override public void onResponse(ClusterStateUpdateResponse response) { listener.onResponse(new DeleteMappingResponse(response.isAcknowledged())); } @Override public void onFailure(Throwable t) { listener.onFailure(t); } }); } }); } @Override public void onFailure(Throwable t) { listener.onFailure(t); } }); } @Override public void onFailure(Throwable t) { listener.onFailure(t); } });
1no label
src_main_java_org_elasticsearch_action_admin_indices_mapping_delete_TransportDeleteMappingAction.java
591
public final class HeartbeatOperation extends AbstractClusterOperation implements JoinOperation, IdentifiedDataSerializable { @Override public void run() { // do nothing ... } @Override public int getFactoryId() { return ClusterDataSerializerHook.F_ID; } @Override public int getId() { return ClusterDataSerializerHook.HEARTBEAT; } }
0true
hazelcast_src_main_java_com_hazelcast_cluster_HeartbeatOperation.java
120
public class TxManager extends AbstractTransactionManager implements Lifecycle { public interface Monitor { void txStarted( Xid xid ); void txCommitted( Xid xid ); void txRolledBack( Xid xid ); void txManagerStopped(); public static class Adapter implements Monitor { @Override public void txStarted( Xid xid ) { } @Override public void txCommitted( Xid xid ) { } @Override public void txRolledBack( Xid xid ) { } @Override public void txManagerStopped() { } } } private ThreadLocalWithSize<TransactionImpl> txThreadMap; // private ThreadLocalWithSize<TransactionImpl> txThreadMap = new ThreadLocalWithSize<>(); private final File txLogDir; private File logSwitcherFileName = null; private String txLog1FileName = "tm_tx_log.1"; private String txLog2FileName = "tm_tx_log.2"; private final int maxTxLogRecordCount = 1000; private final AtomicInteger eventIdentifierCounter = new AtomicInteger( 0 ); private final Map<RecoveredBranchInfo, Boolean> branches = new HashMap<>(); private volatile TxLog txLog = null; private final AtomicInteger startedTxCount = new AtomicInteger( 0 ); private final AtomicInteger comittedTxCount = new AtomicInteger( 0 ); private final AtomicInteger rolledBackTxCount = new AtomicInteger( 0 ); private int peakConcurrentTransactions = 0; private final StringLogger log; private final XaDataSourceManager xaDataSourceManager; private final FileSystemAbstraction fileSystem; private TxManager.TxManagerDataSourceRegistrationListener dataSourceRegistrationListener; private Throwable recoveryError; private final TransactionStateFactory stateFactory; private final Factory<byte[]> xidGlobalIdFactory; private final KernelHealth kernelHealth; private final Monitors monitors; private final Monitor monitor; public TxManager( File txLogDir, XaDataSourceManager xaDataSourceManager, StringLogger log, FileSystemAbstraction fileSystem, TransactionStateFactory stateFactory, Factory<byte[]> xidGlobalIdFactory, KernelHealth kernelHealth, Monitors monitors ) { this( txLogDir, xaDataSourceManager, log, fileSystem, stateFactory, new Monitor.Adapter(), xidGlobalIdFactory, kernelHealth, monitors ); } public TxManager( File txLogDir, XaDataSourceManager xaDataSourceManager, StringLogger log, FileSystemAbstraction fileSystem, TransactionStateFactory stateFactory, Monitor monitor, Factory<byte[]> xidGlobalIdFactory, KernelHealth kernelHealth, Monitors monitors ) { this.txLogDir = txLogDir; this.xaDataSourceManager = xaDataSourceManager; this.fileSystem = fileSystem; this.log = log; this.stateFactory = stateFactory; this.monitor = monitor; this.xidGlobalIdFactory = xidGlobalIdFactory; this.kernelHealth = kernelHealth; this.monitors = monitors; } int getNextEventIdentifier() { return eventIdentifierCounter.incrementAndGet(); } private <E extends Exception> E logAndReturn( String msg, E exception ) { try { log.error( msg, exception ); return exception; } catch ( Throwable t ) { return exception; } } private volatile boolean recovered = false; @Override public void init() { } @Override public synchronized void start() throws Throwable { txThreadMap = new ThreadLocalWithSize<>(); openLog(); findPendingDatasources(); dataSourceRegistrationListener = new TxManagerDataSourceRegistrationListener(); xaDataSourceManager.addDataSourceRegistrationListener( dataSourceRegistrationListener ); } private void findPendingDatasources() { try { Iterable<List<TxLog.Record>> danglingRecordList = txLog.getDanglingRecords(); for ( List<TxLog.Record> tx : danglingRecordList ) { for ( TxLog.Record rec : tx ) { if ( rec.getType() == TxLog.BRANCH_ADD ) { RecoveredBranchInfo branchId = new RecoveredBranchInfo( rec.getBranchId()) ; if ( branches.containsKey( branchId ) ) { continue; } branches.put( branchId, false ); } } } } catch ( IOException e ) { throw logAndReturn( "Failed to start transaction manager: Unable to recover pending branches.", new TransactionFailureException( "Unable to start TM", e ) ); } } @Override public synchronized void stop() { recovered = false; xaDataSourceManager.removeDataSourceRegistrationListener( dataSourceRegistrationListener ); closeLog(); monitor.txManagerStopped(); } @Override public void shutdown() throws Throwable { } synchronized TxLog getTxLog() throws IOException { if ( txLog.getRecordCount() > maxTxLogRecordCount ) { if ( txLog.getName().endsWith( txLog1FileName ) ) { txLog.switchToLogFile( new File( txLogDir, txLog2FileName )); changeActiveLog( txLog2FileName ); } else if ( txLog.getName().endsWith( txLog2FileName ) ) { txLog.switchToLogFile( new File( txLogDir, txLog1FileName )); changeActiveLog( txLog1FileName ); } else { setTmNotOk( new Exception( "Unknown active tx log file[" + txLog.getName() + "], unable to switch." ) ); final IOException ex = new IOException( "Unknown txLogFile[" + txLog.getName() + "] not equals to either [" + txLog1FileName + "] or [" + txLog2FileName + "]" ); throw logAndReturn( "TM error accessing log file", ex ); } } return txLog; } private void closeLog() { if ( txLog != null ) { try { txLog.close(); txLog = null; recovered = false; } catch ( IOException e ) { log.error( "Unable to close tx log[" + txLog.getName() + "]", e ); } } log.info( "TM shutting down" ); } private void changeActiveLog( String newFileName ) throws IOException { // change active log StoreChannel fc = fileSystem.open( logSwitcherFileName, "rw" ); ByteBuffer buf = ByteBuffer.wrap( UTF8.encode( newFileName ) ); fc.truncate( 0 ); fc.write( buf ); fc.force( true ); fc.close(); } synchronized void setTmNotOk( Throwable cause ) { kernelHealth.panic( cause ); } @Override public void begin() throws NotSupportedException, SystemException { begin( ForceMode.forced ); } @Override public void begin( ForceMode forceMode ) throws NotSupportedException, SystemException { assertTmOk(); TransactionImpl tx = txThreadMap.get(); if ( tx != null ) { throw logAndReturn( "TM error tx begin", new NotSupportedException( "Nested transactions not supported. Thread: " + Thread.currentThread() ) ); } tx = new TransactionImpl( xidGlobalIdFactory.newInstance(), this, forceMode, stateFactory, log ); txThreadMap.set( tx ); int concurrentTxCount = txThreadMap.size(); if ( concurrentTxCount > peakConcurrentTransactions ) { peakConcurrentTransactions = concurrentTxCount; } startedTxCount.incrementAndGet(); monitor.txStarted( new XidImpl( tx.getGlobalId(), new byte[0] ) ); // start record written on resource enlistment } private void assertTmOk() throws SystemException { if ( !recovered ) { throw new SystemException( "TxManager not recovered" ); } kernelHealth.assertHealthy( SystemException.class ); } // called when a resource gets enlisted void writeStartRecord( byte globalId[] ) throws SystemException { try { getTxLog().txStart( globalId ); } catch ( IOException e ) { setTmNotOk( e ); throw logAndReturn( "Error writing start record", Exceptions.withCause( new SystemException( "TM " + "encountered a problem, " + " error writing transaction log," ), e ) ); } } @Override public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, IllegalStateException, SystemException { TransactionImpl tx = txThreadMap.get(); if ( tx == null ) { throw logAndReturn( "TM error tx commit", new IllegalStateException( "Not in transaction. Thread: " + Thread.currentThread() ) ); } boolean successful = false; try { assertTmOk(); if ( tx.getStatus() != Status.STATUS_ACTIVE && tx.getStatus() != Status.STATUS_MARKED_ROLLBACK ) { throw logAndReturn( "TM error tx commit", new IllegalStateException( "Tx status is: " + getTxStatusAsString( tx.getStatus() ) ) ); } tx.doBeforeCompletion(); // delist resources? if ( tx.getStatus() == Status.STATUS_ACTIVE ) { comittedTxCount.incrementAndGet(); commit( tx ); } else if ( tx.getStatus() == Status.STATUS_MARKED_ROLLBACK ) { rolledBackTxCount.incrementAndGet(); rollbackCommit( tx ); } else { throw logAndReturn( "TM error tx commit", new IllegalStateException( "Tx status is: " + getTxStatusAsString( tx.getStatus() ) ) ); } successful = true; } finally { // Call after completion as a safety net tx.doAfterCompletion(); monitor.txCommitted( new XidImpl( tx.getGlobalId(), new byte[0] ) ); txThreadMap.remove(); if ( successful ) { tx.finish( true ); } else { try { tx.finish( false ); } catch ( RuntimeException e ) { log.error( "Failed to commit transaction, and was then subsequently unable to " + "finish the failed tx.", e ); } } } } private void commit( TransactionImpl tx ) throws SystemException, HeuristicMixedException, HeuristicRollbackException { // mark as commit in log done TxImpl.doCommit() Throwable commitFailureCause = null; int xaErrorCode = -1; /* * The attempt to commit and the corresponding rollback in case of failure happens under the same lock. * This is necessary for a transaction to be able to cleanup its state in case it fails to commit * without any other transaction coming in and disrupting things. Hooks will be called under this * lock in case of rollback but not if commit succeeds, which should be ok throughput wise. There is * some performance degradation related to this, since now we hold a lock over commit() for * (potentially) all resource managers, while without this monitor each commit() on each * XaResourceManager locks only that. */ if ( tx.getResourceCount() == 0 ) { tx.setStatus( Status.STATUS_COMMITTED ); } else { try { tx.doCommit(); } catch ( CommitNotificationFailedException e ) { // Let this pass through. Catching this exception here will still have the exception // propagate out to the user (wrapped in a TransactionFailureException), but will not // set this transaction manager in "not OK" state. // At the time of adding this, this approach was chosen over throwing an XAException // with a specific error code since no error code seemed suitable. log.warn( "Commit notification failed: " + e ); } catch ( XAException e ) { // Behold, the error handling decision maker of great power. // // The thinking behind the code below is that there are certain types of errors that we understand, // and know that we can safely roll back after they occur. An example would be a user trying to delete // a node that still has relationships. For these errors, we keep a whitelist (the switch below), // and roll back when they occur. // // For *all* errors that we don't know exactly what they mean, we panic and run around in circles. // Other errors could involve out of disk space (can't recover) or out of memory (can't recover) // or anything else. The point is that there is no way for us to trust the state of the system any // more, so we set transaction manager to not ok and expect the user to fix the problem and do recovery. switch(e.errorCode) { // These are error states that we can safely recover from /* * User tried to delete a node that still had relationships, or in some other way violated * data model constraints. */ case XAException.XA_RBINTEGRITY: /* * A network error occurred. */ case XAException.XA_HEURCOM: xaErrorCode = e.errorCode; commitFailureCause = e; log.error( "Commit failed, status=" + getTxStatusAsString( tx.getStatus() ) + ", errorCode=" + xaErrorCode, e ); break; // Error codes where we are not *certain* that we still know the state of the system default: setTmNotOk( e ); throw logAndReturn("TM error tx commit",new TransactionFailureException( "commit threw exception", e )); } } catch ( Throwable t ) { setTmNotOk( t ); // this should never be throw logAndReturn("Commit failed for " + tx, new TransactionFailureException( "commit threw exception but status is committed?", t )); } } if ( tx.getStatus() != Status.STATUS_COMMITTED ) { try { tx.doRollback(); } catch ( Throwable e ) { setTmNotOk( e ); String commitError = commitFailureCause != null ? "error in commit: " + commitFailureCause : "error code in commit: " + xaErrorCode; String rollbackErrorCode = "Unknown error code"; if ( e instanceof XAException ) { rollbackErrorCode = Integer.toString( ((XAException) e).errorCode ); } throw logAndReturn( "Unable to rollback transaction "+ tx +". " + "Some resources may be commited others not. " + "Neo4j kernel should be SHUTDOWN for " + "resource maintance and transaction recovery ---->", Exceptions.withCause( new HeuristicMixedException( "Unable to rollback "+tx+" ---> " + commitError + " ---> error code for rollback: " + rollbackErrorCode ), e ) ); } tx.doAfterCompletion(); try { if ( tx.isGlobalStartRecordWritten() ) { getTxLog().txDone( tx.getGlobalId() ); } } catch ( IOException e ) { setTmNotOk( e ); throw logAndReturn( "Error writing transaction log for " + tx, Exceptions.withCause( new SystemException( "TM encountered a problem, while committing transaction " + tx + ", error writing transaction log" ), e ) ); } tx.setStatus( Status.STATUS_NO_TRANSACTION ); if ( commitFailureCause == null ) { throw logAndReturn( "TM error tx commit", new HeuristicRollbackException( "Failed to commit, transaction "+ tx +" rolled back ---> " + "error code was: " + xaErrorCode ) ); } else { throw logAndReturn( "TM error tx commit", Exceptions.withCause( new HeuristicRollbackException( "Failed to commit transaction "+ tx +", transaction rolled back ---> " + commitFailureCause ), commitFailureCause ) ); } } tx.doAfterCompletion(); try { if ( tx.isGlobalStartRecordWritten() ) { getTxLog().txDone( tx.getGlobalId() ); } } catch ( IOException e ) { setTmNotOk( e ); throw logAndReturn( "Error writing transaction log for " + tx, Exceptions.withCause( new SystemException( "TM encountered a problem, " + " error writing transaction log for "+ tx ), e ) ); } tx.setStatus( Status.STATUS_NO_TRANSACTION ); } private void rollbackCommit( TransactionImpl tx ) throws HeuristicMixedException, RollbackException, SystemException { try { tx.doRollback(); } catch ( XAException e ) { setTmNotOk( e ); throw logAndReturn( "Unable to rollback marked transaction. " + "Some resources may be commited others not. " + "Neo4j kernel should be SHUTDOWN for " + "resource maintance and transaction recovery: " + tx, Exceptions.withCause( new HeuristicMixedException( "Unable to rollback " + tx + " ---> error code for rollback: " + e.errorCode ), e ) ); } tx.doAfterCompletion(); try { if ( tx.isGlobalStartRecordWritten() ) { getTxLog().txDone( tx.getGlobalId() ); } } catch ( IOException e ) { setTmNotOk( e ); throw logAndReturn( "Error writing transaction log for " + tx, Exceptions.withCause( new SystemException( "TM encountered a problem, error writing transaction log" ), e ) ); } tx.setStatus( Status.STATUS_NO_TRANSACTION ); RollbackException rollbackException = new RollbackException( "Failed to commit, transaction rolled back" ); ExceptionCauseSetter.setCause( rollbackException, tx.getRollbackCause() ); throw rollbackException; } @Override public void rollback() throws IllegalStateException, SystemException { TransactionImpl tx = txThreadMap.get(); if ( tx == null ) { throw logAndReturn( "TM error tx commit", new IllegalStateException( "Not in transaction. Thread: " + Thread.currentThread() ) ); } try { assertTmOk(); if ( tx.getStatus() == Status.STATUS_ACTIVE || tx.getStatus() == Status.STATUS_MARKED_ROLLBACK || tx.getStatus() == Status.STATUS_PREPARING ) { tx.setStatus( Status.STATUS_MARKED_ROLLBACK ); tx.doBeforeCompletion(); // delist resources? try { rolledBackTxCount.incrementAndGet(); tx.doRollback(); } catch ( XAException e ) { setTmNotOk( e ); throw logAndReturn( "Unable to rollback marked or active transaction "+ tx +". " + "Some resources may be commited others not. " + "Neo4j kernel should be SHUTDOWN for " + "resource maintance and transaction recovery ---->", Exceptions.withCause( new SystemException( "Unable to rollback " + tx + " ---> error code for rollback: " + e.errorCode ), e ) ); } tx.doAfterCompletion(); try { if ( tx.isGlobalStartRecordWritten() ) { getTxLog().txDone( tx.getGlobalId() ); } } catch ( IOException e ) { setTmNotOk( e ); throw logAndReturn( "Error writing transaction log for " + tx, Exceptions.withCause( new SystemException( "TM encountered a problem, " + " error writing transaction log" ), e ) ); } tx.setStatus( Status.STATUS_NO_TRANSACTION ); } else { throw new IllegalStateException( "Tx status is: " + getTxStatusAsString( tx.getStatus() ) ); } } finally { // Call after completion as a safety net tx.doAfterCompletion(); txThreadMap.remove(); tx.finish( false ); } monitor.txRolledBack( new XidImpl( tx.getGlobalId(), new byte[0] ) ); } @Override public int getStatus() { TransactionImpl tx = txThreadMap.get(); if ( tx != null ) { return tx.getStatus(); } return Status.STATUS_NO_TRANSACTION; } @Override public Transaction getTransaction() throws SystemException { // It's pretty important that we check the tmOk state here. This method is called from getForceMode // which in turn is called from XaResourceManager.commit(Xid, boolean) and so on all the way up to // TxManager.commit(Thread, TransactionImpl), wherein the monitor lock on TxManager is held! // It's very important that we check the tmOk state, during commit, while holding the lock on the // TxManager, as we could otherwise get into a situation where a transaction crashes the database // during commit, while another makes it past the check and then procedes to rotate the log, making // the crashed transaction unrecoverable. assertTmOk(); return txThreadMap.get(); } @Override public void resume( Transaction tx ) throws IllegalStateException, SystemException { assertTmOk(); Transaction associatedTx = txThreadMap.get(); if ( associatedTx != null ) { throw new ThreadAssociatedWithOtherTransactionException( Thread.currentThread(), associatedTx, tx ); } TransactionImpl txImpl = (TransactionImpl) tx; if ( txImpl.getStatus() != Status.STATUS_NO_TRANSACTION ) { if ( txImpl.isActive() ) { throw new TransactionAlreadyActiveException( Thread.currentThread(), tx ); } txImpl.markAsActive(); txThreadMap.set( txImpl ); } } @Override public Transaction suspend() throws SystemException { assertTmOk(); // check for ACTIVE/MARKED_ROLLBACK? TransactionImpl tx = txThreadMap.get(); if ( tx != null ) { txThreadMap.remove(); tx.markAsSuspended(); } // OK to return null here according to the JTA spec (at least 1.1) return tx; } @Override public void setRollbackOnly() throws IllegalStateException, SystemException { assertTmOk(); TransactionImpl tx = txThreadMap.get(); if ( tx == null ) { throw new IllegalStateException( "Not in transaction. Thread: " + Thread.currentThread() ); } tx.setRollbackOnly(); } @Override public void setTransactionTimeout( int seconds ) throws SystemException { assertTmOk(); // ... } private void openLog() { logSwitcherFileName = new File( txLogDir, "active_tx_log"); txLog1FileName = "tm_tx_log.1"; txLog2FileName = "tm_tx_log.2"; try { if ( fileSystem.fileExists( logSwitcherFileName ) ) { StoreChannel fc = fileSystem.open( logSwitcherFileName, "rw" ); byte fileName[] = new byte[256]; ByteBuffer buf = ByteBuffer.wrap( fileName ); fc.read( buf ); fc.close(); File currentTxLog = new File( txLogDir, UTF8.decode( fileName ).trim()); if ( !fileSystem.fileExists( currentTxLog ) ) { throw logAndReturn( "TM startup failure", new TransactionFailureException( "Unable to start TM, " + "active tx log file[" + currentTxLog + "] not found." ) ); } txLog = new TxLog( currentTxLog, fileSystem, monitors ); log.info( "TM opening log: " + currentTxLog ); } else { if ( fileSystem.fileExists( new File( txLogDir, txLog1FileName )) || fileSystem.fileExists( new File( txLogDir, txLog2FileName ) )) { throw logAndReturn( "TM startup failure", new TransactionFailureException( "Unable to start TM, " + "no active tx log file found but found either " + txLog1FileName + " or " + txLog2FileName + " file, please set one of them as active or " + "remove them." ) ); } ByteBuffer buf = ByteBuffer.wrap( txLog1FileName .getBytes( "UTF-8" ) ); StoreChannel fc = fileSystem.open( logSwitcherFileName, "rw" ); fc.write( buf ); txLog = new TxLog( new File( txLogDir, txLog1FileName), fileSystem, monitors ); log.info( "TM new log: " + txLog1FileName ); fc.force( true ); fc.close(); } } catch ( IOException e ) { throw logAndReturn( "TM startup failure", new TransactionFailureException( "Unable to start TM", e ) ); } } @Override public void doRecovery() { if ( txLog == null ) { openLog(); } if ( recovered ) { return; } try { // Assuming here that the last datasource to register is the Neo one // Do recovery on start - all Resources should be registered by now Iterable<List<TxLog.Record>> knownDanglingRecordList = txLog.getDanglingRecords(); boolean danglingRecordsFound = knownDanglingRecordList.iterator().hasNext(); if ( danglingRecordsFound ) { log.info( "Unresolved transactions found in " + txLog.getName() + ", recovery started... " ); } // Recover DataSources. Always call due to some internal state using it as a trigger. xaDataSourceManager.recover( knownDanglingRecordList.iterator() ); if ( danglingRecordsFound ) { log.info( "Recovery completed, all transactions have been " + "resolved to a consistent state." ); } getTxLog().truncate(); recovered = true; kernelHealth.healed(); } catch ( Throwable t ) { setTmNotOk( t ); recoveryError = t; } } byte[] getBranchId( XAResource xaRes ) { if ( xaRes instanceof XaResource ) { byte branchId[] = ((XaResource) xaRes).getBranchId(); if ( branchId != null ) { return branchId; } } return xaDataSourceManager.getBranchId( xaRes ); } String getTxStatusAsString( int status ) { switch ( status ) { case Status.STATUS_ACTIVE: return "STATUS_ACTIVE"; case Status.STATUS_NO_TRANSACTION: return "STATUS_NO_TRANSACTION"; case Status.STATUS_PREPARING: return "STATUS_PREPARING"; case Status.STATUS_PREPARED: return "STATUS_PREPARED"; case Status.STATUS_COMMITTING: return "STATUS_COMMITING"; case Status.STATUS_COMMITTED: return "STATUS_COMMITED"; case Status.STATUS_ROLLING_BACK: return "STATUS_ROLLING_BACK"; case Status.STATUS_ROLLEDBACK: return "STATUS_ROLLEDBACK"; case Status.STATUS_UNKNOWN: return "STATUS_UNKNOWN"; case Status.STATUS_MARKED_ROLLBACK: return "STATUS_MARKED_ROLLBACK"; default: return "STATUS_UNKNOWN(" + status + ")"; } } /** * @return The current transaction's event identifier or -1 if no * transaction is currently running. */ @Override public int getEventIdentifier() { TransactionImpl tx; try { tx = (TransactionImpl) getTransaction(); } catch ( SystemException e ) { throw new RuntimeException( e ); } if ( tx != null ) { return tx.getEventIdentifier(); } return -1; } @Override public ForceMode getForceMode() { try { // The call to getTransaction() is important. See the comment in getTransaction(). return ((TransactionImpl)getTransaction()).getForceMode(); } catch ( SystemException e ) { throw new RuntimeException( e ); } } @Override public Throwable getRecoveryError() { return recoveryError; } public int getStartedTxCount() { return startedTxCount.get(); } public int getCommittedTxCount() { return comittedTxCount.get(); } public int getRolledbackTxCount() { return rolledBackTxCount.get(); } public int getActiveTxCount() { return txThreadMap.size(); } public int getPeakConcurrentTxCount() { return peakConcurrentTransactions; } @Override public TransactionState getTransactionState() { Transaction tx; try { tx = getTransaction(); } catch ( SystemException e ) { throw new RuntimeException( e ); } return tx != null ? ((TransactionImpl)tx).getState() : TransactionState.NO_STATE; } private class TxManagerDataSourceRegistrationListener implements DataSourceRegistrationListener { @Override public void registeredDataSource( XaDataSource ds ) { branches.put( new RecoveredBranchInfo( ds.getBranchId() ), true ); boolean everythingRegistered = true; for ( boolean dsRegistered : branches.values() ) { everythingRegistered &= dsRegistered; } if ( everythingRegistered ) { doRecovery(); } } @Override public void unregisteredDataSource( XaDataSource ds ) { branches.put( new RecoveredBranchInfo( ds.getBranchId() ), false ); boolean everythingUnregistered = true; for ( boolean dsRegistered : branches.values() ) { everythingUnregistered &= !dsRegistered; } if ( everythingUnregistered ) { closeLog(); } } } /* * We use a hash map to store the branch ids. byte[] however does not offer a useful implementation of equals() or * hashCode(), so we need a wrapper that does that. */ private static final class RecoveredBranchInfo { final byte[] branchId; private RecoveredBranchInfo( byte[] branchId ) { this.branchId = branchId; } @Override public int hashCode() { return Arrays.hashCode( branchId ); } @Override public boolean equals( Object obj ) { if ( obj == null || obj.getClass() != RecoveredBranchInfo.class ) { return false; } return Arrays.equals( branchId, ( ( RecoveredBranchInfo )obj ).branchId ); } } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TxManager.java
169
public static interface ForkJoinWorkerThreadFactory { /** * Returns a new worker thread operating in the given pool. * * @param pool the pool this thread works in * @throws NullPointerException if the pool is null */ public ForkJoinWorkerThread newThread(ForkJoinPool pool); }
0true
src_main_java_jsr166y_ForkJoinPool.java
1,654
@Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD}) public @interface Nullable { }
0true
src_main_java_org_elasticsearch_common_Nullable.java
214
Collections.sort(indexes, new Comparator<OIndex<?>>() { public int compare(OIndex<?> o1, OIndex<?> o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } });
0true
tools_src_main_java_com_orientechnologies_orient_console_OConsoleDatabaseApp.java
1,365
private static class ScriptCallable implements Callable, Serializable, HazelcastInstanceAware { private final String script; private final Map<String, Object> map; private transient HazelcastInstance hazelcastInstance; ScriptCallable(String script, Map<String, Object> map) { this.script = script; this.map = map; } public Object call() { final ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine e = scriptEngineManager.getEngineByName("javascript"); if (map != null) { for (Map.Entry<String, Object> entry : map.entrySet()) { e.put(entry.getKey(), entry.getValue()); } } e.put("hazelcast", hazelcastInstance); try { // For new JavaScript engine called Nashorn we need the compatibility script if (e.getFactory().getEngineName().toLowerCase().contains("nashorn")) { e.eval("load('nashorn:mozilla_compat.js');"); } e.eval("importPackage(java.lang);"); e.eval("importPackage(java.util);"); e.eval("importPackage(com.hazelcast.core);"); e.eval("importPackage(com.hazelcast.config);"); e.eval("importPackage(java.util.concurrent);"); e.eval("importPackage(org.junit);"); return e.eval(script); } catch (ScriptException e1) { throw new RuntimeException(e1); } } public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { this.hazelcastInstance = hazelcastInstance; } }
0true
hazelcast_src_test_java_com_hazelcast_executor_ExecutorServiceTest.java
2,056
public interface TypeConverter { /** * Converts a string value. Throws an exception if a conversion error occurs. */ Object convert(String value, TypeLiteral<?> toType); }
0true
src_main_java_org_elasticsearch_common_inject_spi_TypeConverter.java
763
@Test public class OSBTreeBonsaiTest { private static final int KEYS_COUNT = 500000; private ODatabaseDocumentTx databaseDocumentTx; protected OSBTreeBonsai<Integer, OIdentifiable> sbTree; @BeforeClass public void beforeClass() { String buildDirectory = System.getProperty("buildDirectory"); if (buildDirectory == null) buildDirectory = "./target"; databaseDocumentTx = new ODatabaseDocumentTx("plocal:" + buildDirectory + "/localSBTreeBonsaiTest"); if (databaseDocumentTx.exists()) { databaseDocumentTx.open("admin", "admin"); databaseDocumentTx.drop(); } databaseDocumentTx.create(); sbTree = new OSBTreeBonsai<Integer, OIdentifiable>(".irs", 1, false); sbTree.create("OSBTreeBonsaiTest", OIntegerSerializer.INSTANCE, OLinkSerializer.INSTANCE, (OStorageLocalAbstract) databaseDocumentTx.getStorage()); } @AfterMethod public void afterMethod() throws Exception { sbTree.clear(); } @AfterClass public void afterClass() throws Exception { sbTree.clear(); sbTree.delete(); databaseDocumentTx.drop(); } public void testKeyPut() throws Exception { for (int i = 0; i < KEYS_COUNT; i++) { sbTree.put(i, new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); } for (int i = 0; i < KEYS_COUNT; i++) Assert.assertEquals(sbTree.get(i), new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i)), i + " key is absent"); Assert.assertEquals(0, (int) sbTree.firstKey()); Assert.assertEquals(KEYS_COUNT - 1, (int) sbTree.lastKey()); for (int i = KEYS_COUNT; i < 2 * KEYS_COUNT; i++) Assert.assertNull(sbTree.get(i)); } public void testKeyPutRandomUniform() throws Exception { final NavigableSet<Integer> keys = new TreeSet<Integer>(); final MersenneTwisterFast random = new MersenneTwisterFast(); while (keys.size() < KEYS_COUNT) { int key = random.nextInt(Integer.MAX_VALUE); sbTree.put(key, new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); keys.add(key); Assert.assertEquals(sbTree.get(key), new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); } Assert.assertEquals(sbTree.firstKey(), keys.first()); Assert.assertEquals(sbTree.lastKey(), keys.last()); for (int key : keys) Assert.assertEquals(sbTree.get(key), new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); } public void testKeyPutRandomGaussian() throws Exception { final double mx = Integer.MAX_VALUE / 2.; final double dx = Integer.MAX_VALUE / 8.; NavigableSet<Integer> keys = new TreeSet<Integer>(); long seed = System.currentTimeMillis(); System.out.println("testKeyPutRandomGaussian seed : " + seed); MersenneTwisterFast random = new MersenneTwisterFast(seed); while (keys.size() < KEYS_COUNT) { int key = generateGaussianKey(mx, dx, random); sbTree.put(key, new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); keys.add(key); Assert.assertEquals(sbTree.get(key), new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); } Assert.assertEquals(sbTree.firstKey(), keys.first()); Assert.assertEquals(sbTree.lastKey(), keys.last()); for (int key : keys) Assert.assertEquals(sbTree.get(key), new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); } private int generateGaussianKey(double mx, double dx, MersenneTwisterFast random) { double v; do { v = random.nextGaussian() * dx + mx; } while (v < 0 || v > Integer.MAX_VALUE); return (int) v; } public void testKeyDeleteRandomUniform() throws Exception { NavigableSet<Integer> keys = new TreeSet<Integer>(); for (int i = 0; i < KEYS_COUNT; i++) { sbTree.put(i, new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); keys.add(i); } Iterator<Integer> keysIterator = keys.iterator(); while (keysIterator.hasNext()) { int key = keysIterator.next(); if (key % 3 == 0) { sbTree.remove(key); keysIterator.remove(); } } Assert.assertEquals(sbTree.firstKey(), keys.first()); Assert.assertEquals(sbTree.lastKey(), keys.last()); for (int key : keys) { if (key % 3 == 0) { Assert.assertNull(sbTree.get(key)); } else { Assert.assertEquals(sbTree.get(key), new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); } } } public void testKeyDeleteRandomGaussian() throws Exception { final double mx = Integer.MAX_VALUE / 2.; final double dx = Integer.MAX_VALUE / 8.; NavigableSet<Integer> keys = new TreeSet<Integer>(); long seed = System.currentTimeMillis(); System.out.println("testKeyDeleteRandomGaussian seed : " + seed); MersenneTwisterFast random = new MersenneTwisterFast(seed); while (keys.size() < KEYS_COUNT) { int key = generateGaussianKey(mx, dx, random); sbTree.put(key, new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); keys.add(key); Assert.assertEquals(sbTree.get(key), new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); } Iterator<Integer> keysIterator = keys.iterator(); while (keysIterator.hasNext()) { int key = keysIterator.next(); if (key % 3 == 0) { sbTree.remove(key); keysIterator.remove(); } } Assert.assertEquals(sbTree.firstKey(), keys.first()); Assert.assertEquals(sbTree.lastKey(), keys.last()); for (int key : keys) { if (key % 3 == 0) { Assert.assertNull(sbTree.get(key)); } else { Assert.assertEquals(sbTree.get(key), new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); } } } public void testKeyDelete() throws Exception { for (int i = 0; i < KEYS_COUNT; i++) { sbTree.put(i, new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); } for (int i = 0; i < KEYS_COUNT; i++) { if (i % 3 == 0) Assert.assertEquals(sbTree.remove(i), new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); } Assert.assertEquals((int) sbTree.firstKey(), 1); Assert.assertEquals((int) sbTree.lastKey(), (KEYS_COUNT - 1) % 3 == 0 ? KEYS_COUNT - 2 : KEYS_COUNT - 1); for (int i = 0; i < KEYS_COUNT; i++) { if (i % 3 == 0) Assert.assertNull(sbTree.get(i)); else Assert.assertEquals(sbTree.get(i), new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); } } public void testKeyAddDelete() throws Exception { for (int i = 0; i < KEYS_COUNT; i++) { sbTree.put(i, new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); Assert.assertEquals(sbTree.get(i), new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); } for (int i = 0; i < KEYS_COUNT; i++) { if (i % 3 == 0) Assert.assertEquals(sbTree.remove(i), new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); if (i % 2 == 0) sbTree.put(KEYS_COUNT + i, new ORecordId((KEYS_COUNT + i) % 32000, OClusterPositionFactory.INSTANCE.valueOf(KEYS_COUNT + i))); } Assert.assertEquals((int) sbTree.firstKey(), 1); Assert.assertEquals((int) sbTree.lastKey(), 2 * KEYS_COUNT - 2); for (int i = 0; i < KEYS_COUNT; i++) { if (i % 3 == 0) Assert.assertNull(sbTree.get(i)); else Assert.assertEquals(sbTree.get(i), new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); if (i % 2 == 0) Assert.assertEquals(sbTree.get(KEYS_COUNT + i), new ORecordId((KEYS_COUNT + i) % 32000, OClusterPositionFactory.INSTANCE.valueOf(KEYS_COUNT + i))); } } public void testValuesMajor() { NavigableMap<Integer, ORID> keyValues = new TreeMap<Integer, ORID>(); MersenneTwisterFast random = new MersenneTwisterFast(); while (keyValues.size() < KEYS_COUNT) { int key = random.nextInt(Integer.MAX_VALUE); sbTree.put(key, new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); keyValues.put(key, new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); } assertMajorValues(keyValues, random, true); assertMajorValues(keyValues, random, false); Assert.assertEquals(sbTree.firstKey(), keyValues.firstKey()); Assert.assertEquals(sbTree.lastKey(), keyValues.lastKey()); } public void testValuesMinor() { NavigableMap<Integer, ORID> keyValues = new TreeMap<Integer, ORID>(); MersenneTwisterFast random = new MersenneTwisterFast(); while (keyValues.size() < KEYS_COUNT) { int key = random.nextInt(Integer.MAX_VALUE); sbTree.put(key, new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); keyValues.put(key, new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); } assertMinorValues(keyValues, random, true); assertMinorValues(keyValues, random, false); Assert.assertEquals(sbTree.firstKey(), keyValues.firstKey()); Assert.assertEquals(sbTree.lastKey(), keyValues.lastKey()); } public void testValuesBetween() { NavigableMap<Integer, ORID> keyValues = new TreeMap<Integer, ORID>(); MersenneTwisterFast random = new MersenneTwisterFast(); while (keyValues.size() < KEYS_COUNT) { int key = random.nextInt(Integer.MAX_VALUE); sbTree.put(key, new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); keyValues.put(key, new ORecordId(key % 32000, OClusterPositionFactory.INSTANCE.valueOf(key))); } assertBetweenValues(keyValues, random, true, true); assertBetweenValues(keyValues, random, true, false); assertBetweenValues(keyValues, random, false, true); assertBetweenValues(keyValues, random, false, false); Assert.assertEquals(sbTree.firstKey(), keyValues.firstKey()); Assert.assertEquals(sbTree.lastKey(), keyValues.lastKey()); } private void assertMajorValues(NavigableMap<Integer, ORID> keyValues, MersenneTwisterFast random, boolean keyInclusive) { for (int i = 0; i < 100; i++) { int upperBorder = keyValues.lastKey() + 5000; int fromKey; if (upperBorder > 0) fromKey = random.nextInt(upperBorder); else fromKey = random.nextInt(Integer.MAX_VALUE); if (random.nextBoolean()) { Integer includedKey = keyValues.ceilingKey(fromKey); if (includedKey != null) fromKey = includedKey; else fromKey = keyValues.floorKey(fromKey); } int maxValuesToFetch = 10000; Collection<OIdentifiable> orids = sbTree.getValuesMajor(fromKey, keyInclusive, maxValuesToFetch); Set<OIdentifiable> result = new HashSet<OIdentifiable>(orids); Iterator<ORID> valuesIterator = keyValues.tailMap(fromKey, keyInclusive).values().iterator(); int fetchedValues = 0; while (valuesIterator.hasNext() && fetchedValues < maxValuesToFetch) { ORID value = valuesIterator.next(); Assert.assertTrue(result.remove(value)); fetchedValues++; } if (valuesIterator.hasNext()) Assert.assertEquals(fetchedValues, maxValuesToFetch); Assert.assertEquals(result.size(), 0); } } public void testAddKeyValuesInTwoBucketsAndMakeFirstEmpty() throws Exception { for (int i = 0; i < 110; i++) sbTree.put(i, new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); for (int i = 0; i < 56; i++) sbTree.remove(i); Assert.assertEquals((int) sbTree.firstKey(), 56); for (int i = 0; i < 56; i++) Assert.assertNull(sbTree.get(i)); for (int i = 56; i < 110; i++) Assert.assertEquals(sbTree.get(i), new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); } public void testAddKeyValuesInTwoBucketsAndMakeLastEmpty() throws Exception { for (int i = 0; i < 110; i++) sbTree.put(i, new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); for (int i = 110; i > 50; i--) sbTree.remove(i); Assert.assertEquals((int) sbTree.lastKey(), 50); for (int i = 110; i > 50; i--) Assert.assertNull(sbTree.get(i)); for (int i = 50; i >= 0; i--) Assert.assertEquals(sbTree.get(i), new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); } public void testAddKeyValuesAndRemoveFirstMiddleAndLastPages() throws Exception { for (int i = 0; i < 326; i++) sbTree.put(i, new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); for (int i = 0; i < 60; i++) sbTree.remove(i); for (int i = 100; i < 220; i++) sbTree.remove(i); for (int i = 260; i < 326; i++) sbTree.remove(i); Assert.assertEquals((int) sbTree.firstKey(), 60); Assert.assertEquals((int) sbTree.lastKey(), 259); Collection<OIdentifiable> result = sbTree.getValuesMinor(250, true, -1); Set<OIdentifiable> identifiables = new HashSet<OIdentifiable>(result); for (int i = 250; i >= 220; i--) { boolean removed = identifiables.remove(new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); Assert.assertTrue(removed); } for (int i = 99; i >= 60; i--) { boolean removed = identifiables.remove(new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); Assert.assertTrue(removed); } Assert.assertTrue(identifiables.isEmpty()); result = sbTree.getValuesMajor(70, true, -1); identifiables = new HashSet<OIdentifiable>(result); for (int i = 70; i < 100; i++) { boolean removed = identifiables.remove(new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); Assert.assertTrue(removed); } for (int i = 220; i < 260; i++) { boolean removed = identifiables.remove(new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); Assert.assertTrue(removed); } Assert.assertTrue(identifiables.isEmpty()); result = sbTree.getValuesBetween(70, true, 250, true, -1); identifiables = new HashSet<OIdentifiable>(result); for (int i = 70; i < 100; i++) { boolean removed = identifiables.remove(new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); Assert.assertTrue(removed); } for (int i = 220; i <= 250; i++) { boolean removed = identifiables.remove(new ORecordId(i % 32000, OClusterPositionFactory.INSTANCE.valueOf(i))); Assert.assertTrue(removed); } Assert.assertTrue(identifiables.isEmpty()); } private void assertMinorValues(NavigableMap<Integer, ORID> keyValues, MersenneTwisterFast random, boolean keyInclusive) { for (int i = 0; i < 100; i++) { int upperBorder = keyValues.lastKey() + 5000; int toKey; if (upperBorder > 0) toKey = random.nextInt(upperBorder) - 5000; else toKey = random.nextInt(Integer.MAX_VALUE) - 5000; if (random.nextBoolean()) { Integer includedKey = keyValues.ceilingKey(toKey); if (includedKey != null) toKey = includedKey; else toKey = keyValues.floorKey(toKey); } int maxValuesToFetch = 10000; Collection<OIdentifiable> orids = sbTree.getValuesMinor(toKey, keyInclusive, maxValuesToFetch); Set<OIdentifiable> result = new HashSet<OIdentifiable>(orids); Iterator<ORID> valuesIterator = keyValues.headMap(toKey, keyInclusive).descendingMap().values().iterator(); int fetchedValues = 0; while (valuesIterator.hasNext() && fetchedValues < maxValuesToFetch) { ORID value = valuesIterator.next(); Assert.assertTrue(result.remove(value)); fetchedValues++; } if (valuesIterator.hasNext()) Assert.assertEquals(fetchedValues, maxValuesToFetch); Assert.assertEquals(result.size(), 0); } } private void assertBetweenValues(NavigableMap<Integer, ORID> keyValues, MersenneTwisterFast random, boolean fromInclusive, boolean toInclusive) { for (int i = 0; i < 100; i++) { int upperBorder = keyValues.lastKey() + 5000; int fromKey; if (upperBorder > 0) fromKey = random.nextInt(upperBorder); else fromKey = random.nextInt(Integer.MAX_VALUE - 1); if (random.nextBoolean()) { Integer includedKey = keyValues.ceilingKey(fromKey); if (includedKey != null) fromKey = includedKey; else fromKey = keyValues.floorKey(fromKey); } int toKey = random.nextInt() + fromKey + 1; if (toKey < 0) toKey = Integer.MAX_VALUE; if (random.nextBoolean()) { Integer includedKey = keyValues.ceilingKey(toKey); if (includedKey != null) toKey = includedKey; else toKey = keyValues.floorKey(toKey); } if (fromKey > toKey) toKey = fromKey; int maxValuesToFetch = 10000; Collection<OIdentifiable> orids = sbTree.getValuesBetween(fromKey, fromInclusive, toKey, toInclusive, maxValuesToFetch); Set<OIdentifiable> result = new HashSet<OIdentifiable>(orids); Iterator<ORID> valuesIterator = keyValues.subMap(fromKey, fromInclusive, toKey, toInclusive).values().iterator(); int fetchedValues = 0; while (valuesIterator.hasNext() && fetchedValues < maxValuesToFetch) { ORID value = valuesIterator.next(); Assert.assertTrue(result.remove(value)); fetchedValues++; } if (valuesIterator.hasNext()) Assert.assertEquals(fetchedValues, maxValuesToFetch); Assert.assertEquals(result.size(), 0); } } }
0true
core_src_test_java_com_orientechnologies_orient_core_index_sbtreebonsai_local_OSBTreeBonsaiTest.java
1,403
@XmlRootElement(name = "orderItemQualifier") @XmlAccessorType(value = XmlAccessType.FIELD) public class OrderItemQualifierWrapper extends BaseWrapper implements APIWrapper<OrderItemQualifier> { @XmlElement protected Long offerId; @XmlElement protected Long quantity; @Override public void wrapDetails(OrderItemQualifier model, HttpServletRequest request) { this.offerId = model.getOffer().getId(); this.quantity = model.getQuantity(); } @Override public void wrapSummary(OrderItemQualifier model, HttpServletRequest request) { wrapDetails(model, request); } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_wrapper_OrderItemQualifierWrapper.java
1,530
public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> { private boolean processVertices; @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { this.processVertices = context.getConfiguration().getBoolean(PROCESS_VERTICES, true); } @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { if (this.processVertices) { value.clearPaths(); DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_PROCESSED, 1L); } long edgesProcessed = 0; for (final Edge edge : value.getEdges(Direction.IN)) { ((StandardFaunusEdge) edge).startPath(); edgesProcessed++; } DEFAULT_COMPAT.incrementContextCounter(context, Counters.IN_EDGES_PROCESSED, edgesProcessed); edgesProcessed = 0; for (final Edge edge : value.getEdges(Direction.OUT)) { ((StandardFaunusEdge) edge).startPath(); edgesProcessed++; } DEFAULT_COMPAT.incrementContextCounter(context, Counters.OUT_EDGES_PROCESSED, edgesProcessed); context.write(NullWritable.get(), value); } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_transform_EdgesMap.java
145
private static class CorrectionMarkerResolution implements IMarkerResolution, IMarkerResolution2 { private int fOffset; private int fLength; private ICompletionProposal fProposal; private final IDocument fDocument; public CorrectionMarkerResolution(int offset, int length, ICompletionProposal proposal, IMarker marker, IDocument document) { fOffset = offset; fLength = length; fProposal = proposal; fDocument = document; } public String getLabel() { return fProposal.getDisplayString(); } public void run(IMarker marker) { try { IEditorPart part = openInEditor(marker.getResource()); if (part instanceof ITextEditor) { ((ITextEditor) part).selectAndReveal(fOffset, fLength); } if (fDocument != null) { fProposal.apply(fDocument); } } catch (CoreException e) { // JavaPlugin.log(e); } } public String getDescription() { return fProposal.getAdditionalProposalInfo(); } public Image getImage() { return fProposal.getImage(); } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_MarkerResolutionGenerator.java
1,921
static final Assisted DEFAULT_ANNOTATION = new Assisted() { public String value() { return ""; } public Class<? extends Annotation> annotationType() { return Assisted.class; } @Override public boolean equals(Object o) { return o instanceof Assisted && ((Assisted) o).value().equals(""); } @Override public int hashCode() { return 127 * "value".hashCode() ^ "".hashCode(); } @Override public String toString() { return "@" + Assisted.class.getName() + "(value=)"; } };
0true
src_main_java_org_elasticsearch_common_inject_assistedinject_FactoryProvider2.java
3,682
public static class Builder extends NumberFieldMapper.Builder<Builder, IntegerFieldMapper> { protected EnabledAttributeMapper enabledState = EnabledAttributeMapper.UNSET_DISABLED; public Builder() { super(Defaults.NAME, new FieldType(Defaults.SIZE_FIELD_TYPE)); builder = this; } public Builder enabled(EnabledAttributeMapper enabled) { this.enabledState = enabled; return builder; } @Override public SizeFieldMapper build(BuilderContext context) { return new SizeFieldMapper(enabledState, fieldType, postingsProvider, docValuesProvider, fieldDataSettings, context.indexSettings()); } }
0true
src_main_java_org_elasticsearch_index_mapper_internal_SizeFieldMapper.java
2,191
public class MoreLikeThisQuery extends Query { public static final float DEFAULT_PERCENT_TERMS_TO_MATCH = 0.3f; private TFIDFSimilarity similarity; private String likeText; private String[] moreLikeFields; private Analyzer analyzer; private float percentTermsToMatch = DEFAULT_PERCENT_TERMS_TO_MATCH; private int minTermFrequency = MoreLikeThis.DEFAULT_MIN_TERM_FREQ; private int maxQueryTerms = MoreLikeThis.DEFAULT_MAX_QUERY_TERMS; private Set<?> stopWords = MoreLikeThis.DEFAULT_STOP_WORDS; private int minDocFreq = MoreLikeThis.DEFAULT_MIN_DOC_FREQ; private int maxDocFreq = MoreLikeThis.DEFAULT_MAX_DOC_FREQ; private int minWordLen = MoreLikeThis.DEFAULT_MIN_WORD_LENGTH; private int maxWordLen = MoreLikeThis.DEFAULT_MAX_WORD_LENGTH; private boolean boostTerms = MoreLikeThis.DEFAULT_BOOST; private float boostTermsFactor = 1; public MoreLikeThisQuery() { } public MoreLikeThisQuery(String likeText, String[] moreLikeFields, Analyzer analyzer) { this.likeText = likeText; this.moreLikeFields = moreLikeFields; this.analyzer = analyzer; } @Override public int hashCode() { int result = boostTerms ? 1 : 0; result = 31 * result + Float.floatToIntBits(boostTermsFactor); result = 31 * result + likeText.hashCode(); result = 31 * result + maxDocFreq; result = 31 * result + maxQueryTerms; result = 31 * result + maxWordLen; result = 31 * result + minDocFreq; result = 31 * result + minTermFrequency; result = 31 * result + minWordLen; result = 31 * result + Arrays.hashCode(moreLikeFields); result = 31 * result + Float.floatToIntBits(percentTermsToMatch); result = 31 * result + (stopWords == null ? 0 : stopWords.hashCode()); result = 31 * result + Float.floatToIntBits(getBoost()); return result; } @Override public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) return false; MoreLikeThisQuery other = (MoreLikeThisQuery) obj; if (getBoost() != other.getBoost()) return false; if (!analyzer.equals(other.analyzer)) return false; if (boostTerms != other.boostTerms) return false; if (boostTermsFactor != other.boostTermsFactor) return false; if (!likeText.equals(other.likeText)) return false; if (maxDocFreq != other.maxDocFreq) return false; if (maxQueryTerms != other.maxQueryTerms) return false; if (maxWordLen != other.maxWordLen) return false; if (minDocFreq != other.minDocFreq) return false; if (minTermFrequency != other.minTermFrequency) return false; if (minWordLen != other.minWordLen) return false; if (!Arrays.equals(moreLikeFields, other.moreLikeFields)) return false; if (percentTermsToMatch != other.percentTermsToMatch) return false; if (similarity == null) { if (other.similarity != null) return false; } else if (!similarity.equals(other.similarity)) return false; if (stopWords == null) { if (other.stopWords != null) return false; } else if (!stopWords.equals(other.stopWords)) return false; return true; } @Override public Query rewrite(IndexReader reader) throws IOException { MoreLikeThis mlt = new MoreLikeThis(reader, similarity == null ? new DefaultSimilarity() : similarity); mlt.setFieldNames(moreLikeFields); mlt.setAnalyzer(analyzer); mlt.setMinTermFreq(minTermFrequency); mlt.setMinDocFreq(minDocFreq); mlt.setMaxDocFreq(maxDocFreq); mlt.setMaxQueryTerms(maxQueryTerms); mlt.setMinWordLen(minWordLen); mlt.setMaxWordLen(maxWordLen); mlt.setStopWords(stopWords); mlt.setBoost(boostTerms); mlt.setBoostFactor(boostTermsFactor); //LUCENE 4 UPGRADE this mapps the 3.6 behavior (only use the first field) BooleanQuery bq = (BooleanQuery) mlt.like(new FastStringReader(likeText), moreLikeFields[0]); BooleanClause[] clauses = bq.getClauses(); bq.setMinimumNumberShouldMatch((int) (clauses.length * percentTermsToMatch)); bq.setBoost(getBoost()); return bq; } @Override public String toString(String field) { return "like:" + likeText; } public String getLikeText() { return likeText; } public void setLikeText(String likeText) { this.likeText = likeText; } public String[] getMoreLikeFields() { return moreLikeFields; } public void setMoreLikeFields(String[] moreLikeFields) { this.moreLikeFields = moreLikeFields; } public Similarity getSimilarity() { return similarity; } public void setSimilarity(Similarity similarity) { if (similarity == null || similarity instanceof TFIDFSimilarity) { //LUCENE 4 UPGRADE we need TFIDF similarity here so I only set it if it is an instance of it this.similarity = (TFIDFSimilarity) similarity; } } public Analyzer getAnalyzer() { return analyzer; } public void setAnalyzer(Analyzer analyzer) { this.analyzer = analyzer; } public float getPercentTermsToMatch() { return percentTermsToMatch; } public void setPercentTermsToMatch(float percentTermsToMatch) { this.percentTermsToMatch = percentTermsToMatch; } public int getMinTermFrequency() { return minTermFrequency; } public void setMinTermFrequency(int minTermFrequency) { this.minTermFrequency = minTermFrequency; } public int getMaxQueryTerms() { return maxQueryTerms; } public void setMaxQueryTerms(int maxQueryTerms) { this.maxQueryTerms = maxQueryTerms; } public Set<?> getStopWords() { return stopWords; } public void setStopWords(Set<?> stopWords) { this.stopWords = stopWords; } public int getMinDocFreq() { return minDocFreq; } public void setMinDocFreq(int minDocFreq) { this.minDocFreq = minDocFreq; } public int getMaxDocFreq() { return maxDocFreq; } public void setMaxDocFreq(int maxDocFreq) { this.maxDocFreq = maxDocFreq; } public int getMinWordLen() { return minWordLen; } public void setMinWordLen(int minWordLen) { this.minWordLen = minWordLen; } public int getMaxWordLen() { return maxWordLen; } public void setMaxWordLen(int maxWordLen) { this.maxWordLen = maxWordLen; } public boolean isBoostTerms() { return boostTerms; } public void setBoostTerms(boolean boostTerms) { this.boostTerms = boostTerms; } public float getBoostTermsFactor() { return boostTermsFactor; } public void setBoostTermsFactor(float boostTermsFactor) { this.boostTermsFactor = boostTermsFactor; } }
0true
src_main_java_org_elasticsearch_common_lucene_search_MoreLikeThisQuery.java
3,217
SINGLE_VALUED_SPARSE_RANDOM { public int numValues(Random r) { return r.nextFloat() < 0.1f ? 1 : 0; } @Override public long nextValue(Random r) { return r.nextLong(); } },
0true
src_test_java_org_elasticsearch_index_fielddata_LongFieldDataTests.java
2,050
public interface ProviderKeyBinding<T> extends Binding<T> { /** * Returns the key used to resolve the provider's binding. That binding can be retrieved from an * injector using {@link org.elasticsearch.common.inject.Injector#getBinding(Key) * Injector.getBinding(providerKey)} */ Key<? extends Provider<? extends T>> getProviderKey(); }
0true
src_main_java_org_elasticsearch_common_inject_spi_ProviderKeyBinding.java
1,820
@Component("blMediaFieldPersistenceProvider") @Scope("prototype") public class MediaFieldPersistenceProvider extends FieldPersistenceProviderAdapter { @Resource(name="blEntityConfiguration") protected EntityConfiguration entityConfiguration; protected boolean canHandlePersistence(PopulateValueRequest populateValueRequest, Serializable instance) { return populateValueRequest.getMetadata().getFieldType() == SupportedFieldType.MEDIA; } protected boolean canHandleExtraction(ExtractValueRequest extractValueRequest, Property property) { return extractValueRequest.getMetadata().getFieldType() == SupportedFieldType.MEDIA; } @Override public FieldProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) throws PersistenceException { if (!canHandlePersistence(populateValueRequest, instance)) { return FieldProviderResponse.NOT_HANDLED; } try { Class<?> valueType = null; if (!populateValueRequest.getProperty().getName().contains(FieldManager.MAPFIELDSEPARATOR)) { valueType = populateValueRequest.getReturnType(); } else { String valueClassName = populateValueRequest.getMetadata().getMapFieldValueClass(); if (valueClassName != null) { valueType = Class.forName(valueClassName); } if (valueType == null) { valueType = populateValueRequest.getReturnType(); } } if (valueType == null) { throw new IllegalAccessException("Unable to determine the valueType for the rule field (" + populateValueRequest.getProperty().getName() + ")"); } if (Media.class.isAssignableFrom(valueType)) { Media newMedia = convertJsonToMedia(populateValueRequest.getProperty().getUnHtmlEncodedValue()); Media media; try { media = (Media) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName()); } catch (FieldNotAvailableException e) { throw new IllegalArgumentException(e); } if (media == null) { media = (Media) valueType.newInstance(); } updateMediaFields(media, newMedia); populateValueRequest.getPersistenceManager().getDynamicEntityDao().persist(media); populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), media); } else { throw new UnsupportedOperationException("MediaFields only work with Media types."); } } catch (Exception e) { throw new PersistenceException(e); } return FieldProviderResponse.HANDLED; } @Override public FieldProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException { if (!canHandleExtraction(extractValueRequest, property)) { return FieldProviderResponse.NOT_HANDLED; } if (extractValueRequest.getRequestedValue() != null) { if (extractValueRequest.getRequestedValue() instanceof Media) { Media media = (Media) extractValueRequest.getRequestedValue(); String jsonString = convertMediaToJson(media); property.setValue(jsonString); property.setUnHtmlEncodedValue(jsonString); property.setDisplayValue(extractValueRequest.getDisplayVal()); } else { throw new UnsupportedOperationException("MEDIA type is currently only supported on fields of type Media"); } } return FieldProviderResponse.HANDLED; } @Override public FieldProviderResponse filterProperties(AddFilterPropertiesRequest addFilterPropertiesRequest, Map<String, FieldMetadata> properties) { // BP: Basically copied this from RuleFieldPersistenceProvider List<Property> propertyList = new ArrayList<Property>(); propertyList.addAll(Arrays.asList(addFilterPropertiesRequest.getEntity().getProperties())); Iterator<Property> itr = propertyList.iterator(); List<Property> additionalProperties = new ArrayList<Property>(); while(itr.hasNext()) { Property prop = itr.next(); if (prop.getName().endsWith("Json")) { for (Map.Entry<String, FieldMetadata> entry : properties.entrySet()) { if (prop.getName().startsWith(entry.getKey())) { BasicFieldMetadata originalFM = (BasicFieldMetadata) entry.getValue(); if (originalFM.getFieldType() == SupportedFieldType.MEDIA) { Property originalProp = addFilterPropertiesRequest.getEntity().findProperty(originalFM .getName()); if (originalProp == null) { originalProp = new Property(); originalProp.setName(originalFM.getName()); additionalProperties.add(originalProp); } originalProp.setValue(prop.getValue()); originalProp.setRawValue(prop.getRawValue()); originalProp.setUnHtmlEncodedValue(prop.getUnHtmlEncodedValue()); itr.remove(); break; } } } } } propertyList.addAll(additionalProperties); addFilterPropertiesRequest.getEntity().setProperties(propertyList.toArray(new Property[propertyList.size()])); return FieldProviderResponse.HANDLED; } @Override public int getOrder() { return FieldPersistenceProvider.MEDIA; } protected String convertMediaToJson(Media media) { String json; try { ObjectMapper om = new ObjectMapper(); return om.writeValueAsString(media); } catch (Exception e) { throw new RuntimeException(e); } } protected Media convertJsonToMedia(String jsonProp) { try { ObjectMapper om = new ObjectMapper(); return om.readValue(jsonProp, entityConfiguration.lookupEntityClass(Media.class.getName(), Media.class)); } catch (Exception e) { throw new RuntimeException(e); } } protected void updateMediaFields(Media oldMedia, Media newMedia) { oldMedia.setAltText(newMedia.getAltText()); oldMedia.setTags(newMedia.getTags()); oldMedia.setTitle(newMedia.getTitle()); oldMedia.setUrl(newMedia.getUrl()); } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_provider_MediaFieldPersistenceProvider.java
463
public class MvelHelper { public static Object convertField(String type, String fieldValue) { if (fieldValue == null) { return null; } try { if (type.equals(SupportedFieldType.BOOLEAN.toString())) { return Boolean.parseBoolean(fieldValue); } else if (type.equals(SupportedFieldType.DATE.toString())) { return FormatUtil.getTimeZoneFormat().parse(fieldValue); } else if (type.equals(SupportedFieldType.INTEGER.toString())) { return Integer.parseInt(fieldValue); } else if (type.equals(SupportedFieldType.MONEY.toString()) || type.equals(SupportedFieldType.DECIMAL.toString())) { return new BigDecimal(fieldValue); } } catch (ParseException e) { throw new RuntimeException(e); } throw new IllegalArgumentException("Unrecognized type(" + type + ") for map field conversion."); } public static Object toUpperCase(String value) { if (value == null) { return null; } return value.toUpperCase(); } }
0true
common_src_main_java_org_broadleafcommerce_common_rule_MvelHelper.java
1,113
public class StringMapAdjustOrPutBenchmark { public static void main(String[] args) { int NUMBER_OF_KEYS = (int) SizeValue.parseSizeValue("20").singles(); int STRING_SIZE = 5; long PUT_OPERATIONS = SizeValue.parseSizeValue("5m").singles(); long ITERATIONS = 10; boolean REUSE = true; String[] values = new String[NUMBER_OF_KEYS]; for (int i = 0; i < values.length; i++) { values[i] = RandomStrings.randomAsciiOfLength(ThreadLocalRandom.current(), STRING_SIZE); } StopWatch stopWatch; stopWatch = new StopWatch().start(); ObjectIntOpenHashMap<String> map = new ObjectIntOpenHashMap<String>(); for (long iter = 0; iter < ITERATIONS; iter++) { if (REUSE) { map.clear(); } else { map = new ObjectIntOpenHashMap<String>(); } for (long i = 0; i < PUT_OPERATIONS; i++) { map.addTo(values[(int) (i % NUMBER_OF_KEYS)], 1); } } map.clear(); map = null; stopWatch.stop(); System.out.println("TObjectIntHashMap: " + stopWatch.totalTime() + ", " + stopWatch.totalTime().millisFrac() / ITERATIONS + "ms"); stopWatch = new StopWatch().start(); // TObjectIntCustomHashMap<String> iMap = new TObjectIntCustomHashMap<String>(new StringIdentityHashingStrategy()); ObjectIntOpenHashMap<String> iMap = new ObjectIntOpenHashMap<String>(); for (long iter = 0; iter < ITERATIONS; iter++) { if (REUSE) { iMap.clear(); } else { iMap = new ObjectIntOpenHashMap<String>(); } for (long i = 0; i < PUT_OPERATIONS; i++) { iMap.addTo(values[(int) (i % NUMBER_OF_KEYS)], 1); } } stopWatch.stop(); System.out.println("TObjectIntCustomHashMap(StringIdentity): " + stopWatch.totalTime() + ", " + stopWatch.totalTime().millisFrac() / ITERATIONS + "ms"); iMap.clear(); iMap = null; stopWatch = new StopWatch().start(); iMap = new ObjectIntOpenHashMap<String>(); for (long iter = 0; iter < ITERATIONS; iter++) { if (REUSE) { iMap.clear(); } else { iMap = new ObjectIntOpenHashMap<String>(); } for (long i = 0; i < PUT_OPERATIONS; i++) { iMap.addTo(values[(int) (i % NUMBER_OF_KEYS)], 1); } } stopWatch.stop(); System.out.println("TObjectIntCustomHashMap(PureIdentity): " + stopWatch.totalTime() + ", " + stopWatch.totalTime().millisFrac() / ITERATIONS + "ms"); iMap.clear(); iMap = null; // now test with THashMap stopWatch = new StopWatch().start(); ObjectObjectOpenHashMap<String, StringEntry> tMap = new ObjectObjectOpenHashMap<String, StringEntry>(); for (long iter = 0; iter < ITERATIONS; iter++) { if (REUSE) { tMap.clear(); } else { tMap = new ObjectObjectOpenHashMap<String, StringEntry>(); } for (long i = 0; i < PUT_OPERATIONS; i++) { String key = values[(int) (i % NUMBER_OF_KEYS)]; StringEntry stringEntry = tMap.get(key); if (stringEntry == null) { stringEntry = new StringEntry(key, 1); tMap.put(key, stringEntry); } else { stringEntry.counter++; } } } tMap.clear(); tMap = null; stopWatch.stop(); System.out.println("THashMap: " + stopWatch.totalTime() + ", " + stopWatch.totalTime().millisFrac() / ITERATIONS + "ms"); stopWatch = new StopWatch().start(); HashMap<String, StringEntry> hMap = new HashMap<String, StringEntry>(); for (long iter = 0; iter < ITERATIONS; iter++) { if (REUSE) { hMap.clear(); } else { hMap = new HashMap<String, StringEntry>(); } for (long i = 0; i < PUT_OPERATIONS; i++) { String key = values[(int) (i % NUMBER_OF_KEYS)]; StringEntry stringEntry = hMap.get(key); if (stringEntry == null) { stringEntry = new StringEntry(key, 1); hMap.put(key, stringEntry); } else { stringEntry.counter++; } } } hMap.clear(); hMap = null; stopWatch.stop(); System.out.println("HashMap: " + stopWatch.totalTime() + ", " + stopWatch.totalTime().millisFrac() / ITERATIONS + "ms"); stopWatch = new StopWatch().start(); IdentityHashMap<String, StringEntry> ihMap = new IdentityHashMap<String, StringEntry>(); for (long iter = 0; iter < ITERATIONS; iter++) { if (REUSE) { ihMap.clear(); } else { hMap = new HashMap<String, StringEntry>(); } for (long i = 0; i < PUT_OPERATIONS; i++) { String key = values[(int) (i % NUMBER_OF_KEYS)]; StringEntry stringEntry = ihMap.get(key); if (stringEntry == null) { stringEntry = new StringEntry(key, 1); ihMap.put(key, stringEntry); } else { stringEntry.counter++; } } } stopWatch.stop(); System.out.println("IdentityHashMap: " + stopWatch.totalTime() + ", " + stopWatch.totalTime().millisFrac() / ITERATIONS + "ms"); ihMap.clear(); ihMap = null; int[] iValues = new int[NUMBER_OF_KEYS]; for (int i = 0; i < values.length; i++) { iValues[i] = ThreadLocalRandom.current().nextInt(); } stopWatch = new StopWatch().start(); IntIntOpenHashMap intMap = new IntIntOpenHashMap(); for (long iter = 0; iter < ITERATIONS; iter++) { if (REUSE) { intMap.clear(); } else { intMap = new IntIntOpenHashMap(); } for (long i = 0; i < PUT_OPERATIONS; i++) { int key = iValues[(int) (i % NUMBER_OF_KEYS)]; intMap.addTo(key, 1); } } stopWatch.stop(); System.out.println("TIntIntHashMap: " + stopWatch.totalTime() + ", " + stopWatch.totalTime().millisFrac() / ITERATIONS + "ms"); intMap.clear(); intMap = null; // now test with THashMap stopWatch = new StopWatch().start(); IntObjectOpenHashMap<IntEntry> tIntMap = new IntObjectOpenHashMap<IntEntry>(); for (long iter = 0; iter < ITERATIONS; iter++) { if (REUSE) { tIntMap.clear(); } else { tIntMap = new IntObjectOpenHashMap<IntEntry>(); } for (long i = 0; i < PUT_OPERATIONS; i++) { int key = iValues[(int) (i % NUMBER_OF_KEYS)]; IntEntry intEntry = tIntMap.get(key); if (intEntry == null) { intEntry = new IntEntry(key, 1); tIntMap.put(key, intEntry); } else { intEntry.counter++; } } } tIntMap.clear(); tIntMap = null; stopWatch.stop(); System.out.println("TIntObjectHashMap: " + stopWatch.totalTime() + ", " + stopWatch.totalTime().millisFrac() / ITERATIONS + "ms"); } static class StringEntry { String key; int counter; StringEntry(String key, int counter) { this.key = key; this.counter = counter; } } static class IntEntry { int key; int counter; IntEntry(int key, int counter) { this.key = key; this.counter = counter; } } }
0true
src_test_java_org_elasticsearch_benchmark_hppc_StringMapAdjustOrPutBenchmark.java
2,883
public class LimitTokenCountFilterFactory extends AbstractTokenFilterFactory { final int maxTokenCount; final boolean consumeAllTokens; @Inject public LimitTokenCountFilterFactory(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); this.maxTokenCount = settings.getAsInt("max_token_count", 1); this.consumeAllTokens = settings.getAsBoolean("consume_all_tokens", false); } @Override public TokenStream create(TokenStream tokenStream) { return new LimitTokenCountFilter(tokenStream, maxTokenCount, consumeAllTokens); } }
0true
src_main_java_org_elasticsearch_index_analysis_LimitTokenCountFilterFactory.java
347
@SuppressWarnings("unchecked") public abstract class ODatabaseRecordWrapperAbstract<DB extends ODatabaseRecord> extends ODatabaseWrapperAbstract<DB> implements ODatabaseComplex<ORecordInternal<?>> { public ODatabaseRecordWrapperAbstract(final DB iDatabase) { super(iDatabase); iDatabase.setDatabaseOwner(this); } @Override public <THISDB extends ODatabase> THISDB create() { checkSecurity(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_CREATE); return (THISDB) super.create(); } @Override public void drop() { checkOpeness(); checkSecurity(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_DELETE); super.drop(); } public int addCluster(final String iType, final String iClusterName, final String iLocation, final String iDataSegmentName, final Object... iParameters) { checkSecurity(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_UPDATE); return super.addCluster(iType, iClusterName, iLocation, iDataSegmentName, iParameters); } public int addCluster(final String iClusterName, final CLUSTER_TYPE iType, final Object... iParameters) { return super.addCluster(iType.toString(), iClusterName, null, null, iParameters); } @Override public boolean dropCluster(final String iClusterName, final boolean iTruncate) { checkSecurity(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_UPDATE); checkClusterBoundedToClass(getClusterIdByName(iClusterName)); return super.dropCluster(iClusterName, iTruncate); } public boolean dropCluster(int iClusterId, final boolean iTruncate) { checkSecurity(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_UPDATE); checkClusterBoundedToClass(iClusterId); return super.dropCluster(iClusterId, iTruncate); } @Override public int addDataSegment(final String iName, final String iLocation) { checkSecurity(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_UPDATE); return super.addDataSegment(iName, iLocation); } @Override public boolean dropDataSegment(final String iName) { checkSecurity(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_UPDATE); return super.dropDataSegment(iName); } public OTransaction getTransaction() { return underlying.getTransaction(); } public void replaceStorage(OStorage iNewStorage) { underlying.replaceStorage(iNewStorage); } public ODatabaseComplex<ORecordInternal<?>> begin() { return underlying.begin(); } public ODatabaseComplex<ORecordInternal<?>> begin(final TXTYPE iType) { return underlying.begin(iType); } public ODatabaseComplex<ORecordInternal<?>> begin(final OTransaction iTx) { return underlying.begin(iTx); } public boolean isMVCC() { checkOpeness(); return underlying.isMVCC(); } public <RET extends ODatabaseComplex<?>> RET setMVCC(final boolean iValue) { checkOpeness(); return (RET) underlying.setMVCC(iValue); } public boolean isValidationEnabled() { return underlying.isValidationEnabled(); } public <RET extends ODatabaseRecord> RET setValidationEnabled(final boolean iValue) { return (RET) underlying.setValidationEnabled(iValue); } public OUser getUser() { return underlying.getUser(); } public void setUser(OUser user) { underlying.setUser(user); } public OMetadata getMetadata() { return underlying.getMetadata(); } public ODictionary<ORecordInternal<?>> getDictionary() { return underlying.getDictionary(); } public byte getRecordType() { return underlying.getRecordType(); } public <REC extends ORecordInternal<?>> ORecordIteratorCluster<REC> browseCluster(final String iClusterName) { return underlying.browseCluster(iClusterName); } public <REC extends ORecordInternal<?>> ORecordIteratorCluster<REC> browseCluster(final String iClusterName, final Class<REC> iRecordClass) { return underlying.browseCluster(iClusterName, iRecordClass); } public <REC extends ORecordInternal<?>> ORecordIteratorCluster<REC> browseCluster(final String iClusterName, final Class<REC> iRecordClass, OClusterPosition startClusterPosition, OClusterPosition endClusterPosition, final boolean loadTombstones) { return underlying.browseCluster(iClusterName, iRecordClass, startClusterPosition, endClusterPosition, loadTombstones); } public <RET extends OCommandRequest> RET command(final OCommandRequest iCommand) { return (RET) underlying.command(iCommand); } public <RET extends List<?>> RET query(final OQuery<? extends Object> iCommand, final Object... iArgs) { return (RET) underlying.query(iCommand, iArgs); } public <RET extends Object> RET newInstance() { return (RET) underlying.newInstance(); } public ODatabaseComplex<ORecordInternal<?>> delete(final ORID iRid) { underlying.delete(iRid); return this; } public ODatabaseComplex<ORecordInternal<?>> delete(final ORID iRid, final ORecordVersion iVersion) { underlying.delete(iRid, iVersion); return this; } @Override public ODatabaseComplex<ORecordInternal<?>> cleanOutRecord(ORID rid, ORecordVersion version) { underlying.cleanOutRecord(rid, version); return this; } public ODatabaseComplex<ORecordInternal<?>> delete(final ORecordInternal<?> iRecord) { underlying.delete(iRecord); return this; } public <RET extends ORecordInternal<?>> RET load(final ORID iRecordId) { return (RET) underlying.load(iRecordId); } public <RET extends ORecordInternal<?>> RET load(final ORID iRecordId, final String iFetchPlan) { return (RET) underlying.load(iRecordId, iFetchPlan); } public <RET extends ORecordInternal<?>> RET load(final ORID iRecordId, final String iFetchPlan, final boolean iIgnoreCache) { return (RET) underlying.load(iRecordId, iFetchPlan, iIgnoreCache); } @Override public <RET extends ORecordInternal<?>> RET load(ORID iRecordId, String iFetchPlan, boolean iIgnoreCache, boolean loadTombstone) { return (RET) underlying.load(iRecordId, iFetchPlan, iIgnoreCache, loadTombstone); } @Override public <RET extends ORecordInternal<?>> RET load(ORecordInternal<?> iObject, String iFetchPlan, boolean iIgnoreCache, boolean loadTombstone) { return (RET) underlying.load(iObject, iFetchPlan, iIgnoreCache, loadTombstone); } public <RET extends ORecordInternal<?>> RET getRecord(final OIdentifiable iIdentifiable) { return (RET) underlying.getRecord(iIdentifiable); } public <RET extends ORecordInternal<?>> RET load(final ORecordInternal<?> iRecord) { return (RET) underlying.load(iRecord); } public <RET extends ORecordInternal<?>> RET load(final ORecordInternal<?> iRecord, final String iFetchPlan) { return (RET) underlying.load(iRecord, iFetchPlan); } public <RET extends ORecordInternal<?>> RET load(final ORecordInternal<?> iRecord, final String iFetchPlan, final boolean iIgnoreCache) { return (RET) underlying.load(iRecord, iFetchPlan, iIgnoreCache); } public <RET extends ORecordInternal<?>> RET reload(final ORecordInternal<?> iRecord) { return (RET) underlying.reload(iRecord, null, true); } public <RET extends ORecordInternal<?>> RET reload(final ORecordInternal<?> iRecord, final String iFetchPlan, final boolean iIgnoreCache) { return (RET) underlying.reload(iRecord, iFetchPlan, iIgnoreCache); } public <RET extends ORecordInternal<?>> RET save(final ORecordInternal<?> iRecord) { return (RET) underlying.save(iRecord); } public <RET extends ORecordInternal<?>> RET save(final ORecordInternal<?> iRecord, final String iClusterName) { return (RET) underlying.save(iRecord, iClusterName); } @Override public boolean updatedReplica(ORecordInternal<?> iObject) { return underlying.updatedReplica(iObject); } public <RET extends ORecordInternal<?>> RET save(final ORecordInternal<?> iRecord, final OPERATION_MODE iMode, boolean iForceCreate, final ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<ORecordVersion> iRecordUpdatedCallback) { return (RET) underlying.save(iRecord, iMode, iForceCreate, iRecordCreatedCallback, iRecordUpdatedCallback); } public <RET extends ORecordInternal<?>> RET save(final ORecordInternal<?> iRecord, final String iClusterName, final OPERATION_MODE iMode, boolean iForceCreate, final ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<ORecordVersion> iRecordUpdatedCallback) { return (RET) underlying.save(iRecord, iClusterName, iMode, iForceCreate, iRecordCreatedCallback, iRecordUpdatedCallback); } public void setInternal(final ATTRIBUTES attribute, final Object iValue) { underlying.setInternal(attribute, iValue); } public boolean isRetainRecords() { return underlying.isRetainRecords(); } public ODatabaseRecord setRetainRecords(boolean iValue) { underlying.setRetainRecords(iValue); return (ODatabaseRecord) this.getClass().cast(this); } public ORecordInternal<?> getRecordByUserObject(final Object iUserObject, final boolean iCreateIfNotAvailable) { if (databaseOwner != this) return getDatabaseOwner().getRecordByUserObject(iUserObject, false); return (ORecordInternal<?>) iUserObject; } public void registerUserObject(final Object iObject, final ORecordInternal<?> iRecord) { if (databaseOwner != this) getDatabaseOwner().registerUserObject(iObject, iRecord); } public void registerUserObjectAfterLinkSave(ORecordInternal<?> iRecord) { if (databaseOwner != this) getDatabaseOwner().registerUserObjectAfterLinkSave(iRecord); } public Object getUserObjectByRecord(final OIdentifiable iRecord, final String iFetchPlan) { if (databaseOwner != this) return databaseOwner.getUserObjectByRecord(iRecord, iFetchPlan); return iRecord; } public boolean existsUserObjectByRID(final ORID iRID) { if (databaseOwner != this) return databaseOwner.existsUserObjectByRID(iRID); return false; } public <DBTYPE extends ODatabaseRecord> DBTYPE checkSecurity(final String iResource, final int iOperation) { return (DBTYPE) underlying.checkSecurity(iResource, iOperation); } public <DBTYPE extends ODatabaseRecord> DBTYPE checkSecurity(final String iResourceGeneric, final int iOperation, final Object iResourceSpecific) { return (DBTYPE) underlying.checkSecurity(iResourceGeneric, iOperation, iResourceSpecific); } public <DBTYPE extends ODatabaseRecord> DBTYPE checkSecurity(final String iResourceGeneric, final int iOperation, final Object... iResourcesSpecific) { return (DBTYPE) underlying.checkSecurity(iResourceGeneric, iOperation, iResourcesSpecific); } public <DBTYPE extends ODatabaseComplex<?>> DBTYPE registerHook(final ORecordHook iHookImpl) { underlying.registerHook(iHookImpl); return (DBTYPE) this; } public <DBTYPE extends ODatabaseComplex<?>> DBTYPE registerHook(final ORecordHook iHookImpl, ORecordHook.HOOK_POSITION iPosition) { underlying.registerHook(iHookImpl, iPosition); return (DBTYPE) this; } public RESULT callbackHooks(final TYPE iType, final OIdentifiable iObject) { return underlying.callbackHooks(iType, iObject); } public Set<ORecordHook> getHooks() { return underlying.getHooks(); } public <DBTYPE extends ODatabaseComplex<?>> DBTYPE unregisterHook(final ORecordHook iHookImpl) { underlying.unregisterHook(iHookImpl); return (DBTYPE) this; } public ODataSegmentStrategy getDataSegmentStrategy() { return underlying.getDataSegmentStrategy(); } public void setDataSegmentStrategy(final ODataSegmentStrategy dataSegmentStrategy) { underlying.setDataSegmentStrategy(dataSegmentStrategy); } @Override public void backup(final OutputStream out, final Map<String, Object> options, final Callable<Object> callable) throws IOException { underlying.backup(out, options, new Callable<Object>() { @Override public Object call() throws Exception { // FLUSHES ALL THE INDEX BEFORE for (OIndex<?> index : getMetadata().getIndexManager().getIndexes()) { index.flush(); } if (callable != null) return callable.call(); return null; } }); } @Override public void restore(final InputStream in, final Map<String, Object> options, final Callable<Object> callable) throws IOException { underlying.restore(in, options, callable); } protected void checkClusterBoundedToClass(final int iClusterId) { if (iClusterId == -1) return; for (OClass clazz : getMetadata().getSchema().getClasses()) { if (clazz.getDefaultClusterId() == iClusterId) throw new OSchemaException("Cannot drop the cluster '" + getClusterNameById(iClusterId) + "' because the classes ['" + clazz.getName() + "'] are bound to it. Drop these classes before dropping the cluster"); else if (clazz.getClusterIds().length > 1) { for (int i : clazz.getClusterIds()) { if (i == iClusterId) throw new OSchemaException("Cannot drop the cluster '" + getClusterNameById(iClusterId) + "' because the classes ['" + clazz.getName() + "'] are bound to it. Drop these classes before dropping the cluster"); } } } } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_ODatabaseRecordWrapperAbstract.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
3,452
class Sync implements Runnable { @Override public void run() { // don't re-schedule if its closed..., we are done if (indexShard.state() == IndexShardState.CLOSED) { return; } if (indexShard.state() == IndexShardState.STARTED && indexShard.translog().syncNeeded()) { threadPool.executor(ThreadPool.Names.SNAPSHOT).execute(new Runnable() { @Override public void run() { try { indexShard.translog().sync(); } catch (Exception e) { if (indexShard.state() == IndexShardState.STARTED) { logger.warn("failed to sync translog", e); } } if (indexShard.state() != IndexShardState.CLOSED) { flushScheduler = threadPool.schedule(syncInterval, ThreadPool.Names.SAME, Sync.this); } } }); } else { flushScheduler = threadPool.schedule(syncInterval, ThreadPool.Names.SAME, Sync.this); } } }
1no label
src_main_java_org_elasticsearch_index_gateway_local_LocalIndexShardGateway.java
319
public class NodesHotThreadsRequestBuilder extends NodesOperationRequestBuilder<NodesHotThreadsRequest, NodesHotThreadsResponse, NodesHotThreadsRequestBuilder> { public NodesHotThreadsRequestBuilder(ClusterAdminClient clusterClient) { super((InternalClusterAdminClient) clusterClient, new NodesHotThreadsRequest()); } public NodesHotThreadsRequestBuilder setThreads(int threads) { request.threads(threads); return this; } public NodesHotThreadsRequestBuilder setType(String type) { request.type(type); return this; } public NodesHotThreadsRequestBuilder setInterval(TimeValue interval) { request.interval(interval); return this; } @Override protected void doExecute(ActionListener<NodesHotThreadsResponse> listener) { ((ClusterAdminClient) client).nodesHotThreads(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_hotthreads_NodesHotThreadsRequestBuilder.java
722
public class OSBTreeMapEntryIterator<K, V> implements Iterator<Map.Entry<K, V>> { private LinkedList<Map.Entry<K, V>> preFetchedValues; private final OTreeInternal<K, V> sbTree; private K firstKey; private Map.Entry<K, V> currentEntry; public OSBTreeMapEntryIterator(OTreeInternal<K, V> sbTree) { this.sbTree = sbTree; if (sbTree.size() == 0) { this.preFetchedValues = null; return; } this.preFetchedValues = new LinkedList<Map.Entry<K, V>>(); firstKey = sbTree.firstKey(); prefetchData(true); } private void prefetchData(boolean firstTime) { sbTree.loadEntriesMajor(firstKey, firstTime, new OTreeInternal.RangeResultListener<K, V>() { @Override public boolean addResult(final Map.Entry<K, V> entry) { final V value = entry.getValue(); final V resultValue; if (value instanceof OIndexRIDContainer) resultValue = (V) new HashSet<OIdentifiable>((Collection<? extends OIdentifiable>) value); else resultValue = value; preFetchedValues.add(new Map.Entry<K, V>() { @Override public K getKey() { return entry.getKey(); } @Override public V getValue() { return resultValue; } @Override public V setValue(V v) { throw new UnsupportedOperationException("setValue"); } }); return preFetchedValues.size() <= 8000; } }); if (preFetchedValues.isEmpty()) preFetchedValues = null; else firstKey = preFetchedValues.getLast().getKey(); } @Override public boolean hasNext() { return preFetchedValues != null; } @Override public Map.Entry<K, V> next() { final Map.Entry<K, V> entry = preFetchedValues.removeFirst(); if (preFetchedValues.isEmpty()) prefetchData(false); currentEntry = entry; return entry; } @Override public void remove() { sbTree.remove(currentEntry.getKey()); currentEntry = null; } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_sbtree_OSBTreeMapEntryIterator.java
141
public static class Order { public static final int Description = 1000; public static final int Internal = 2000; public static final int Rules = 1000; }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContentImpl.java
2,693
public class FsGatewayModule extends BlobStoreGatewayModule { @Override protected void configure() { bind(Gateway.class).to(FsGateway.class).asEagerSingleton(); } }
0true
src_main_java_org_elasticsearch_gateway_fs_FsGatewayModule.java
311
String.class, null, new OConfigurationChangeCallback() { public void change(final Object iCurrentValue, final Object iNewValue) { Orient.instance().getProfiler().configure(iNewValue.toString()); } }),
0true
core_src_main_java_com_orientechnologies_orient_core_config_OGlobalConfiguration.java
1,163
public class OSQLMethodTrim extends OAbstractSQLMethod { public static final String NAME = "trim"; public OSQLMethodTrim() { super(NAME); } @Override public Object execute(OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iMethodParams) { ioResult = ioResult != null ? ioResult.toString().trim() : null; return ioResult; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodTrim.java
702
public class TransportBulkAction extends TransportAction<BulkRequest, BulkResponse> { private final AutoCreateIndex autoCreateIndex; private final boolean allowIdGeneration; private final ClusterService clusterService; private final TransportShardBulkAction shardBulkAction; private final TransportCreateIndexAction createIndexAction; @Inject public TransportBulkAction(Settings settings, ThreadPool threadPool, TransportService transportService, ClusterService clusterService, TransportShardBulkAction shardBulkAction, TransportCreateIndexAction createIndexAction) { super(settings, threadPool); this.clusterService = clusterService; this.shardBulkAction = shardBulkAction; this.createIndexAction = createIndexAction; this.autoCreateIndex = new AutoCreateIndex(settings); this.allowIdGeneration = componentSettings.getAsBoolean("action.allow_id_generation", true); transportService.registerHandler(BulkAction.NAME, new TransportHandler()); } @Override protected void doExecute(final BulkRequest bulkRequest, final ActionListener<BulkResponse> listener) { final long startTime = System.currentTimeMillis(); Set<String> indices = Sets.newHashSet(); for (ActionRequest request : bulkRequest.requests) { if (request instanceof IndexRequest) { IndexRequest indexRequest = (IndexRequest) request; if (!indices.contains(indexRequest.index())) { indices.add(indexRequest.index()); } } else if (request instanceof DeleteRequest) { DeleteRequest deleteRequest = (DeleteRequest) request; if (!indices.contains(deleteRequest.index())) { indices.add(deleteRequest.index()); } } else if (request instanceof UpdateRequest) { UpdateRequest updateRequest = (UpdateRequest) request; if (!indices.contains(updateRequest.index())) { indices.add(updateRequest.index()); } } } if (autoCreateIndex.needToCheck()) { final AtomicInteger counter = new AtomicInteger(indices.size()); final AtomicBoolean failed = new AtomicBoolean(); ClusterState state = clusterService.state(); for (String index : indices) { if (autoCreateIndex.shouldAutoCreate(index, state)) { createIndexAction.execute(new CreateIndexRequest(index).cause("auto(bulk api)"), new ActionListener<CreateIndexResponse>() { @Override public void onResponse(CreateIndexResponse result) { if (counter.decrementAndGet() == 0) { executeBulk(bulkRequest, startTime, listener); } } @Override public void onFailure(Throwable e) { if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) { // we have the index, do it if (counter.decrementAndGet() == 0) { executeBulk(bulkRequest, startTime, listener); } } else if (failed.compareAndSet(false, true)) { listener.onFailure(e); } } }); } else { if (counter.decrementAndGet() == 0) { executeBulk(bulkRequest, startTime, listener); } } } } else { executeBulk(bulkRequest, startTime, listener); } } private void executeBulk(final BulkRequest bulkRequest, final long startTime, final ActionListener<BulkResponse> listener) { ClusterState clusterState = clusterService.state(); // TODO use timeout to wait here if its blocked... clusterState.blocks().globalBlockedRaiseException(ClusterBlockLevel.WRITE); MetaData metaData = clusterState.metaData(); final AtomicArray<BulkItemResponse> responses = new AtomicArray<BulkItemResponse>(bulkRequest.requests.size()); for (int i = 0; i < bulkRequest.requests.size(); i++) { ActionRequest request = bulkRequest.requests.get(i); if (request instanceof IndexRequest) { IndexRequest indexRequest = (IndexRequest) request; String aliasOrIndex = indexRequest.index(); indexRequest.index(clusterState.metaData().concreteIndex(indexRequest.index())); MappingMetaData mappingMd = null; if (metaData.hasIndex(indexRequest.index())) { mappingMd = metaData.index(indexRequest.index()).mappingOrDefault(indexRequest.type()); } try { indexRequest.process(metaData, aliasOrIndex, mappingMd, allowIdGeneration); } catch (ElasticsearchParseException e) { BulkItemResponse.Failure failure = new BulkItemResponse.Failure(indexRequest.index(), indexRequest.type(), indexRequest.id(), e); BulkItemResponse bulkItemResponse = new BulkItemResponse(i, "index", failure); responses.set(i, bulkItemResponse); // make sure the request gets never processed again bulkRequest.requests.set(i, null); } } else if (request instanceof DeleteRequest) { DeleteRequest deleteRequest = (DeleteRequest) request; deleteRequest.routing(clusterState.metaData().resolveIndexRouting(deleteRequest.routing(), deleteRequest.index())); deleteRequest.index(clusterState.metaData().concreteIndex(deleteRequest.index())); } else if (request instanceof UpdateRequest) { UpdateRequest updateRequest = (UpdateRequest) request; updateRequest.routing(clusterState.metaData().resolveIndexRouting(updateRequest.routing(), updateRequest.index())); updateRequest.index(clusterState.metaData().concreteIndex(updateRequest.index())); } } // first, go over all the requests and create a ShardId -> Operations mapping Map<ShardId, List<BulkItemRequest>> requestsByShard = Maps.newHashMap(); for (int i = 0; i < bulkRequest.requests.size(); i++) { ActionRequest request = bulkRequest.requests.get(i); if (request instanceof IndexRequest) { IndexRequest indexRequest = (IndexRequest) request; ShardId shardId = clusterService.operationRouting().indexShards(clusterState, indexRequest.index(), indexRequest.type(), indexRequest.id(), indexRequest.routing()).shardId(); List<BulkItemRequest> list = requestsByShard.get(shardId); if (list == null) { list = Lists.newArrayList(); requestsByShard.put(shardId, list); } list.add(new BulkItemRequest(i, request)); } else if (request instanceof DeleteRequest) { DeleteRequest deleteRequest = (DeleteRequest) request; MappingMetaData mappingMd = clusterState.metaData().index(deleteRequest.index()).mappingOrDefault(deleteRequest.type()); if (mappingMd != null && mappingMd.routing().required() && deleteRequest.routing() == null) { // if routing is required, and no routing on the delete request, we need to broadcast it.... GroupShardsIterator groupShards = clusterService.operationRouting().broadcastDeleteShards(clusterState, deleteRequest.index()); for (ShardIterator shardIt : groupShards) { List<BulkItemRequest> list = requestsByShard.get(shardIt.shardId()); if (list == null) { list = Lists.newArrayList(); requestsByShard.put(shardIt.shardId(), list); } list.add(new BulkItemRequest(i, new DeleteRequest(deleteRequest))); } } else { ShardId shardId = clusterService.operationRouting().deleteShards(clusterState, deleteRequest.index(), deleteRequest.type(), deleteRequest.id(), deleteRequest.routing()).shardId(); List<BulkItemRequest> list = requestsByShard.get(shardId); if (list == null) { list = Lists.newArrayList(); requestsByShard.put(shardId, list); } list.add(new BulkItemRequest(i, request)); } } else if (request instanceof UpdateRequest) { UpdateRequest updateRequest = (UpdateRequest) request; MappingMetaData mappingMd = clusterState.metaData().index(updateRequest.index()).mappingOrDefault(updateRequest.type()); if (mappingMd != null && mappingMd.routing().required() && updateRequest.routing() == null) { continue; // What to do? } ShardId shardId = clusterService.operationRouting().indexShards(clusterState, updateRequest.index(), updateRequest.type(), updateRequest.id(), updateRequest.routing()).shardId(); List<BulkItemRequest> list = requestsByShard.get(shardId); if (list == null) { list = Lists.newArrayList(); requestsByShard.put(shardId, list); } list.add(new BulkItemRequest(i, request)); } } if (requestsByShard.isEmpty()) { listener.onResponse(new BulkResponse(responses.toArray(new BulkItemResponse[responses.length()]), System.currentTimeMillis() - startTime)); return; } final AtomicInteger counter = new AtomicInteger(requestsByShard.size()); for (Map.Entry<ShardId, List<BulkItemRequest>> entry : requestsByShard.entrySet()) { final ShardId shardId = entry.getKey(); final List<BulkItemRequest> requests = entry.getValue(); BulkShardRequest bulkShardRequest = new BulkShardRequest(shardId.index().name(), shardId.id(), bulkRequest.refresh(), requests.toArray(new BulkItemRequest[requests.size()])); bulkShardRequest.replicationType(bulkRequest.replicationType()); bulkShardRequest.consistencyLevel(bulkRequest.consistencyLevel()); bulkShardRequest.timeout(bulkRequest.timeout()); shardBulkAction.execute(bulkShardRequest, new ActionListener<BulkShardResponse>() { @Override public void onResponse(BulkShardResponse bulkShardResponse) { for (BulkItemResponse bulkItemResponse : bulkShardResponse.getResponses()) { responses.set(bulkItemResponse.getItemId(), bulkItemResponse); } if (counter.decrementAndGet() == 0) { finishHim(); } } @Override public void onFailure(Throwable e) { // create failures for all relevant requests String message = ExceptionsHelper.detailedMessage(e); RestStatus status = ExceptionsHelper.status(e); for (BulkItemRequest request : requests) { if (request.request() instanceof IndexRequest) { IndexRequest indexRequest = (IndexRequest) request.request(); responses.set(request.id(), new BulkItemResponse(request.id(), indexRequest.opType().toString().toLowerCase(Locale.ENGLISH), new BulkItemResponse.Failure(indexRequest.index(), indexRequest.type(), indexRequest.id(), message, status))); } else if (request.request() instanceof DeleteRequest) { DeleteRequest deleteRequest = (DeleteRequest) request.request(); responses.set(request.id(), new BulkItemResponse(request.id(), "delete", new BulkItemResponse.Failure(deleteRequest.index(), deleteRequest.type(), deleteRequest.id(), message, status))); } else if (request.request() instanceof UpdateRequest) { UpdateRequest updateRequest = (UpdateRequest) request.request(); responses.set(request.id(), new BulkItemResponse(request.id(), "update", new BulkItemResponse.Failure(updateRequest.index(), updateRequest.type(), updateRequest.id(), message, status))); } } if (counter.decrementAndGet() == 0) { finishHim(); } } private void finishHim() { listener.onResponse(new BulkResponse(responses.toArray(new BulkItemResponse[responses.length()]), System.currentTimeMillis() - startTime)); } }); } } class TransportHandler extends BaseTransportRequestHandler<BulkRequest> { @Override public BulkRequest newInstance() { return new BulkRequest(); } @Override public void messageReceived(final BulkRequest request, final TransportChannel channel) throws Exception { // no need to use threaded listener, since we just send a response request.listenerThreaded(false); execute(request, new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse 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 error response for action [" + BulkAction.NAME + "] and request [" + request + "]", e1); } } }); } @Override public String executor() { return ThreadPool.Names.SAME; } } }
1no label
src_main_java_org_elasticsearch_action_bulk_TransportBulkAction.java
1,613
private class LifecycleListenerImpl implements LifecycleListener { @Override public void stateChanged(final LifecycleEvent event) { if (event.getState() == LifecycleState.STARTED) { try { start(); } catch (Exception e) { logger.severe("ManagementCenterService could not be started!", e); } } } }
0true
hazelcast_src_main_java_com_hazelcast_management_ManagementCenterService.java
93
public interface NamedOperationComponent { List<String> setOperationValues(Map<String, String> originalParameters, Map<String, String> derivedParameters); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_service_operation_NamedOperationComponent.java
628
c3.addListenerConfig(new ListenerConfig(new LifecycleListener() { public void stateChanged(final LifecycleEvent event) { if (event.getState() == LifecycleState.MERGING) { h1.shutdown(); } else if (event.getState() == LifecycleState.MERGED) { latch.countDown(); } } }));
0true
hazelcast_src_test_java_com_hazelcast_cluster_SplitBrainHandlerTest.java
154
public static final Map<String, ConfigOption> REGISTERED_STORAGE_MANAGERS_SHORTHAND = new HashMap<String, ConfigOption>() {{ put("berkeleyje", STORAGE_DIRECTORY); put("hazelcast", STORAGE_DIRECTORY); put("hazelcastcache", STORAGE_DIRECTORY); put("infinispan", STORAGE_DIRECTORY); put("cassandra", STORAGE_HOSTS); put("cassandrathrift", STORAGE_HOSTS); put("astyanax", STORAGE_HOSTS); put("hbase", STORAGE_HOSTS); put("embeddedcassandra", STORAGE_CONF_FILE); put("inmemory", null); }};
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_Backend.java
461
@Service("blResourceMinificationService") public class ResourceMinificationServiceImpl implements ResourceMinificationService { protected static final Log LOG = LogFactory.getLog(ResourceMinificationServiceImpl.class); @Value("${minify.enabled}") protected boolean enabled; @Value("${minify.linebreak}") protected int linebreak; @Value("${minify.munge}") protected boolean munge; @Value("${minify.verbose}") protected boolean verbose; @Value("${minify.preserveAllSemiColons}") protected boolean preserveAllSemiColons; @Value("${minify.disableOptimizations}") protected boolean disableOptimizations; @Override public byte[] minify(String filename, byte[] bytes) { if (!enabled) { return bytes; } String type = null; if (filename.endsWith(".js")) { type = "js"; } else if (filename.endsWith(".css")) { type = "css"; } if (!"js".equals(type) && !"css".equals(type)) { throw new IllegalArgumentException("Can only minify js or css resources"); } byte[] minifiedBytes; // Input streams to read the bytes ByteArrayInputStream bais = new ByteArrayInputStream(bytes); InputStreamReader isr = new InputStreamReader(bais); BufferedReader in = new BufferedReader(isr); // Output streams to save the modified bytes ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(baos); BufferedWriter out = new BufferedWriter(osw); try { if ("js".equals(type)) { JavaScriptCompressor jsc = new JavaScriptCompressor(in, getLogBasedErrorReporter()); jsc.compress(out, linebreak, true, verbose, preserveAllSemiColons, disableOptimizations); } else if ("css".equals(type)) { CssCompressor cssc = new CssCompressor(in); cssc.compress(out, 100); } out.flush(); minifiedBytes = baos.toByteArray(); } catch (Exception e) { // Catch everything - on a runtime exception, we still want to return the unminified bytes LOG.warn("Could not minify resources, returned unminified bytes", e); return bytes; } finally { try { in.close(); out.close(); } catch (IOException e2) { throw new RuntimeException(e2); } } return minifiedBytes; } protected ErrorReporter getLogBasedErrorReporter() { return new ErrorReporter() { @Override public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) { if (line < 0) { LOG.warn(message); } else { LOG.warn(line + ':' + lineOffset + ':' + message); } } @Override public void error(String message, String sourceName, int line, String lineSource, int lineOffset) { if (line < 0) { LOG.error(message); } else { LOG.error(line + ':' + lineOffset + ':' + message); } } @Override public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) { error(message, sourceName, line, lineSource, lineOffset); return new EvaluatorException(message); } }; } }
1no label
common_src_main_java_org_broadleafcommerce_common_resource_service_ResourceMinificationServiceImpl.java
309
private static class Update implements Iterable<NodePropertyUpdate> { private final NodeLabelUpdate labels; private final List<NodePropertyUpdate> propertyUpdates = new ArrayList<>(); Update( long nodeId, long[] labels ) { this.labels = labelChanges( nodeId, EMPTY_LONG_ARRAY, labels ); } void add( NodePropertyUpdate update ) { propertyUpdates.add( update ); } @Override public Iterator<NodePropertyUpdate> iterator() { return propertyUpdates.iterator(); } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreIndexStoreView.java
113
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_PAGE_RULE") public class PageRuleImpl implements PageRule { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator= "PageRuleId") @GenericGenerator( name="PageRuleId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="PageRuleImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.cms.page.domain.PageRuleImpl") } ) @Column(name = "PAGE_RULE_ID") protected Long id; @Lob @Type(type = "org.hibernate.type.StringClobType") @Column(name = "MATCH_RULE", length = Integer.MAX_VALUE - 1) protected String matchRule; /* (non-Javadoc) * @see org.broadleafcommerce.core.offer.domain.StructuredContentRule#getId() */ @Override public Long getId() { return id; } /* (non-Javadoc) * @see org.broadleafcommerce.core.offer.domain.StructuredContentRule#setId(java.lang.Long) */ @Override public void setId(Long id) { this.id = id; } /* (non-Javadoc) * @see org.broadleafcommerce.core.offer.domain.StructuredContentRule#getMatchRule() */ @Override public String getMatchRule() { return matchRule; } /* (non-Javadoc) * @see org.broadleafcommerce.core.offer.domain.StructuredContentRule#setMatchRule(java.lang.String) */ @Override public void setMatchRule(String matchRule) { this.matchRule = matchRule; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((matchRule == null) ? 0 : matchRule.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; PageRuleImpl other = (PageRuleImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (matchRule == null) { if (other.matchRule != null) return false; } else if (!matchRule.equals(other.matchRule)) return false; return true; } @Override public PageRule cloneEntity() { PageRuleImpl newField = new PageRuleImpl(); newField.matchRule = matchRule; return newField; } }
1no label
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_domain_PageRuleImpl.java
410
runConflictingTx(new TxJob() { @Override public void run(IndexTransaction tx) { tx.delete(defStore, defDoc, TEXT, ImmutableMap.of(), true); } }, new TxJob() {
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexProviderTest.java
2,122
public class ConsoleAppender extends WriterAppender { public static final String SYSTEM_OUT = "System.out"; public static final String SYSTEM_ERR = "System.err"; protected String target = SYSTEM_OUT; /** * Determines if the appender honors reassignments of System.out * or System.err made after configuration. */ private boolean follow = true; /** * Constructs an unconfigured appender. */ public ConsoleAppender() { } /** * Creates a configured appender. * * @param layout layout, may not be null. */ public ConsoleAppender(Layout layout) { this(layout, SYSTEM_OUT); } /** * Creates a configured appender. * * @param layout layout, may not be null. * @param target target, either "System.err" or "System.out". */ public ConsoleAppender(Layout layout, String target) { setLayout(layout); setTarget(target); activateOptions(); } /** * Sets the value of the <b>Target</b> option. Recognized values * are "System.out" and "System.err". Any other value will be * ignored. */ public void setTarget(String value) { String v = value.trim(); if (SYSTEM_OUT.equalsIgnoreCase(v)) { target = SYSTEM_OUT; } else if (SYSTEM_ERR.equalsIgnoreCase(v)) { target = SYSTEM_ERR; } else { targetWarn(value); } } /** * Returns the current value of the <b>Target</b> property. The * default value of the option is "System.out". * <p/> * See also {@link #setTarget}. */ public String getTarget() { return target; } /** * Sets whether the appender honors reassignments of System.out * or System.err made after configuration. * * @param newValue if true, appender will use value of System.out or * System.err in force at the time when logging events are appended. * @since 1.2.13 */ public final void setFollow(final boolean newValue) { follow = newValue; } /** * Gets whether the appender honors reassignments of System.out * or System.err made after configuration. * * @return true if appender will use value of System.out or * System.err in force at the time when logging events are appended. * @since 1.2.13 */ public final boolean getFollow() { return follow; } void targetWarn(String val) { LogLog.warn("[" + val + "] should be System.out or System.err."); LogLog.warn("Using previously set target, System.out by default."); } /** * Prepares the appender for use. */ public void activateOptions() { if (follow) { if (target.equals(SYSTEM_ERR)) { setWriter(createWriter(new SystemErrStream())); } else { setWriter(createWriter(new SystemOutStream())); } } else { if (target.equals(SYSTEM_ERR)) { setWriter(createWriter(System.err)); } else { setWriter(createWriter(System.out)); } } super.activateOptions(); } /** * {@inheritDoc} */ protected final void closeWriter() { if (follow) { super.closeWriter(); } } /** * An implementation of OutputStream that redirects to the * current System.err. */ private static class SystemErrStream extends OutputStream { public SystemErrStream() { } public void close() { } public void flush() { System.err.flush(); } public void write(final byte[] b) throws IOException { if (!Loggers.consoleLoggingEnabled()) { return; } System.err.write(b); } public void write(final byte[] b, final int off, final int len) throws IOException { if (!Loggers.consoleLoggingEnabled()) { return; } System.err.write(b, off, len); } public void write(final int b) throws IOException { if (!Loggers.consoleLoggingEnabled()) { return; } System.err.write(b); } } /** * An implementation of OutputStream that redirects to the * current System.out. */ private static class SystemOutStream extends OutputStream { public SystemOutStream() { } public void close() { } public void flush() { System.out.flush(); } public void write(final byte[] b) throws IOException { if (!Loggers.consoleLoggingEnabled()) { return; } System.out.write(b); } public void write(final byte[] b, final int off, final int len) throws IOException { if (!Loggers.consoleLoggingEnabled()) { return; } System.out.write(b, off, len); } public void write(final int b) throws IOException { if (!Loggers.consoleLoggingEnabled()) { return; } System.out.write(b); } } }
0true
src_main_java_org_elasticsearch_common_logging_log4j_ConsoleAppender.java
352
public interface BroadleafClassTransformer extends ClassTransformer { public void compileJPAProperties(Properties props, Object key) throws Exception; }
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_jpa_convert_BroadleafClassTransformer.java
711
constructors[COLLECTION_ADD_ALL] = new ConstructorFunction<Integer, Portable>() { public Portable createNew(Integer arg) { return new CollectionAddAllRequest(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java
1,083
@Service("blOrderItemService") public class OrderItemServiceImpl implements OrderItemService { @Resource(name="blOrderItemDao") protected OrderItemDao orderItemDao; @Resource(name="blDynamicSkuPricingService" ) protected DynamicSkuPricingService dynamicSkuPricingService; @Override public OrderItem readOrderItemById(final Long orderItemId) { return orderItemDao.readOrderItemById(orderItemId); } @Override public OrderItem saveOrderItem(final OrderItem orderItem) { return orderItemDao.saveOrderItem(orderItem); } @Override public void delete(final OrderItem item) { orderItemDao.delete(item); } @Override public PersonalMessage createPersonalMessage() { return orderItemDao.createPersonalMessage(); } protected void populateDiscreteOrderItem(DiscreteOrderItem item, AbstractOrderItemRequest itemRequest) { item.setSku(itemRequest.getSku()); item.setQuantity(itemRequest.getQuantity()); item.setCategory(itemRequest.getCategory()); item.setProduct(itemRequest.getProduct()); item.setOrder(itemRequest.getOrder()); if (itemRequest.getItemAttributes() != null && itemRequest.getItemAttributes().size() > 0) { Map<String,OrderItemAttribute> orderItemAttributes = new HashMap<String,OrderItemAttribute>(); item.setOrderItemAttributes(orderItemAttributes); for (String key : itemRequest.getItemAttributes().keySet()) { String value = itemRequest.getItemAttributes().get(key); OrderItemAttribute attribute = new OrderItemAttributeImpl(); attribute.setName(key); attribute.setValue(value); attribute.setOrderItem(item); orderItemAttributes.put(key, attribute); } } } @Override public OrderItem createOrderItem(final OrderItemRequest itemRequest) { final OrderItem item = orderItemDao.create(OrderItemType.BASIC); item.setName(itemRequest.getItemName()); item.setQuantity(itemRequest.getQuantity()); item.setOrder(itemRequest.getOrder()); if (itemRequest.getSalePriceOverride() != null) { item.setSalePriceOverride(Boolean.TRUE); item.setSalePrice(itemRequest.getSalePriceOverride()); } if (itemRequest.getRetailPriceOverride() != null) { item.setRetailPriceOverride(Boolean.TRUE); item.setRetailPrice(itemRequest.getRetailPriceOverride()); } return item; } @Override public DiscreteOrderItem createDiscreteOrderItem(final DiscreteOrderItemRequest itemRequest) { final DiscreteOrderItem item = (DiscreteOrderItem) orderItemDao.create(OrderItemType.DISCRETE); populateDiscreteOrderItem(item, itemRequest); item.setBundleOrderItem(itemRequest.getBundleOrderItem()); item.setBaseSalePrice(itemRequest.getSalePriceOverride()==null?itemRequest.getSku().getSalePrice():itemRequest.getSalePriceOverride()); item.setBaseRetailPrice(itemRequest.getSku().getRetailPrice()); item.setDiscreteOrderItemFeePrices(itemRequest.getDiscreteOrderItemFeePrices()); if (itemRequest.getSalePriceOverride() != null) { item.setSalePriceOverride(Boolean.TRUE); item.setSalePrice(itemRequest.getSalePriceOverride()); item.setBaseSalePrice(itemRequest.getSalePriceOverride()); } if (itemRequest.getRetailPriceOverride() != null) { item.setRetailPriceOverride(Boolean.TRUE); item.setRetailPrice(itemRequest.getRetailPriceOverride()); item.setBaseRetailPrice(itemRequest.getRetailPriceOverride()); } for (DiscreteOrderItemFeePrice feePrice : item.getDiscreteOrderItemFeePrices()) { feePrice.setDiscreteOrderItem(item); } item.setPersonalMessage(itemRequest.getPersonalMessage()); return item; } public DiscreteOrderItem createDiscreteOrderItem(final AbstractOrderItemRequest itemRequest) { final DiscreteOrderItem item = (DiscreteOrderItem) orderItemDao.create(OrderItemType.DISCRETE); populateDiscreteOrderItem(item, itemRequest); item.setBaseSalePrice(itemRequest.getSku().getSalePrice()); item.setBaseRetailPrice(itemRequest.getSku().getRetailPrice()); // item.updatePrices(); item.updateSaleAndRetailPrices(); item.assignFinalPrice(); item.setPersonalMessage(itemRequest.getPersonalMessage()); return item; } @Override public DiscreteOrderItem createDynamicPriceDiscreteOrderItem(final DiscreteOrderItemRequest itemRequest, @SuppressWarnings("rawtypes") HashMap skuPricingConsiderations) { final DiscreteOrderItem item = (DiscreteOrderItem) orderItemDao.create(OrderItemType.EXTERNALLY_PRICED); populateDiscreteOrderItem(item, itemRequest); DynamicSkuPrices prices = dynamicSkuPricingService.getSkuPrices(itemRequest.getSku(), skuPricingConsiderations); item.setBundleOrderItem(itemRequest.getBundleOrderItem()); item.setBaseRetailPrice(prices.getRetailPrice()); item.setBaseSalePrice(prices.getSalePrice()); item.setSalePrice(prices.getSalePrice()); item.setRetailPrice(prices.getRetailPrice()); if (itemRequest.getSalePriceOverride() != null) { item.setSalePriceOverride(Boolean.TRUE); item.setSalePrice(itemRequest.getSalePriceOverride()); item.setBaseSalePrice(itemRequest.getSalePriceOverride()); } if (itemRequest.getRetailPriceOverride() != null) { item.setRetailPriceOverride(Boolean.TRUE); item.setRetailPrice(itemRequest.getRetailPriceOverride()); item.setBaseRetailPrice(itemRequest.getRetailPriceOverride()); } item.setDiscreteOrderItemFeePrices(itemRequest.getDiscreteOrderItemFeePrices()); for (DiscreteOrderItemFeePrice fee : itemRequest.getDiscreteOrderItemFeePrices()) { item.setSalePrice(item.getSalePrice().add(fee.getAmount())); item.setRetailPrice(item.getRetailPrice().add(fee.getAmount())); } item.setPersonalMessage(itemRequest.getPersonalMessage()); return item; } @Override public GiftWrapOrderItem createGiftWrapOrderItem(final GiftWrapOrderItemRequest itemRequest) { final GiftWrapOrderItem item = (GiftWrapOrderItem) orderItemDao.create(OrderItemType.GIFTWRAP); item.setSku(itemRequest.getSku()); item.setOrder(itemRequest.getOrder()); item.setBundleOrderItem(itemRequest.getBundleOrderItem()); item.setQuantity(itemRequest.getQuantity()); item.setCategory(itemRequest.getCategory()); item.setProduct(itemRequest.getProduct()); item.setBaseSalePrice(itemRequest.getSku().getSalePrice()); item.setBaseRetailPrice(itemRequest.getSku().getRetailPrice()); item.setDiscreteOrderItemFeePrices(itemRequest.getDiscreteOrderItemFeePrices()); if (itemRequest.getSalePriceOverride() != null) { item.setSalePriceOverride(Boolean.TRUE); item.setSalePrice(itemRequest.getSalePriceOverride()); item.setBaseSalePrice(itemRequest.getSalePriceOverride()); } if (itemRequest.getRetailPriceOverride() != null) { item.setRetailPriceOverride(Boolean.TRUE); item.setRetailPrice(itemRequest.getRetailPriceOverride()); item.setBaseRetailPrice(itemRequest.getRetailPriceOverride()); } //item.updatePrices(); item.updateSaleAndRetailPrices(); item.assignFinalPrice(); item.getWrappedItems().addAll(itemRequest.getWrappedItems()); for (OrderItem orderItem : item.getWrappedItems()) { orderItem.setGiftWrapOrderItem(item); } return item; } @Override public BundleOrderItem createBundleOrderItem(final BundleOrderItemRequest itemRequest) { final BundleOrderItem item = (BundleOrderItem) orderItemDao.create(OrderItemType.BUNDLE); item.setQuantity(itemRequest.getQuantity()); item.setCategory(itemRequest.getCategory()); item.setName(itemRequest.getName()); item.setBundleOrderItemFeePrices(itemRequest.getBundleOrderItemFeePrices()); item.setOrder(itemRequest.getOrder()); if (itemRequest.getSalePriceOverride() != null) { item.setSalePriceOverride(Boolean.TRUE); item.setSalePrice(itemRequest.getSalePriceOverride()); item.setBaseSalePrice(itemRequest.getSalePriceOverride()); } if (itemRequest.getRetailPriceOverride() != null) { item.setRetailPriceOverride(Boolean.TRUE); item.setRetailPrice(itemRequest.getRetailPriceOverride()); item.setBaseRetailPrice(itemRequest.getRetailPriceOverride()); } for (DiscreteOrderItemRequest discreteItemRequest : itemRequest.getDiscreteOrderItems()) { discreteItemRequest.setBundleOrderItem(item); DiscreteOrderItem discreteOrderItem; if (discreteItemRequest instanceof GiftWrapOrderItemRequest) { discreteOrderItem = createGiftWrapOrderItem((GiftWrapOrderItemRequest) discreteItemRequest); } else { discreteOrderItem = createDiscreteOrderItem(discreteItemRequest); } item.getDiscreteOrderItems().add(discreteOrderItem); } return item; } @Override public BundleOrderItem createBundleOrderItem(final ProductBundleOrderItemRequest itemRequest) { ProductBundle productBundle = itemRequest.getProductBundle(); BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItemDao.create(OrderItemType.BUNDLE); bundleOrderItem.setQuantity(itemRequest.getQuantity()); bundleOrderItem.setCategory(itemRequest.getCategory()); bundleOrderItem.setSku(itemRequest.getSku()); bundleOrderItem.setName(itemRequest.getName()); bundleOrderItem.setProductBundle(productBundle); bundleOrderItem.setOrder(itemRequest.getOrder()); if (itemRequest.getSalePriceOverride() != null) { bundleOrderItem.setSalePriceOverride(Boolean.TRUE); bundleOrderItem.setSalePrice(itemRequest.getSalePriceOverride()); bundleOrderItem.setBaseSalePrice(itemRequest.getSalePriceOverride()); } if (itemRequest.getRetailPriceOverride() != null) { bundleOrderItem.setRetailPriceOverride(Boolean.TRUE); bundleOrderItem.setRetailPrice(itemRequest.getRetailPriceOverride()); bundleOrderItem.setBaseRetailPrice(itemRequest.getRetailPriceOverride()); } for (SkuBundleItem skuBundleItem : productBundle.getSkuBundleItems()) { Product bundleProduct = skuBundleItem.getBundle(); Sku bundleSku = skuBundleItem.getSku(); Category bundleCategory = null; if (itemRequest.getCategory() != null) { bundleCategory = itemRequest.getCategory(); } if (bundleCategory == null && bundleProduct != null) { bundleCategory = bundleProduct.getDefaultCategory(); } DiscreteOrderItemRequest bundleItemRequest = new DiscreteOrderItemRequest(); bundleItemRequest.setCategory(bundleCategory); bundleItemRequest.setProduct(bundleProduct); bundleItemRequest.setQuantity(skuBundleItem.getQuantity()); bundleItemRequest.setSku(bundleSku); bundleItemRequest.setItemAttributes(itemRequest.getItemAttributes()); bundleItemRequest.setSalePriceOverride(skuBundleItem.getSalePrice()); bundleItemRequest.setBundleOrderItem(bundleOrderItem); DiscreteOrderItem bundleDiscreteItem = createDiscreteOrderItem(bundleItemRequest); bundleDiscreteItem.setSkuBundleItem(skuBundleItem); bundleOrderItem.getDiscreteOrderItems().add(bundleDiscreteItem); } bundleOrderItem = (BundleOrderItem) saveOrderItem(bundleOrderItem); return bundleOrderItem; } @Override public OrderItemRequestDTO buildOrderItemRequestDTOFromOrderItem(OrderItem item) { OrderItemRequestDTO orderItemRequest; if (item instanceof DiscreteOrderItem) { DiscreteOrderItem doi = (DiscreteOrderItem) item; orderItemRequest = new OrderItemRequestDTO(); orderItemRequest.setQuantity(doi.getQuantity()); if (doi.getCategory() != null) { orderItemRequest.setCategoryId(doi.getCategory().getId()); } if (doi.getProduct() != null) { orderItemRequest.setProductId(doi.getProduct().getId()); } if (doi.getSku() != null) { orderItemRequest.setSkuId(doi.getSku().getId()); } if (doi.getOrderItemAttributes() != null) { for (Entry<String, OrderItemAttribute> entry : item.getOrderItemAttributes().entrySet()) { orderItemRequest.getItemAttributes().put(entry.getKey(), entry.getValue().getValue()); } } } else { orderItemRequest = new NonDiscreteOrderItemRequestDTO(); NonDiscreteOrderItemRequestDTO ndr = (NonDiscreteOrderItemRequestDTO) orderItemRequest; ndr.setItemName(item.getName()); ndr.setQuantity(item.getQuantity()); ndr.setOverrideRetailPrice(item.getRetailPrice()); ndr.setOverrideSalePrice(item.getSalePrice()); } return orderItemRequest; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_OrderItemServiceImpl.java
1,602
public interface PersistencePerspectiveItem extends Serializable { public void accept(PersistencePerspectiveItemVisitor visitor); public PersistencePerspectiveItem clonePersistencePerspectiveItem(); }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_PersistencePerspectiveItem.java
3,501
public interface TypeParser { public static class ParserContext { private final PostingsFormatService postingsFormatService; private final DocValuesFormatService docValuesFormatService; private final AnalysisService analysisService; private final SimilarityLookupService similarityLookupService; private final ImmutableMap<String, TypeParser> typeParsers; private final Version indexVersionCreated; public ParserContext(PostingsFormatService postingsFormatService, DocValuesFormatService docValuesFormatService, AnalysisService analysisService, SimilarityLookupService similarityLookupService, ImmutableMap<String, TypeParser> typeParsers, Version indexVersionCreated) { this.postingsFormatService = postingsFormatService; this.docValuesFormatService = docValuesFormatService; this.analysisService = analysisService; this.similarityLookupService = similarityLookupService; this.typeParsers = typeParsers; this.indexVersionCreated = indexVersionCreated; } public AnalysisService analysisService() { return analysisService; } public PostingsFormatService postingFormatService() { return postingsFormatService; } public DocValuesFormatService docValuesFormatService() { return docValuesFormatService; } public SimilarityLookupService similarityLookupService() { return similarityLookupService; } public TypeParser typeParser(String type) { return typeParsers.get(Strings.toUnderscoreCase(type)); } public Version indexVersionCreated() { return indexVersionCreated; } } Mapper.Builder<?,?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException; }
0true
src_main_java_org_elasticsearch_index_mapper_Mapper.java
187
ItemListener listener = new ItemListener() { public void itemAdded(ItemEvent itemEvent) { latch.countDown(); } public void itemRemoved(ItemEvent item) { } };
0true
hazelcast-client_src_test_java_com_hazelcast_client_collections_ClientSetTest.java
486
private class InMemoryTransaction extends AbstractStoreTransaction { public InMemoryTransaction(final BaseTransactionConfig config) { super(config); } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_inmemory_InMemoryStoreManager.java
3,260
public enum SortMode { /** * Sum of all the values. */ SUM { /** * Returns the sum of the two values */ @Override public double apply(double a, double b) { return a + b; } /** * Returns the sum of the two values */ @Override public long apply(long a, long b) { return a + b; } }, /** * Average of all the values. */ AVG { /** * Returns the sum of the two values */ @Override public double apply(double a, double b) { return a + b; } /** * Returns the sum of the two values */ @Override public long apply(long a, long b) { return a + b; } /** * Returns <code>a / Math.max(1.0d, numValues)</code> */ @Override public double reduce(double a, int numValues) { return a / Math.max(1.0d, (double) numValues); } /** * Returns <code>Math.round(a / Math.max(1.0, numValues))</code> */ @Override public long reduce(long a, int numValues) { return Math.round(a / Math.max(1.0, numValues)); } }, /** * Pick the lowest value. */ MIN { /** * Equivalent to {@link Math#min(double, double)} */ @Override public double apply(double a, double b) { return Math.min(a, b); } /** * Equivalent to {@link Math#min(long, long)} */ @Override public long apply(long a, long b) { return Math.min(a, b); } /** * Returns {@link Double#POSITIVE_INFINITY} */ @Override public double startDouble() { return Double.POSITIVE_INFINITY; } /** * Returns {@link Long#MAX_VALUE} */ @Override public long startLong() { return Long.MAX_VALUE; } /** * Returns the first value returned for the given <tt>docId</tt> or the <tt>defaultValue</tt> if the document * has no values. */ @Override public double getRelevantValue(DoubleValues values, int docId, double defaultValue) { assert values.getOrder() != AtomicFieldData.Order.NONE; if (values.setDocument(docId) > 0) { return values.nextValue(); } return defaultValue; } /** * Returns the first value returned for the given <tt>docId</tt> or the <tt>defaultValue</tt> if the document * has no values. */ @Override public long getRelevantValue(LongValues values, int docId, long defaultValue) { assert values.getOrder() != AtomicFieldData.Order.NONE; if (values.setDocument(docId) > 0) { return values.nextValue(); } return defaultValue; } /** * Returns the first value returned for the given <tt>docId</tt> or the <tt>defaultValue</tt> if the document * has no values. */ @Override public BytesRef getRelevantValue(BytesValues values, int docId, BytesRef defaultValue) { assert values.getOrder() != AtomicFieldData.Order.NONE; if (values.setDocument(docId) > 0) { return values.nextValue(); } return defaultValue; } }, /** * Pick the highest value. */ MAX { /** * Equivalent to {@link Math#max(double, double)} */ @Override public double apply(double a, double b) { return Math.max(a, b); } /** * Equivalent to {@link Math#max(long, long)} */ @Override public long apply(long a, long b) { return Math.max(a, b); } /** * Returns {@link Double#NEGATIVE_INFINITY} */ @Override public double startDouble() { return Double.NEGATIVE_INFINITY; } /** * Returns {@link Long#MIN_VALUE} */ @Override public long startLong() { return Long.MIN_VALUE; } /** * Returns the last value returned for the given <tt>docId</tt> or the <tt>defaultValue</tt> if the document * has no values. */ @Override public double getRelevantValue(DoubleValues values, int docId, double defaultValue) { assert values.getOrder() != AtomicFieldData.Order.NONE; final int numValues = values.setDocument(docId); double retVal = defaultValue; for (int i = 0; i < numValues; i++) { retVal = values.nextValue(); } return retVal; } /** * Returns the last value returned for the given <tt>docId</tt> or the <tt>defaultValue</tt> if the document * has no values. */ @Override public long getRelevantValue(LongValues values, int docId, long defaultValue) { assert values.getOrder() != AtomicFieldData.Order.NONE; final int numValues = values.setDocument(docId); long retVal = defaultValue; for (int i = 0; i < numValues; i++) { retVal = values.nextValue(); } return retVal; } /** * Returns the last value returned for the given <tt>docId</tt> or the <tt>defaultValue</tt> if the document * has no values. */ @Override public BytesRef getRelevantValue(BytesValues values, int docId, BytesRef defaultValue) { assert values.getOrder() != AtomicFieldData.Order.NONE; final int numValues = values.setDocument(docId); BytesRef currentVal = defaultValue; for (int i = 0; i < numValues; i++) { currentVal = values.nextValue(); } return currentVal; } }; /** * Applies the sort mode and returns the result. This method is meant to be * a binary function that is commonly used in a loop to find the relevant * value for the sort mode in a list of values. For instance if the sort mode * is {@link SortMode#MAX} this method is equivalent to {@link Math#max(double, double)}. * * Note: all implementations are idempotent. * * @param a an argument * @param b another argument * @return the result of the function. */ public abstract double apply(double a, double b); /** * Applies the sort mode and returns the result. This method is meant to be * a binary function that is commonly used in a loop to find the relevant * value for the sort mode in a list of values. For instance if the sort mode * is {@link SortMode#MAX} this method is equivalent to {@link Math#max(long, long)}. * * Note: all implementations are idempotent. * * @param a an argument * @param b another argument * @return the result of the function. */ public abstract long apply(long a, long b); /** * Returns an initial value for the sort mode that is guaranteed to have no impact if passed * to {@link #apply(double, double)}. This value should be used as the initial value if the * sort mode is applied to a non-empty list of values. For instance: * <pre> * double relevantValue = sortMode.startDouble(); * for (int i = 0; i < array.length; i++) { * relevantValue = sortMode.apply(array[i], relevantValue); * } * </pre> * * Note: This method return <code>0</code> by default. * * @return an initial value for the sort mode. */ public double startDouble() { return 0; } /** * Returns an initial value for the sort mode that is guaranteed to have no impact if passed * to {@link #apply(long, long)}. This value should be used as the initial value if the * sort mode is applied to a non-empty list of values. For instance: * <pre> * long relevantValue = sortMode.startLong(); * for (int i = 0; i < array.length; i++) { * relevantValue = sortMode.apply(array[i], relevantValue); * } * </pre> * * Note: This method return <code>0</code> by default. * @return an initial value for the sort mode. */ public long startLong() { return 0; } /** * Returns the aggregated value based on the sort mode. For instance if {@link SortMode#AVG} is used * this method divides the given value by the number of values. The default implementation returns * the first argument. * * Note: all implementations are idempotent. */ public double reduce(double a, int numValues) { return a; } /** * Returns the aggregated value based on the sort mode. For instance if {@link SortMode#AVG} is used * this method divides the given value by the number of values. The default implementation returns * the first argument. * * Note: all implementations are idempotent. */ public long reduce(long a, int numValues) { return a; } /** * A case insensitive version of {@link #valueOf(String)} * * @throws org.elasticsearch.ElasticsearchIllegalArgumentException if the given string doesn't match a sort mode or is <code>null</code>. */ public static SortMode fromString(String sortMode) { try { return valueOf(sortMode.toUpperCase(Locale.ROOT)); } catch (Throwable t) { throw new ElasticsearchIllegalArgumentException("Illegal sort_mode " + sortMode); } } /** * Returns the relevant value for the given document based on the {@link SortMode}. This * method will apply each value for the given document to {@link #apply(double, double)} and returns * the reduced value from {@link #reduce(double, int)} if the document has at least one value. Otherwise it will * return the given default value. * @param values the values to fetch the relevant value from. * @param docId the doc id to fetch the relevant value for. * @param defaultValue the default value if the document has no value * @return the relevant value or the default value passed to the method. */ public double getRelevantValue(DoubleValues values, int docId, double defaultValue) { final int numValues = values.setDocument(docId); double relevantVal = startDouble(); double result = defaultValue; for (int i = 0; i < numValues; i++) { result = relevantVal = apply(relevantVal, values.nextValue()); } return reduce(result, numValues); } /** * Returns the relevant value for the given document based on the {@link SortMode}. This * method will apply each value for the given document to {@link #apply(long, long)} and returns * the reduced value from {@link #reduce(long, int)} if the document has at least one value. Otherwise it will * return the given default value. * @param values the values to fetch the relevant value from. * @param docId the doc id to fetch the relevant value for. * @param defaultValue the default value if the document has no value * @return the relevant value or the default value passed to the method. */ public long getRelevantValue(LongValues values, int docId, long defaultValue) { final int numValues = values.setDocument(docId); long relevantVal = startLong(); long result = defaultValue; for (int i = 0; i < numValues; i++) { result = relevantVal = apply(relevantVal, values.nextValue()); } return reduce(result, numValues); } /** * Returns the relevant value for the given document based on the {@link SortMode} * if the document has at least one value. Otherwise it will return same object given as the default value. * Note: This method is optional and will throw {@link UnsupportedOperationException} if the sort mode doesn't * allow a relevant value. * * @param values the values to fetch the relevant value from. * @param docId the doc id to fetch the relevant value for. * @param defaultValue the default value if the document has no value. This object will never be modified. * @return the relevant value or the default value passed to the method. */ public BytesRef getRelevantValue(BytesValues values, int docId, BytesRef defaultValue) { throw new UnsupportedOperationException("no relevant bytes value for sort mode: " + this.name()); } }
0true
src_main_java_org_elasticsearch_index_fielddata_fieldcomparator_SortMode.java
1,107
MULTI_VALUED_ENUM { public int numValues() { return RANDOM.nextInt(3); } @Override public long nextValue() { return 3 + RANDOM.nextInt(8); } },
0true
src_test_java_org_elasticsearch_benchmark_fielddata_LongFieldDataBenchmark.java
99
@SuppressWarnings("serial") static final class SearchValuesTask<K,V,U> extends BulkTask<K,V,U> { final Fun<? super V, ? extends U> searchFunction; final AtomicReference<U> result; SearchValuesTask (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t, Fun<? super V, ? extends U> searchFunction, AtomicReference<U> result) { super(p, b, i, f, t); this.searchFunction = searchFunction; this.result = result; } public final U getRawResult() { return result.get(); } public final void compute() { final Fun<? super V, ? extends U> searchFunction; final AtomicReference<U> result; if ((searchFunction = this.searchFunction) != null && (result = this.result) != null) { for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { if (result.get() != null) return; addToPendingCount(1); new SearchValuesTask<K,V,U> (this, batch >>>= 1, baseLimit = h, f, tab, searchFunction, result).fork(); } while (result.get() == null) { U u; Node<K,V> p; if ((p = advance()) == null) { propagateCompletion(); break; } if ((u = searchFunction.apply(p.val)) != null) { if (result.compareAndSet(null, u)) quietlyCompleteRoot(); break; } } } } }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
1,863
static enum NullAnnotationStrategy implements AnnotationStrategy { INSTANCE; public boolean hasAttributes() { return false; } public AnnotationStrategy withoutAttributes() { throw new UnsupportedOperationException("Key already has no attributes."); } public Annotation getAnnotation() { return null; } public Class<? extends Annotation> getAnnotationType() { return null; } @Override public String toString() { return "[none]"; } }
0true
src_main_java_org_elasticsearch_common_inject_Key.java
811
@Entity @Table(name = "BLC_OFFER_CODE") @Inheritance(strategy=InheritanceType.JOINED) @Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements") @AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.FALSE, friendlyName = "OfferCodeImpl_baseOfferCode") public class OfferCodeImpl implements OfferCode { public static final long serialVersionUID = 1L; @Id @GeneratedValue(generator= "OfferCodeId") @GenericGenerator( name="OfferCodeId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="OfferCodeImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.offer.domain.OfferCodeImpl") } ) @Column(name = "OFFER_CODE_ID") @AdminPresentation(friendlyName = "OfferCodeImpl_Offer_Code_Id") protected Long id; @ManyToOne(targetEntity = OfferImpl.class, optional=false) @JoinColumn(name = "OFFER_ID") @Index(name="OFFERCODE_OFFER_INDEX", columnNames={"OFFER_ID"}) @AdminPresentation(friendlyName = "OfferCodeImpl_Offer", order=2000, prominent = true, gridOrder = 2000) @AdminPresentationToOneLookup() protected Offer offer; @Column(name = "OFFER_CODE", nullable=false) @Index(name="OFFERCODE_CODE_INDEX", columnNames={"OFFER_CODE"}) @AdminPresentation(friendlyName = "OfferCodeImpl_Offer_Code", order = 1000, prominent = true, gridOrder = 1000) protected String offerCode; @Column(name = "START_DATE") @AdminPresentation(friendlyName = "OfferCodeImpl_Code_Start_Date", order = 3000) protected Date offerCodeStartDate; @Column(name = "END_DATE") @AdminPresentation(friendlyName = "OfferCodeImpl_Code_End_Date", order = 4000) protected Date offerCodeEndDate; @Column(name = "MAX_USES") @AdminPresentation(friendlyName = "OfferCodeImpl_Code_Max_Uses", order = 5000) protected Integer maxUses; @Column(name = "USES") @Deprecated protected int uses; @ManyToMany(fetch = FetchType.LAZY, mappedBy="addedOfferCodes", targetEntity = OrderImpl.class) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements") protected List<Order> orders = new ArrayList<Order>(); @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public Offer getOffer() { return offer; } @Override public void setOffer(Offer offer) { this.offer = offer; } @Override public String getOfferCode() { return offerCode; } @Override public void setOfferCode(String offerCode) { this.offerCode = offerCode; } @Override public int getMaxUses() { return maxUses == null ? 0 : maxUses; } @Override public void setMaxUses(int maxUses) { this.maxUses = maxUses; } @Override public boolean isUnlimitedUse() { return getMaxUses() == 0; } @Override public boolean isLimitedUse() { return getMaxUses() > 0; } @Override @Deprecated public int getUses() { return uses; } @Override @Deprecated public void setUses(int uses) { this.uses = uses; } @Override public Date getStartDate() { return offerCodeStartDate; } @Override public void setStartDate(Date startDate) { this.offerCodeStartDate = startDate; } @Override public Date getEndDate() { return offerCodeEndDate; } @Override public void setEndDate(Date endDate) { this.offerCodeEndDate = endDate; } @Override public List<Order> getOrders() { return orders; } @Override public void setOrders(List<Order> orders) { this.orders = orders; } @Override public int hashCode() { return new HashCodeBuilder() .append(offer) .append(offerCode) .build(); } @Override public boolean equals(Object o) { if (o instanceof OfferCodeImpl) { OfferCodeImpl that = (OfferCodeImpl) o; return new EqualsBuilder() .append(this.id, that.id) .append(this.offer, that.offer) .append(this.offerCode, that.offerCode) .build(); } return false; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_OfferCodeImpl.java
1,528
public class ShardsLimitAllocationTests extends ElasticsearchAllocationTestCase { private final ESLogger logger = Loggers.getLogger(ShardsLimitAllocationTests.class); @Test public void indexLevelShardsLimitAllocate() { AllocationService strategy = createAllocationService(settingsBuilder().put("cluster.routing.allocation.concurrent_recoveries", 10).build()); logger.info("Building initial routing table"); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test").settings(ImmutableSettings.settingsBuilder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 4) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) .put(ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE, 2))) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("Adding two nodes and performing rerouting"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2"))).build(); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(clusterState.readOnlyRoutingNodes().node("node1").numberOfShardsWithState(ShardRoutingState.INITIALIZING), equalTo(2)); assertThat(clusterState.readOnlyRoutingNodes().node("node2").numberOfShardsWithState(ShardRoutingState.INITIALIZING), equalTo(2)); logger.info("Start the primary shards"); RoutingNodes routingNodes = clusterState.routingNodes(); routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(clusterState.readOnlyRoutingNodes().node("node1").numberOfShardsWithState(ShardRoutingState.STARTED), equalTo(2)); assertThat(clusterState.readOnlyRoutingNodes().node("node1").numberOfShardsWithState(ShardRoutingState.INITIALIZING), equalTo(0)); assertThat(clusterState.readOnlyRoutingNodes().node("node2").numberOfShardsWithState(ShardRoutingState.STARTED), equalTo(2)); assertThat(clusterState.readOnlyRoutingNodes().node("node2").numberOfShardsWithState(ShardRoutingState.INITIALIZING), equalTo(0)); assertThat(clusterState.readOnlyRoutingNodes().unassigned().size(), equalTo(4)); logger.info("Do another reroute, make sure its still not allocated"); routingNodes = clusterState.routingNodes(); routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); } @Test public void indexLevelShardsLimitRemain() { AllocationService strategy = createAllocationService(settingsBuilder() .put("cluster.routing.allocation.concurrent_recoveries", 10) .put("cluster.routing.allocation.node_initial_primaries_recoveries", 10) .put("cluster.routing.allocation.cluster_concurrent_rebalance", -1) .put("cluster.routing.allocation.balance.index", 0.0f) .put("cluster.routing.allocation.balance.replica", 1.0f) .put("cluster.routing.allocation.balance.primary", 0.0f) .build()); logger.info("Building initial routing table"); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test").settings(ImmutableSettings.settingsBuilder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 5) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0) )) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("Adding one node and reroute"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1"))).build(); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); logger.info("Start the primary shards"); RoutingNodes routingNodes = clusterState.routingNodes(); routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(numberOfShardsOfType(clusterState.readOnlyRoutingNodes(), STARTED), equalTo(5)); logger.info("add another index with 5 shards"); metaData = MetaData.builder(metaData) .put(IndexMetaData.builder("test1").settings(ImmutableSettings.settingsBuilder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 5) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0) )) .build(); routingTable = RoutingTable.builder(routingTable) .addAsNew(metaData.index("test1")) .build(); clusterState = ClusterState.builder(clusterState).metaData(metaData).routingTable(routingTable).build(); logger.info("Add another one node and reroute"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node2"))).build(); routingTable = strategy.reroute(clusterState).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(); assertThat(numberOfShardsOfType(clusterState.readOnlyRoutingNodes(), STARTED), equalTo(10)); for (MutableShardRouting shardRouting : clusterState.readOnlyRoutingNodes().node("node1")) { assertThat(shardRouting.index(), equalTo("test")); } for (MutableShardRouting shardRouting : clusterState.readOnlyRoutingNodes().node("node2")) { assertThat(shardRouting.index(), equalTo("test1")); } logger.info("update " + ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE + " for test, see that things move"); metaData = MetaData.builder(metaData) .put(IndexMetaData.builder("test").settings(ImmutableSettings.settingsBuilder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 5) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0) .put(ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE, 3) )) .build(); clusterState = ClusterState.builder(clusterState).metaData(metaData).build(); logger.info("reroute after setting"); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(clusterState.readOnlyRoutingNodes().node("node1").numberOfShardsWithState(STARTED), equalTo(3)); assertThat(clusterState.readOnlyRoutingNodes().node("node1").numberOfShardsWithState(RELOCATING), equalTo(2)); assertThat(clusterState.readOnlyRoutingNodes().node("node2").numberOfShardsWithState(RELOCATING), equalTo(2)); assertThat(clusterState.readOnlyRoutingNodes().node("node2").numberOfShardsWithState(STARTED), equalTo(3)); // the first move will destroy the balance and the balancer will move 2 shards from node2 to node one right after // moving the nodes to node2 since we consider INITIALIZING nodes during rebalance routingNodes = clusterState.routingNodes(); routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); // now we are done compared to EvenShardCountAllocator since the Balancer is not soely based on the average assertThat(clusterState.readOnlyRoutingNodes().node("node1").numberOfShardsWithState(STARTED), equalTo(5)); assertThat(clusterState.readOnlyRoutingNodes().node("node2").numberOfShardsWithState(STARTED), equalTo(5)); } }
0true
src_test_java_org_elasticsearch_cluster_routing_allocation_ShardsLimitAllocationTests.java
6,227
public class ReproduceInfoPrinter extends RunListener { protected final ESLogger logger = Loggers.getLogger(ElasticsearchTestCase.class); @Override public void testStarted(Description description) throws Exception { logger.info("Test {} started", description.getDisplayName()); } @Override public void testFinished(Description description) throws Exception { logger.info("Test {} finished", description.getDisplayName()); } @Override public void testFailure(Failure failure) throws Exception { // Ignore assumptions. if (failure.getException() instanceof AssumptionViolatedException) { return; } final Description d = failure.getDescription(); final StringBuilder b = new StringBuilder(); b.append("FAILURE : ").append(d.getDisplayName()).append("\n"); b.append("REPRODUCE WITH : mvn test"); ReproduceErrorMessageBuilder builder = reproduceErrorMessageBuilder(b).appendAllOpts(failure.getDescription()); if (mustAppendClusterSeed(failure)) { appendClusterSeed(builder); } b.append("\n"); b.append("Throwable:\n"); if (failure.getException() != null) { traces().formatThrowable(b, failure.getException()); } logger.error(b.toString()); } protected boolean mustAppendClusterSeed(Failure failure) { return ElasticsearchIntegrationTest.class.isAssignableFrom(failure.getDescription().getTestClass()); } protected void appendClusterSeed(ReproduceErrorMessageBuilder builder) { builder.appendOpt(TESTS_CLUSTER_SEED, SeedUtils.formatSeed(SHARED_CLUSTER_SEED)); } protected ReproduceErrorMessageBuilder reproduceErrorMessageBuilder(StringBuilder b) { return new MavenMessageBuilder(b); } protected TraceFormatting traces() { TraceFormatting traces = new TraceFormatting(); try { traces = RandomizedContext.current().getRunner().getTraceFormatting(); } catch (IllegalStateException e) { // Ignore if no context. } return traces; } protected static class MavenMessageBuilder extends ReproduceErrorMessageBuilder { public MavenMessageBuilder(StringBuilder b) { super(b); } @Override public ReproduceErrorMessageBuilder appendAllOpts(Description description) { super.appendAllOpts(description); return appendESProperties(); } /** * Append a single VM option. */ @Override public ReproduceErrorMessageBuilder appendOpt(String sysPropName, String value) { if (sysPropName.equals(SYSPROP_ITERATIONS())) { // we don't want the iters to be in there! return this; } if (Strings.hasLength(value)) { return super.appendOpt(sysPropName, value); } return this; } public ReproduceErrorMessageBuilder appendESProperties() { appendProperties("es.logger.level", "es.node.mode", "es.node.local", TestCluster.TESTS_ENABLE_MOCK_MODULES, "tests.assertion.disabled", "tests.security.manager"); if (System.getProperty("tests.jvm.argline") != null && !System.getProperty("tests.jvm.argline").isEmpty()) { appendOpt("tests.jvm.argline", "\"" + System.getProperty("tests.jvm.argline") + "\""); } return this; } protected ReproduceErrorMessageBuilder appendProperties(String... properties) { for (String sysPropName : properties) { if (Strings.hasLength(System.getProperty(sysPropName))) { appendOpt(sysPropName, System.getProperty(sysPropName)); } } return this; } } }
1no label
src_test_java_org_elasticsearch_test_junit_listeners_ReproduceInfoPrinter.java
504
@Service("blSiteService") public class SiteServiceImpl implements SiteService { @Resource(name = "blSiteDao") protected SiteDao siteDao; @Override public Site retrieveSiteById(Long id) { Site response = siteDao.retrieve(id); if (response != null) { response = response.clone(); } return response; } @Override @Transactional(value = "blTransactionManager", readOnly = true) public Site retrieveSiteByDomainName(String domainName) { String domainPrefix = null; if (domainName != null) { int pos = domainName.indexOf('.'); if (pos >= 0) { domainPrefix = domainName.substring(0, pos); } else { domainPrefix = domainName; } } Site response = siteDao.retrieveSiteByDomainOrDomainPrefix(domainName, domainPrefix); if (response != null) { response = response.clone(); } return response; } @Override @Transactional("blTransactionManager") public Site save(Site site) { return siteDao.save(site).clone(); } @Override @Transactional(value = "blTransactionManager", readOnly = true) public Site retrieveDefaultSite() { return siteDao.retrieveDefaultSite().clone(); } @Override @Transactional(value = "blTransactionManager", readOnly = true) public List<Site> findAllActiveSites() { List<Site> response = new ArrayList<Site>(); List<Site> sites = siteDao.readAllActiveSites(); for (Site site : sites) { response.add(site.clone()); } return response; } }
0true
common_src_main_java_org_broadleafcommerce_common_site_service_SiteServiceImpl.java
264
public class ImportsTransfer extends ByteArrayTransfer { public static final ImportsTransfer INSTANCE = new ImportsTransfer(); private static final String TYPE_NAME = "ceylon-source-with-imports-transfer-format" + System.currentTimeMillis(); private static final int TYPEID = registerType(TYPE_NAME); public static Map<Declaration,String> imports; @Override protected int[] getTypeIds() { return new int[] { TYPEID }; } @Override protected String[] getTypeNames() { return new String[] { TYPE_NAME }; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override protected void javaToNative(Object object, TransferData transferData) { if (isSupportedType(transferData)) { //TODO: serialize qualified names to NSStrings imports = (Map) object; super.javaToNative(new byte[1], transferData); } } @Override protected Map<Declaration,String> nativeToJava(TransferData transferData) { if (isSupportedType(transferData)) { //TODO: unserialize qualified names from NSStrings return imports; } else { return null; } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_ImportsTransfer.java
2,519
public class SmileXContent implements XContent { public static XContentBuilder contentBuilder() throws IOException { return XContentBuilder.builder(smileXContent); } final static SmileFactory smileFactory; public final static SmileXContent smileXContent; static { smileFactory = new SmileFactory(); smileFactory.configure(SmileGenerator.Feature.ENCODE_BINARY_AS_7BIT, false); // for now, this is an overhead, might make sense for web sockets smileXContent = new SmileXContent(); } private SmileXContent() { } @Override public XContentType type() { return XContentType.SMILE; } @Override public byte streamSeparator() { return (byte) 0xFF; } @Override public XContentGenerator createGenerator(OutputStream os) throws IOException { return new SmileXContentGenerator(smileFactory.createGenerator(os, JsonEncoding.UTF8)); } @Override public XContentGenerator createGenerator(Writer writer) throws IOException { return new SmileXContentGenerator(smileFactory.createGenerator(writer)); } @Override public XContentParser createParser(String content) throws IOException { return new SmileXContentParser(smileFactory.createParser(new FastStringReader(content))); } @Override public XContentParser createParser(InputStream is) throws IOException { return new SmileXContentParser(smileFactory.createParser(is)); } @Override public XContentParser createParser(byte[] data) throws IOException { return new SmileXContentParser(smileFactory.createParser(data)); } @Override public XContentParser createParser(byte[] data, int offset, int length) throws IOException { return new SmileXContentParser(smileFactory.createParser(data, offset, length)); } @Override public XContentParser createParser(BytesReference bytes) throws IOException { if (bytes.hasArray()) { return createParser(bytes.array(), bytes.arrayOffset(), bytes.length()); } return createParser(bytes.streamInput()); } @Override public XContentParser createParser(Reader reader) throws IOException { return new JsonXContentParser(smileFactory.createParser(reader)); } }
1no label
src_main_java_org_elasticsearch_common_xcontent_smile_SmileXContent.java
3,687
return new Comparator<Map.Entry>() { public int compare(Map.Entry entry1, Map.Entry entry2) { return SortingUtil.compare(pagingPredicate.getComparator(), pagingPredicate.getIterationType(), entry1, entry2); } };
1no label
hazelcast_src_main_java_com_hazelcast_util_SortingUtil.java
778
public class TransportMoreLikeThisAction extends TransportAction<MoreLikeThisRequest, SearchResponse> { private final TransportSearchAction searchAction; private final TransportGetAction getAction; private final IndicesService indicesService; private final ClusterService clusterService; private final TransportService transportService; @Inject public TransportMoreLikeThisAction(Settings settings, ThreadPool threadPool, TransportSearchAction searchAction, TransportGetAction getAction, ClusterService clusterService, IndicesService indicesService, TransportService transportService) { super(settings, threadPool); this.searchAction = searchAction; this.getAction = getAction; this.indicesService = indicesService; this.clusterService = clusterService; this.transportService = transportService; transportService.registerHandler(MoreLikeThisAction.NAME, new TransportHandler()); } @Override protected void doExecute(final MoreLikeThisRequest request, final ActionListener<SearchResponse> listener) { // update to actual index name ClusterState clusterState = clusterService.state(); // update to the concrete index final String concreteIndex = clusterState.metaData().concreteIndex(request.index()); Iterable<MutableShardRouting> routingNode = clusterState.getRoutingNodes().routingNodeIter(clusterService.localNode().getId()); if (routingNode == null) { redirect(request, concreteIndex, listener, clusterState); return; } boolean hasIndexLocally = false; for (MutableShardRouting shardRouting : routingNode) { if (concreteIndex.equals(shardRouting.index())) { hasIndexLocally = true; break; } } if (!hasIndexLocally) { redirect(request, concreteIndex, listener, clusterState); return; } Set<String> getFields = newHashSet(); if (request.fields() != null) { Collections.addAll(getFields, request.fields()); } // add the source, in case we need to parse it to get fields getFields.add(SourceFieldMapper.NAME); GetRequest getRequest = getRequest(concreteIndex) .fields(getFields.toArray(new String[getFields.size()])) .type(request.type()) .id(request.id()) .routing(request.routing()) .listenerThreaded(true) .operationThreaded(true); request.beforeLocalFork(); getAction.execute(getRequest, new ActionListener<GetResponse>() { @Override public void onResponse(GetResponse getResponse) { if (!getResponse.isExists()) { listener.onFailure(new DocumentMissingException(null, request.type(), request.id())); return; } final BoolQueryBuilder boolBuilder = boolQuery(); try { final DocumentMapper docMapper = indicesService.indexServiceSafe(concreteIndex).mapperService().documentMapper(request.type()); if (docMapper == null) { throw new ElasticsearchException("No DocumentMapper found for type [" + request.type() + "]"); } final Set<String> fields = newHashSet(); if (request.fields() != null) { for (String field : request.fields()) { FieldMappers fieldMappers = docMapper.mappers().smartName(field); if (fieldMappers != null) { fields.add(fieldMappers.mapper().names().indexName()); } else { fields.add(field); } } } if (!fields.isEmpty()) { // if fields are not empty, see if we got them in the response for (Iterator<String> it = fields.iterator(); it.hasNext(); ) { String field = it.next(); GetField getField = getResponse.getField(field); if (getField != null) { for (Object value : getField.getValues()) { addMoreLikeThis(request, boolBuilder, getField.getName(), value.toString(), true); } it.remove(); } } if (!fields.isEmpty()) { // if we don't get all the fields in the get response, see if we can parse the source parseSource(getResponse, boolBuilder, docMapper, fields, request); } } else { // we did not ask for any fields, try and get it from the source parseSource(getResponse, boolBuilder, docMapper, fields, request); } if (!boolBuilder.hasClauses()) { // no field added, fail listener.onFailure(new ElasticsearchException("No fields found to fetch the 'likeText' from")); return; } // exclude myself Term uidTerm = docMapper.uidMapper().term(request.type(), request.id()); boolBuilder.mustNot(termQuery(uidTerm.field(), uidTerm.text())); boolBuilder.adjustPureNegative(false); } catch (Throwable e) { listener.onFailure(e); return; } String[] searchIndices = request.searchIndices(); if (searchIndices == null) { searchIndices = new String[]{request.index()}; } String[] searchTypes = request.searchTypes(); if (searchTypes == null) { searchTypes = new String[]{request.type()}; } int size = request.searchSize() != 0 ? request.searchSize() : 10; int from = request.searchFrom() != 0 ? request.searchFrom() : 0; SearchRequest searchRequest = searchRequest(searchIndices) .types(searchTypes) .searchType(request.searchType()) .scroll(request.searchScroll()) .extraSource(searchSource() .query(boolBuilder) .from(from) .size(size) ) .listenerThreaded(request.listenerThreaded()); if (request.searchSource() != null) { searchRequest.source(request.searchSource(), request.searchSourceUnsafe()); } searchAction.execute(searchRequest, new ActionListener<SearchResponse>() { @Override public void onResponse(SearchResponse response) { listener.onResponse(response); } @Override public void onFailure(Throwable e) { listener.onFailure(e); } }); } @Override public void onFailure(Throwable e) { listener.onFailure(e); } }); } // Redirects the request to a data node, that has the index meta data locally available. private void redirect(MoreLikeThisRequest request, String concreteIndex, final ActionListener<SearchResponse> listener, ClusterState clusterState) { ShardIterator shardIterator = clusterService.operationRouting().getShards(clusterState, concreteIndex, request.type(), request.id(), request.routing(), null); ShardRouting shardRouting = shardIterator.firstOrNull(); if (shardRouting == null) { throw new ElasticsearchException("No shards for index " + request.index()); } String nodeId = shardRouting.currentNodeId(); DiscoveryNode discoveryNode = clusterState.nodes().get(nodeId); transportService.sendRequest(discoveryNode, MoreLikeThisAction.NAME, request, new TransportResponseHandler<SearchResponse>() { @Override public SearchResponse newInstance() { return new SearchResponse(); } @Override public void handleResponse(SearchResponse response) { listener.onResponse(response); } @Override public void handleException(TransportException exp) { listener.onFailure(exp); } @Override public String executor() { return ThreadPool.Names.SAME; } }); } private void parseSource(GetResponse getResponse, final BoolQueryBuilder boolBuilder, DocumentMapper docMapper, final Set<String> fields, final MoreLikeThisRequest request) { if (getResponse.isSourceEmpty()) { return; } docMapper.parse(SourceToParse.source(getResponse.getSourceAsBytesRef()).type(request.type()).id(request.id()), new DocumentMapper.ParseListenerAdapter() { @Override public boolean beforeFieldAdded(FieldMapper fieldMapper, Field field, Object parseContext) { if (!field.fieldType().indexed()) { return false; } if (fieldMapper instanceof InternalMapper) { return true; } String value = fieldMapper.value(convertField(field)).toString(); if (value == null) { return false; } if (fields.isEmpty() || fields.contains(field.name())) { addMoreLikeThis(request, boolBuilder, fieldMapper, field, !fields.isEmpty()); } return false; } }); } private Object convertField(Field field) { if (field.stringValue() != null) { return field.stringValue(); } else if (field.binaryValue() != null) { return BytesRef.deepCopyOf(field.binaryValue()).bytes; } else if (field.numericValue() != null) { return field.numericValue(); } else { throw new ElasticsearchIllegalStateException("Field should have either a string, numeric or binary value"); } } private void addMoreLikeThis(MoreLikeThisRequest request, BoolQueryBuilder boolBuilder, FieldMapper fieldMapper, Field field, boolean failOnUnsupportedField) { addMoreLikeThis(request, boolBuilder, field.name(), fieldMapper.value(convertField(field)).toString(), failOnUnsupportedField); } private void addMoreLikeThis(MoreLikeThisRequest request, BoolQueryBuilder boolBuilder, String fieldName, String likeText, boolean failOnUnsupportedField) { MoreLikeThisFieldQueryBuilder mlt = moreLikeThisFieldQuery(fieldName) .likeText(likeText) .percentTermsToMatch(request.percentTermsToMatch()) .boostTerms(request.boostTerms()) .minDocFreq(request.minDocFreq()) .maxDocFreq(request.maxDocFreq()) .minWordLength(request.minWordLength()) .maxWordLen(request.maxWordLength()) .minTermFreq(request.minTermFreq()) .maxQueryTerms(request.maxQueryTerms()) .stopWords(request.stopWords()) .failOnUnsupportedField(failOnUnsupportedField); boolBuilder.should(mlt); } private class TransportHandler extends BaseTransportRequestHandler<MoreLikeThisRequest> { @Override public MoreLikeThisRequest newInstance() { return new MoreLikeThisRequest(); } @Override public void messageReceived(MoreLikeThisRequest request, final TransportChannel channel) throws Exception { // no need to have a threaded listener since we just send back a response request.listenerThreaded(false); execute(request, new ActionListener<SearchResponse>() { @Override public void onResponse(SearchResponse 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; } } }
1no label
src_main_java_org_elasticsearch_action_mlt_TransportMoreLikeThisAction.java
1,618
private class ReconnectToNodes implements Runnable { private ConcurrentMap<DiscoveryNode, Integer> failureCount = ConcurrentCollections.newConcurrentMap(); @Override public void run() { // master node will check against all nodes if its alive with certain discoveries implementations, // but we can't rely on that, so we check on it as well for (DiscoveryNode node : clusterState.nodes()) { if (lifecycle.stoppedOrClosed()) { return; } if (!nodeRequiresConnection(node)) { continue; } if (clusterState.nodes().nodeExists(node.id())) { // we double check existence of node since connectToNode might take time... if (!transportService.nodeConnected(node)) { try { transportService.connectToNode(node); } catch (Exception e) { if (lifecycle.stoppedOrClosed()) { return; } if (clusterState.nodes().nodeExists(node.id())) { // double check here as well, maybe its gone? Integer nodeFailureCount = failureCount.get(node); if (nodeFailureCount == null) { nodeFailureCount = 1; } else { nodeFailureCount = nodeFailureCount + 1; } // log every 6th failure if ((nodeFailureCount % 6) == 0) { // reset the failure count... nodeFailureCount = 0; logger.warn("failed to reconnect to node {}", e, node); } failureCount.put(node, nodeFailureCount); } } } } } // go over and remove failed nodes that have been removed DiscoveryNodes nodes = clusterState.nodes(); for (Iterator<DiscoveryNode> failedNodesIt = failureCount.keySet().iterator(); failedNodesIt.hasNext(); ) { DiscoveryNode failedNode = failedNodesIt.next(); if (!nodes.nodeExists(failedNode.id())) { failedNodesIt.remove(); } } if (lifecycle.started()) { reconnectToNodes = threadPool.schedule(reconnectInterval, ThreadPool.Names.GENERIC, this); } } }
0true
src_main_java_org_elasticsearch_cluster_service_InternalClusterService.java