Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
202
new IResourceChangeListener() { public void resourceChanged(IResourceChangeEvent event) { if (parseController==null) return; IProject project = parseController.getProject(); if (project!=null) { //things external to the workspace don't move IPath oldWSRelPath = project.getFullPath().append(parseController.getPath()); IResourceDelta rd = event.getDelta().findMember(oldWSRelPath); if (rd != null) { if ((rd.getFlags() & IResourceDelta.MOVED_TO) != 0) { // The net effect of the following is to re-initialize() the parse controller with the new path IPath newPath = rd.getMovedToPath(); IPath newProjRelPath = newPath.removeFirstSegments(1); String newProjName = newPath.segment(0); IProject proj = project.getName().equals(newProjName) ? project : project.getWorkspace().getRoot() .getProject(newProjName); // Tell the parse controller about the move - it caches the path // parserScheduler.cancel(); // avoid a race condition if ParserScheduler was starting/in the middle of a run parseController.initialize(newProjRelPath, proj, annotationCreator); } } } } };
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonEditor.java
2,227
public class FiltersFunctionScoreQuery extends Query { public static class FilterFunction { public final Filter filter; public final ScoreFunction function; public FilterFunction(Filter filter, ScoreFunction function) { this.filter = filter; this.function = function; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FilterFunction that = (FilterFunction) o; if (filter != null ? !filter.equals(that.filter) : that.filter != null) return false; if (function != null ? !function.equals(that.function) : that.function != null) return false; return true; } @Override public int hashCode() { int result = filter != null ? filter.hashCode() : 0; result = 31 * result + (function != null ? function.hashCode() : 0); return result; } } public static enum ScoreMode { First, Avg, Max, Sum, Min, Multiply } Query subQuery; final FilterFunction[] filterFunctions; final ScoreMode scoreMode; final float maxBoost; protected CombineFunction combineFunction; public FiltersFunctionScoreQuery(Query subQuery, ScoreMode scoreMode, FilterFunction[] filterFunctions, float maxBoost) { this.subQuery = subQuery; this.scoreMode = scoreMode; this.filterFunctions = filterFunctions; this.maxBoost = maxBoost; combineFunction = CombineFunction.MULT; } public FiltersFunctionScoreQuery setCombineFunction(CombineFunction combineFunction) { this.combineFunction = combineFunction; return this; } public Query getSubQuery() { return subQuery; } public FilterFunction[] getFilterFunctions() { return filterFunctions; } @Override public Query rewrite(IndexReader reader) throws IOException { Query newQ = subQuery.rewrite(reader); if (newQ == subQuery) return this; FiltersFunctionScoreQuery bq = (FiltersFunctionScoreQuery) this.clone(); bq.subQuery = newQ; return bq; } @Override public void extractTerms(Set<Term> terms) { subQuery.extractTerms(terms); } @Override public Weight createWeight(IndexSearcher searcher) throws IOException { Weight subQueryWeight = subQuery.createWeight(searcher); return new CustomBoostFactorWeight(subQueryWeight, filterFunctions.length); } class CustomBoostFactorWeight extends Weight { final Weight subQueryWeight; final Bits[] docSets; public CustomBoostFactorWeight(Weight subQueryWeight, int filterFunctionLength) throws IOException { this.subQueryWeight = subQueryWeight; this.docSets = new Bits[filterFunctionLength]; } public Query getQuery() { return FiltersFunctionScoreQuery.this; } @Override public float getValueForNormalization() throws IOException { float sum = subQueryWeight.getValueForNormalization(); sum *= getBoost() * getBoost(); return sum; } @Override public void normalize(float norm, float topLevelBoost) { subQueryWeight.normalize(norm, topLevelBoost * getBoost()); } @Override public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException { // we ignore scoreDocsInOrder parameter, because we need to score in // order if documents are scored with a script. The // ShardLookup depends on in order scoring. Scorer subQueryScorer = subQueryWeight.scorer(context, true, false, acceptDocs); if (subQueryScorer == null) { return null; } for (int i = 0; i < filterFunctions.length; i++) { FilterFunction filterFunction = filterFunctions[i]; filterFunction.function.setNextReader(context); docSets[i] = DocIdSets.toSafeBits(context.reader(), filterFunction.filter.getDocIdSet(context, acceptDocs)); } return new CustomBoostFactorScorer(this, subQueryScorer, scoreMode, filterFunctions, maxBoost, docSets, combineFunction); } @Override public Explanation explain(AtomicReaderContext context, int doc) throws IOException { Explanation subQueryExpl = subQueryWeight.explain(context, doc); if (!subQueryExpl.isMatch()) { return subQueryExpl; } // First: Gather explanations for all filters List<ComplexExplanation> filterExplanations = new ArrayList<ComplexExplanation>(); for (FilterFunction filterFunction : filterFunctions) { Bits docSet = DocIdSets.toSafeBits(context.reader(), filterFunction.filter.getDocIdSet(context, context.reader().getLiveDocs())); if (docSet.get(doc)) { filterFunction.function.setNextReader(context); Explanation functionExplanation = filterFunction.function.explainScore(doc, subQueryExpl); double factor = functionExplanation.getValue(); float sc = CombineFunction.toFloat(factor); ComplexExplanation filterExplanation = new ComplexExplanation(true, sc, "function score, product of:"); filterExplanation.addDetail(new Explanation(1.0f, "match filter: " + filterFunction.filter.toString())); filterExplanation.addDetail(functionExplanation); filterExplanations.add(filterExplanation); } } if (filterExplanations.size() == 0) { float sc = getBoost() * subQueryExpl.getValue(); Explanation res = new ComplexExplanation(true, sc, "function score, no filter match, product of:"); res.addDetail(subQueryExpl); res.addDetail(new Explanation(getBoost(), "queryBoost")); return res; } // Second: Compute the factor that would have been computed by the // filters double factor = 1.0; switch (scoreMode) { case First: factor = filterExplanations.get(0).getValue(); break; case Max: factor = Double.NEGATIVE_INFINITY; for (int i = 0; i < filterExplanations.size(); i++) { factor = Math.max(filterExplanations.get(i).getValue(), factor); } break; case Min: factor = Double.POSITIVE_INFINITY; for (int i = 0; i < filterExplanations.size(); i++) { factor = Math.min(filterExplanations.get(i).getValue(), factor); } break; case Multiply: for (int i = 0; i < filterExplanations.size(); i++) { factor *= filterExplanations.get(i).getValue(); } break; default: // Avg / Total double totalFactor = 0.0f; int count = 0; for (int i = 0; i < filterExplanations.size(); i++) { totalFactor += filterExplanations.get(i).getValue(); count++; } if (count != 0) { factor = totalFactor; if (scoreMode == ScoreMode.Avg) { factor /= count; } } } ComplexExplanation factorExplanaition = new ComplexExplanation(true, CombineFunction.toFloat(factor), "function score, score mode [" + scoreMode.toString().toLowerCase(Locale.ROOT) + "]"); for (int i = 0; i < filterExplanations.size(); i++) { factorExplanaition.addDetail(filterExplanations.get(i)); } return combineFunction.explain(getBoost(), subQueryExpl, factorExplanaition, maxBoost); } } static class CustomBoostFactorScorer extends Scorer { private final float subQueryBoost; private final Scorer scorer; private final FilterFunction[] filterFunctions; private final ScoreMode scoreMode; private final float maxBoost; private final Bits[] docSets; private final CombineFunction scoreCombiner; private CustomBoostFactorScorer(CustomBoostFactorWeight w, Scorer scorer, ScoreMode scoreMode, FilterFunction[] filterFunctions, float maxBoost, Bits[] docSets, CombineFunction scoreCombiner) throws IOException { super(w); this.subQueryBoost = w.getQuery().getBoost(); this.scorer = scorer; this.scoreMode = scoreMode; this.filterFunctions = filterFunctions; this.maxBoost = maxBoost; this.docSets = docSets; this.scoreCombiner = scoreCombiner; } @Override public int docID() { return scorer.docID(); } @Override public int advance(int target) throws IOException { return scorer.advance(target); } @Override public int nextDoc() throws IOException { return scorer.nextDoc(); } @Override public float score() throws IOException { int docId = scorer.docID(); double factor = 1.0f; float subQueryScore = scorer.score(); if (scoreMode == ScoreMode.First) { for (int i = 0; i < filterFunctions.length; i++) { if (docSets[i].get(docId)) { factor = filterFunctions[i].function.score(docId, subQueryScore); break; } } } else if (scoreMode == ScoreMode.Max) { double maxFactor = Double.NEGATIVE_INFINITY; for (int i = 0; i < filterFunctions.length; i++) { if (docSets[i].get(docId)) { maxFactor = Math.max(filterFunctions[i].function.score(docId, subQueryScore), maxFactor); } } if (maxFactor != Float.NEGATIVE_INFINITY) { factor = maxFactor; } } else if (scoreMode == ScoreMode.Min) { double minFactor = Double.POSITIVE_INFINITY; for (int i = 0; i < filterFunctions.length; i++) { if (docSets[i].get(docId)) { minFactor = Math.min(filterFunctions[i].function.score(docId, subQueryScore), minFactor); } } if (minFactor != Float.POSITIVE_INFINITY) { factor = minFactor; } } else if (scoreMode == ScoreMode.Multiply) { for (int i = 0; i < filterFunctions.length; i++) { if (docSets[i].get(docId)) { factor *= filterFunctions[i].function.score(docId, subQueryScore); } } } else { // Avg / Total double totalFactor = 0.0f; int count = 0; for (int i = 0; i < filterFunctions.length; i++) { if (docSets[i].get(docId)) { totalFactor += filterFunctions[i].function.score(docId, subQueryScore); count++; } } if (count != 0) { factor = totalFactor; if (scoreMode == ScoreMode.Avg) { factor /= count; } } } return scoreCombiner.combine(subQueryBoost, subQueryScore, factor, maxBoost); } @Override public int freq() throws IOException { return scorer.freq(); } @Override public long cost() { return scorer.cost(); } } public String toString(String field) { StringBuilder sb = new StringBuilder(); sb.append("function score (").append(subQuery.toString(field)).append(", functions: ["); for (FilterFunction filterFunction : filterFunctions) { sb.append("{filter(").append(filterFunction.filter).append("), function [").append(filterFunction.function).append("]}"); } sb.append("])"); sb.append(ToStringUtils.boost(getBoost())); return sb.toString(); } public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; FiltersFunctionScoreQuery other = (FiltersFunctionScoreQuery) o; if (this.getBoost() != other.getBoost()) return false; if (!this.subQuery.equals(other.subQuery)) { return false; } return Arrays.equals(this.filterFunctions, other.filterFunctions); } public int hashCode() { return subQuery.hashCode() + 31 * Arrays.hashCode(filterFunctions) ^ Float.floatToIntBits(getBoost()); } }
1no label
src_main_java_org_elasticsearch_common_lucene_search_function_FiltersFunctionScoreQuery.java
1,350
private final class FlushTask implements Runnable { private FlushTask() { } @Override public void run() { try { commit(); } catch (Throwable e) { OLogManager.instance().error(this, "Error during WAL background flush", e); } } private void commit() throws IOException { if (pagesCache.isEmpty()) return; if (!flushNewData) return; flushNewData = false; final int maxSize = pagesCache.size(); ODirectMemoryPointer[] pagesToFlush = new ODirectMemoryPointer[maxSize]; long filePointer = nextPositionToFlush; int lastRecordOffset = -1; long lastPageIndex = -1; int flushedPages = 0; Iterator<OWALPage> pageIterator = pagesCache.iterator(); while (flushedPages < maxSize) { final OWALPage page = pageIterator.next(); synchronized (page) { ODirectMemoryPointer dataPointer; if (flushedPages == maxSize - 1) { dataPointer = new ODirectMemoryPointer(OWALPage.PAGE_SIZE); page.getPagePointer().moveData(0, dataPointer, 0, OWALPage.PAGE_SIZE); } else { dataPointer = page.getPagePointer(); } pagesToFlush[flushedPages] = dataPointer; int recordOffset = findLastRecord(page, true); if (recordOffset >= 0) { lastRecordOffset = recordOffset; lastPageIndex = flushedPages; } } flushedPages++; } flushId++; synchronized (rndFile) { rndFile.seek(filePointer); for (int i = 0; i < pagesToFlush.length; i++) { ODirectMemoryPointer dataPointer = pagesToFlush[i]; byte[] pageContent = dataPointer.get(0, OWALPage.PAGE_SIZE); if (i == pagesToFlush.length - 1) dataPointer.free(); OLongSerializer.INSTANCE.serializeNative(flushId, pageContent, OWALPage.FLUSH_ID_OFFSET); OIntegerSerializer.INSTANCE.serializeNative(i, pageContent, OWALPage.FLUSH_INDEX_OFFSET); flushPage(pageContent); filePointer += OWALPage.PAGE_SIZE; } rndFile.getFD().sync(); } long oldPositionToFlush = nextPositionToFlush; nextPositionToFlush = filePointer - OWALPage.PAGE_SIZE; if (lastRecordOffset >= 0) flushedLsn = new OLogSequenceNumber(order, oldPositionToFlush + lastPageIndex * OWALPage.PAGE_SIZE + lastRecordOffset); for (int i = 0; i < flushedPages - 1; i++) { OWALPage page = pagesCache.poll(); page.getPagePointer().free(); } assert !pagesCache.isEmpty(); } private void flushPage(byte[] content) throws IOException { CRC32 crc32 = new CRC32(); crc32.update(content, OIntegerSerializer.INT_SIZE, OWALPage.PAGE_SIZE - OIntegerSerializer.INT_SIZE); OIntegerSerializer.INSTANCE.serializeNative((int) crc32.getValue(), content, 0); rndFile.write(content); } }
1no label
core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_wal_OWriteAheadLog.java
12
enum TextCommandType { GET((byte) 0), PARTIAL_GET((byte) 1), GETS((byte) 2), SET((byte) 3), APPEND((byte) 4), PREPEND((byte) 5), ADD((byte) 6), REPLACE((byte) 7), DELETE((byte) 8), QUIT((byte) 9), STATS((byte) 10), GET_END((byte) 11), ERROR_CLIENT((byte) 12), ERROR_SERVER((byte) 13), UNKNOWN((byte) 14), VERSION((byte) 15), TOUCH((byte) 16), INCREMENT((byte) 17), DECREMENT((byte) 18), HTTP_GET((byte) 30), HTTP_POST((byte) 31), HTTP_PUT((byte) 32), HTTP_DELETE((byte) 33), NO_OP((byte) 98), STOP((byte) 99); final byte value; TextCommandType(byte type) { value = type; } public byte getValue() { return value; } }
0true
hazelcast_src_main_java_com_hazelcast_ascii_TextCommandConstants.java
2,571
clusterService.submitStateUpdateTask("zen-disco-join (elected_as_master)", Priority.URGENT, new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { DiscoveryNodes.Builder builder = new DiscoveryNodes.Builder() .localNodeId(localNode.id()) .masterNodeId(localNode.id()) // put our local node .put(localNode); // update the fact that we are the master... latestDiscoNodes = builder.build(); ClusterBlocks clusterBlocks = ClusterBlocks.builder().blocks(currentState.blocks()).removeGlobalBlock(NO_MASTER_BLOCK).build(); return ClusterState.builder(currentState).nodes(latestDiscoNodes).blocks(clusterBlocks).build(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { sendInitialStateEventIfNeeded(); } });
1no label
src_main_java_org_elasticsearch_discovery_zen_ZenDiscovery.java
1,934
public class BindingBuilder<T> extends AbstractBindingBuilder<T> implements AnnotatedBindingBuilder<T> { public BindingBuilder(Binder binder, List<Element> elements, Object source, Key<T> key) { super(binder, elements, source, key); } public BindingBuilder<T> annotatedWith(Class<? extends Annotation> annotationType) { annotatedWithInternal(annotationType); return this; } public BindingBuilder<T> annotatedWith(Annotation annotation) { annotatedWithInternal(annotation); return this; } public BindingBuilder<T> to(Class<? extends T> implementation) { return to(Key.get(implementation)); } public BindingBuilder<T> to(TypeLiteral<? extends T> implementation) { return to(Key.get(implementation)); } public BindingBuilder<T> to(Key<? extends T> linkedKey) { checkNotNull(linkedKey, "linkedKey"); checkNotTargetted(); BindingImpl<T> base = getBinding(); setBinding(new LinkedBindingImpl<T>( base.getSource(), base.getKey(), base.getScoping(), linkedKey)); return this; } public void toInstance(T instance) { checkNotTargetted(); // lookup the injection points, adding any errors to the binder's errors list Set<InjectionPoint> injectionPoints; if (instance != null) { try { injectionPoints = InjectionPoint.forInstanceMethodsAndFields(instance.getClass()); } catch (ConfigurationException e) { for (Message message : e.getErrorMessages()) { binder.addError(message); } injectionPoints = e.getPartialValue(); } } else { binder.addError(BINDING_TO_NULL); injectionPoints = ImmutableSet.of(); } BindingImpl<T> base = getBinding(); setBinding(new InstanceBindingImpl<T>( base.getSource(), base.getKey(), base.getScoping(), injectionPoints, instance)); } public BindingBuilder<T> toProvider(Provider<? extends T> provider) { checkNotNull(provider, "provider"); checkNotTargetted(); // lookup the injection points, adding any errors to the binder's errors list Set<InjectionPoint> injectionPoints; try { injectionPoints = InjectionPoint.forInstanceMethodsAndFields(provider.getClass()); } catch (ConfigurationException e) { for (Message message : e.getErrorMessages()) { binder.addError(message); } injectionPoints = e.getPartialValue(); } BindingImpl<T> base = getBinding(); setBinding(new ProviderInstanceBindingImpl<T>( base.getSource(), base.getKey(), base.getScoping(), injectionPoints, provider)); return this; } public BindingBuilder<T> toProvider(Class<? extends Provider<? extends T>> providerType) { return toProvider(Key.get(providerType)); } public BindingBuilder<T> toProvider(Key<? extends Provider<? extends T>> providerKey) { checkNotNull(providerKey, "providerKey"); checkNotTargetted(); BindingImpl<T> base = getBinding(); setBinding(new LinkedProviderBindingImpl<T>( base.getSource(), base.getKey(), base.getScoping(), providerKey)); return this; } @Override public String toString() { return "BindingBuilder<" + getBinding().getKey().getTypeLiteral() + ">"; } }
0true
src_main_java_org_elasticsearch_common_inject_internal_BindingBuilder.java
724
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name="BLC_SKU_FEE") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") public class SkuFeeImpl implements SkuFee { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "SkuFeeId") @GenericGenerator( name = "SkuFeeId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="SkuFeeImpl"), @Parameter(name = "entity_name", value = "org.broadleafcommerce.core.order.domain.SkuFeeImpl") } ) @Column(name = "SKU_FEE_ID") protected Long id; @Column(name = "NAME") protected String name; @Column(name = "DESCRIPTION") protected String description; @Column(name ="AMOUNT", precision=19, scale=5, nullable=false) protected BigDecimal amount; @Column(name = "TAXABLE") protected Boolean taxable = Boolean.FALSE; @Lob @Type(type = "org.hibernate.type.StringClobType") @Column(name = "EXPRESSION", length = Integer.MAX_VALUE - 1) protected String expression; @Column(name = "FEE_TYPE") @AdminPresentation(fieldType=SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration="org.broadleafcommerce.core.catalog.service.type.SkuFeeType") protected String feeType = SkuFeeType.FULFILLMENT.getType(); @ManyToMany(fetch = FetchType.LAZY, targetEntity = SkuImpl.class) @JoinTable(name = "BLC_SKU_FEE_XREF", joinColumns = @JoinColumn(name = "SKU_FEE_ID", referencedColumnName = "SKU_FEE_ID", nullable = true), inverseJoinColumns = @JoinColumn(name = "SKU_ID", referencedColumnName = "SKU_ID", nullable = true)) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") protected List<Sku> skus; @ManyToOne(targetEntity = BroadleafCurrencyImpl.class) @JoinColumn(name = "CURRENCY_CODE") @AdminPresentation(friendlyName = "TaxDetailImpl_Currency_Code", order=1, group = "FixedPriceFulfillmentOptionImpl_Details", prominent=true) protected BroadleafCurrency currency; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } @Override public Money getAmount() { return BroadleafCurrencyUtils.getMoney(amount, getCurrency()); } @Override public void setAmount(Money amount) { this.amount = Money.toAmount(amount); } @Override public Boolean getTaxable() { return taxable; } @Override public void setTaxable(Boolean taxable) { this.taxable = taxable; } @Override public String getExpression() { return expression; } @Override public void setExpression(String expression) { this.expression = expression; } @Override public SkuFeeType getFeeType() { return SkuFeeType.getInstance(feeType); } @Override public void setFeeType(SkuFeeType feeType) { this.feeType = (feeType == null) ? null : feeType.getType(); } @Override public List<Sku> getSkus() { return skus; } @Override public void setSkus(List<Sku> skus) { this.skus = skus; } @Override public BroadleafCurrency getCurrency() { return currency; } @Override public void setCurrency(BroadleafCurrency currency) { this.currency = currency; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_SkuFeeImpl.java
342
Comparator<Node> idCompare = new Comparator<Node>() { public int compare(Node arg0, Node arg1) { Node id1 = arg0.getAttributes().getNamedItem(attribute); Node id2 = arg1.getAttributes().getNamedItem(attribute); String idVal1 = id1.getNodeValue(); String idVal2 = id2.getNodeValue(); return idVal1.compareTo(idVal2); } };
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_handlers_NodeReplaceInsert.java
3,377
static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues.WithOrdinals { private final MonotonicAppendingLongBuffer values; DoubleValues(MonotonicAppendingLongBuffer values, Ordinals.Docs ordinals) { super(ordinals); this.values = values; } @Override public double getValueByOrd(long ord) { assert ord != Ordinals.MISSING_ORDINAL; return values.get(ord - 1); } }
0true
src_main_java_org_elasticsearch_index_fielddata_plain_PackedArrayAtomicFieldData.java
115
assertTrueEventually(new AssertTask() { public void run() throws Exception { NearCacheStats stats = clientMap.getLocalMapStats().getNearCacheStats(); assertEquals(0, stats.getOwnedEntryCount()); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_ClientNearCacheTest.java
587
getEntries(iKeys, new IndexEntriesResultListener() { @Override public boolean addResult(ODocument entry) { result.add(entry); return true; } });
0true
core_src_main_java_com_orientechnologies_orient_core_index_OIndexAbstract.java
428
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface ValidationConfiguration { /** * <p>The fully qualified classname of the org.broadleafcommerce.openadmin.server.service.persistence.validation.PropertyValidator * instance to use for validation</p> * * <p>If you need to do dependency injection, this can also correspond to a bean ID that implements the * org.broadleafcommerce.openadmin.server.service.persistence.validation.PropertyValidator interface.</p> * * @return the validator implementation. This implementation should be an instance of * org.broadleafcommerce.openadmin.server.service.persistence.validation.PropertyValidator and could be either a bean * name or fully-qualified class name */ String validationImplementation(); /** * <p>Optional configuration items that can be used to setup the validator</p>. Most validators should have at least * a single configuration item with {@link ConfigurationItem#ERROR_MESSAGE}. * * @return validator configuration attributes */ ConfigurationItem[] configurationItems() default {}; }
0true
common_src_main_java_org_broadleafcommerce_common_presentation_ValidationConfiguration.java
418
public class ClientLockProxy extends ClientProxy implements ILock { private volatile Data key; public ClientLockProxy(String instanceName, String serviceName, String objectId) { super(instanceName, serviceName, objectId); } @Deprecated public Object getKey() { return getName(); } public boolean isLocked() { IsLockedRequest request = new IsLockedRequest(getKeyData()); Boolean result = invoke(request); return result; } public boolean isLockedByCurrentThread() { IsLockedRequest request = new IsLockedRequest(getKeyData(), ThreadUtil.getThreadId()); Boolean result = invoke(request); return result; } public int getLockCount() { GetLockCountRequest request = new GetLockCountRequest(getKeyData()); return (Integer) invoke(request); } public long getRemainingLeaseTime() { GetRemainingLeaseRequest request = new GetRemainingLeaseRequest(getKeyData()); return (Long) invoke(request); } public void lock(long leaseTime, TimeUnit timeUnit) { shouldBePositive(leaseTime, "leaseTime"); LockRequest request = new LockRequest(getKeyData(), ThreadUtil.getThreadId(), getTimeInMillis(leaseTime, timeUnit), -1); invoke(request); } public void forceUnlock() { UnlockRequest request = new UnlockRequest(getKeyData(), ThreadUtil.getThreadId(), true); invoke(request); } public ICondition newCondition(String name) { return new ClientConditionProxy(instanceName, this, name, getContext()); } public void lock() { lock(Long.MAX_VALUE, null); } public void lockInterruptibly() throws InterruptedException { lock(); } public boolean tryLock() { try { return tryLock(0, null); } catch (InterruptedException e) { return false; } } public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { LockRequest request = new LockRequest(getKeyData(), ThreadUtil.getThreadId(), Long.MAX_VALUE, getTimeInMillis(time, unit)); Boolean result = invoke(request); return result; } public void unlock() { UnlockRequest request = new UnlockRequest(getKeyData(), ThreadUtil.getThreadId()); invoke(request); } public Condition newCondition() { throw new UnsupportedOperationException(); } protected void onDestroy() { } private Data getKeyData() { if (key == null) { key = toData(getName()); } return key; } private long getTimeInMillis(final long time, final TimeUnit timeunit) { return timeunit != null ? timeunit.toMillis(time) : time; } protected <T> T invoke(ClientRequest req) { return super.invoke(req, getKeyData()); } @Override public String toString() { return "ILock{" + "name='" + getName() + '\'' + '}'; } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientLockProxy.java
197
public class UniqueTokenFilterTests extends ElasticsearchTestCase { @Test public void simpleTest() throws IOException { Analyzer analyzer = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName, Reader reader) { Tokenizer t = new WhitespaceTokenizer(Lucene.VERSION, reader); return new TokenStreamComponents(t, new UniqueTokenFilter(t)); } }; TokenStream test = analyzer.tokenStream("test", "this test with test"); test.reset(); CharTermAttribute termAttribute = test.addAttribute(CharTermAttribute.class); assertThat(test.incrementToken(), equalTo(true)); assertThat(termAttribute.toString(), equalTo("this")); assertThat(test.incrementToken(), equalTo(true)); assertThat(termAttribute.toString(), equalTo("test")); assertThat(test.incrementToken(), equalTo(true)); assertThat(termAttribute.toString(), equalTo("with")); assertThat(test.incrementToken(), equalTo(false)); } }
0true
src_test_java_org_apache_lucene_analysis_miscellaneous_UniqueTokenFilterTests.java
5,441
public class ScriptLongValues extends LongValues implements ScriptValues { final SearchScript script; private Object value; private long[] values = new long[4]; private int valueCount; private int valueOffset; public ScriptLongValues(SearchScript script) { super(true); // assume multi-valued this.script = script; } @Override public SearchScript script() { return script; } @Override public int setDocument(int docId) { this.docId = docId; script.setNextDocId(docId); value = script.run(); if (value == null) { valueCount = 0; } else if (value instanceof Number) { valueCount = 1; values[0] = ((Number) value).longValue(); } else if (value.getClass().isArray()) { valueCount = Array.getLength(value); values = ArrayUtil.grow(values, valueCount); for (int i = 0; i < valueCount; ++i) { values[i] = ((Number) Array.get(value, i++)).longValue(); } } else if (value instanceof Collection) { valueCount = ((Collection<?>) value).size(); int i = 0; for (Iterator<?> it = ((Collection<?>) value).iterator(); it.hasNext(); ++i) { values[i] = ((Number) it.next()).longValue(); } assert i == valueCount; } else { throw new AggregationExecutionException("Unsupported script value [" + value + "]"); } valueOffset = 0; return valueCount; } @Override public long nextValue() { assert valueOffset < valueCount; return values[valueOffset++]; } }
1no label
src_main_java_org_elasticsearch_search_aggregations_support_numeric_ScriptLongValues.java
3,633
public class GeoPointFieldMapper extends AbstractFieldMapper<GeoPoint> implements ArrayValueMapperParser { public static final String CONTENT_TYPE = "geo_point"; public static class Names { public static final String LAT = "lat"; public static final String LAT_SUFFIX = "." + LAT; public static final String LON = "lon"; public static final String LON_SUFFIX = "." + LON; public static final String GEOHASH = "geohash"; public static final String GEOHASH_SUFFIX = "." + GEOHASH; } public static class Defaults { public static final ContentPath.Type PATH_TYPE = ContentPath.Type.FULL; public static final boolean STORE = false; public static final boolean ENABLE_LATLON = false; public static final boolean ENABLE_GEOHASH = false; public static final boolean ENABLE_GEOHASH_PREFIX = false; public static final int GEO_HASH_PRECISION = GeoHashUtils.PRECISION; public static final boolean NORMALIZE_LAT = true; public static final boolean NORMALIZE_LON = true; public static final boolean VALIDATE_LAT = true; public static final boolean VALIDATE_LON = true; public static final FieldType FIELD_TYPE = new FieldType(StringFieldMapper.Defaults.FIELD_TYPE); static { FIELD_TYPE.setIndexed(true); FIELD_TYPE.setTokenized(false); FIELD_TYPE.setOmitNorms(true); FIELD_TYPE.setIndexOptions(IndexOptions.DOCS_ONLY); FIELD_TYPE.freeze(); } } public static class Builder extends AbstractFieldMapper.Builder<Builder, GeoPointFieldMapper> { private ContentPath.Type pathType = Defaults.PATH_TYPE; private boolean enableGeoHash = Defaults.ENABLE_GEOHASH; private boolean enableGeohashPrefix = Defaults.ENABLE_GEOHASH_PREFIX; private boolean enableLatLon = Defaults.ENABLE_LATLON; private Integer precisionStep; private int geoHashPrecision = Defaults.GEO_HASH_PRECISION; boolean validateLat = Defaults.VALIDATE_LAT; boolean validateLon = Defaults.VALIDATE_LON; boolean normalizeLat = Defaults.NORMALIZE_LAT; boolean normalizeLon = Defaults.NORMALIZE_LON; public Builder(String name) { super(name, new FieldType(Defaults.FIELD_TYPE)); this.builder = this; } public Builder multiFieldPathType(ContentPath.Type pathType) { this.pathType = pathType; return this; } public Builder enableGeoHash(boolean enableGeoHash) { this.enableGeoHash = enableGeoHash; return this; } public Builder geohashPrefix(boolean enableGeohashPrefix) { this.enableGeohashPrefix = enableGeohashPrefix; return this; } public Builder enableLatLon(boolean enableLatLon) { this.enableLatLon = enableLatLon; return this; } public Builder precisionStep(int precisionStep) { this.precisionStep = precisionStep; return this; } public Builder geoHashPrecision(int precision) { this.geoHashPrecision = precision; return this; } public Builder fieldDataSettings(Settings settings) { this.fieldDataSettings = settings; return builder; } @Override public GeoPointFieldMapper build(BuilderContext context) { ContentPath.Type origPathType = context.path().pathType(); context.path().pathType(pathType); DoubleFieldMapper latMapper = null; DoubleFieldMapper lonMapper = null; context.path().add(name); if (enableLatLon) { NumberFieldMapper.Builder<?, ?> latMapperBuilder = doubleField(Names.LAT).includeInAll(false); NumberFieldMapper.Builder<?, ?> lonMapperBuilder = doubleField(Names.LON).includeInAll(false); if (precisionStep != null) { latMapperBuilder.precisionStep(precisionStep); lonMapperBuilder.precisionStep(precisionStep); } latMapper = (DoubleFieldMapper) latMapperBuilder.includeInAll(false).store(fieldType.stored()).build(context); lonMapper = (DoubleFieldMapper) lonMapperBuilder.includeInAll(false).store(fieldType.stored()).build(context); } StringFieldMapper geohashMapper = null; if (enableGeoHash) { geohashMapper = stringField(Names.GEOHASH).index(true).tokenized(false).includeInAll(false).omitNorms(true).indexOptions(IndexOptions.DOCS_ONLY).build(context); } context.path().remove(); context.path().pathType(origPathType); // this is important: even if geo points feel like they need to be tokenized to distinguish lat from lon, we actually want to // store them as a single token. fieldType.setTokenized(false); return new GeoPointFieldMapper(buildNames(context), fieldType, docValues, indexAnalyzer, searchAnalyzer, postingsProvider, docValuesProvider, similarity, fieldDataSettings, context.indexSettings(), origPathType, enableLatLon, enableGeoHash, enableGeohashPrefix, precisionStep, geoHashPrecision, latMapper, lonMapper, geohashMapper, validateLon, validateLat, normalizeLon, normalizeLat , multiFieldsBuilder.build(this, context)); } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder<?, ?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { Builder builder = geoPointField(name); parseField(builder, name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("path")) { builder.multiFieldPathType(parsePathType(name, fieldNode.toString())); } else if (fieldName.equals("lat_lon")) { builder.enableLatLon(XContentMapValues.nodeBooleanValue(fieldNode)); } else if (fieldName.equals("geohash")) { builder.enableGeoHash(XContentMapValues.nodeBooleanValue(fieldNode)); } else if (fieldName.equals("geohash_prefix")) { builder.geohashPrefix(XContentMapValues.nodeBooleanValue(fieldNode)); if (XContentMapValues.nodeBooleanValue(fieldNode)) { builder.enableGeoHash(true); } } else if (fieldName.equals("precision_step")) { builder.precisionStep(XContentMapValues.nodeIntegerValue(fieldNode)); } else if (fieldName.equals("geohash_precision")) { builder.geoHashPrecision(XContentMapValues.nodeIntegerValue(fieldNode)); } else if (fieldName.equals("validate")) { builder.validateLat = XContentMapValues.nodeBooleanValue(fieldNode); builder.validateLon = XContentMapValues.nodeBooleanValue(fieldNode); } else if (fieldName.equals("validate_lon")) { builder.validateLon = XContentMapValues.nodeBooleanValue(fieldNode); } else if (fieldName.equals("validate_lat")) { builder.validateLat = XContentMapValues.nodeBooleanValue(fieldNode); } else if (fieldName.equals("normalize")) { builder.normalizeLat = XContentMapValues.nodeBooleanValue(fieldNode); builder.normalizeLon = XContentMapValues.nodeBooleanValue(fieldNode); } else if (fieldName.equals("normalize_lat")) { builder.normalizeLat = XContentMapValues.nodeBooleanValue(fieldNode); } else if (fieldName.equals("normalize_lon")) { builder.normalizeLon = XContentMapValues.nodeBooleanValue(fieldNode); } else { parseMultiField(builder, name, node, parserContext, fieldName, fieldNode); } } return builder; } } /** * A byte-aligned fixed-length encoding for latitudes and longitudes. */ public static final class Encoding { // With 14 bytes we already have better precision than a double since a double has 11 bits of exponent private static final int MAX_NUM_BYTES = 14; private static final Encoding[] INSTANCES; static { INSTANCES = new Encoding[MAX_NUM_BYTES + 1]; for (int numBytes = 2; numBytes <= MAX_NUM_BYTES; numBytes += 2) { INSTANCES[numBytes] = new Encoding(numBytes); } } /** Get an instance based on the number of bytes that has been used to encode values. */ public static final Encoding of(int numBytesPerValue) { final Encoding instance = INSTANCES[numBytesPerValue]; if (instance == null) { throw new ElasticsearchIllegalStateException("No encoding for " + numBytesPerValue + " bytes per value"); } return instance; } /** Get an instance based on the expected precision. Here are examples of the number of required bytes per value depending on the * expected precision:<ul> * <li>1km: 4 bytes</li> * <li>3m: 6 bytes</li> * <li>1m: 8 bytes</li> * <li>1cm: 8 bytes</li> * <li>1mm: 10 bytes</li></ul> */ public static final Encoding of(DistanceUnit.Distance precision) { for (Encoding encoding : INSTANCES) { if (encoding != null && encoding.precision().compareTo(precision) <= 0) { return encoding; } } return INSTANCES[MAX_NUM_BYTES]; } private final DistanceUnit.Distance precision; private final int numBytes; private final int numBytesPerCoordinate; private final double factor; private Encoding(int numBytes) { assert numBytes >= 1 && numBytes <= MAX_NUM_BYTES; assert (numBytes & 1) == 0; // we don't support odd numBytes for the moment this.numBytes = numBytes; this.numBytesPerCoordinate = numBytes / 2; this.factor = Math.pow(2, - numBytesPerCoordinate * 8 + 9); assert (1L << (numBytesPerCoordinate * 8 - 1)) * factor > 180 && (1L << (numBytesPerCoordinate * 8 - 2)) * factor < 180 : numBytesPerCoordinate + " " + factor; if (numBytes == MAX_NUM_BYTES) { // no precision loss compared to a double precision = new DistanceUnit.Distance(0, DistanceUnit.DEFAULT); } else { precision = new DistanceUnit.Distance( GeoDistance.PLANE.calculate(0, 0, factor / 2, factor / 2, DistanceUnit.DEFAULT), // factor/2 because we use Math.round instead of a cast to convert the double to a long DistanceUnit.DEFAULT); } } public DistanceUnit.Distance precision() { return precision; } /** The number of bytes required to encode a single geo point. */ public final int numBytes() { return numBytes; } /** The number of bits required to encode a single coordinate of a geo point. */ public int numBitsPerCoordinate() { return numBytesPerCoordinate << 3; } /** Return the bits that encode a latitude/longitude. */ public long encodeCoordinate(double lat) { return Math.round((lat + 180) / factor); } /** Decode a sequence of bits into the original coordinate. */ public double decodeCoordinate(long bits) { return bits * factor - 180; } private void encodeBits(long bits, byte[] out, int offset) { for (int i = 0; i < numBytesPerCoordinate; ++i) { out[offset++] = (byte) bits; bits >>>= 8; } assert bits == 0; } private long decodeBits(byte [] in, int offset) { long r = in[offset++] & 0xFFL; for (int i = 1; i < numBytesPerCoordinate; ++i) { r = (in[offset++] & 0xFFL) << (i * 8); } return r; } /** Encode a geo point into a byte-array, over {@link #numBytes()} bytes. */ public void encode(double lat, double lon, byte[] out, int offset) { encodeBits(encodeCoordinate(lat), out, offset); encodeBits(encodeCoordinate(lon), out, offset + numBytesPerCoordinate); } /** Decode a geo point from a byte-array, reading {@link #numBytes()} bytes. */ public GeoPoint decode(byte[] in, int offset, GeoPoint out) { final long latBits = decodeBits(in, offset); final long lonBits = decodeBits(in, offset + numBytesPerCoordinate); return decode(latBits, lonBits, out); } /** Decode a geo point from the bits of the encoded latitude and longitudes. */ public GeoPoint decode(long latBits, long lonBits, GeoPoint out) { final double lat = decodeCoordinate(latBits); final double lon = decodeCoordinate(lonBits); return out.reset(lat, lon); } } private final ContentPath.Type pathType; private final boolean enableLatLon; private final boolean enableGeoHash; private final boolean enableGeohashPrefix; private final Integer precisionStep; private final int geoHashPrecision; private final DoubleFieldMapper latMapper; private final DoubleFieldMapper lonMapper; private final StringFieldMapper geohashMapper; private final boolean validateLon; private final boolean validateLat; private final boolean normalizeLon; private final boolean normalizeLat; public GeoPointFieldMapper(FieldMapper.Names names, FieldType fieldType, Boolean docValues, NamedAnalyzer indexAnalyzer, NamedAnalyzer searchAnalyzer, PostingsFormatProvider postingsFormat, DocValuesFormatProvider docValuesFormat, SimilarityProvider similarity, @Nullable Settings fieldDataSettings, Settings indexSettings, ContentPath.Type pathType, boolean enableLatLon, boolean enableGeoHash, boolean enableGeohashPrefix, Integer precisionStep, int geoHashPrecision, DoubleFieldMapper latMapper, DoubleFieldMapper lonMapper, StringFieldMapper geohashMapper, boolean validateLon, boolean validateLat, boolean normalizeLon, boolean normalizeLat, MultiFields multiFields) { super(names, 1f, fieldType, docValues, null, indexAnalyzer, postingsFormat, docValuesFormat, similarity, null, fieldDataSettings, indexSettings, multiFields, null); this.pathType = pathType; this.enableLatLon = enableLatLon; this.enableGeoHash = enableGeoHash || enableGeohashPrefix; // implicitly enable geohashes if geohash_prefix is set this.enableGeohashPrefix = enableGeohashPrefix; this.precisionStep = precisionStep; this.geoHashPrecision = geoHashPrecision; this.latMapper = latMapper; this.lonMapper = lonMapper; this.geohashMapper = geohashMapper; this.validateLat = validateLat; this.validateLon = validateLon; this.normalizeLat = normalizeLat; this.normalizeLon = normalizeLon; } @Override protected String contentType() { return CONTENT_TYPE; } @Override public FieldType defaultFieldType() { return Defaults.FIELD_TYPE; } @Override public FieldDataType defaultFieldDataType() { return new FieldDataType("geo_point"); } public DoubleFieldMapper latMapper() { return latMapper; } public DoubleFieldMapper lonMapper() { return lonMapper; } public StringFieldMapper geoHashStringMapper() { return this.geohashMapper; } public boolean isEnableLatLon() { return enableLatLon; } public boolean isEnableGeohashPrefix() { return enableGeohashPrefix; } @Override public GeoPoint value(Object value) { if (value instanceof GeoPoint) { return (GeoPoint) value; } else { return GeoPoint.parseFromLatLon(value.toString()); } } @Override protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException { throw new UnsupportedOperationException("Parsing is implemented in parse(), this method should NEVER be called"); } @Override public void parse(ParseContext context) throws IOException { ContentPath.Type origPathType = context.path().pathType(); context.path().pathType(pathType); context.path().add(name()); XContentParser.Token token = context.parser().currentToken(); if (token == XContentParser.Token.START_ARRAY) { token = context.parser().nextToken(); if (token == XContentParser.Token.START_ARRAY) { // its an array of array of lon/lat [ [1.2, 1.3], [1.4, 1.5] ] while (token != XContentParser.Token.END_ARRAY) { token = context.parser().nextToken(); double lon = context.parser().doubleValue(); token = context.parser().nextToken(); double lat = context.parser().doubleValue(); while ((token = context.parser().nextToken()) != XContentParser.Token.END_ARRAY) { } parseLatLon(context, lat, lon); token = context.parser().nextToken(); } } else { // its an array of other possible values if (token == XContentParser.Token.VALUE_NUMBER) { double lon = context.parser().doubleValue(); token = context.parser().nextToken(); double lat = context.parser().doubleValue(); while ((token = context.parser().nextToken()) != XContentParser.Token.END_ARRAY) { } parseLatLon(context, lat, lon); } else { while (token != XContentParser.Token.END_ARRAY) { if (token == XContentParser.Token.START_OBJECT) { parseObjectLatLon(context); } else if (token == XContentParser.Token.VALUE_STRING) { parseStringLatLon(context); } token = context.parser().nextToken(); } } } } else if (token == XContentParser.Token.START_OBJECT) { parseObjectLatLon(context); } else if (token == XContentParser.Token.VALUE_STRING) { parseStringLatLon(context); } context.path().remove(); context.path().pathType(origPathType); } private void parseStringLatLon(ParseContext context) throws IOException { String value = context.parser().text(); int comma = value.indexOf(','); if (comma != -1) { double lat = Double.parseDouble(value.substring(0, comma).trim()); double lon = Double.parseDouble(value.substring(comma + 1).trim()); parseLatLon(context, lat, lon); } else { // geo hash parseGeohash(context, value); } } private void parseObjectLatLon(ParseContext context) throws IOException { XContentParser.Token token; String currentName = context.parser().currentName(); Double lat = null; Double lon = null; String geohash = null; while ((token = context.parser().nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentName = context.parser().currentName(); } else if (token.isValue()) { if (currentName.equals(Names.LAT)) { lat = context.parser().doubleValue(); } else if (currentName.equals(Names.LON)) { lon = context.parser().doubleValue(); } else if (currentName.equals(Names.GEOHASH)) { geohash = context.parser().text(); } } } if (geohash != null) { parseGeohash(context, geohash); } else if (lat != null && lon != null) { parseLatLon(context, lat, lon); } } private void parseGeohashField(ParseContext context, String geohash) throws IOException { int len = Math.min(geoHashPrecision, geohash.length()); int min = enableGeohashPrefix ? 1 : geohash.length(); for (int i = len; i >= min; i--) { context.externalValue(geohash.substring(0, i)); // side effect of this call is adding the field geohashMapper.parse(context); } } private void parseLatLon(ParseContext context, double lat, double lon) throws IOException { parse(context, new GeoPoint(lat, lon), null); } private void parseGeohash(ParseContext context, String geohash) throws IOException { GeoPoint point = GeoHashUtils.decode(geohash); parse(context, point, geohash); } private void parse(ParseContext context, GeoPoint point, String geohash) throws IOException { if (normalizeLat || normalizeLon) { GeoUtils.normalizePoint(point, normalizeLat, normalizeLon); } if (validateLat) { if (point.lat() > 90.0 || point.lat() < -90.0) { throw new ElasticsearchIllegalArgumentException("illegal latitude value [" + point.lat() + "] for " + name()); } } if (validateLon) { if (point.lon() > 180.0 || point.lon() < -180) { throw new ElasticsearchIllegalArgumentException("illegal longitude value [" + point.lon() + "] for " + name()); } } if (fieldType.indexed() || fieldType.stored()) { Field field = new Field(names.indexName(), Double.toString(point.lat()) + ',' + Double.toString(point.lon()), fieldType); context.doc().add(field); } if (enableGeoHash) { if (geohash == null) { geohash = GeoHashUtils.encode(point.lat(), point.lon()); } parseGeohashField(context, geohash); } if (enableLatLon) { context.externalValue(point.lat()); latMapper.parse(context); context.externalValue(point.lon()); lonMapper.parse(context); } if (hasDocValues()) { CustomGeoPointDocValuesField field = (CustomGeoPointDocValuesField) context.doc().getByKey(names().indexName()); if (field == null) { field = new CustomGeoPointDocValuesField(names().indexName(), point.lat(), point.lon()); context.doc().addWithKey(names().indexName(), field); } else { field.add(point.lat(), point.lon()); } } multiFields.parse(this, context); } @Override public void close() { super.close(); if (latMapper != null) { latMapper.close(); } if (lonMapper != null) { lonMapper.close(); } if (geohashMapper != null) { geohashMapper.close(); } } @Override public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException { super.merge(mergeWith, mergeContext); // TODO: geo-specific properties } @Override public void traverse(FieldMapperListener fieldMapperListener) { super.traverse(fieldMapperListener); if (enableGeoHash) { geohashMapper.traverse(fieldMapperListener); } if (enableLatLon) { latMapper.traverse(fieldMapperListener); lonMapper.traverse(fieldMapperListener); } } @Override public void traverse(ObjectMapperListener objectMapperListener) { } @Override protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException { super.doXContentBody(builder, includeDefaults, params); if (includeDefaults || pathType != Defaults.PATH_TYPE) { builder.field("path", pathType.name().toLowerCase(Locale.ROOT)); } if (includeDefaults || enableLatLon != Defaults.ENABLE_LATLON) { builder.field("lat_lon", enableLatLon); } if (includeDefaults || enableGeoHash != Defaults.ENABLE_GEOHASH) { builder.field("geohash", enableGeoHash); } if (includeDefaults || enableGeohashPrefix != Defaults.ENABLE_GEOHASH_PREFIX) { builder.field("geohash_prefix", enableGeohashPrefix); } if (includeDefaults || geoHashPrecision != Defaults.GEO_HASH_PRECISION) { builder.field("geohash_precision", geoHashPrecision); } if (includeDefaults || precisionStep != null) { builder.field("precision_step", precisionStep); } if (includeDefaults || validateLat != Defaults.VALIDATE_LAT || validateLon != Defaults.VALIDATE_LON) { if (validateLat && validateLon) { builder.field("validate", true); } else if (!validateLat && !validateLon) { builder.field("validate", false); } else { if (includeDefaults || validateLat != Defaults.VALIDATE_LAT) { builder.field("validate_lat", validateLat); } if (includeDefaults || validateLon != Defaults.VALIDATE_LON) { builder.field("validate_lon", validateLon); } } } if (includeDefaults || normalizeLat != Defaults.NORMALIZE_LAT || normalizeLon != Defaults.NORMALIZE_LON) { if (normalizeLat && normalizeLon) { builder.field("normalize", true); } else if (!normalizeLat && !normalizeLon) { builder.field("normalize", false); } else { if (includeDefaults || normalizeLat != Defaults.NORMALIZE_LAT) { builder.field("normalize_lat", normalizeLat); } if (includeDefaults || normalizeLon != Defaults.NORMALIZE_LON) { builder.field("normalize_lon", normalizeLat); } } } } public static class CustomGeoPointDocValuesField extends CustomNumericDocValuesField { public static final FieldType TYPE = new FieldType(); static { TYPE.setDocValueType(FieldInfo.DocValuesType.BINARY); TYPE.freeze(); } private final ObjectOpenHashSet<GeoPoint> points; public CustomGeoPointDocValuesField(String name, double lat, double lon) { super(name); points = new ObjectOpenHashSet<GeoPoint>(2); points.add(new GeoPoint(lat, lon)); } public void add(double lat, double lon) { points.add(new GeoPoint(lat, lon)); } @Override public BytesRef binaryValue() { final byte[] bytes = new byte[points.size() * 16]; int off = 0; for (Iterator<ObjectCursor<GeoPoint>> it = points.iterator(); it.hasNext(); ) { final GeoPoint point = it.next().value; ByteUtils.writeDoubleLE(point.getLat(), bytes, off); ByteUtils.writeDoubleLE(point.getLon(), bytes, off + 8); off += 16; } return new BytesRef(bytes); } } }
1no label
src_main_java_org_elasticsearch_index_mapper_geo_GeoPointFieldMapper.java
906
public class LegacyOfferServiceTest extends LegacyCommonSetupBaseTest { @Resource protected OfferService offerService; @Resource(name = "blOrderService") protected OrderService orderService; @Resource protected CustomerService customerService; @Resource protected CatalogService catalogService; @Resource(name = "blOrderItemService") protected OrderItemService orderItemService; private Order createTestOrderWithOfferAndGiftWrap() throws PricingException { Customer customer = customerService.createCustomerFromId(null); Order order = orderService.createNewCartForCustomer(customer); customerService.saveCustomer(order.getCustomer()); createCountry(); createState(); Address address = new AddressImpl(); address.setAddressLine1("123 Test Rd"); address.setCity("Dallas"); address.setFirstName("Jeff"); address.setLastName("Fischer"); address.setPostalCode("75240"); address.setPrimaryPhone("972-978-9067"); address.setState(stateService.findStateByAbbreviation("KY")); address.setCountry(countryService.findCountryByAbbreviation("US")); FulfillmentGroup group = new FulfillmentGroupImpl(); group.setAddress(address); group.setIsShippingPriceTaxable(true); List<FulfillmentGroup> groups = new ArrayList<FulfillmentGroup>(); group.setMethod("standard"); group.setService(ShippingServiceType.BANDED_SHIPPING.getType()); group.setShippingPrice(new Money("0")); group.setOrder(order); groups.add(group); group.setTotal(new Money(0)); order.setFulfillmentGroups(groups); Money total = new Money(5D); group.setRetailShippingPrice(total); group.setShippingPrice(total); DiscreteOrderItem item1; { item1 = new DiscreteOrderItemImpl(); Sku sku = new SkuImpl(); sku.setName("Test Sku"); sku.setRetailPrice(new Money(10D)); sku.setDiscountable(true); sku = catalogService.saveSku(sku); item1.setSku(sku); item1.setQuantity(2); item1.setOrder(order); item1.setOrderItemType(OrderItemType.DISCRETE); item1 = (DiscreteOrderItem) orderItemService.saveOrderItem(item1); order.addOrderItem(item1); FulfillmentGroupItem fgItem = new FulfillmentGroupItemImpl(); fgItem.setFulfillmentGroup(group); fgItem.setOrderItem(item1); fgItem.setQuantity(2); //fgItem.setPrice(new Money(0D)); group.addFulfillmentGroupItem(fgItem); } { DiscreteOrderItem item = new DiscreteOrderItemImpl(); Sku sku = new SkuImpl(); sku.setName("Test Product 2"); sku.setRetailPrice(new Money(20D)); sku.setDiscountable(true); sku = catalogService.saveSku(sku); item.setSku(sku); item.setQuantity(1); item.setOrder(order); item.setOrderItemType(OrderItemType.DISCRETE); item = (DiscreteOrderItem) orderItemService.saveOrderItem(item); order.addOrderItem(item); FulfillmentGroupItem fgItem = new FulfillmentGroupItemImpl(); fgItem.setFulfillmentGroup(group); fgItem.setOrderItem(item); fgItem.setQuantity(1); //fgItem.setPrice(new Money(0D)); group.addFulfillmentGroupItem(fgItem); } { GiftWrapOrderItem item = new GiftWrapOrderItemImpl(); Sku sku = new SkuImpl(); sku.setName("Test GiftWrap"); sku.setRetailPrice(new Money(1D)); sku.setDiscountable(true); sku = catalogService.saveSku(sku); item.setSku(sku); item.setQuantity(1); item.setOrder(order); item.getWrappedItems().add(item1); item.setOrderItemType(OrderItemType.GIFTWRAP); item = (GiftWrapOrderItem) orderItemService.saveOrderItem(item); order.addOrderItem(item); FulfillmentGroupItem fgItem = new FulfillmentGroupItemImpl(); fgItem.setFulfillmentGroup(group); fgItem.setOrderItem(item); fgItem.setQuantity(1); //fgItem.setPrice(new Money(0D)); group.addFulfillmentGroupItem(fgItem); } return order; } public int countPriceDetails(Order order) { int count = 0; for (OrderItem orderItem : order.getOrderItems()) { if (orderItem.getOrderItemPriceDetails().isEmpty()) { count += 1; } else { count += orderItem.getOrderItemPriceDetails().size(); } } return count; } /* The offer portion of this test was commented to support price lists - without this the test is not valid TODO fix test if GiftWrapOrderItems will continue to be supported by offers */ /*@Test(groups = {"testOffersWithGiftWrapLegacy"}, dependsOnGroups = { "testShippingInsertLegacy"}) @Transactional public void testOrderItemOfferWithGiftWrap() throws PricingException { Order order = createTestOrderWithOfferAndGiftWrap(); OfferDataItemProvider dataProvider = new OfferDataItemProvider(); List<Offer> offers = dataProvider.createItemBasedOfferWithItemCriteria( "order.subTotal.getAmount()>20", OfferDiscountType.PERCENT_OFF, "([MVEL.eval(\"toUpperCase()\",\"Test Sku\")] contains MVEL.eval(\"toUpperCase()\", discreteOrderItem.sku.name))", "([MVEL.eval(\"toUpperCase()\",\"Test Sku\")] contains MVEL.eval(\"toUpperCase()\", discreteOrderItem.sku.name))" ); for (Offer offer : offers) { offer.setName("testOffer"); //reset the offer is the targets and qualifiers, otherwise the reference is incorrect for (OfferItemCriteria criteria : offer.getTargetItemCriteria()) { criteria.setTargetOffer(null); } for (OfferItemCriteria criteria : offer.getQualifyingItemCriteria()) { criteria.setQualifyingOffer(null); } offerService.save(offer); } order = orderService.save(order, true); assert order.getTotalTax().equals(new Money("2.05")); assert order.getTotalShipping().equals(new Money("0")); assert order.getSubTotal().equals(new Money("41.00")); assert order.getTotal().equals(new Money("43.05")); assert countPriceDetails(order) == 3; boolean foundGiftItemAndCorrectQuantity = false; for (OrderItem orderItem : order.getOrderItems()) { if (orderItem instanceof GiftWrapOrderItem && ((GiftWrapOrderItem) orderItem).getWrappedItems().size() == 1) { foundGiftItemAndCorrectQuantity = true; break; } } assert foundGiftItemAndCorrectQuantity; }*/ }
0true
integration_src_test_java_org_broadleafcommerce_core_offer_service_legacy_LegacyOfferServiceTest.java
800
public class OFunctionLibraryProxy extends OProxedResource<OFunctionLibrary> implements OFunctionLibrary { public OFunctionLibraryProxy(final OFunctionLibrary iDelegate, final ODatabaseRecord iDatabase) { super(iDelegate, iDatabase); } @Override public Set<String> getFunctionNames() { return delegate.getFunctionNames(); } @Override public OFunction getFunction(final String iName) { return delegate.getFunction(iName); } @Override public OFunction createFunction(final String iName) { return delegate.createFunction(iName); } @Override public void create() { delegate.create(); } @Override public void load() { delegate.load(); } @Override public void close() { delegate.close(); } }
0true
core_src_main_java_com_orientechnologies_orient_core_metadata_function_OFunctionLibraryProxy.java
219
public static class ResourceObject { private final String name; ResourceObject( String name ) { this.name = name; } @Override public String toString() { return this.name; } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_LockWorker.java
1,058
public class TermVectorRequestBuilder extends ActionRequestBuilder<TermVectorRequest, TermVectorResponse, TermVectorRequestBuilder> { public TermVectorRequestBuilder(Client client) { super((InternalClient) client, new TermVectorRequest()); } public TermVectorRequestBuilder(Client client, String index, String type, String id) { super((InternalClient) client, new TermVectorRequest(index, type, id)); } /** * Sets the routing. Required if routing isn't id based. */ public TermVectorRequestBuilder setRouting(String routing) { request.routing(routing); return this; } /** * Sets the parent id of this document. Will simply set the routing to this value, as it is only * used for routing with delete requests. */ public TermVectorRequestBuilder setParent(String parent) { request.parent(parent); return this; } /** * Sets the preference to execute the search. Defaults to randomize across shards. Can be set to * <tt>_local</tt> to prefer local shards, <tt>_primary</tt> to execute only on primary shards, or * a custom value, which guarantees that the same order will be used across different requests. */ public TermVectorRequestBuilder setPreference(String preference) { request.preference(preference); return this; } public TermVectorRequestBuilder setOffsets(boolean offsets) { request.offsets(offsets); return this; } public TermVectorRequestBuilder setPositions(boolean positions) { request.positions(positions); return this; } public TermVectorRequestBuilder setPayloads(boolean payloads) { request.payloads(payloads); return this; } public TermVectorRequestBuilder setTermStatistics(boolean termStatistics) { request.termStatistics(termStatistics); return this; } public TermVectorRequestBuilder setFieldStatistics(boolean fieldStatistics) { request.fieldStatistics(fieldStatistics); return this; } public TermVectorRequestBuilder setSelectedFields(String... fields) { request.selectedFields(fields); return this; } @Override protected void doExecute(ActionListener<TermVectorResponse> listener) { ((Client) client).termVector(request, listener); } }
0true
src_main_java_org_elasticsearch_action_termvector_TermVectorRequestBuilder.java
915
EasyMock.expect(fgServiceMock.collapseToOneFulfillmentGroup(EasyMock.isA(Order.class), EasyMock.eq(false))).andAnswer(new IAnswer<Order>() { @Override public Order answer() throws Throwable { Order order = (Order) EasyMock.getCurrentArguments()[0]; order.getFulfillmentGroups().get(0).getFulfillmentGroupItems().addAll(order.getFulfillmentGroups().get(1).getFulfillmentGroupItems()); order.getFulfillmentGroups().remove(order.getFulfillmentGroups().get(1)); return order; } }).anyTimes();
0true
core_broadleaf-framework_src_test_java_org_broadleafcommerce_core_offer_service_processor_FulfillmentGroupOfferProcessorTest.java
101
public class TestManualAcquireLock extends AbstractNeo4jTestCase { private Worker worker; @Before public void doBefore() throws Exception { worker = new Worker(); } @After public void doAfter() throws Exception { worker.close(); } @Test public void releaseReleaseManually() throws Exception { String key = "name"; Node node = getGraphDb().createNode(); Transaction tx = newTransaction(); Worker worker = new Worker(); Lock nodeLock = tx.acquireWriteLock( node ); worker.beginTx(); try { worker.setProperty( node, key, "ksjd" ); fail( "Shouldn't be able to grab it" ); } catch ( Exception e ) { } nodeLock.release(); worker.setProperty( node, key, "yo" ); worker.finishTx(); } @Test public void canOnlyReleaseOnce() throws Exception { Node node = getGraphDb().createNode(); Transaction tx = newTransaction(); Lock nodeLock = tx.acquireWriteLock( node ); nodeLock.release(); try { nodeLock.release(); fail( "Shouldn't be able to release more than once" ); } catch ( IllegalStateException e ) { // Good } } @Test public void makeSureNodeStaysLockedEvenAfterManualRelease() throws Exception { String key = "name"; Node node = getGraphDb().createNode(); Transaction tx = newTransaction(); Lock nodeLock = tx.acquireWriteLock( node ); node.setProperty( key, "value" ); nodeLock.release(); Worker worker = new Worker(); worker.beginTx(); try { worker.setProperty( node, key, "ksjd" ); fail( "Shouldn't be able to grab it" ); } catch ( Exception e ) { } commit(); tx.success(); tx.finish(); worker.finishTx(); } private class State { private final GraphDatabaseService graphDb; private Transaction tx; public State( GraphDatabaseService graphDb ) { this.graphDb = graphDb; } } private class Worker extends OtherThreadExecutor<State> { public Worker() { super( "other thread", new State( getGraphDb() ) ); } void beginTx() throws Exception { execute( new WorkerCommand<State, Void>() { @Override public Void doWork( State state ) { state.tx = state.graphDb.beginTx(); return null; } } ); } void finishTx() throws Exception { execute( new WorkerCommand<State, Void>() { @Override public Void doWork( State state ) { state.tx.success(); state.tx.finish(); return null; } } ); } void setProperty( final Node node, final String key, final Object value ) throws Exception { execute( new WorkerCommand<State, Object>() { @Override public Object doWork( State state ) { node.setProperty( key, value ); return null; } }, 200, MILLISECONDS ); } } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestManualAcquireLock.java
616
MulticastListener listener = new MulticastListener() { public void onMessage(Object msg) { systemLogService.logJoin("MulticastListener onMessage " + msg); if (msg != null && msg instanceof JoinMessage) { JoinMessage joinRequest = (JoinMessage) msg; if (node.getThisAddress() != null && !node.getThisAddress().equals(joinRequest.getAddress())) { q.add(joinRequest); } } } };
0true
hazelcast_src_main_java_com_hazelcast_cluster_MulticastJoiner.java
715
constructors[COLLECTION_ADD_LISTENER] = new ConstructorFunction<Integer, Portable>() { public Portable createNew(Integer arg) { return new CollectionAddListenerRequest(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java
1,497
public class ProductLookupTag extends BodyTagSupport { private static final long serialVersionUID = 1L; private String var; private long productId; public long getProductId() { return productId; } public void setProductId(long productId) { this.productId = productId; } @Override public int doStartTag() throws JspException { WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext()); CatalogService catalogService = (CatalogService) applicationContext.getBean("blCatalogService"); pageContext.setAttribute(var, catalogService.findProductById(productId)); return EVAL_PAGE; } public String getVar() { return var; } public void setVar(String var) { this.var = var; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_layout_tags_ProductLookupTag.java
575
public interface OIndex<T> { /** * Creates the index. * * * @param name * * @param clusterIndexName * Cluster name where to place the TreeMap * @param clustersToIndex * @param rebuild * @param progressListener */ OIndex<T> create(String name, OIndexDefinition indexDefinition, String clusterIndexName, Set<String> clustersToIndex, boolean rebuild, OProgressListener progressListener); /** * Unloads the index freeing the resource in memory. */ void unload(); String getDatabaseName(); /** * Types of the keys that index can accept, if index contains composite key, list of types of elements from which this index * consist will be returned, otherwise single element (key type obviously) will be returned. */ OType[] getKeyTypes(); /** * Gets the set of records associated with the passed key. * * @param iKey * The key to search * @return The Record set if found, otherwise an empty Set */ T get(Object iKey); /** * Counts the elements associated with the passed key, if any. * * @param iKey * The key to count * @return The size of found records, otherwise 0 if the key is not found */ long count(Object iKey); public long count(Object iRangeFrom, boolean iFromInclusive, Object iRangeTo, boolean iToInclusive, int maxValuesToFetch); /** * Tells if a key is contained in the index. * * @param iKey * The key to search * @return True if the key is contained, otherwise false */ boolean contains(Object iKey); /** * Inserts a new entry in the index. The behaviour depends by the index implementation. * * @param iKey * Entry's key * @param iValue * Entry's value as OIdentifiable instance * @return The index instance itself to allow in chain calls */ OIndex<T> put(Object iKey, OIdentifiable iValue); /** * Removes an entry by its key. * * @param key * The entry's key to remove * @return True if the entry has been found and removed, otherwise false */ boolean remove(Object key); /** * Removes an entry by its key and value. * * @param iKey * The entry's key to remove * @return True if the entry has been found and removed, otherwise false */ boolean remove(Object iKey, OIdentifiable iRID); /** * Clears the index removing all the entries in one shot. * * @return The index instance itself to allow in chain calls */ OIndex<T> clear(); /** * @return number of entries in the index. */ long getSize(); /** * @return Number of keys in index */ long getKeySize(); /** * For unique indexes it will throw exception if passed in key is contained in index. * * @param iRecord * @param iKey */ void checkEntry(OIdentifiable iRecord, Object iKey); /** * Flushes in-memory changes to disk. */ public void flush(); /** * Delete the index. * * @return The index instance itself to allow in chain calls */ OIndex<T> delete(); void deleteWithoutIndexLoad(String indexName); /** * Returns the index name. * * @return The name of the index */ String getName(); /** * Returns the type of the index as string. */ String getType(); /** * Tells if the index is automatic. Automatic means it's maintained automatically by OrientDB. This is the case of indexes created * against schema properties. Automatic indexes can always been rebuilt. * * @return True if the index is automatic, otherwise false */ boolean isAutomatic(); /** * Rebuilds an automatic index. * * @return The number of entries rebuilt */ long rebuild(); /** * Populate the index with all the existent records. */ long rebuild(OProgressListener iProgressListener); /** * Returns the index configuration. * * @return An ODocument object containing all the index properties */ ODocument getConfiguration(); /** * Returns the internal index used. * */ OIndexInternal<T> getInternal(); /** * Returns set of records with keys in specific set * * @param iKeys * Set of keys * @return */ Collection<OIdentifiable> getValues(Collection<?> iKeys); void getValues(Collection<?> iKeys, IndexValuesResultListener resultListener); /** * Returns a set of documents with keys in specific set * * @param iKeys * Set of keys * @return */ Collection<ODocument> getEntries(Collection<?> iKeys); void getEntries(Collection<?> iKeys, IndexEntriesResultListener resultListener); OIndexDefinition getDefinition(); /** * Returns Names of clusters that will be indexed. * * @return Names of clusters that will be indexed. */ Set<String> getClusters(); /** * Returns an iterator to walk across all the index items from the first to the latest one. * * @return */ public Iterator<Entry<Object, T>> iterator(); /** * Returns an iterator to walk across all the index items from the last to the first one. * * @return */ public Iterator<Entry<Object, T>> inverseIterator(); /** * Returns an iterator to walk across all the index values from the first to the latest one. * * @return */ public Iterator<OIdentifiable> valuesIterator(); /** * Returns an iterator to walk across all the index values from the last to the first one. * * @return */ public Iterator<OIdentifiable> valuesInverseIterator(); /** * Returns an Iterable instance of all the keys contained in the index. * * @return A Iterable<Object> that lazy load the entries once fetched */ public Iterable<Object> keys(); /** * Returns a set of records with key between the range passed as parameter. Range bounds are included. * * In case of {@link com.orientechnologies.common.collection.OCompositeKey}s partial keys can be used as values boundaries. * * @param iRangeFrom * Starting range * @param iRangeTo * Ending range * * @return a set of records with key between the range passed as parameter. Range bounds are included. * @see com.orientechnologies.common.collection.OCompositeKey#compareTo(com.orientechnologies.common.collection.OCompositeKey) * @see #getValuesBetween(Object, boolean, Object, boolean) */ public Collection<OIdentifiable> getValuesBetween(Object iRangeFrom, Object iRangeTo); /** * Returns a set of records with key between the range passed as parameter. * * In case of {@link com.orientechnologies.common.collection.OCompositeKey}s partial keys can be used as values boundaries. * * @param iRangeFrom * Starting range * @param iFromInclusive * Indicates whether start range boundary is included in result. * @param iRangeTo * Ending range * @param iToInclusive * Indicates whether end range boundary is included in result. * * @return Returns a set of records with key between the range passed as parameter. * * @see com.orientechnologies.common.collection.OCompositeKey#compareTo(com.orientechnologies.common.collection.OCompositeKey) * */ public Collection<OIdentifiable> getValuesBetween(Object iRangeFrom, boolean iFromInclusive, Object iRangeTo, boolean iToInclusive); public void getValuesBetween(Object iRangeFrom, boolean iFromInclusive, Object iRangeTo, boolean iToInclusive, IndexValuesResultListener resultListener); /** * Returns a set of records with keys greater than passed parameter. * * @param fromKey * Starting key. * @param isInclusive * Indicates whether record with passed key will be included. * * @return set of records with keys greater than passed parameter. */ public abstract Collection<OIdentifiable> getValuesMajor(Object fromKey, boolean isInclusive); public abstract void getValuesMajor(Object fromKey, boolean isInclusive, IndexValuesResultListener valuesResultListener); /** * Returns a set of records with keys less than passed parameter. * * @param toKey * Ending key. * @param isInclusive * Indicates whether record with passed key will be included. * * @return set of records with keys less than passed parameter. */ public abstract Collection<OIdentifiable> getValuesMinor(Object toKey, boolean isInclusive); public abstract void getValuesMinor(Object toKey, boolean isInclusive, IndexValuesResultListener valuesResultListener); /** * Returns a set of documents that contains fields ("key", "rid") where "key" - index key, "rid" - record id of records with keys * greater than passed parameter. * * @param fromKey * Starting key. * @param isInclusive * Indicates whether record with passed key will be included. * * @return set of records with key greater than passed parameter. */ public abstract Collection<ODocument> getEntriesMajor(Object fromKey, boolean isInclusive); public abstract void getEntriesMajor(Object fromKey, boolean isInclusive, IndexEntriesResultListener entriesResultListener); /** * Returns a set of documents that contains fields ("key", "rid") where "key" - index key, "rid" - record id of records with keys * less than passed parameter. * * @param toKey * Ending key. * @param isInclusive * Indicates whether record with passed key will be included. * * @return set of records with key greater than passed parameter. */ public abstract Collection<ODocument> getEntriesMinor(Object toKey, boolean isInclusive); public abstract void getEntriesMinor(Object toKey, boolean isInclusive, IndexEntriesResultListener entriesResultListener); /** * Returns a set of documents with key between the range passed as parameter. * * @param iRangeFrom * Starting range * @param iRangeTo * Ending range * @param iInclusive * Include from/to bounds * @see #getEntriesBetween(Object, Object) * @return */ public abstract Collection<ODocument> getEntriesBetween(final Object iRangeFrom, final Object iRangeTo, final boolean iInclusive); public abstract void getEntriesBetween(final Object iRangeFrom, final Object iRangeTo, final boolean iInclusive, IndexEntriesResultListener entriesResultListener); public Collection<ODocument> getEntriesBetween(Object iRangeFrom, Object iRangeTo); /** * Returns the Record Identity of the index if persistent. * * @return Valid ORID if it's persistent, otherwise ORID(-1:-1) */ public ORID getIdentity(); public boolean supportsOrderedIterations(); public boolean isRebuiding(); public interface IndexValuesResultListener { boolean addResult(OIdentifiable value); } public interface IndexEntriesResultListener { boolean addResult(ODocument entry); } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_OIndex.java
196
new IProblemChangedListener() { @Override public void problemsChanged(IResource[] changedResources, boolean isMarkerChange) { if (isMarkerChange) { IEditorInput input= getEditorInput(); if (input instanceof IFileEditorInput) { // The editor might be looking at something outside the workspace (e.g. system include files). IFileEditorInput fileInput = (IFileEditorInput) input; IFile file = fileInput.getFile(); if (file != null) { for (int i= 0; i<changedResources.length; i++) { if (changedResources[i].equals(file)) { Shell shell= getEditorSite().getShell(); if (shell!=null && !shell.isDisposed()) { shell.getDisplay().syncExec(new Runnable() { @Override public void run() { updateTitleImage(); } }); } } } } } } } };
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonEditor.java
721
public class DeleteResponse extends ActionResponse { private String index; private String id; private String type; private long version; private boolean found; public DeleteResponse() { } public DeleteResponse(String index, String type, String id, long version, boolean found) { this.index = index; this.id = id; this.type = type; this.version = version; this.found = found; } /** * The index the document was deleted from. */ public String getIndex() { return this.index; } /** * The type of the document deleted. */ public String getType() { return this.type; } /** * The id of the document deleted. */ public String getId() { return this.id; } /** * The version of the delete operation. */ public long getVersion() { return this.version; } /** * Returns <tt>true</tt> if a doc was found to delete. */ public boolean isFound() { return found; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); index = in.readSharedString(); type = in.readSharedString(); id = in.readString(); version = in.readLong(); found = in.readBoolean(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeSharedString(index); out.writeSharedString(type); out.writeString(id); out.writeLong(version); out.writeBoolean(found); } }
0true
src_main_java_org_elasticsearch_action_delete_DeleteResponse.java
484
public interface ExploitProtectionService { /** * Detect and remove possible XSS threats from the passed in string. This * includes {@code <script>} tags, and the like. * * @param string The possibly dirty string * @return The cleansed version of the string * @throws ServiceException */ public String cleanString(String string) throws ServiceException; /** * Detect and remove possible XSS threats from the passed in string. This * includes {@code <script>} tags, and the like. If an html, validation, or * security problem is detected, an exception is thrown. This method also emits * well formed xml, which is important if using Thymeleaf to display the results. * * @param string The possibly dirty string * @return The cleansed version of the string * @throws ServiceException, CleanStringException */ public String cleanStringWithResults(String string) throws ServiceException; public String getAntiSamyPolicyFileLocation(); public void setAntiSamyPolicyFileLocation(String antiSamyPolicyFileLocation); /** * Detect possible XSRF attacks by comparing the csrf token included * in the request against the true token for this user from the session. If they are * different, then the exception is thrown. * * @param passedToken The csrf token that was passed in the request * @throws ServiceException */ public void compareToken(String passedToken) throws ServiceException; public String getCSRFToken() throws ServiceException; public String getCsrfTokenParameter(); }
0true
common_src_main_java_org_broadleafcommerce_common_security_service_ExploitProtectionService.java
20
class DiskQuotaHelper { private static final Logger LOGGER = LoggerFactory.getLogger(DiskQuotaHelper.class); private double usableSpaceAvailableInPercentage = 0; private double freeSpaceAvailableInPercentage = 0; private double totalSpaceInMB = 0; private double freeSpaceInMB = 0; private double usableSpaceInMB = 0; private int bufferMinDiskSpaceAvailableInMB = 10; private int bufferMinDiskSpaceAvailableInPercentage = 1; public String DISK_SPACE_PERCENTAGE_ERROR_MSG = "bufferMinDiskSpaceAvailableInMB = " + bufferMinDiskSpaceAvailableInMB + " bufferMinDiskSpaceAvailableInPercentage= " + bufferMinDiskSpaceAvailableInPercentage + "%"; public DiskQuotaHelper(Properties prop, File bufferHome) { bufferMinDiskSpaceAvailableInMB = Integer.parseInt(prop.getProperty("buffer.min.disk.space.megabytes")); bufferMinDiskSpaceAvailableInPercentage = Integer.parseInt(prop.getProperty("buffer.min.percentage.disk.space")); DISK_SPACE_PERCENTAGE_ERROR_MSG = "Disk space for MCT Buffer is &lt;= " + bufferMinDiskSpaceAvailableInMB + " MB or Total free disk space available is &lt;= " + bufferMinDiskSpaceAvailableInPercentage + "%"; printAvailableDiskSpace("bufferHome from properties", bufferHome); } private void printAvailableDiskSpace(String fileNameDesignation, File filePartition) { // NOTE: Usable Disk Space available in JVM is always less than Free Disk Space LOGGER.info("*** Disk Partition '" + fileNameDesignation + "' at path:"+ filePartition.getAbsolutePath()+" ***"); // Prints total disk space in bytes for volume partition specified by file abstract pathname. long totalSpace = filePartition.getTotalSpace(); totalSpaceInMB = totalSpace /1024 /1024; // Prints an accurate estimate of the total free (and available to this JVM) bytes // on the volume. This method may return the same result as 'getFreeSpace()' on some platforms. long usableSpace = filePartition.getUsableSpace(); usableSpaceInMB = usableSpace /1024 /1024; // Prints the total free unallocated bytes for the volume in bytes. long freeSpace = filePartition.getFreeSpace(); freeSpaceInMB = freeSpace /1024 /1024; LOGGER.info("MCT property specifying Min Disk Space Available (in MB): " + bufferMinDiskSpaceAvailableInMB ); LOGGER.info("MCT property specifying Min Disk Space Available (in Percentage): " + bufferMinDiskSpaceAvailableInPercentage ); LOGGER.info("total Space In MB: " + totalSpaceInMB + " MB"); LOGGER.info("usable Space In MB: " + usableSpaceInMB + " MB"); LOGGER.info("free Space In MB: " + freeSpaceInMB + " MB"); if (totalSpaceInMB > 0) { usableSpaceAvailableInPercentage = (usableSpaceInMB / totalSpaceInMB) * 100; freeSpaceAvailableInPercentage = (freeSpaceInMB / totalSpaceInMB) * 100; LOGGER.info("Calculated Usable Space Available (in Percentage): " + usableSpaceAvailableInPercentage + " %"); LOGGER.info("Calculated Free Space Available (in Percentage): " + freeSpaceAvailableInPercentage + " %"); } else { LOGGER.info("filePartition.getTotalSpace() reported: " + totalSpace); } String m = String.format("The disc is full when: " + "\n usableSpaceAvailableInPercentage (%.1f) <= bufferMinDiskSpaceAvailableInPercentage (%d), or \n " + "usableSpaceInMB (%.1f) <= bufferMinDiskSpaceAvailableInMB (%d), or \n " + "freeSpaceInMB (%.1f) <= bufferMinDiskSpaceAvailableInMB (%d) \n" + "***", usableSpaceAvailableInPercentage, bufferMinDiskSpaceAvailableInPercentage, usableSpaceInMB, bufferMinDiskSpaceAvailableInMB, freeSpaceInMB, bufferMinDiskSpaceAvailableInMB); LOGGER.info(m); } public String getErrorMsg() { return ("<HTML>" + DISK_SPACE_PERCENTAGE_ERROR_MSG + "<BR>Total Disk Space (in MB): " + totalSpaceInMB + "<BR>JVM Usable Disk Space Available (in MB): " + usableSpaceInMB + "<BR>System Free Disk Space Availble (in MB): " + freeSpaceInMB + "<BR>Percentage JVM Usable Disk Space Available: " + usableSpaceAvailableInPercentage + "%<BR>Percentage System Free Disk Space Available: " + freeSpaceAvailableInPercentage + "%</HTML>"); } public boolean isDiskBufferFull() { return (usableSpaceAvailableInPercentage <= bufferMinDiskSpaceAvailableInPercentage) || (usableSpaceInMB <= bufferMinDiskSpaceAvailableInMB) || (freeSpaceInMB <= bufferMinDiskSpaceAvailableInMB); } }
0true
timeSequenceFeedAggregator_src_main_java_gov_nasa_arc_mct_buffer_config_DiskQuotaHelper.java
1,288
public final class SimpleMapTest { private static final String NAMESPACE = "default"; private static final long STATS_SECONDS = 10; private final HazelcastInstance instance; private final ILogger logger; private final Stats stats = new Stats(); private final Random random; private final int threadCount; private final int entryCount; private final int valueSize; private final int getPercentage; private final int putPercentage; private final boolean load; static { System.setProperty("hazelcast.version.check.enabled", "false"); System.setProperty("java.net.preferIPv4Stack", "true"); } private SimpleMapTest(final int threadCount, final int entryCount, final int valueSize, final int getPercentage, final int putPercentage, final boolean load) { this.threadCount = threadCount; this.entryCount = entryCount; this.valueSize = valueSize; this.getPercentage = getPercentage; this.putPercentage = putPercentage; this.load = load; Config cfg = new XmlConfigBuilder().build(); instance = Hazelcast.newHazelcastInstance(cfg); logger = instance.getLoggingService().getLogger("SimpleMapTest"); random = new Random(); } /** * * Expects the Management Center to be running. * @param input * @throws InterruptedException */ public static void main(String[] input) throws InterruptedException { int threadCount = 40; int entryCount = 10 * 1000; int valueSize = 1000; int getPercentage = 40; int putPercentage = 40; boolean load = false; if (input != null && input.length > 0) { for (String arg : input) { arg = arg.trim(); if (arg.startsWith("t")) { threadCount = Integer.parseInt(arg.substring(1)); } else if (arg.startsWith("c")) { entryCount = Integer.parseInt(arg.substring(1)); } else if (arg.startsWith("v")) { valueSize = Integer.parseInt(arg.substring(1)); } else if (arg.startsWith("g")) { getPercentage = Integer.parseInt(arg.substring(1)); } else if (arg.startsWith("p")) { putPercentage = Integer.parseInt(arg.substring(1)); } else if (arg.startsWith("load")) { load = true; } } } else { System.out.println("Help: sh test.sh t200 v130 p10 g85 "); System.out.println("means 200 threads, value-size 130 bytes, 10% put, 85% get"); System.out.println(); } SimpleMapTest test = new SimpleMapTest(threadCount, entryCount, valueSize, getPercentage, putPercentage, load); test.start(); } private void start() throws InterruptedException { printVariables(); ExecutorService es = Executors.newFixedThreadPool(threadCount); startPrintStats(); load(es); run(es); } private void run(ExecutorService es) { final IMap<String, Object> map = instance.getMap(NAMESPACE); for (int i = 0; i < threadCount; i++) { es.execute(new Runnable() { public void run() { try { while (true) { int key = (int) (random.nextFloat() * entryCount); int operation = ((int) (random.nextFloat() * 100)); if (operation < getPercentage) { map.get(String.valueOf(key)); stats.gets.incrementAndGet(); } else if (operation < getPercentage + putPercentage) { map.put(String.valueOf(key), createValue()); stats.puts.incrementAndGet(); } else { map.remove(String.valueOf(key)); stats.removes.incrementAndGet(); } } } catch (HazelcastInstanceNotActiveException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }); } } private Object createValue() { return new byte[valueSize]; } private void load(ExecutorService es) throws InterruptedException { if (!load) { return; } final IMap<String, Object> map = instance.getMap(NAMESPACE); final Member thisMember = instance.getCluster().getLocalMember(); List<String> lsOwnedEntries = new LinkedList<String>(); for (int i = 0; i < entryCount; i++) { final String key = String.valueOf(i); Partition partition = instance.getPartitionService().getPartition(key); if (thisMember.equals(partition.getOwner())) { lsOwnedEntries.add(key); } } final CountDownLatch latch = new CountDownLatch(lsOwnedEntries.size()); for (final String ownedKey : lsOwnedEntries) { es.execute(new Runnable() { public void run() { map.put(ownedKey, createValue()); latch.countDown(); } }); } latch.await(); } private void startPrintStats() { Thread t = new Thread() { { setDaemon(true); setName("PrintStats." + instance.getName()); } public void run() { while (true) { try { Thread.sleep(STATS_SECONDS * 1000); stats.printAndReset(); } catch (InterruptedException ignored) { return; } } } }; t.start(); } /** * A basic statistics class */ private class Stats { private AtomicLong gets = new AtomicLong(); private AtomicLong puts = new AtomicLong(); private AtomicLong removes = new AtomicLong(); public void printAndReset() { long getsNow = gets.getAndSet(0); long putsNow = puts.getAndSet(0); long removesNow = removes.getAndSet(0); long total = getsNow + putsNow + removesNow; logger.info("total= " + total + ", gets:" + getsNow + ", puts:" + putsNow + ", removes:" + removesNow); logger.info("Operations per Second : " + total / STATS_SECONDS); } } private void printVariables() { logger.info("Starting Test with "); logger.info("Thread Count: " + threadCount); logger.info("Entry Count: " + entryCount); logger.info("Value Size: " + valueSize); logger.info("Get Percentage: " + getPercentage); logger.info("Put Percentage: " + putPercentage); logger.info("Remove Percentage: " + (100 - (putPercentage + getPercentage))); logger.info("Load: " + load); } }
0true
hazelcast_src_main_java_com_hazelcast_examples_SimpleMapTest.java
357
future.andThen(new ExecutionCallback<Map<String, Integer>>() { @Override public void onResponse(Map<String, Integer> response) { listenerResults.putAll(response); semaphore.release(); } @Override public void onFailure(Throwable t) { semaphore.release(); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_ClientMapReduceTest.java
3,145
public class InternalIndexEngine extends AbstractIndexComponent implements IndexEngine { public InternalIndexEngine(Index index) { this(index, EMPTY_SETTINGS); } @Inject public InternalIndexEngine(Index index, @IndexSettings Settings indexSettings) { super(index, indexSettings); } @Override public void close() { } }
0true
src_main_java_org_elasticsearch_index_engine_internal_InternalIndexEngine.java
3,429
private class ProxyRegistry { final String serviceName; final RemoteService service; final ConcurrentMap<String, DistributedObjectFuture> proxies = new ConcurrentHashMap<String, DistributedObjectFuture>(); private ProxyRegistry(String serviceName) { this.serviceName = serviceName; this.service = nodeEngine.getService(serviceName); if (service == null) { if (nodeEngine.isActive()) { throw new IllegalArgumentException("Unknown service: " + serviceName); } else { throw new HazelcastInstanceNotActiveException(); } } } /** * Retrieves a DistributedObject proxy or creates it if it's not available * * @param name name of the proxy object * @param publishEvent true if a DistributedObjectEvent should be fired * @param initialize true if proxy object should be initialized * @return a DistributedObject instance */ DistributedObject getOrCreateProxy(final String name, boolean publishEvent, boolean initialize) { DistributedObjectFuture proxyFuture = proxies.get(name); if (proxyFuture == null) { if (!nodeEngine.isActive()) { throw new HazelcastInstanceNotActiveException(); } proxyFuture = createProxy(name, publishEvent, initialize); if (proxyFuture == null) { // warning; recursive call! I (@mdogan) do not think this will ever cause a stack overflow.. return getOrCreateProxy(name, publishEvent, initialize); } } return proxyFuture.get(); } /** * Creates a DistributedObject proxy if it's not created yet * * @param name name of the proxy object * @param publishEvent true if a DistributedObjectEvent should be fired * @param initialize true if proxy object should be initialized * @return a DistributedObject instance if it's created by this method, null otherwise */ DistributedObjectFuture createProxy(final String name, boolean publishEvent, boolean initialize) { if (!proxies.containsKey(name)) { if (!nodeEngine.isActive()) { throw new HazelcastInstanceNotActiveException(); } DistributedObjectFuture proxyFuture = new DistributedObjectFuture(); if (proxies.putIfAbsent(name, proxyFuture) == null) { DistributedObject proxy = service.createDistributedObject(name); if (initialize && proxy instanceof InitializingObject) { try { ((InitializingObject) proxy).initialize(); } catch (Exception e) { logger.warning("Error while initializing proxy: " + proxy, e); } } nodeEngine.eventService.executeEvent(new ProxyEventProcessor(CREATED, serviceName, proxy)); if (publishEvent) { publish(new DistributedObjectEventPacket(CREATED, serviceName, name)); } proxyFuture.set(proxy); return proxyFuture; } } return null; } void destroyProxy(String name, boolean publishEvent) { final DistributedObjectFuture proxyFuture = proxies.remove(name); if (proxyFuture != null) { DistributedObject proxy = proxyFuture.get(); nodeEngine.eventService.executeEvent(new ProxyEventProcessor(DESTROYED, serviceName, proxy)); if (publishEvent) { publish(new DistributedObjectEventPacket(DESTROYED, serviceName, name)); } } } private void publish(DistributedObjectEventPacket event) { final EventService eventService = nodeEngine.getEventService(); final Collection<EventRegistration> registrations = eventService.getRegistrations(SERVICE_NAME, SERVICE_NAME); eventService.publishEvent(SERVICE_NAME, registrations, event, event.getName().hashCode()); } private boolean contains(String name) { return proxies.containsKey(name); } void destroy() { for (DistributedObjectFuture future : proxies.values()) { DistributedObject distributedObject = future.get(); if (distributedObject instanceof AbstractDistributedObject) { ((AbstractDistributedObject) distributedObject).invalidate(); } } proxies.clear(); } public int getProxyCount() { return proxies.size(); } }
1no label
hazelcast_src_main_java_com_hazelcast_spi_impl_ProxyServiceImpl.java
1,022
public abstract class SemaphoreOperation extends AbstractNamedOperation implements PartitionAwareOperation { protected int permitCount; protected transient Object response; protected SemaphoreOperation() { } protected SemaphoreOperation(String name, int permitCount) { super(name); this.permitCount = permitCount; } @Override public Object getResponse() { return response; } public Permit getPermit() { SemaphoreService service = getService(); return service.getOrCreatePermit(name); } @Override public void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeInt(permitCount); } @Override public void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); permitCount = in.readInt(); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_semaphore_operations_SemaphoreOperation.java
829
public interface OrderItemAdjustment extends Adjustment { public OrderItem getOrderItem(); public void init(OrderItem orderItem, Offer offer, String reason); public void setOrderItem(OrderItem orderItem); /** * Even for items that are on sale, it is possible that an adjustment was made * to the retail price that gave the customer a better offer. * * Since some offers can be applied to the sale price and some only to the * retail price, this setting provides the required value. * * @return true if this adjustment was applied to the sale price */ public boolean isAppliedToSalePrice(); public void setAppliedToSalePrice(boolean appliedToSalePrice); /** * Value of this adjustment relative to the retail price. * @return */ public Money getRetailPriceValue(); public void setRetailPriceValue(Money retailPriceValue); /** * Value of this adjustment relative to the sale price. * * @return */ public Money getSalesPriceValue(); public void setSalesPriceValue(Money salesPriceValue); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_OrderItemAdjustment.java
1,687
public abstract class AbstractURLBlobContainer extends AbstractBlobContainer { protected final URLBlobStore blobStore; protected final URL path; /** * Constructs new AbstractURLBlobContainer * * @param blobStore blob store * @param blobPath blob path for this container * @param path URL for this container */ public AbstractURLBlobContainer(URLBlobStore blobStore, BlobPath blobPath, URL path) { super(blobPath); this.blobStore = blobStore; this.path = path; } /** * Returns URL for this container * * @return URL for this container */ public URL url() { return this.path; } /** * This operation is not supported by AbstractURLBlobContainer */ @Override public ImmutableMap<String, BlobMetaData> listBlobs() throws IOException { throw new UnsupportedOperationException("URL repository doesn't support this operation"); } /** * This operation is not supported by AbstractURLBlobContainer */ @Override public boolean deleteBlob(String blobName) throws IOException { throw new UnsupportedOperationException("URL repository is read only"); } /** * This operation is not supported by AbstractURLBlobContainer */ @Override public boolean blobExists(String blobName) { throw new UnsupportedOperationException("URL repository doesn't support this operation"); } /** * {@inheritDoc} */ @Override public void readBlob(final String blobName, final ReadBlobListener listener) { blobStore.executor().execute(new Runnable() { @Override public void run() { byte[] buffer = new byte[blobStore.bufferSizeInBytes()]; InputStream is = null; try { is = new URL(path, blobName).openStream(); int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { listener.onPartial(buffer, 0, bytesRead); } } catch (Throwable t) { IOUtils.closeWhileHandlingException(is); listener.onFailure(t); return; } try { IOUtils.closeWhileHandlingException(is); listener.onCompleted(); } catch (Throwable t) { listener.onFailure(t); } } }); } }
0true
src_main_java_org_elasticsearch_common_blobstore_url_AbstractURLBlobContainer.java
860
EasyMock.expect(multishipOptionServiceMock.findOrderMultishipOptions(EasyMock.isA(Long.class))).andAnswer(new IAnswer<List<OrderMultishipOption>>() { @Override public List<OrderMultishipOption> answer() throws Throwable { return new ArrayList<OrderMultishipOption>(); } }).anyTimes();
0true
core_broadleaf-framework_src_test_java_org_broadleafcommerce_core_offer_service_OfferServiceTest.java
5,852
public abstract class SearchContext implements Releasable { private static ThreadLocal<SearchContext> current = new ThreadLocal<SearchContext>(); public static void setCurrent(SearchContext value) { current.set(value); QueryParseContext.setTypes(value.types()); } public static void removeCurrent() { current.remove(); QueryParseContext.removeTypes(); } public static SearchContext current() { return current.get(); } public abstract boolean clearAndRelease(); /** * Should be called before executing the main query and after all other parameters have been set. */ public abstract void preProcess(); public abstract Filter searchFilter(String[] types); public abstract long id(); public abstract String source(); public abstract ShardSearchRequest request(); public abstract SearchType searchType(); public abstract SearchContext searchType(SearchType searchType); public abstract SearchShardTarget shardTarget(); public abstract int numberOfShards(); public abstract boolean hasTypes(); public abstract String[] types(); public abstract float queryBoost(); public abstract SearchContext queryBoost(float queryBoost); public abstract long nowInMillis(); public abstract Scroll scroll(); public abstract SearchContext scroll(Scroll scroll); public abstract SearchContextAggregations aggregations(); public abstract SearchContext aggregations(SearchContextAggregations aggregations); public abstract SearchContextFacets facets(); public abstract SearchContext facets(SearchContextFacets facets); public abstract SearchContextHighlight highlight(); public abstract void highlight(SearchContextHighlight highlight); public abstract SuggestionSearchContext suggest(); public abstract void suggest(SuggestionSearchContext suggest); /** * @return list of all rescore contexts. empty if there aren't any. */ public abstract List<RescoreSearchContext> rescore(); public abstract void addRescore(RescoreSearchContext rescore); public abstract boolean hasFieldDataFields(); public abstract FieldDataFieldsContext fieldDataFields(); public abstract boolean hasScriptFields(); public abstract ScriptFieldsContext scriptFields(); public abstract boolean hasPartialFields(); public abstract PartialFieldsContext partialFields(); /** * A shortcut function to see whether there is a fetchSourceContext and it says the source is requested. * * @return */ public abstract boolean sourceRequested(); public abstract boolean hasFetchSourceContext(); public abstract FetchSourceContext fetchSourceContext(); public abstract SearchContext fetchSourceContext(FetchSourceContext fetchSourceContext); public abstract ContextIndexSearcher searcher(); public abstract IndexShard indexShard(); public abstract MapperService mapperService(); public abstract AnalysisService analysisService(); public abstract IndexQueryParserService queryParserService(); public abstract SimilarityService similarityService(); public abstract ScriptService scriptService(); public abstract CacheRecycler cacheRecycler(); public abstract PageCacheRecycler pageCacheRecycler(); public abstract FilterCache filterCache(); public abstract DocSetCache docSetCache(); public abstract IndexFieldDataService fieldData(); public abstract IdCache idCache(); public abstract long timeoutInMillis(); public abstract void timeoutInMillis(long timeoutInMillis); public abstract SearchContext minimumScore(float minimumScore); public abstract Float minimumScore(); public abstract SearchContext sort(Sort sort); public abstract Sort sort(); public abstract SearchContext trackScores(boolean trackScores); public abstract boolean trackScores(); public abstract SearchContext parsedPostFilter(ParsedFilter postFilter); public abstract ParsedFilter parsedPostFilter(); public abstract Filter aliasFilter(); public abstract SearchContext parsedQuery(ParsedQuery query); public abstract ParsedQuery parsedQuery(); /** * The query to execute, might be rewritten. */ public abstract Query query(); /** * Has the query been rewritten already? */ public abstract boolean queryRewritten(); /** * Rewrites the query and updates it. Only happens once. */ public abstract SearchContext updateRewriteQuery(Query rewriteQuery); public abstract int from(); public abstract SearchContext from(int from); public abstract int size(); public abstract SearchContext size(int size); public abstract boolean hasFieldNames(); public abstract List<String> fieldNames(); public abstract void emptyFieldNames(); public abstract boolean explain(); public abstract void explain(boolean explain); @Nullable public abstract List<String> groupStats(); public abstract void groupStats(List<String> groupStats); public abstract boolean version(); public abstract void version(boolean version); public abstract int[] docIdsToLoad(); public abstract int docIdsToLoadFrom(); public abstract int docIdsToLoadSize(); public abstract SearchContext docIdsToLoad(int[] docIdsToLoad, int docsIdsToLoadFrom, int docsIdsToLoadSize); public abstract void accessed(long accessTime); public abstract long lastAccessTime(); public abstract long keepAlive(); public abstract void keepAlive(long keepAlive); public abstract SearchLookup lookup(); public abstract DfsSearchResult dfsResult(); public abstract QuerySearchResult queryResult(); public abstract FetchSearchResult fetchResult(); public abstract void addReleasable(Releasable releasable); public abstract void clearReleasables(); public abstract ScanContext scanContext(); public abstract MapperService.SmartNameFieldMappers smartFieldMappers(String name); public abstract FieldMappers smartNameFieldMappers(String name); public abstract FieldMapper smartNameFieldMapper(String name); public abstract MapperService.SmartNameObjectMapper smartNameObjectMapper(String name); }
1no label
src_main_java_org_elasticsearch_search_internal_SearchContext.java
1,727
public class AbstractComponent { protected final ESLogger logger; protected final Settings settings; protected final Settings componentSettings; public AbstractComponent(Settings settings) { this.logger = Loggers.getLogger(getClass(), settings); this.settings = settings; this.componentSettings = settings.getComponentSettings(getClass()); } public AbstractComponent(Settings settings, String prefixSettings) { this.logger = Loggers.getLogger(getClass(), settings); this.settings = settings; this.componentSettings = settings.getComponentSettings(prefixSettings, getClass()); } public AbstractComponent(Settings settings, Class customClass) { this.logger = Loggers.getLogger(customClass, settings); this.settings = settings; this.componentSettings = settings.getComponentSettings(customClass); } public AbstractComponent(Settings settings, String prefixSettings, Class customClass) { this.logger = Loggers.getLogger(customClass, settings); this.settings = settings; this.componentSettings = settings.getComponentSettings(prefixSettings, customClass); } public AbstractComponent(Settings settings, Class loggerClass, Class componentClass) { this.logger = Loggers.getLogger(loggerClass, settings); this.settings = settings; this.componentSettings = settings.getComponentSettings(componentClass); } public AbstractComponent(Settings settings, String prefixSettings, Class loggerClass, Class componentClass) { this.logger = Loggers.getLogger(loggerClass, settings); this.settings = settings; this.componentSettings = settings.getComponentSettings(prefixSettings, componentClass); } public String nodeName() { return settings.get("name", ""); } }
0true
src_main_java_org_elasticsearch_common_component_AbstractComponent.java
407
@Test public class TrackedListTest { public void testAddNotificationOne() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.ADD); Assert.assertNull(event.getOldValue()); Assert.assertEquals(event.getKey().intValue(), 0); Assert.assertEquals(event.getValue(), "value1"); changed.value = true; } }); trackedList.add("value1"); Assert.assertTrue(changed.value); Assert.assertTrue(doc.isDirty()); } public void testAddNotificationTwo() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.ADD); Assert.assertNull(event.getOldValue()); Assert.assertEquals(event.getKey().intValue(), 2); Assert.assertEquals(event.getValue(), "value3"); changed.value = true; } }); trackedList.add("value3"); Assert.assertTrue(changed.value); Assert.assertTrue(doc.isDirty()); } public void testAddNotificationThree() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); Assert.assertTrue(doc.isDirty()); } public void testAddNotificationFour() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { changed.value = true; } }); trackedList.add("value3"); Assert.assertEquals(changed.value, Boolean.FALSE); Assert.assertFalse(doc.isDirty()); } public void testAddAllNotificationOne() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); final List<String> valuesToAdd = new ArrayList<String>(); valuesToAdd.add("value1"); valuesToAdd.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>(); firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.ADD, 0, "value1")); firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.ADD, 1, "value3")); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { if (firedEvents.get(0).equals(event)) firedEvents.remove(0); else Assert.fail(); } }); trackedList.addAll(valuesToAdd); Assert.assertEquals(firedEvents.size(), 0); Assert.assertTrue(doc.isDirty()); } public void testAddAllNotificationTwo() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); final List<String> valuesToAdd = new ArrayList<String>(); valuesToAdd.add("value1"); valuesToAdd.add("value3"); trackedList.addAll(valuesToAdd); Assert.assertTrue(doc.isDirty()); } public void testAddAllNotificationThree() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); final List<String> valuesToAdd = new ArrayList<String>(); valuesToAdd.add("value1"); valuesToAdd.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { changed.value = true; } }); trackedList.addAll(valuesToAdd); Assert.assertFalse(changed.value); Assert.assertFalse(doc.isDirty()); } public void testAddIndexNotificationOne() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.ADD); Assert.assertNull(event.getOldValue()); Assert.assertEquals(event.getKey().intValue(), 1); Assert.assertEquals(event.getValue(), "value3"); changed.value = true; } }); trackedList.add(1, "value3"); Assert.assertEquals(changed.value, Boolean.TRUE); Assert.assertTrue(doc.isDirty()); } public void testAddIndexNotificationTwo() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); trackedList.add(1, "value3"); Assert.assertTrue(doc.isDirty()); } public void testAddIndexNotificationThree() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { changed.value = true; } }); trackedList.add(1, "value3"); Assert.assertEquals(changed.value, Boolean.FALSE); Assert.assertFalse(doc.isDirty()); } public void testSetNotificationOne() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.UPDATE); Assert.assertEquals(event.getOldValue(), "value2"); Assert.assertEquals(event.getKey().intValue(), 1); Assert.assertEquals(event.getValue(), "value4"); changed.value = true; } }); trackedList.set(1, "value4"); Assert.assertEquals(changed.value, Boolean.TRUE); Assert.assertTrue(doc.isDirty()); } public void testSetNotificationTwo() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); trackedList.set(1, "value4"); Assert.assertTrue(doc.isDirty()); } public void testSetNotificationThree() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { changed.value = true; } }); trackedList.set(1, "value4"); Assert.assertFalse(changed.value); Assert.assertFalse(doc.isDirty()); } public void testRemoveNotificationOne() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.REMOVE); Assert.assertEquals(event.getOldValue(), "value2"); Assert.assertEquals(event.getKey().intValue(), 1); Assert.assertNull(event.getValue()); changed.value = true; } }); trackedList.remove("value2"); Assert.assertTrue(changed.value); Assert.assertTrue(doc.isDirty()); } public void testRemoveNotificationTwo() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); trackedList.remove("value2"); Assert.assertTrue(doc.isDirty()); } public void testRemoveNotificationThree() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { changed.value = true; } }); trackedList.remove("value2"); Assert.assertFalse(changed.value); Assert.assertFalse(doc.isDirty()); } public void testRemoveNotificationFour() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { changed.value = true; } }); trackedList.remove("value4"); Assert.assertFalse(changed.value); Assert.assertFalse(doc.isDirty()); } public void testRemoveIndexOne() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.REMOVE); Assert.assertEquals(event.getOldValue(), "value2"); Assert.assertEquals(event.getKey().intValue(), 1); Assert.assertNull(event.getValue()); changed.value = true; } }); trackedList.remove(1); Assert.assertTrue(changed.value); Assert.assertTrue(doc.isDirty()); } public void testRemoveIndexTwo() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); trackedList.remove(1); Assert.assertTrue(doc.isDirty()); } public void testRemoveIndexThree() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { changed.value = true; } }); trackedList.remove(1); Assert.assertFalse(changed.value); Assert.assertFalse(doc.isDirty()); } public void testClearOne() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>(); firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.REMOVE, 2, null, "value3")); firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.REMOVE, 1, null, "value2")); firedEvents.add(new OMultiValueChangeEvent<Integer, String>(OMultiValueChangeEvent.OChangeType.REMOVE, 0, null, "value1")); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { if (firedEvents.get(0).equals(event)) firedEvents.remove(0); else Assert.fail(); } }); trackedList.clear(); Assert.assertEquals(0, firedEvents.size()); Assert.assertTrue(doc.isDirty()); } public void testClearTwo() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); trackedList.clear(); Assert.assertTrue(doc.isDirty()); } public void testClearThree() { final ODocument doc = new ODocument(); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); doc.unsetDirty(); Assert.assertFalse(doc.isDirty()); final ORef<Boolean> changed = new ORef<Boolean>(false); trackedList.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { changed.value = true; } }); trackedList.clear(); Assert.assertFalse(changed.value); Assert.assertFalse(doc.isDirty()); } public void testReturnOriginalStateOne() { final ODocument doc = new ODocument(); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); trackedList.add("value4"); trackedList.add("value5"); final List<String> original = new ArrayList<String>(trackedList); final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>(); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { firedEvents.add(event); } }); trackedList.add("value6"); trackedList.add("value7"); trackedList.set(2, "value10"); trackedList.add(1, "value8"); trackedList.add(1, "value8"); trackedList.remove(3); trackedList.remove("value7"); trackedList.add(0, "value9"); trackedList.add(0, "value9"); trackedList.add(0, "value9"); trackedList.add(0, "value9"); trackedList.remove("value9"); trackedList.remove("value9"); trackedList.add(4, "value11"); Assert.assertEquals(original, trackedList.returnOriginalState(firedEvents)); } public void testReturnOriginalStateTwo() { final ODocument doc = new ODocument(); final OTrackedList<String> trackedList = new OTrackedList<String>(doc); trackedList.add("value1"); trackedList.add("value2"); trackedList.add("value3"); trackedList.add("value4"); trackedList.add("value5"); final List<String> original = new ArrayList<String>(trackedList); final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>(); trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { firedEvents.add(event); } }); trackedList.add("value6"); trackedList.add("value7"); trackedList.set(2, "value10"); trackedList.add(1, "value8"); trackedList.remove(3); trackedList.clear(); trackedList.remove("value7"); trackedList.add(0, "value9"); trackedList.add("value11"); trackedList.add(0, "value12"); trackedList.add("value12"); Assert.assertEquals(original, trackedList.returnOriginalState(firedEvents)); } /** * Test that {@link OTrackedList} is serialised correctly. */ @Test public void testSerialization() throws Exception { class NotSerializableDocument extends ODocument { private static final long serialVersionUID = 1L; private void writeObject(ObjectOutputStream oos) throws IOException { throw new NotSerializableException(); } } final OTrackedList<String> beforeSerialization = new OTrackedList<String>(new NotSerializableDocument()); beforeSerialization.add("firstVal"); beforeSerialization.add("secondVal"); final OMemoryStream memoryStream = new OMemoryStream(); ObjectOutputStream out = new ObjectOutputStream(memoryStream); out.writeObject(beforeSerialization); out.close(); final ObjectInputStream input = new ObjectInputStream(new OMemoryInputStream(memoryStream.copy())); @SuppressWarnings("unchecked") final List<String> afterSerialization = (List<String>) input.readObject(); Assert.assertEquals(afterSerialization.size(), beforeSerialization.size(), "List size"); for (int i = 0; i < afterSerialization.size(); i++) { Assert.assertEquals(afterSerialization.get(i), beforeSerialization.get(i)); } } }
0true
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedListTest.java
85
public class ClientEngineImpl implements ClientEngine, CoreService, ManagedService, MembershipAwareService, EventPublishingService<ClientEndpoint, ClientListener> { public static final String SERVICE_NAME = "hz:core:clientEngine"; public static final int DESTROY_ENDPOINT_DELAY_MS = 1111; public static final int ENDPOINT_REMOVE_DELAY_MS = 10; public static final int THREADS_PER_CORE = 10; public static final int RIDICULOUS_THREADS_PER_CORE = 100000; static final Data NULL = new Data(); private final Node node; private final NodeEngineImpl nodeEngine; private final Executor executor; private final SerializationService serializationService; private final ConcurrentMap<Connection, ClientEndpoint> endpoints = new ConcurrentHashMap<Connection, ClientEndpoint>(); private final ILogger logger; private final ConnectionListener connectionListener = new ConnectionListenerImpl(); public ClientEngineImpl(Node node) { this.node = node; this.serializationService = node.getSerializationService(); this.nodeEngine = node.nodeEngine; int coreSize = Runtime.getRuntime().availableProcessors(); this.executor = nodeEngine.getExecutionService().register(ExecutionService.CLIENT_EXECUTOR, coreSize * THREADS_PER_CORE, coreSize * RIDICULOUS_THREADS_PER_CORE, ExecutorType.CONCRETE); this.logger = node.getLogger(ClientEngine.class); } //needed for testing purposes public ConnectionListener getConnectionListener() { return connectionListener; } @Override public int getClientEndpointCount() { return endpoints.size(); } public void handlePacket(ClientPacket packet) { executor.execute(new ClientPacketProcessor(packet)); } @Override public Object toObject(Data data) { return serializationService.toObject(data); } @Override public Data toData(Object obj) { return serializationService.toData(obj); } @Override public InternalPartitionService getPartitionService() { return nodeEngine.getPartitionService(); } @Override public ClusterService getClusterService() { return nodeEngine.getClusterService(); } @Override public SerializationService getSerializationService() { return serializationService; } @Override public EventService getEventService() { return nodeEngine.getEventService(); } @Override public ProxyService getProxyService() { return nodeEngine.getProxyService(); } void sendOperation(Operation op, Address target) { getOperationService().send(op, target); } InvocationBuilder createInvocationBuilder(String serviceName, Operation op, final int partitionId) { return getOperationService().createInvocationBuilder(serviceName, op, partitionId); } private OperationService getOperationService() { return nodeEngine.getOperationService(); } InvocationBuilder createInvocationBuilder(String serviceName, Operation op, Address target) { return getOperationService().createInvocationBuilder(serviceName, op, target); } Map<Integer, Object> invokeOnAllPartitions(String serviceName, OperationFactory operationFactory) throws Exception { return getOperationService().invokeOnAllPartitions(serviceName, operationFactory); } Map<Integer, Object> invokeOnPartitions(String serviceName, OperationFactory operationFactory, Collection<Integer> partitions) throws Exception { return getOperationService().invokeOnPartitions(serviceName, operationFactory, partitions); } void sendResponse(ClientEndpoint endpoint, ClientResponse response) { Data resultData = serializationService.toData(response); Connection conn = endpoint.getConnection(); conn.write(new DataAdapter(resultData, serializationService.getSerializationContext())); } @Override public TransactionManagerService getTransactionManagerService() { return nodeEngine.getTransactionManagerService(); } @Override public Address getMasterAddress() { return node.getMasterAddress(); } @Override public Address getThisAddress() { return node.getThisAddress(); } @Override public MemberImpl getLocalMember() { return node.getLocalMember(); } @Override public Config getConfig() { return node.getConfig(); } @Override public ILogger getLogger(Class clazz) { return node.getLogger(clazz); } @Override public ILogger getLogger(String className) { return node.getLogger(className); } Set<ClientEndpoint> getEndpoints(String uuid) { Set<ClientEndpoint> endpointSet = new HashSet<ClientEndpoint>(); for (ClientEndpoint endpoint : endpoints.values()) { if (uuid.equals(endpoint.getUuid())) { endpointSet.add(endpoint); } } return endpointSet; } ClientEndpoint getEndpoint(Connection conn) { return endpoints.get(conn); } ClientEndpoint createEndpoint(Connection conn) { if (!conn.live()) { logger.severe("Can't create and endpoint for a dead connection"); return null; } String clientUuid = UuidUtil.createClientUuid(conn.getEndPoint()); ClientEndpoint endpoint = new ClientEndpoint(ClientEngineImpl.this, conn, clientUuid); if (endpoints.putIfAbsent(conn, endpoint) != null) { logger.severe("An endpoint already exists for connection:" + conn); } return endpoint; } ClientEndpoint removeEndpoint(final Connection connection) { return removeEndpoint(connection, false); } ClientEndpoint removeEndpoint(final Connection connection, boolean closeImmediately) { final ClientEndpoint endpoint = endpoints.remove(connection); destroyEndpoint(endpoint, closeImmediately); return endpoint; } private void destroyEndpoint(ClientEndpoint endpoint, boolean closeImmediately) { if (endpoint != null) { logger.info("Destroying " + endpoint); try { endpoint.destroy(); } catch (LoginException e) { logger.warning(e); } final Connection connection = endpoint.getConnection(); if (closeImmediately) { try { connection.close(); } catch (Throwable e) { logger.warning("While closing client connection: " + connection, e); } } else { nodeEngine.getExecutionService().schedule(new Runnable() { public void run() { if (connection.live()) { try { connection.close(); } catch (Throwable e) { logger.warning("While closing client connection: " + e.toString()); } } } }, DESTROY_ENDPOINT_DELAY_MS, TimeUnit.MILLISECONDS); } sendClientEvent(endpoint); } } @Override public SecurityContext getSecurityContext() { return node.securityContext; } void bind(final ClientEndpoint endpoint) { final Connection conn = endpoint.getConnection(); if (conn instanceof TcpIpConnection) { Address address = new Address(conn.getRemoteSocketAddress()); TcpIpConnectionManager connectionManager = (TcpIpConnectionManager) node.getConnectionManager(); connectionManager.bind((TcpIpConnection) conn, address, null, false); } sendClientEvent(endpoint); } private void sendClientEvent(ClientEndpoint endpoint) { if (!endpoint.isFirstConnection()) { final EventService eventService = nodeEngine.getEventService(); final Collection<EventRegistration> regs = eventService.getRegistrations(SERVICE_NAME, SERVICE_NAME); eventService.publishEvent(SERVICE_NAME, regs, endpoint, endpoint.getUuid().hashCode()); } } @Override public void dispatchEvent(ClientEndpoint event, ClientListener listener) { if (event.isAuthenticated()) { listener.clientConnected(event); } else { listener.clientDisconnected(event); } } @Override public void memberAdded(MembershipServiceEvent event) { } @Override public void memberRemoved(MembershipServiceEvent event) { if (event.getMember().localMember()) { return; } final String uuid = event.getMember().getUuid(); try { nodeEngine.getExecutionService().schedule(new Runnable() { @Override public void run() { Iterator<ClientEndpoint> iterator = endpoints.values().iterator(); while (iterator.hasNext()) { ClientEndpoint endpoint = iterator.next(); String ownerUuid = endpoint.getPrincipal().getOwnerUuid(); if (uuid.equals(ownerUuid)) { iterator.remove(); destroyEndpoint(endpoint, true); } } } }, ENDPOINT_REMOVE_DELAY_MS, TimeUnit.SECONDS); } catch (RejectedExecutionException e) { if (logger.isFinestEnabled()) { logger.finest(e); } } } @Override public void memberAttributeChanged(MemberAttributeServiceEvent event) { } String addClientListener(ClientListener clientListener) { EventService eventService = nodeEngine.getEventService(); EventRegistration registration = eventService .registerLocalListener(SERVICE_NAME, SERVICE_NAME, clientListener); return registration.getId(); } boolean removeClientListener(String registrationId) { return nodeEngine.getEventService().deregisterListener(SERVICE_NAME, SERVICE_NAME, registrationId); } public ClientService getClientService() { return new ClientServiceProxy(this); } public Collection<Client> getClients() { final HashSet<Client> clients = new HashSet<Client>(); for (ClientEndpoint endpoint : endpoints.values()) { if (!endpoint.isFirstConnection()) { clients.add(endpoint); } } return clients; } @Override public void init(NodeEngine nodeEngine, Properties properties) { ClassDefinitionBuilder builder = new ClassDefinitionBuilder(ClientPortableHook.ID, ClientPortableHook.PRINCIPAL); builder.addUTFField("uuid").addUTFField("ownerUuid"); serializationService.getSerializationContext().registerClassDefinition(builder.build()); node.getConnectionManager().addConnectionListener(connectionListener); } @Override public void reset() { } public void shutdown(boolean terminate) { for (ClientEndpoint endpoint : endpoints.values()) { try { endpoint.destroy(); } catch (LoginException e) { logger.finest(e.getMessage()); } try { final Connection conn = endpoint.getConnection(); if (conn.live()) { conn.close(); } } catch (Exception e) { logger.finest(e); } } endpoints.clear(); } private final class ClientPacketProcessor implements Runnable { final ClientPacket packet; private ClientPacketProcessor(ClientPacket packet) { this.packet = packet; } @Override public void run() { Connection conn = packet.getConn(); ClientEndpoint endpoint = getEndpoint(conn); ClientRequest request = null; try { request = loadRequest(); if (request == null) { handlePacketWithNullRequest(); } else if (request instanceof AuthenticationRequest) { endpoint = createEndpoint(conn); if (endpoint != null) { processRequest(endpoint, request); } else { handleEndpointNotCreatedConnectionNotAlive(); } } else if (endpoint == null) { handleMissingEndpoint(conn); } else if (endpoint.isAuthenticated()) { processRequest(endpoint, request); } else { handleAuthenticationFailure(conn, endpoint, request); } } catch (Throwable e) { handleProcessingFailure(endpoint, request, e); } } private ClientRequest loadRequest() { Data data = packet.getData(); return serializationService.toObject(data); } private void handleEndpointNotCreatedConnectionNotAlive() { logger.warning("Dropped: " + packet + " -> endpoint not created for AuthenticationRequest, " + "connection not alive"); } private void handlePacketWithNullRequest() { logger.warning("Dropped: " + packet + " -> null request"); } private void handleMissingEndpoint(Connection conn) { if (conn.live()) { logger.severe("Dropping: " + packet + " -> no endpoint found for live connection."); } else { if (logger.isFinestEnabled()) { logger.finest("Dropping: " + packet + " -> no endpoint found for dead connection."); } } } private void handleProcessingFailure(ClientEndpoint endpoint, ClientRequest request, Throwable e) { Level level = nodeEngine.isActive() ? Level.SEVERE : Level.FINEST; if (logger.isLoggable(level)) { if (request == null) { logger.log(level, e.getMessage(), e); } else { logger.log(level, "While executing request: " + request + " -> " + e.getMessage(), e); } } if (request != null && endpoint != null) { endpoint.sendResponse(e, request.getCallId()); } } private void processRequest(ClientEndpoint endpoint, ClientRequest request) throws Exception { request.setEndpoint(endpoint); initService(request); request.setClientEngine(ClientEngineImpl.this); checkPermissions(endpoint, request); request.process(); } private void checkPermissions(ClientEndpoint endpoint, ClientRequest request) { SecurityContext securityContext = getSecurityContext(); if (securityContext != null) { Permission permission = request.getRequiredPermission(); if (permission != null) { securityContext.checkPermission(endpoint.getSubject(), permission); } } } private void initService(ClientRequest request) { String serviceName = request.getServiceName(); if (serviceName == null) { return; } Object service = nodeEngine.getService(serviceName); if (service == null) { if (nodeEngine.isActive()) { throw new IllegalArgumentException("No service registered with name: " + serviceName); } throw new HazelcastInstanceNotActiveException(); } request.setService(service); } private void handleAuthenticationFailure(Connection conn, ClientEndpoint endpoint, ClientRequest request) { Exception exception; if (nodeEngine.isActive()) { String message = "Client " + conn + " must authenticate before any operation."; logger.severe(message); exception = new AuthenticationException(message); } else { exception = new HazelcastInstanceNotActiveException(); } endpoint.sendResponse(exception, request.getCallId()); removeEndpoint(conn); } } private final class ConnectionListenerImpl implements ConnectionListener { @Override public void connectionAdded(Connection conn) { //no-op //unfortunately we can't do the endpoint creation here, because this event is only called when the //connection is bound, but we need to use the endpoint connection before that. } @Override public void connectionRemoved(Connection connection) { if (connection.isClient() && connection instanceof TcpIpConnection && nodeEngine.isActive()) { ClientEndpoint endpoint = endpoints.get(connection); if (endpoint == null) { return; } String localMemberUuid = node.getLocalMember().getUuid(); String ownerUuid = endpoint.getPrincipal().getOwnerUuid(); if (localMemberUuid.equals(ownerUuid)) { doRemoveEndpoint(connection, endpoint); } } } private void doRemoveEndpoint(Connection connection, ClientEndpoint endpoint) { removeEndpoint(connection, true); if (!endpoint.isFirstConnection()) { return; } NodeEngine nodeEngine = node.nodeEngine; Collection<MemberImpl> memberList = nodeEngine.getClusterService().getMemberList(); OperationService operationService = nodeEngine.getOperationService(); for (MemberImpl member : memberList) { ClientDisconnectionOperation op = new ClientDisconnectionOperation(endpoint.getUuid()); op.setNodeEngine(nodeEngine) .setServiceName(SERVICE_NAME) .setService(ClientEngineImpl.this) .setResponseHandler(createEmptyResponseHandler()); if (member.localMember()) { operationService.runOperationOnCallingThread(op); } else { operationService.send(op, member.getAddress()); } } } } }
1no label
hazelcast_src_main_java_com_hazelcast_client_ClientEngineImpl.java
896
public class IdGeneratorProxy extends AbstractDistributedObject<IdGeneratorService> implements IdGenerator { public static final int BLOCK_SIZE = 10000; private final String name; private final IAtomicLong blockGenerator; private final AtomicInteger residue = new AtomicInteger(BLOCK_SIZE); private final AtomicLong local = new AtomicLong(-1); public IdGeneratorProxy(IAtomicLong blockGenerator, String name, NodeEngine nodeEngine, IdGeneratorService service) { super(nodeEngine, service); this.name = name; this.blockGenerator = blockGenerator; } @Override public boolean init(long id) { if (id <= 0) { return false; } long step = (id / BLOCK_SIZE); synchronized (this) { boolean init = blockGenerator.compareAndSet(0, step + 1); if (init) { local.set(step); residue.set((int) (id % BLOCK_SIZE) + 1); } return init; } } @Override public long newId() { int value = residue.getAndIncrement(); if (value >= BLOCK_SIZE) { synchronized (this) { value = residue.get(); if (value >= BLOCK_SIZE) { local.set(blockGenerator.getAndIncrement()); residue.set(0); } //todo: we need to get rid of this. return newId(); } } return local.get() * BLOCK_SIZE + value; } @Override public String getName() { return name; } @Override public String getServiceName() { return IdGeneratorService.SERVICE_NAME; } @Override protected void postDestroy() { blockGenerator.destroy(); //todo: this behavior is racy; imagine what happens when destroy is called by different threads local.set(-1); residue.set(BLOCK_SIZE); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_idgen_IdGeneratorProxy.java
1,170
public interface ISet<E> extends Set<E>, ICollection<E> { }
0true
hazelcast_src_main_java_com_hazelcast_core_ISet.java
1,498
public class DefaultNodeContext implements NodeContext { @Override public AddressPicker createAddressPicker(Node node) { return new DefaultAddressPicker(node); } @Override public Joiner createJoiner(Node node) { return node.createJoiner(); } @Override public ConnectionManager createConnectionManager(Node node, ServerSocketChannel serverSocketChannel) { NodeIOService ioService = new NodeIOService(node); return new TcpIpConnectionManager(ioService, serverSocketChannel); } }
0true
hazelcast_src_main_java_com_hazelcast_instance_DefaultNodeContext.java
1,489
public abstract class AbstractCheckoutController extends BroadleafAbstractController { /* Services */ @Resource(name = "blOrderService") protected OrderService orderService; @Resource(name = "blFulfillmentOptionService") protected FulfillmentOptionService fulfillmentOptionService; @Resource(name = "blFulfillmentPricingService") protected FulfillmentPricingService fulfillmentPricingService; @Resource(name = "blFulfillmentGroupService") protected FulfillmentGroupService fulfillmentGroupService; @Resource(name = "blCheckoutService") protected CheckoutService checkoutService; @Resource(name = "blCustomerService") protected CustomerService customerService; @Resource(name = "blStateService") protected StateService stateService; @Resource(name = "blCountryService") protected CountryService countryService; @Resource(name = "blCustomerAddressService") protected CustomerAddressService customerAddressService; @Resource(name = "blAddressService") protected AddressService addressService; @Resource(name = "blOrderMultishipOptionService") protected OrderMultishipOptionService orderMultishipOptionService; @Resource(name = "blSecurePaymentInfoService") protected SecurePaymentInfoService securePaymentInfoService; @Resource(name = "blPaymentInfoTypeService") protected BroadleafPaymentInfoTypeService paymentInfoTypeService; /* Factories */ @Resource(name = "blCreditCardPaymentInfoFactory") protected PaymentInfoFactory creditCardPaymentInfoFactory; /* Validators */ @Resource(name = "blShippingInfoFormValidator") protected ShippingInfoFormValidator shippingInfoFormValidator; @Resource(name = "blMultishipAddAddressFormValidator") protected MultishipAddAddressFormValidator multishipAddAddressFormValidator; @Resource(name = "blBillingInfoFormValidator") protected BillingInfoFormValidator billingInfoFormValidator; @Resource(name = "blOrderInfoFormValidator") protected OrderInfoFormValidator orderInfoFormValidator; }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_checkout_AbstractCheckoutController.java
2,005
public static class RecordingMapStore implements MapStore<String, String> { private static final boolean DEBUG = false; private final CountDownLatch expectedStore; private final CountDownLatch expectedRemove; private final ConcurrentHashMap<String, String> store; public RecordingMapStore(int expectedStore, int expectedRemove) { this.expectedStore = new CountDownLatch(expectedStore); this.expectedRemove = new CountDownLatch(expectedRemove); this.store = new ConcurrentHashMap<String, String>(); } public ConcurrentHashMap<String, String> getStore() { return store; } @Override public String load(String key) { log("load(" + key + ") called."); return store.get(key); } @Override public Map<String, String> loadAll(Collection<String> keys) { if (DEBUG) { List<String> keysList = new ArrayList<String>(keys); Collections.sort(keysList); log("loadAll(" + keysList + ") called."); } Map<String, String> result = new HashMap<String, String>(); for (String key : keys) { String value = store.get(key); if (value != null) { result.put(key, value); } } return result; } @Override public Set<String> loadAllKeys() { log("loadAllKeys() called."); Set<String> result = new HashSet<String>(store.keySet()); log("loadAllKeys result = " + result); return result; } @Override public void store(String key, String value) { log("store(" + key + ") called."); String valuePrev = store.put(key, value); expectedStore.countDown(); if (valuePrev != null) { log("- Unexpected Update (operations reordered?): " + key); } } @Override public void storeAll(Map<String, String> map) { if (DEBUG) { TreeSet<String> setSorted = new TreeSet<String>(map.keySet()); log("storeAll(" + setSorted + ") called."); } store.putAll(map); final int size = map.keySet().size(); for (int i = 0; i < size; i++) { expectedStore.countDown(); } } @Override public void delete(String key) { log("delete(" + key + ") called."); String valuePrev = store.remove(key); expectedRemove.countDown(); if (valuePrev == null) { log("- Unnecessary delete (operations reordered?): " + key); } } @Override public void deleteAll(Collection<String> keys) { if (DEBUG) { List<String> keysList = new ArrayList<String>(keys); Collections.sort(keysList); log("deleteAll(" + keysList + ") called."); } for (String key : keys) { String valuePrev = store.remove(key); expectedRemove.countDown(); if (valuePrev == null) { log("- Unnecessary delete (operations reordered?): " + key); } } } public void awaitStores() { assertOpenEventually(expectedStore); } public void awaitRemoves() { assertOpenEventually(expectedRemove); } private void log(String msg) { if (DEBUG) { System.out.println(msg); } } }
0true
hazelcast_src_test_java_com_hazelcast_map_mapstore_MapStoreTest.java
618
public class MulticastService implements Runnable { private static final int DATAGRAM_BUFFER_SIZE = 64 * 1024; private final ILogger logger; private final MulticastSocket multicastSocket; private final DatagramPacket datagramPacketSend; private final DatagramPacket datagramPacketReceive; private final Object sendLock = new Object(); private final CountDownLatch stopLatch = new CountDownLatch(1); private final List<MulticastListener> listeners = new CopyOnWriteArrayList<MulticastListener>(); private final Node node; private final BufferObjectDataOutput sendOutput; private volatile boolean running = true; public MulticastService(Node node, MulticastSocket multicastSocket) throws Exception { this.node = node; logger = node.getLogger(MulticastService.class.getName()); Config config = node.getConfig(); this.multicastSocket = multicastSocket; sendOutput = node.getSerializationService().createObjectDataOutput(1024); datagramPacketReceive = new DatagramPacket(new byte[DATAGRAM_BUFFER_SIZE], DATAGRAM_BUFFER_SIZE); final MulticastConfig multicastConfig = config.getNetworkConfig().getJoin().getMulticastConfig(); datagramPacketSend = new DatagramPacket(new byte[0], 0, InetAddress .getByName(multicastConfig.getMulticastGroup()), multicastConfig.getMulticastPort()); running = true; } public void addMulticastListener(MulticastListener multicastListener) { listeners.add(multicastListener); } public void removeMulticastListener(MulticastListener multicastListener) { listeners.remove(multicastListener); } public void stop() { try { if (!running && multicastSocket.isClosed()) { return; } try { multicastSocket.close(); } catch (Throwable ignored) { } running = false; if (!stopLatch.await(5, TimeUnit.SECONDS)) { logger.warning("Failed to shutdown MulticastService in 5 seconds!"); } } catch (Throwable e) { logger.warning(e); } } private void cleanup() { running = false; try { sendOutput.close(); datagramPacketReceive.setData(new byte[0]); datagramPacketSend.setData(new byte[0]); } catch (Throwable ignored) { } stopLatch.countDown(); } @SuppressWarnings("WhileLoopSpinsOnField") @Override public void run() { try { while (running) { try { final JoinMessage joinMessage = receive(); if (joinMessage != null) { for (MulticastListener multicastListener : listeners) { try { multicastListener.onMessage(joinMessage); } catch (Exception e) { logger.warning(e); } } } } catch (OutOfMemoryError e) { OutOfMemoryErrorDispatcher.onOutOfMemory(e); } catch (Exception e) { logger.warning(e); } } } finally { cleanup(); } } private JoinMessage receive() { try { try { multicastSocket.receive(datagramPacketReceive); } catch (IOException ignore) { return null; } try { final byte[] data = datagramPacketReceive.getData(); final int offset = datagramPacketReceive.getOffset(); final BufferObjectDataInput input = node.getSerializationService().createObjectDataInput(data); input.position(offset); final byte packetVersion = input.readByte(); if (packetVersion != Packet.VERSION) { logger.warning("Received a JoinRequest with a different packet version! This -> " + Packet.VERSION + ", Incoming -> " + packetVersion + ", Sender -> " + datagramPacketReceive.getAddress()); return null; } try { return input.readObject(); } finally { input.close(); } } catch (Exception e) { if (e instanceof EOFException || e instanceof HazelcastSerializationException) { logger.warning("Received data format is invalid." + " (An old version of Hazelcast may be running here.)", e); } else { throw e; } } } catch (Exception e) { logger.warning(e); } return null; } public void send(JoinMessage joinMessage) { if (!running) return; final BufferObjectDataOutput out = sendOutput; synchronized (sendLock) { try { out.writeByte(Packet.VERSION); out.writeObject(joinMessage); datagramPacketSend.setData(out.toByteArray()); multicastSocket.send(datagramPacketSend); out.clear(); } catch (IOException e) { logger.warning("You probably have too long Hazelcast configuration!", e); } } } }
0true
hazelcast_src_main_java_com_hazelcast_cluster_MulticastService.java
316
public class EarlyStageMergeBeanPostProcessor extends AbstractMergeBeanPostProcessor implements PriorityOrdered { protected int order = Integer.MIN_VALUE; /** * This is the priority order for this post processor and will determine when this processor is run in relation * to other priority ordered processors (e.g. {@link org.springframework.context.annotation.CommonAnnotationBeanPostProcessor}) * The default value if Integer.MIN_VALUE. */ @Override public int getOrder() { return order; } /** * This is the priority order for this post processor and will determine when this processor is run in relation * to other priority ordered processors (e.g. {@link org.springframework.context.annotation.CommonAnnotationBeanPostProcessor}) * The default value if Integer.MIN_VALUE. * * @param order the priority ordering */ public void setOrder(int order) { this.order = order; } }
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_EarlyStageMergeBeanPostProcessor.java
585
lifecycleService.runUnderLifecycleLock(new Runnable() { public void run() { lifecycleService.fireLifecycleEvent(MERGING); final NodeEngineImpl nodeEngine = node.nodeEngine; final Collection<SplitBrainHandlerService> services = nodeEngine.getServices(SplitBrainHandlerService.class); final Collection<Runnable> tasks = new LinkedList<Runnable>(); for (SplitBrainHandlerService service : services) { final Runnable runnable = service.prepareMergeRunnable(); if (runnable != null) { tasks.add(runnable); } } final Collection<ManagedService> managedServices = nodeEngine.getServices(ManagedService.class); for (ManagedService service : managedServices) { service.reset(); } node.onRestart(); node.connectionManager.restart(); node.rejoin(); final Collection<Future> futures = new LinkedList<Future>(); for (Runnable task : tasks) { Future f = nodeEngine.getExecutionService().submit("hz:system", task); futures.add(f); } long callTimeout = node.groupProperties.OPERATION_CALL_TIMEOUT_MILLIS.getLong(); for (Future f : futures) { try { waitOnFutureInterruptible(f, callTimeout, TimeUnit.MILLISECONDS); } catch (Exception e) { logger.severe("While merging...", e); } } lifecycleService.fireLifecycleEvent(MERGED); } });
1no label
hazelcast_src_main_java_com_hazelcast_cluster_ClusterServiceImpl.java
3,429
public class IndexShardGatewaySnapshotFailedException extends IndexShardGatewayException { public IndexShardGatewaySnapshotFailedException(ShardId shardId, String msg, Throwable cause) { super(shardId, msg, cause); } }
0true
src_main_java_org_elasticsearch_index_gateway_IndexShardGatewaySnapshotFailedException.java
833
BOOLEAN("Boolean", 0, new Class<?>[] { Boolean.class, Boolean.TYPE }, new Class<?>[] { Boolean.class, Number.class }) { },
0true
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OType.java
258
public final class StoreUtils { private StoreUtils() { } public static String toString(Directory directory) { if (directory instanceof NIOFSDirectory) { NIOFSDirectory niofsDirectory = (NIOFSDirectory)directory; return "niofs(" + niofsDirectory.getDirectory() + ")"; } if (directory instanceof MMapDirectory) { MMapDirectory mMapDirectory = (MMapDirectory)directory; return "mmapfs(" + mMapDirectory.getDirectory() + ")"; } if (directory instanceof SimpleFSDirectory) { SimpleFSDirectory simpleFSDirectory = (SimpleFSDirectory)directory; return "simplefs(" + simpleFSDirectory.getDirectory() + ")"; } return directory.toString(); } }
0true
src_main_java_org_apache_lucene_store_StoreUtils.java
665
public class ValidateQueryRequest extends BroadcastOperationRequest<ValidateQueryRequest> { private static final XContentType contentType = Requests.CONTENT_TYPE; private BytesReference source; private boolean sourceUnsafe; private boolean explain; private String[] types = Strings.EMPTY_ARRAY; long nowInMillis; ValidateQueryRequest() { this(Strings.EMPTY_ARRAY); } /** * Constructs a new validate request against the provided indices. No indices provided means it will * run against all indices. */ public ValidateQueryRequest(String... indices) { super(indices); indicesOptions(IndicesOptions.fromOptions(false, false, true, false)); } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = super.validate(); return validationException; } @Override protected void beforeStart() { if (sourceUnsafe) { source = source.copyBytesArray(); sourceUnsafe = false; } } /** * The source to execute. */ BytesReference source() { return source; } public ValidateQueryRequest source(QuerySourceBuilder sourceBuilder) { this.source = sourceBuilder.buildAsBytes(contentType); this.sourceUnsafe = false; return this; } /** * The source to execute in the form of a map. */ public ValidateQueryRequest source(Map source) { try { XContentBuilder builder = XContentFactory.contentBuilder(contentType); builder.map(source); return source(builder); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); } } public ValidateQueryRequest source(XContentBuilder builder) { this.source = builder.bytes(); this.sourceUnsafe = false; return this; } /** * The query source to validate. It is preferable to use either {@link #source(byte[])} * or {@link #source(QuerySourceBuilder)}. */ public ValidateQueryRequest source(String source) { this.source = new BytesArray(source); this.sourceUnsafe = false; return this; } /** * The source to validate. */ public ValidateQueryRequest source(byte[] source) { return source(source, 0, source.length, false); } /** * The source to validate. */ public ValidateQueryRequest source(byte[] source, int offset, int length, boolean unsafe) { return source(new BytesArray(source, offset, length), unsafe); } /** * The source to validate. */ public ValidateQueryRequest source(BytesReference source, boolean unsafe) { this.source = source; this.sourceUnsafe = unsafe; return this; } /** * The types of documents the query will run against. Defaults to all types. */ public String[] types() { return this.types; } /** * The types of documents the query will run against. Defaults to all types. */ public ValidateQueryRequest types(String... types) { this.types = types; return this; } /** * Indicate if detailed information about query is requested */ public void explain(boolean explain) { this.explain = explain; } /** * Indicates if detailed information about query is requested */ public boolean explain() { return explain; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); sourceUnsafe = false; source = in.readBytesReference(); int typesSize = in.readVInt(); if (typesSize > 0) { types = new String[typesSize]; for (int i = 0; i < typesSize; i++) { types[i] = in.readString(); } } explain = in.readBoolean(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeBytesReference(source); out.writeVInt(types.length); for (String type : types) { out.writeString(type); } out.writeBoolean(explain); } @Override public String toString() { String sSource = "_na_"; try { sSource = XContentHelper.convertToJson(source, false); } catch (Exception e) { // ignore } return "[" + Arrays.toString(indices) + "]" + Arrays.toString(types) + ", source[" + sSource + "], explain:" + explain; } }
0true
src_main_java_org_elasticsearch_action_admin_indices_validate_query_ValidateQueryRequest.java
629
public class BLCDialect extends AbstractDialect { private Set<IProcessor> processors = new HashSet<IProcessor>(); @Resource(name = "blVariableExpressionEvaluator") private IStandardVariableExpressionEvaluator expressionEvaluator; @Override public String getPrefix() { return "blc"; } @Override public boolean isLenient() { return true; } @Override public Set<IProcessor> getProcessors() { return processors; } public void setProcessors(Set<IProcessor> processors) { this.processors = processors; } @Override public Map<String, Object> getExecutionAttributes() { final StandardExpressionExecutor executor = StandardExpressionProcessor.createStandardExpressionExecutor(expressionEvaluator); final StandardExpressionParser parser = StandardExpressionProcessor.createStandardExpressionParser(executor); final Map<String,Object> executionAttributes = new LinkedHashMap<String, Object>(); executionAttributes.put(StandardDialect.EXPRESSION_EVALUATOR_EXECUTION_ATTRIBUTE, expressionEvaluator); executionAttributes.put(StandardExpressionProcessor.STANDARD_EXPRESSION_EXECUTOR_ATTRIBUTE_NAME, executor); executionAttributes.put(StandardExpressionProcessor.STANDARD_EXPRESSION_PARSER_ATTRIBUTE_NAME, parser); return executionAttributes; } }
0true
common_src_main_java_org_broadleafcommerce_common_web_dialect_BLCDialect.java
159
public interface StructuredContentRuleProcessor { /** * Returns true if the passed in <code>StructuredContent</code> is valid according * to this rule processor. * * @param sc * @return */ public boolean checkForMatch(StructuredContentDTO sc, Map<String,Object> valueMap); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_service_StructuredContentRuleProcessor.java
762
public class PricingServiceActivity extends BaseActivity<CheckoutContext> { @Resource(name="blPricingService") private PricingService pricingService; @Override public CheckoutContext execute(CheckoutContext context) throws Exception { CheckoutSeed seed = context.getSeedData(); Order order = pricingService.executePricing(seed.getOrder()); seed.setOrder(order); return context; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_checkout_service_workflow_PricingServiceActivity.java
4,295
public class IndicesModule extends AbstractModule implements SpawnModules { private final Settings settings; public IndicesModule(Settings settings) { this.settings = settings; } @Override public Iterable<? extends Module> spawnModules() { return ImmutableList.of(new IndicesQueriesModule(), new IndicesAnalysisModule()); } @Override protected void configure() { bind(IndicesLifecycle.class).to(InternalIndicesLifecycle.class).asEagerSingleton(); bind(IndicesService.class).to(InternalIndicesService.class).asEagerSingleton(); bind(RecoverySettings.class).asEagerSingleton(); bind(RecoveryTarget.class).asEagerSingleton(); bind(RecoverySource.class).asEagerSingleton(); bind(IndicesStore.class).asEagerSingleton(); bind(IndicesClusterStateService.class).asEagerSingleton(); bind(IndexingMemoryController.class).asEagerSingleton(); bind(IndicesFilterCache.class).asEagerSingleton(); bind(IndicesFieldDataCache.class).asEagerSingleton(); bind(IndicesTermsFilterCache.class).asEagerSingleton(); bind(TransportNodesListShardStoreMetaData.class).asEagerSingleton(); bind(IndicesTTLService.class).asEagerSingleton(); bind(IndicesWarmer.class).to(InternalIndicesWarmer.class).asEagerSingleton(); bind(UpdateHelper.class).asEagerSingleton(); bind(CircuitBreakerService.class).to(InternalCircuitBreakerService.class).asEagerSingleton(); } }
1no label
src_main_java_org_elasticsearch_indices_IndicesModule.java
165
public class NullURLHandler implements URLHandler,java.io.Serializable { private static final long serialVersionUID = 1L; @Override public Long getId() { return null; } @Override public void setId(Long id) { } @Override public String getIncomingURL() { return null; } @Override public void setIncomingURL(String incomingURL) { } @Override public String getNewURL() { return null; } @Override public void setNewURL(String newURL) { } @Override public URLRedirectType getUrlRedirectType() { return null; } @Override public void setUrlRedirectType(URLRedirectType redirectType) { } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_url_domain_NullURLHandler.java
151
static final class Itr<E> implements ListIterator<E>, Enumeration<E> { final StampedLock lock; final ReadMostlyVector<E> list; Object[] items; long seq; int cursor; int fence; int lastRet; Itr(ReadMostlyVector<E> list, int index) { final StampedLock lock = list.lock; long stamp = lock.readLock(); try { this.list = list; this.lock = lock; this.items = list.array; this.fence = list.count; this.cursor = index; this.lastRet = -1; } finally { this.seq = lock.tryConvertToOptimisticRead(stamp); } if (index < 0 || index > fence) throw new ArrayIndexOutOfBoundsException(index); } public boolean hasPrevious() { return cursor > 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } public boolean hasNext() { return cursor < fence; } public E next() { int i = cursor; Object[] es = items; if (es == null || i < 0 || i >= fence || i >= es.length) throw new NoSuchElementException(); @SuppressWarnings("unchecked") E e = (E)es[i]; lastRet = i; cursor = i + 1; if (!lock.validate(seq)) throw new ConcurrentModificationException(); return e; } public E previous() { int i = cursor - 1; Object[] es = items; if (es == null || i < 0 || i >= fence || i >= es.length) throw new NoSuchElementException(); @SuppressWarnings("unchecked") E e = (E)es[i]; lastRet = i; cursor = i; if (!lock.validate(seq)) throw new ConcurrentModificationException(); return e; } public void remove() { int i = lastRet; if (i < 0) throw new IllegalStateException(); if ((seq = lock.tryConvertToWriteLock(seq)) == 0) throw new ConcurrentModificationException(); try { list.rawRemoveAt(i); fence = list.count; cursor = i; lastRet = -1; } finally { seq = lock.tryConvertToOptimisticRead(seq); } } public void set(E e) { int i = lastRet; Object[] es = items; if (es == null || i < 0 | i >= fence) throw new IllegalStateException(); if ((seq = lock.tryConvertToWriteLock(seq)) == 0) throw new ConcurrentModificationException(); try { es[i] = e; } finally { seq = lock.tryConvertToOptimisticRead(seq); } } public void add(E e) { int i = cursor; if (i < 0) throw new IllegalStateException(); if ((seq = lock.tryConvertToWriteLock(seq)) == 0) throw new ConcurrentModificationException(); try { list.rawAddAt(i, e); items = list.array; fence = list.count; cursor = i + 1; lastRet = -1; } finally { seq = lock.tryConvertToOptimisticRead(seq); } } public boolean hasMoreElements() { return hasNext(); } public E nextElement() { return next(); } }
0true
src_main_java_jsr166e_extra_ReadMostlyVector.java
103
public class ODynamicFactoryInverse<K, V> extends ODynamicFactory<K, V> { protected Map<V, K> inverseRegistry = new HashMap<V, K>(); public K getInverse(V iValue) { return inverseRegistry.get(iValue); } @Override public void register(K iKey, V iValue) { super.register(iKey, iValue); inverseRegistry.put(iValue, iKey); } @Override public void unregister(K iKey) { V value = get(iKey); if (value == null) return; super.unregister(iKey); inverseRegistry.remove(value); } }
0true
commons_src_main_java_com_orientechnologies_common_factory_ODynamicFactoryInverse.java
1,915
@BindingAnnotation @Target({FIELD, PARAMETER, METHOD}) @Retention(RUNTIME) public @interface Assisted { /** * The unique name for this parameter. This is matched to the {@literal @Assisted} constructor * parameter with the same value. Names are not necessary when the parameter types are distinct. */ String value() default ""; }
0true
src_main_java_org_elasticsearch_common_inject_assistedinject_Assisted.java
3,062
public static class DeletionPolicySettings { public static final String TYPE = "index.deletionpolicy.type"; }
0true
src_main_java_org_elasticsearch_index_deletionpolicy_DeletionPolicyModule.java
30
final class KeyValue { private final String feedID; private final long timestamp; KeyValue(String feedID, long timestamp) { this.feedID = feedID; this.timestamp = timestamp; } String getFeedID() { return feedID; } long getTimestamp() { return timestamp; } }
0true
timeSequenceFeedAggregator_src_main_java_gov_nasa_arc_mct_buffer_disk_internal_KeyValue.java
1,014
public class OStringSerializerEmbedded implements OStringSerializer { public static final OStringSerializerEmbedded INSTANCE = new OStringSerializerEmbedded(); public static final String NAME = "em"; /** * Re-Create any object if the class has a public constructor that accepts a String as unique parameter. */ public Object fromStream(final String iStream) { if (iStream == null || iStream.length() == 0) // NULL VALUE return null; final OSerializableStream instance = new ODocument(); instance.fromStream(OBinaryProtocol.string2bytes(iStream)); return instance; } /** * Serialize the class name size + class name + object content * * @param iValue */ public StringBuilder toStream(final StringBuilder iOutput, Object iValue) { if (iValue != null) { if (!(iValue instanceof OSerializableStream)) throw new OSerializationException("Cannot serialize the object since it's not implements the OSerializableStream interface"); OSerializableStream stream = (OSerializableStream) iValue; iOutput.append(iValue.getClass().getName()); iOutput.append(OStreamSerializerHelper.SEPARATOR); iOutput.append(OBinaryProtocol.bytes2string(stream.toStream())); } return iOutput; } public String getName() { return NAME; } }
0true
core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_string_OStringSerializerEmbedded.java
277
public class VersionTests extends ElasticsearchTestCase { @Test public void testVersions() throws Exception { assertThat(V_0_20_0.before(V_0_90_0), is(true)); assertThat(V_0_20_0.before(V_0_20_0), is(false)); assertThat(V_0_90_0.before(V_0_20_0), is(false)); assertThat(V_0_20_0.onOrBefore(V_0_90_0), is(true)); assertThat(V_0_20_0.onOrBefore(V_0_20_0), is(true)); assertThat(V_0_90_0.onOrBefore(V_0_20_0), is(false)); assertThat(V_0_20_0.after(V_0_90_0), is(false)); assertThat(V_0_20_0.after(V_0_20_0), is(false)); assertThat(V_0_90_0.after(V_0_20_0), is(true)); assertThat(V_0_20_0.onOrAfter(V_0_90_0), is(false)); assertThat(V_0_20_0.onOrAfter(V_0_20_0), is(true)); assertThat(V_0_90_0.onOrAfter(V_0_20_0), is(true)); } @Test public void testVersionConstantPresent() { assertThat(Version.CURRENT, sameInstance(Version.fromId(Version.CURRENT.id))); assertThat(Version.CURRENT.luceneVersion.ordinal(), equalTo(org.apache.lucene.util.Version.LUCENE_CURRENT.ordinal() - 1)); final int iters = atLeast(20); for (int i = 0; i < iters; i++) { Version version = randomVersion(); assertThat(version, sameInstance(Version.fromId(version.id))); assertThat(version.luceneVersion, sameInstance(Version.fromId(version.id).luceneVersion)); } } }
0true
src_test_java_org_elasticsearch_VersionTests.java
1,162
public class OSQLMethodToUpperCase extends OAbstractSQLMethod { public static final String NAME = "touppercase"; public OSQLMethodToUpperCase() { super(NAME); } @Override public Object execute(OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iMethodParams) { ioResult = ioResult != null ? ioResult.toString().toUpperCase() : null; return ioResult; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodToUpperCase.java
2,204
public class XBooleanFilter extends Filter implements Iterable<FilterClause> { final List<FilterClause> clauses = new ArrayList<FilterClause>(); /** * Returns the a DocIdSetIterator representing the Boolean composition * of the filters that have been added. */ @Override public DocIdSet getDocIdSet(AtomicReaderContext context, Bits acceptDocs) throws IOException { FixedBitSet res = null; final AtomicReader reader = context.reader(); // optimize single case... if (clauses.size() == 1) { FilterClause clause = clauses.get(0); DocIdSet set = clause.getFilter().getDocIdSet(context, acceptDocs); if (clause.getOccur() == Occur.MUST_NOT) { if (DocIdSets.isEmpty(set)) { return new AllDocIdSet(reader.maxDoc()); } else { return new NotDocIdSet(set, reader.maxDoc()); } } // SHOULD or MUST, just return the set... if (DocIdSets.isEmpty(set)) { return null; } return set; } // first, go over and see if we can shortcut the execution // and gather Bits if we need to List<ResultClause> results = new ArrayList<ResultClause>(clauses.size()); boolean hasShouldClauses = false; boolean hasNonEmptyShouldClause = false; boolean hasMustClauses = false; boolean hasMustNotClauses = false; for (int i = 0; i < clauses.size(); i++) { FilterClause clause = clauses.get(i); DocIdSet set = clause.getFilter().getDocIdSet(context, acceptDocs); if (clause.getOccur() == Occur.MUST) { hasMustClauses = true; if (DocIdSets.isEmpty(set)) { return null; } } else if (clause.getOccur() == Occur.SHOULD) { hasShouldClauses = true; if (DocIdSets.isEmpty(set)) { continue; } hasNonEmptyShouldClause = true; } else if (clause.getOccur() == Occur.MUST_NOT) { hasMustNotClauses = true; if (DocIdSets.isEmpty(set)) { // we mark empty ones as null for must_not, handle it in the next run... results.add(new ResultClause(null, null, clause)); continue; } } Bits bits = null; if (!DocIdSets.isFastIterator(set)) { bits = set.bits(); } results.add(new ResultClause(set, bits, clause)); } if (hasShouldClauses && !hasNonEmptyShouldClause) { return null; } // now, go over the clauses and apply the "fast" ones first... hasNonEmptyShouldClause = false; boolean hasBits = false; // But first we need to handle the "fast" should clauses, otherwise a should clause can unset docs // that don't match with a must or must_not clause. List<ResultClause> fastOrClauses = new ArrayList<ResultClause>(); for (int i = 0; i < results.size(); i++) { ResultClause clause = results.get(i); // we apply bits in based ones (slow) in the second run if (clause.bits != null) { hasBits = true; continue; } if (clause.clause.getOccur() == Occur.SHOULD) { if (hasMustClauses || hasMustNotClauses) { fastOrClauses.add(clause); } else if (res == null) { DocIdSetIterator it = clause.docIdSet.iterator(); if (it != null) { hasNonEmptyShouldClause = true; res = new FixedBitSet(reader.maxDoc()); res.or(it); } } else { DocIdSetIterator it = clause.docIdSet.iterator(); if (it != null) { hasNonEmptyShouldClause = true; res.or(it); } } } } // Now we safely handle the "fast" must and must_not clauses. for (int i = 0; i < results.size(); i++) { ResultClause clause = results.get(i); // we apply bits in based ones (slow) in the second run if (clause.bits != null) { hasBits = true; continue; } if (clause.clause.getOccur() == Occur.MUST) { DocIdSetIterator it = clause.docIdSet.iterator(); if (it == null) { return null; } if (res == null) { res = new FixedBitSet(reader.maxDoc()); res.or(it); } else { res.and(it); } } else if (clause.clause.getOccur() == Occur.MUST_NOT) { if (res == null) { res = new FixedBitSet(reader.maxDoc()); res.set(0, reader.maxDoc()); // NOTE: may set bits on deleted docs } if (clause.docIdSet != null) { DocIdSetIterator it = clause.docIdSet.iterator(); if (it != null) { res.andNot(it); } } } } if (!hasBits) { if (!fastOrClauses.isEmpty()) { DocIdSetIterator it = res.iterator(); at_least_one_should_clause_iter: for (int setDoc = it.nextDoc(); setDoc != DocIdSetIterator.NO_MORE_DOCS; setDoc = it.nextDoc()) { for (ResultClause fastOrClause : fastOrClauses) { DocIdSetIterator clauseIterator = fastOrClause.iterator(); if (clauseIterator == null) { continue; } if (iteratorMatch(clauseIterator, setDoc)) { hasNonEmptyShouldClause = true; continue at_least_one_should_clause_iter; } } res.clear(setDoc); } } if (hasShouldClauses && !hasNonEmptyShouldClause) { return null; } else { return res; } } // we have some clauses with bits, apply them... // we let the "res" drive the computation, and check Bits for that List<ResultClause> slowOrClauses = new ArrayList<ResultClause>(); for (int i = 0; i < results.size(); i++) { ResultClause clause = results.get(i); if (clause.bits == null) { continue; } if (clause.clause.getOccur() == Occur.SHOULD) { if (hasMustClauses || hasMustNotClauses) { slowOrClauses.add(clause); } else { if (res == null) { DocIdSetIterator it = clause.docIdSet.iterator(); if (it == null) { continue; } hasNonEmptyShouldClause = true; res = new FixedBitSet(reader.maxDoc()); res.or(it); } else { for (int doc = 0; doc < reader.maxDoc(); doc++) { if (!res.get(doc) && clause.bits.get(doc)) { hasNonEmptyShouldClause = true; res.set(doc); } } } } } else if (clause.clause.getOccur() == Occur.MUST) { if (res == null) { // nothing we can do, just or it... res = new FixedBitSet(reader.maxDoc()); DocIdSetIterator it = clause.docIdSet.iterator(); if (it == null) { return null; } res.or(it); } else { Bits bits = clause.bits; // use the "res" to drive the iteration DocIdSetIterator it = res.iterator(); for (int doc = it.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = it.nextDoc()) { if (!bits.get(doc)) { res.clear(doc); } } } } else if (clause.clause.getOccur() == Occur.MUST_NOT) { if (res == null) { res = new FixedBitSet(reader.maxDoc()); res.set(0, reader.maxDoc()); // NOTE: may set bits on deleted docs DocIdSetIterator it = clause.docIdSet.iterator(); if (it != null) { res.andNot(it); } } else { Bits bits = clause.bits; // let res drive the iteration DocIdSetIterator it = res.iterator(); for (int doc = it.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = it.nextDoc()) { if (bits.get(doc)) { res.clear(doc); } } } } } // From a boolean_logic behavior point of view a should clause doesn't have impact on a bool filter if there // is already a must or must_not clause. However in the current ES bool filter behaviour at least one should // clause must match in order for a doc to be a match. What we do here is checking if matched docs match with // any should filter. TODO: Add an option to have disable minimum_should_match=1 behaviour if (!slowOrClauses.isEmpty() || !fastOrClauses.isEmpty()) { DocIdSetIterator it = res.iterator(); at_least_one_should_clause_iter: for (int setDoc = it.nextDoc(); setDoc != DocIdSetIterator.NO_MORE_DOCS; setDoc = it.nextDoc()) { for (ResultClause fastOrClause : fastOrClauses) { DocIdSetIterator clauseIterator = fastOrClause.iterator(); if (clauseIterator == null) { continue; } if (iteratorMatch(clauseIterator, setDoc)) { hasNonEmptyShouldClause = true; continue at_least_one_should_clause_iter; } } for (ResultClause slowOrClause : slowOrClauses) { if (slowOrClause.bits.get(setDoc)) { hasNonEmptyShouldClause = true; continue at_least_one_should_clause_iter; } } res.clear(setDoc); } } if (hasShouldClauses && !hasNonEmptyShouldClause) { return null; } else { return res; } } /** * Adds a new FilterClause to the Boolean Filter container * * @param filterClause A FilterClause object containing a Filter and an Occur parameter */ public void add(FilterClause filterClause) { clauses.add(filterClause); } public final void add(Filter filter, Occur occur) { add(new FilterClause(filter, occur)); } /** * Returns the list of clauses */ public List<FilterClause> clauses() { return clauses; } /** * Returns an iterator on the clauses in this query. It implements the {@link Iterable} interface to * make it possible to do: * <pre class="prettyprint">for (FilterClause clause : booleanFilter) {}</pre> */ public final Iterator<FilterClause> iterator() { return clauses().iterator(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if ((obj == null) || (obj.getClass() != this.getClass())) { return false; } final XBooleanFilter other = (XBooleanFilter) obj; return clauses.equals(other.clauses); } @Override public int hashCode() { return 657153718 ^ clauses.hashCode(); } /** * Prints a user-readable version of this Filter. */ @Override public String toString() { final StringBuilder buffer = new StringBuilder("BooleanFilter("); final int minLen = buffer.length(); for (final FilterClause c : clauses) { if (buffer.length() > minLen) { buffer.append(' '); } buffer.append(c); } return buffer.append(')').toString(); } static class ResultClause { public final DocIdSet docIdSet; public final Bits bits; public final FilterClause clause; DocIdSetIterator docIdSetIterator; ResultClause(DocIdSet docIdSet, Bits bits, FilterClause clause) { this.docIdSet = docIdSet; this.bits = bits; this.clause = clause; } /** * @return An iterator, but caches it for subsequent usage. Don't use if iterator is consumed in one invocation. */ DocIdSetIterator iterator() throws IOException { if (docIdSetIterator != null) { return docIdSetIterator; } else { return docIdSetIterator = docIdSet.iterator(); } } } static boolean iteratorMatch(DocIdSetIterator docIdSetIterator, int target) throws IOException { assert docIdSetIterator != null; int current = docIdSetIterator.docID(); if (current == DocIdSetIterator.NO_MORE_DOCS || target < current) { return false; } else { if (current == target) { return true; } else { return docIdSetIterator.advance(target) == target; } } } }
0true
src_main_java_org_elasticsearch_common_lucene_search_XBooleanFilter.java
1,717
@Service("blDynamicEntityRemoteService") @Transactional(value="blTransactionManager", rollbackFor = ServiceException.class) public class DynamicEntityRemoteService implements DynamicEntityService, DynamicEntityRemote, ApplicationContextAware { public static final String DEFAULTPERSISTENCEMANAGERREF = "blPersistenceManager"; private static final Log LOG = LogFactory.getLog(DynamicEntityRemoteService.class); protected static final Map<BatchPersistencePackage, BatchDynamicResultSet> METADATA_CACHE = MapUtils.synchronizedMap(new LRUMap<BatchPersistencePackage, BatchDynamicResultSet>(100, 1000)); protected String persistenceManagerRef = DEFAULTPERSISTENCEMANAGERREF; private ApplicationContext applicationContext; @Resource(name="blExploitProtectionService") protected ExploitProtectionService exploitProtectionService; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } protected ServiceException recreateSpecificServiceException(ServiceException e, String message, Throwable cause) { try { ServiceException newException; if (cause == null) { Constructor constructor = e.getClass().getConstructor(String.class); newException = (ServiceException) constructor.newInstance(message); } else { Constructor constructor = e.getClass().getConstructor(String.class, Throwable.class); newException = (ServiceException) constructor.newInstance(message, cause); } return newException; } catch (Exception e1) { throw new RuntimeException(e1); } } @Override public DynamicResultSet inspect(PersistencePackage persistencePackage) throws ServiceException { String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname(); try { PersistenceManager persistenceManager = (PersistenceManager) applicationContext.getBean(persistenceManagerRef); persistenceManager.setTargetMode(TargetModeType.SANDBOX); return persistenceManager.inspect(persistencePackage); } catch (ServiceException e) { String message = exploitProtectionService.cleanString(e.getMessage()); throw recreateSpecificServiceException(e, message, e.getCause()); } catch (Exception e) { LOG.error("Problem inspecting results for " + ceilingEntityFullyQualifiedClassname, e); throw new ServiceException(exploitProtectionService.cleanString("Unable to fetch results for " + ceilingEntityFullyQualifiedClassname), e); } } @Override public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto) throws ServiceException { try { PersistenceManager persistenceManager = (PersistenceManager) applicationContext.getBean(persistenceManagerRef); persistenceManager.setTargetMode(TargetModeType.SANDBOX); return persistenceManager.fetch(persistencePackage, cto); } catch (ServiceException e) { LOG.error("Problem fetching results for " + persistencePackage.getCeilingEntityFullyQualifiedClassname(), e); String message = exploitProtectionService.cleanString(e.getMessage()); throw recreateSpecificServiceException(e, message, e.getCause()); } } protected void cleanEntity(Entity entity) throws ServiceException { Property currentProperty = null; try { for (Property property : entity.getProperties()) { currentProperty = property; property.setRawValue(property.getValue()); property.setValue(exploitProtectionService.cleanStringWithResults(property.getValue())); property.setUnHtmlEncodedValue(StringEscapeUtils.unescapeHtml(property.getValue())); } } catch (CleanStringException e) { StringBuilder sb = new StringBuilder(); for (int j=0;j<e.getCleanResults().getNumberOfErrors();j++){ sb.append(j+1); sb.append(") "); sb.append((String) e.getCleanResults().getErrorMessages().get(j)); sb.append("\n"); } sb.append("\nNote - "); sb.append(exploitProtectionService.getAntiSamyPolicyFileLocation()); sb.append(" policy in effect. Set a new policy file to modify validation behavior/strictness."); entity.addValidationError(currentProperty.getName(), sb.toString()); } } @Override public Entity add(PersistencePackage persistencePackage) throws ServiceException { cleanEntity(persistencePackage.getEntity()); if (persistencePackage.getEntity().isValidationFailure()) { return persistencePackage.getEntity(); } try { PersistenceManager persistenceManager = (PersistenceManager) applicationContext.getBean(persistenceManagerRef); persistenceManager.setTargetMode(TargetModeType.SANDBOX); return persistenceManager.add(persistencePackage); } catch (ServiceException e) { //immediately throw validation exceptions without printing a stack trace if (e instanceof ValidationException) { throw e; } else if (e.getCause() instanceof ValidationException) { throw (ValidationException) e.getCause(); } String message = exploitProtectionService.cleanString(e.getMessage()); LOG.error("Problem adding new " + persistencePackage.getCeilingEntityFullyQualifiedClassname(), e); throw recreateSpecificServiceException(e, message, e.getCause()); } } @Override public Entity update(PersistencePackage persistencePackage) throws ServiceException { cleanEntity(persistencePackage.getEntity()); if (persistencePackage.getEntity().isValidationFailure()) { return persistencePackage.getEntity(); } try { PersistenceManager persistenceManager = (PersistenceManager) applicationContext.getBean(persistenceManagerRef); persistenceManager.setTargetMode(TargetModeType.SANDBOX); return persistenceManager.update(persistencePackage); } catch (ServiceException e) { //immediately throw validation exceptions without printing a stack trace if (e instanceof ValidationException) { throw e; } else if (e.getCause() instanceof ValidationException) { throw (ValidationException) e.getCause(); } LOG.error("Problem updating " + persistencePackage.getCeilingEntityFullyQualifiedClassname(), e); String message = exploitProtectionService.cleanString(e.getMessage()); throw recreateSpecificServiceException(e, message, e.getCause()); } } @Override public void remove(PersistencePackage persistencePackage) throws ServiceException { try { PersistenceManager persistenceManager = (PersistenceManager) applicationContext.getBean(persistenceManagerRef); persistenceManager.setTargetMode(TargetModeType.SANDBOX); persistenceManager.remove(persistencePackage); } catch (ServiceException e) { LOG.error("Problem removing " + persistencePackage.getCeilingEntityFullyQualifiedClassname(), e); String message = exploitProtectionService.cleanString(e.getMessage()); throw recreateSpecificServiceException(e, message, e.getCause()); } } @Override public String getPersistenceManagerRef() { return persistenceManagerRef; } @Override public void setPersistenceManagerRef(String persistenceManagerRef) { this.persistenceManagerRef = persistenceManagerRef; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_DynamicEntityRemoteService.java
502
public class ThemeDTO implements Theme { public String path = ""; public String name = ""; public ThemeDTO() { // empty constructor } public ThemeDTO(String name, String path) { this.name = name; this.path = path; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
0true
common_src_main_java_org_broadleafcommerce_common_site_domain_ThemeDTO.java
435
map.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { changed.value = true; } });
0true
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedMapTest.java
1,283
esStats.submit(new Runnable() { public void run() { final ILogger logger = hazelcast.getLoggingService().getLogger(hazelcast.getName()); while (running) { try { Thread.sleep(STATS_SECONDS * 1000); int clusterSize = hazelcast.getCluster().getMembers().size(); Stats currentStats = stats.getAndReset(); logger.info("Cluster size: " + clusterSize + ", Operations per Second: " + (currentStats.total() / STATS_SECONDS)); } catch (HazelcastInstanceNotActiveException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } } });
0true
hazelcast_src_main_java_com_hazelcast_examples_LongRunningTest.java
1,502
@Component("blCartStateRefresher") public class CartStateRefresher implements ApplicationListener<OrderPersistedEvent> { /** * <p>Resets {@link CartState} with the newly persisted Order. If {@link CartState} was empty, this will only update it if * the {@link Order} that has been persisted is the {@link OrderStatus#IN_PROCESS} {@link Order} for the active * {@link Customer} (as determined by {@link CustomerState#getCustomer()}. If {@link CartState} was <b>not</b> empty, * then it will be replaced only if this newly persisted {@link Order} has the same id.</p> * * <p>This ensures that whatever is returned from {@link CartState#getCart()} will always be the most up-to-date * database version (meaning, safe to write to the DB).</p> */ @Override public void onApplicationEvent(final OrderPersistedEvent event) { WebRequest request = BroadleafRequestContext.getBroadleafRequestContext().getWebRequest(); if (request != null) { Order dbOrder = event.getOrder(); //Update the cart state ONLY IF the IDs of the newly persisted order and whatever is already in CartState match boolean emptyCartState = CartState.getCart() == null || CartState.getCart() instanceof NullOrderImpl; if (emptyCartState) { //If cart state is empty, set it to this newly persisted order if it's the active Customer's cart if (CustomerState.getCustomer() != null && CustomerState.getCustomer().getId().equals(dbOrder.getCustomer().getId()) && OrderStatus.IN_PROCESS.equals(dbOrder.getStatus())) { CartState.setCart(dbOrder); } } else if (CartState.getCart().getId().equals(dbOrder.getId())) { CartState.setCart(dbOrder); } } } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_order_CartStateRefresher.java
873
public class OExecuteBlock extends OAbstractBlock { public static final String NAME = "execute"; private Object returnValue; @Override public Object processBlock(OComposableProcessor iManager, final OCommandContext iContext, final ODocument iConfig, ODocument iOutput, final boolean iReadOnly) { final Object foreach = getField(iContext, iConfig, "foreach", false); String returnType = (String) getFieldOfClass(iContext, iConfig, "returnType", String.class); returnValue = null; if (returnType == null) returnType = "last"; else if ("list".equalsIgnoreCase(returnType)) returnValue = new ArrayList<Object>(); else if ("set".equalsIgnoreCase(returnType)) returnValue = new HashSet<Object>(); int iterated = 0; final Object beginClause = getField(iContext, iConfig, "begin"); if (beginClause != null) executeBlock(iManager, iContext, "begin", beginClause, iOutput, iReadOnly, returnType, returnValue); if (foreach != null) { Object result; if (foreach instanceof ODocument) result = delegate("foreach", iManager, (ODocument) foreach, iContext, iOutput, iReadOnly); else if (foreach instanceof Map) result = ((Map<?, ?>) foreach).values(); else result = foreach; if (!OMultiValue.isIterable(result)) throw new OProcessException("Result of 'foreach' block (" + foreach + ") must be iterable but found " + result.getClass()); for (Object current : OMultiValue.getMultiValueIterable(result)) { if (current instanceof Map.Entry) current = ((Entry<?, ?>) current).getValue(); assignVariable(iContext, "current", current); assignVariable(iContext, "currentIndex", iterated); debug(iContext, "Executing..."); final Object doClause = getRequiredField(iContext, iConfig, "do"); returnValue = executeDo(iManager, iContext, doClause, returnType, returnValue, iOutput, iReadOnly); debug(iContext, "Done"); iterated++; } } else { debug(iContext, "Executing..."); final Object doClause = getRequiredField(iContext, iConfig, "do"); returnValue = executeDo(iManager, iContext, doClause, returnType, returnValue, iOutput, iReadOnly); debug(iContext, "Done"); } final Object endClause = getField(iContext, iConfig, "end"); if (endClause != null) executeBlock(iManager, iContext, "end", endClause, iOutput, iReadOnly, returnType, returnValue); debug(iContext, "Executed %d iteration and returned type %s", iterated, returnType); return returnValue; } private Object executeDo(OComposableProcessor iManager, final OCommandContext iContext, final Object iDoClause, final String returnType, Object returnValue, ODocument iOutput, final boolean iReadOnly) { int i = 0; if (isBlock(iDoClause)) { returnValue = executeBlock(iManager, iContext, "do", iDoClause, iOutput, iReadOnly, returnType, returnValue); } else for (Object item : OMultiValue.getMultiValueIterable(iDoClause)) { final String blockId = "do[" + i + "]"; returnValue = executeBlock(iManager, iContext, blockId, item, iOutput, iReadOnly, returnType, returnValue); ++i; } return returnValue; } @SuppressWarnings("unchecked") private Object executeBlock(OComposableProcessor iManager, final OCommandContext iContext, final String iName, final Object iValue, ODocument iOutput, final boolean iReadOnly, final String returnType, Object returnValue) { Boolean merge = iValue instanceof ODocument ? getFieldOfClass(iContext, (ODocument) iValue, "merge", Boolean.class) : Boolean.FALSE; if (merge == null) merge = Boolean.FALSE; Object result; if (isBlock(iValue)) { // EXECUTE SINGLE BLOCK final ODocument value = (ODocument) iValue; result = delegate(iName, iManager, value, iContext, iOutput, iReadOnly); if (value.containsField("return")) return returnValue; } else { // EXECUTE ENTIRE PROCESS try { result = iManager.processFromFile(iName, iContext, iReadOnly); } catch (Exception e) { throw new OProcessException("Error on processing '" + iName + "' field of '" + getName() + "' block", e); } } if ("last".equalsIgnoreCase(returnType)) returnValue = result; else if (result != null && ("list".equalsIgnoreCase(returnType) || "set".equalsIgnoreCase(returnType))) { if (result instanceof Collection<?> && merge) { debug(iContext, "Merging content of collection with size %d with the master with size %d", ((Collection<? extends Object>) result).size(), ((Collection<? extends Object>) returnValue).size()); ((Collection<Object>) returnValue).addAll((Collection<? extends Object>) result); } else ((Collection<Object>) returnValue).add(result); } return returnValue; } @Override public String getName() { return NAME; } public Object getReturnValue() { return returnValue; } public void setReturnValue(Object returnValue) { this.returnValue = returnValue; } }
0true
core_src_main_java_com_orientechnologies_orient_core_processor_block_OExecuteBlock.java
823
return getDatabase().getStorage().callInLock(new Callable<Integer>() { @Override public Integer call() throws Exception { return document.getRecordVersion().getCounter(); } }, false);
0true
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OSchemaShared.java
1,309
public class PositionEntry { private final long pageIndex; private final int recordPosition; public PositionEntry(long pageIndex, int recordPosition) { this.pageIndex = pageIndex; this.recordPosition = recordPosition; } public long getPageIndex() { return pageIndex; } public int getRecordPosition() { return recordPosition; } }
0true
core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_OClusterPositionMapBucket.java
1,596
static class Slf4jLogger extends AbstractLogger { private final Logger logger; public Slf4jLogger(Logger logger) { this.logger = logger; } @Override public void log(Level level, String message) { if (Level.FINEST == level) { logger.debug(message); } else if (Level.SEVERE == level) { logger.error(message); } else if (Level.WARNING == level) { logger.warn(message); } else { logger.info(message); } } @Override public Level getLevel() { if (logger.isErrorEnabled()) { return Level.SEVERE; } else if (logger.isWarnEnabled()) { return Level.WARNING; } else if (logger.isInfoEnabled()) { return Level.INFO; } else { return Level.FINEST; } } @Override public boolean isLoggable(Level level) { if (Level.OFF == level) { return false; } else if (Level.FINEST == level) { return logger.isDebugEnabled(); } else if (Level.INFO == level) { return logger.isInfoEnabled(); } else if (Level.WARNING == level) { return logger.isWarnEnabled(); } else if (Level.SEVERE == level) { return logger.isErrorEnabled(); } else { return logger.isInfoEnabled(); } } @Override public void log(Level level, String message, Throwable thrown) { if (Level.FINEST == level) { logger.debug(message, thrown); } else if (Level.INFO == level) { logger.info(message, thrown); } else if (Level.WARNING == level) { logger.warn(message, thrown); } else if (Level.SEVERE == level) { logger.error(message, thrown); } else { logger.info(message, thrown); } } @Override public void log(LogEvent logEvent) { LogRecord logRecord = logEvent.getLogRecord(); Level level = logEvent.getLogRecord().getLevel(); String message = logRecord.getMessage(); Throwable thrown = logRecord.getThrown(); log(level, message, thrown); } }
0true
hazelcast_src_main_java_com_hazelcast_logging_Slf4jFactory.java
454
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
688
public class CollectionEventFilter implements EventFilter, IdentifiedDataSerializable { boolean includeValue; public CollectionEventFilter() { } public CollectionEventFilter(boolean includeValue) { this.includeValue = includeValue; } public boolean isIncludeValue() { return includeValue; } @Override public boolean eval(Object arg) { return false; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeBoolean(includeValue); } @Override public void readData(ObjectDataInput in) throws IOException { includeValue = in.readBoolean(); } @Override public int getFactoryId() { return CollectionDataSerializerHook.F_ID; } @Override public int getId() { return CollectionDataSerializerHook.COLLECTION_EVENT_FILTER; } }
1no label
hazelcast_src_main_java_com_hazelcast_collection_CollectionEventFilter.java
267
return new RecordIterator<Entry>() { final Iterator<Entry> columns = CassandraHelper.makeEntryIterator(mostRecentRow.getColumns(), entryGetter, columnSlice.getSliceEnd(), columnSlice.getLimit()); @Override public boolean hasNext() { ensureOpen(); return columns.hasNext(); } @Override public Entry next() { ensureOpen(); return columns.next(); } @Override public void close() { closeIterator(); } @Override public void remove() { throw new UnsupportedOperationException(); } };
0true
titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_thrift_CassandraThriftKeyColumnValueStore.java
1,201
public class OSQLAsynchQuery<T extends Object> extends OSQLQuery<T> implements OCommandRequestAsynch { private static final long serialVersionUID = 1L; protected int resultCount = 0; /** * Empty constructor for unmarshalling. */ public OSQLAsynchQuery() { } public OSQLAsynchQuery(final String iText) { this(iText, null); } public OSQLAsynchQuery(final String iText, final OCommandResultListener iResultListener) { this(iText, -1, iResultListener); } public OSQLAsynchQuery(final String iText, final int iLimit, final String iFetchPlan, final Map<Object, Object> iArgs, final OCommandResultListener iResultListener) { this(iText, iLimit, iResultListener); this.fetchPlan = iFetchPlan; this.parameters = iArgs; } public OSQLAsynchQuery(final String iText, final int iLimit, final OCommandResultListener iResultListener) { super(iText); limit = iLimit; resultListener = iResultListener; } @SuppressWarnings("unchecked") public <RET> RET execute2(final String iText, final Object... iArgs) { text = iText; return (RET) execute(iArgs); } public T executeFirst() { execute(1); return null; } @Override public boolean isAsynchronous() { return true; } }
0true
core_src_main_java_com_orientechnologies_orient_core_sql_query_OSQLAsynchQuery.java
98
public class ODirectMemoryViolationException extends OException { public ODirectMemoryViolationException(String message) { super(message); } }
0true
commons_src_main_java_com_orientechnologies_common_directmemory_ODirectMemoryViolationException.java
292
public class NeoStoreXaDataSource extends LogBackedXaDataSource implements NeoStoreProvider { public static final String DEFAULT_DATA_SOURCE_NAME = "nioneodb"; @SuppressWarnings("deprecation") public static abstract class Configuration extends LogBackedXaDataSource.Configuration { public static final Setting<Boolean> read_only= GraphDatabaseSettings.read_only; public static final Setting<File> store_dir = InternalAbstractGraphDatabase.Configuration.store_dir; public static final Setting<File> neo_store = InternalAbstractGraphDatabase.Configuration.neo_store; public static final Setting<File> logical_log = InternalAbstractGraphDatabase.Configuration.logical_log; } public static final byte BRANCH_ID[] = UTF8.encode( "414141" ); public static final String LOGICAL_LOG_DEFAULT_NAME = "nioneo_logical.log"; private final StringLogger msgLog; private final Logging logging; private final AbstractTransactionManager txManager; private final DependencyResolver dependencyResolver; private final TransactionStateFactory stateFactory; @SuppressWarnings("deprecation") private final TransactionInterceptorProviders providers; private final TokenNameLookup tokenNameLookup; private final PropertyKeyTokenHolder propertyKeyTokens; private final LabelTokenHolder labelTokens; private final RelationshipTypeTokenHolder relationshipTypeTokens; private final PersistenceManager persistenceManager; private final LockManager lockManager; private final SchemaWriteGuard schemaWriteGuard; private final StoreFactory storeFactory; private final XaFactory xaFactory; private final JobScheduler scheduler; private final UpdateableSchemaState updateableSchemaState; private final Config config; private final LockService locks; private LifeSupport life; private KernelAPI kernel; private NeoStore neoStore; private IndexingService indexingService; private SchemaIndexProvider indexProvider; private XaContainer xaContainer; private ArrayMap<Class<?>,Store> idGenerators; private IntegrityValidator integrityValidator; private NeoStoreFileListing fileListing; private File storeDir; private boolean readOnly; private boolean logApplied = false; private CacheAccessBackDoor cacheAccess; private PersistenceCache persistenceCache; private SchemaCache schemaCache; private LabelScanStore labelScanStore; private final IndexingService.Monitor indexingServiceMonitor; private enum Diagnostics implements DiagnosticsExtractor<NeoStoreXaDataSource> { NEO_STORE_VERSIONS( "Store versions:" ) { @Override void dump( NeoStoreXaDataSource source, StringLogger.LineLogger log ) { source.neoStore.logVersions( log ); } }, NEO_STORE_ID_USAGE( "Id usage:" ) { @Override void dump( NeoStoreXaDataSource source, StringLogger.LineLogger log ) { source.neoStore.logIdUsage( log ); } }, PERSISTENCE_WINDOW_POOL_STATS( "Persistence Window Pool stats:" ) { @Override void dump( NeoStoreXaDataSource source, StringLogger.LineLogger log ) { source.neoStore.logAllWindowPoolStats( log ); } @Override boolean applicable( DiagnosticsPhase phase ) { return phase.isExplicitlyRequested(); } }; private final String message; private Diagnostics( String message ) { this.message = message; } @Override public void dumpDiagnostics( final NeoStoreXaDataSource source, DiagnosticsPhase phase, StringLogger log ) { if ( applicable( phase ) ) { log.logLongMessage( message, new Visitor<StringLogger.LineLogger, RuntimeException>() { @Override public boolean visit( StringLogger.LineLogger logger ) { dump( source, logger ); return false; } }, true ); } } boolean applicable( DiagnosticsPhase phase ) { return phase.isInitialization() || phase.isExplicitlyRequested(); } abstract void dump( NeoStoreXaDataSource source, StringLogger.LineLogger log ); } /** * Creates a <CODE>NeoStoreXaDataSource</CODE> using configuration from * <CODE>params</CODE>. First the map is checked for the parameter * <CODE>config</CODE>. * If that parameter exists a config file with that value is loaded (via * {@link Properties#load}). Any parameter that exist in the config file * and in the map passed into this constructor will take the value from the * map. * <p> * If <CODE>config</CODE> parameter is set but file doesn't exist an * <CODE>IOException</CODE> is thrown. If any problem is found with that * configuration file or Neo4j store can't be loaded an <CODE>IOException is * thrown</CODE>. * * Note that the tremendous number of dependencies for this class, clearly, is an architecture smell. It is part * of the ongoing work on introducing the Kernel API, where components that were previously spread throughout the * core API are now slowly accumulating in the Kernel implementation. Over time, these components should be * refactored into bigger components that wrap the very granular things we depend on here. */ public NeoStoreXaDataSource( Config config, StoreFactory sf, StringLogger stringLogger, XaFactory xaFactory, TransactionStateFactory stateFactory, @SuppressWarnings("deprecation") TransactionInterceptorProviders providers, JobScheduler scheduler, Logging logging, UpdateableSchemaState updateableSchemaState, TokenNameLookup tokenNameLookup, DependencyResolver dependencyResolver, AbstractTransactionManager txManager, PropertyKeyTokenHolder propertyKeyTokens, LabelTokenHolder labelTokens, RelationshipTypeTokenHolder relationshipTypeTokens, PersistenceManager persistenceManager, LockManager lockManager, SchemaWriteGuard schemaWriteGuard, IndexingService.Monitor indexingServiceMonitor ) { super( BRANCH_ID, DEFAULT_DATA_SOURCE_NAME ); this.config = config; this.stateFactory = stateFactory; this.tokenNameLookup = tokenNameLookup; this.dependencyResolver = dependencyResolver; this.providers = providers; this.scheduler = scheduler; this.logging = logging; this.txManager = txManager; this.propertyKeyTokens = propertyKeyTokens; this.labelTokens = labelTokens; this.relationshipTypeTokens = relationshipTypeTokens; this.persistenceManager = persistenceManager; this.lockManager = lockManager; this.schemaWriteGuard = schemaWriteGuard; this.indexingServiceMonitor = indexingServiceMonitor; readOnly = config.get( Configuration.read_only ); msgLog = stringLogger; this.storeFactory = sf; this.xaFactory = xaFactory; this.updateableSchemaState = updateableSchemaState; this.locks = new ReentrantLockService(); } @Override public void init() { // We do our own internal life management: // start() does life.init() and life.start(), // stop() does life.stop() and life.shutdown(). } @Override public void start() throws IOException { life = new LifeSupport(); readOnly = config.get( Configuration.read_only ); storeDir = config.get( Configuration.store_dir ); File store = config.get( Configuration.neo_store ); storeFactory.ensureStoreExists(); final TransactionFactory tf; if ( providers.shouldInterceptCommitting() ) { tf = new InterceptingTransactionFactory(); } else { tf = new TransactionFactory(); } neoStore = storeFactory.newNeoStore( store ); schemaCache = new SchemaCache( Collections.<SchemaRule>emptyList() ); final NodeManager nodeManager = dependencyResolver.resolveDependency( NodeManager.class ); Iterator<? extends Cache<?>> caches = nodeManager.caches().iterator(); persistenceCache = new PersistenceCache( (AutoLoadingCache<NodeImpl>)caches.next(), (AutoLoadingCache<RelationshipImpl>)caches.next(), new Thunk<GraphPropertiesImpl>() { @Override public GraphPropertiesImpl evaluate() { return nodeManager.getGraphProperties(); } } ); cacheAccess = new BridgingCacheAccess( nodeManager, schemaCache, updateableSchemaState, persistenceCache ); try { indexProvider = dependencyResolver.resolveDependency( SchemaIndexProvider.class, SchemaIndexProvider.HIGHEST_PRIORITIZED_OR_NONE ); // TODO: Build a real provider map DefaultSchemaIndexProviderMap providerMap = new DefaultSchemaIndexProviderMap( indexProvider ); indexingService = life.add( new IndexingService( scheduler, providerMap, new NeoStoreIndexStoreView( locks, neoStore ), tokenNameLookup, updateableSchemaState, logging, indexingServiceMonitor ) ); integrityValidator = new IntegrityValidator( neoStore, indexingService ); xaContainer = xaFactory.newXaContainer(this, config.get( Configuration.logical_log ), new CommandFactory( neoStore, indexingService ), new NeoStoreInjectedTransactionValidator(integrityValidator), tf, stateFactory, providers, readOnly ); labelScanStore = life.add( dependencyResolver.resolveDependency( LabelScanStoreProvider.class, LabelScanStoreProvider.HIGHEST_PRIORITIZED ).getLabelScanStore() ); fileListing = new NeoStoreFileListing( xaContainer, storeDir, labelScanStore, indexingService ); kernel = life.add( new Kernel( txManager, propertyKeyTokens, labelTokens, relationshipTypeTokens, persistenceManager, lockManager, updateableSchemaState, schemaWriteGuard, indexingService, nodeManager, new Provider<NeoStore>() { @Override public NeoStore instance() { return getNeoStore(); } }, persistenceCache, schemaCache, providerMap, labelScanStore, readOnly )); life.init(); // TODO: Why isn't this done in the init() method of the indexing service? if ( !readOnly ) { neoStore.setRecoveredStatus( true ); try { indexingService.initIndexes( loadIndexRules() ); xaContainer.openLogicalLog(); } finally { neoStore.setRecoveredStatus( false ); } } if ( !xaContainer.getResourceManager().hasRecoveredTransactions() ) { neoStore.makeStoreOk(); } else { msgLog.debug( "Waiting for TM to take care of recovered " + "transactions." ); } idGenerators = new ArrayMap<>( (byte)5, false, false ); this.idGenerators.put( Node.class, neoStore.getNodeStore() ); this.idGenerators.put( Relationship.class, neoStore.getRelationshipStore() ); this.idGenerators.put( RelationshipType.class, neoStore.getRelationshipTypeStore() ); this.idGenerators.put( Label.class, neoStore.getLabelTokenStore() ); this.idGenerators.put( PropertyStore.class, neoStore.getPropertyStore() ); this.idGenerators.put( PropertyKeyTokenRecord.class, neoStore.getPropertyStore().getPropertyKeyTokenStore() ); setLogicalLogAtCreationTime( xaContainer.getLogicalLog() ); // TODO Problem here is that we don't know if recovery has been performed at this point // if it hasn't then no index recovery will be performed since the node store is still in // "not ok" state and forceGetRecord will always return place holder node records that are not in use. // This issue will certainly introduce index inconsistencies. life.start(); } catch ( Throwable e ) { // Something unexpected happened during startup try { // Close the neostore, so that locks are released properly neoStore.close(); } catch ( Exception closeException ) { msgLog.logMessage( "Couldn't close neostore after startup failure" ); } throw Exceptions.launderedException( e ); } } public NeoStore getNeoStore() { return neoStore; } public IndexingService getIndexService() { return indexingService; } public SchemaIndexProvider getIndexProvider() { return indexProvider; } public LabelScanStore getLabelScanStore() { return labelScanStore; } public LockService getLockService() { return locks; } @Override public void stop() { super.stop(); if ( !readOnly ) { forceEverything(); } life.shutdown(); xaContainer.close(); if ( logApplied ) { neoStore.rebuildIdGenerators(); logApplied = false; } neoStore.close(); msgLog.info( "NeoStore closed" ); } private void forceEverything() { neoStore.flushAll(); indexingService.flushAll(); labelScanStore.force(); } @Override public void shutdown() { // We do our own internal life management: // start() does life.init() and life.start(), // stop() does life.stop() and life.shutdown(). } public StoreId getStoreId() { return neoStore.getStoreId(); } @Override public NeoStoreXaConnection getXaConnection() { return new NeoStoreXaConnection( neoStore, xaContainer.getResourceManager(), getBranchId() ); } private static class CommandFactory extends XaCommandFactory { private final NeoStore neoStore; private final IndexingService indexingService; CommandFactory( NeoStore neoStore, IndexingService indexingService ) { this.neoStore = neoStore; this.indexingService = indexingService; } @Override public XaCommand readCommand( ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException { return Command.readCommand( neoStore, indexingService, byteChannel, buffer ); } } private class InterceptingTransactionFactory extends TransactionFactory { @Override public XaTransaction create( long lastCommittedTxWhenTransactionStarted, TransactionState state ) { TransactionInterceptor first = providers.resolveChain( NeoStoreXaDataSource.this ); return new InterceptingWriteTransaction( lastCommittedTxWhenTransactionStarted, getLogicalLog(), neoStore, state, cacheAccess, indexingService, labelScanStore, first, integrityValidator, (KernelTransactionImplementation)kernel.newTransaction(), locks ); } } private class TransactionFactory extends XaTransactionFactory { @Override public XaTransaction create( long lastCommittedTxWhenTransactionStarted, TransactionState state ) { return new NeoStoreTransaction( lastCommittedTxWhenTransactionStarted, getLogicalLog(), state, neoStore, cacheAccess, indexingService, labelScanStore, integrityValidator, (KernelTransactionImplementation)kernel.newTransaction(), locks ); } @Override public void recoveryComplete() { msgLog.debug( "Recovery complete, " + "all transactions have been resolved" ); msgLog.debug( "Rebuilding id generators as needed. " + "This can take a while for large stores..." ); forceEverything(); neoStore.makeStoreOk(); neoStore.setVersion( xaContainer.getLogicalLog().getHighestLogVersion() ); msgLog.debug( "Rebuild of id generators complete." ); } @Override public long getCurrentVersion() { return neoStore.getVersion(); } @Override public long getAndSetNewVersion() { return neoStore.incrementVersion(); } @Override public void setVersion( long version ) { neoStore.setVersion( version ); } @Override public void flushAll() { forceEverything(); } @Override public long getLastCommittedTx() { return neoStore.getLastCommittedTx(); } } public long nextId( Class<?> clazz ) { Store store = idGenerators.get( clazz ); if ( store == null ) { throw new IdGenerationFailedException( "No IdGenerator for: " + clazz ); } return store.nextId(); } public long getHighestPossibleIdInUse( Class<?> clazz ) { Store store = idGenerators.get( clazz ); if ( store == null ) { throw new IdGenerationFailedException( "No IdGenerator for: " + clazz ); } return store.getHighestPossibleIdInUse(); } public long getNumberOfIdsInUse( Class<?> clazz ) { Store store = idGenerators.get( clazz ); if ( store == null ) { throw new IdGenerationFailedException( "No IdGenerator for: " + clazz ); } return store.getNumberOfIdsInUse(); } public String getStoreDir() { return storeDir.getPath(); } @Override public long getCreationTime() { return neoStore.getCreationTime(); } @Override public long getRandomIdentifier() { return neoStore.getRandomNumber(); } @Override public long getCurrentLogVersion() { return neoStore.getVersion(); } public long incrementAndGetLogVersion() { return neoStore.incrementVersion(); } // used for testing, do not use. @Override public void setLastCommittedTxId( long txId ) { neoStore.setRecoveredStatus( true ); try { neoStore.setLastCommittedTx( txId ); } finally { neoStore.setRecoveredStatus( false ); } } public boolean isReadOnly() { return readOnly; } public List<WindowPoolStats> getWindowPoolStats() { return neoStore.getAllWindowPoolStats(); } @Override public long getLastCommittedTxId() { return neoStore.getLastCommittedTx(); } @Override public XaContainer getXaContainer() { return xaContainer; } @Override public boolean setRecovered( boolean recovered ) { boolean currentValue = neoStore.isInRecoveryMode(); neoStore.setRecoveredStatus( true ); return currentValue; } @Override public ResourceIterator<File> listStoreFiles( boolean includeLogicalLogs ) throws IOException { return fileListing.listStoreFiles( includeLogicalLogs ); } @Override public ResourceIterator<File> listStoreFiles() throws IOException { return fileListing.listStoreFiles(); } @Override public ResourceIterator<File> listLogicalLogs() throws IOException { return fileListing.listLogicalLogs(); } public void registerDiagnosticsWith( DiagnosticsManager manager ) { manager.registerAll( Diagnostics.class, this ); } private Iterator<IndexRule> loadIndexRules() { return new SchemaStorage( neoStore.getSchemaStore() ).allIndexRules(); } @Override public NeoStore evaluate() { return neoStore; } @Override public void recoveryCompleted() throws IOException { indexingService.startIndexes(); } public LogBufferFactory createLogBufferFactory() { return xaContainer.getLogicalLog().createLogWriter( new Function<Config, File>() { @Override public File apply( Config config ) { return config.get( Configuration.logical_log ); } } ); } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreXaDataSource.java
2,234
class CustomBoostFactorWeight extends Weight { final Weight subQueryWeight; public CustomBoostFactorWeight(Weight subQueryWeight) throws IOException { this.subQueryWeight = subQueryWeight; } public Query getQuery() { return FunctionScoreQuery.this; } @Override public float getValueForNormalization() throws IOException { float sum = subQueryWeight.getValueForNormalization(); sum *= getBoost() * getBoost(); return sum; } @Override public void normalize(float norm, float topLevelBoost) { subQueryWeight.normalize(norm, topLevelBoost * getBoost()); } @Override public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException { // we ignore scoreDocsInOrder parameter, because we need to score in // order if documents are scored with a script. The // ShardLookup depends on in order scoring. Scorer subQueryScorer = subQueryWeight.scorer(context, true, false, acceptDocs); if (subQueryScorer == null) { return null; } function.setNextReader(context); return new CustomBoostFactorScorer(this, subQueryScorer, function, maxBoost, combineFunction); } @Override public Explanation explain(AtomicReaderContext context, int doc) throws IOException { Explanation subQueryExpl = subQueryWeight.explain(context, doc); if (!subQueryExpl.isMatch()) { return subQueryExpl; } function.setNextReader(context); Explanation functionExplanation = function.explainScore(doc, subQueryExpl); return combineFunction.explain(getBoost(), subQueryExpl, functionExplanation, maxBoost); } }
1no label
src_main_java_org_elasticsearch_common_lucene_search_function_FunctionScoreQuery.java
1,368
FilterConfig config = new FilterConfig() { public String getFilterName() { return null; } public String getInitParameter(String param) { return "category/temp.*\n stellar/test/tester another/small/test"; } public Enumeration<String> getInitParameterNames() { return null; } public ServletContext getServletContext() { return null; } };
0true
core_broadleaf-framework-web_src_test_java_org_broadleafcommerce_core_web_SpringTemporaryRedirectOverrideFilterTest.java
196
public interface MemoryLockerLinux extends Library { // http://www-numi.fnal.gov/offline_software/srt_public_context/WebDocs/Errors/unix_system_errors.html // #define EPERM 1 /* Operation not permitted */ The calling process does not have the appropriate privilege to perform the // requested operation. static final int EPERM = 1; // #define EAGAIN 11 /* Try again */ Some or all of the memory identified by the operation could not be locked when the call was // made. static final int EAGAIN = 11; // #define ENOMEM 12 /* Out of memory */ Locking all of the pages currently mapped into the address space of the process would // exceed an implementation-dependent limit on the amount of memory that the process may lock. static final int ENOMEM = 12; // #define EINVAL 22 /* Invalid argument */ The flags argument is zero, or includes unimplemented flags. static final int EINVAL = 22; // #define ENOSYS 38 /* Function not implemented */ The implementation does not support this memory locking interface. static final int ENOSYS = 38; // Linux/include/asm-generic/mman.h // // 16 #define MCL_CURRENT 1 /* lock all current mappings */ // 17 #define MCL_FUTURE 2 /* lock all future mappings */ static final int LOCK_CURRENT_MEMORY = 1; static final int LOCK_ALL_MEMORY_DURING_APPLICATION_LIFE = 2; MemoryLockerLinux INSTANCE = (MemoryLockerLinux) Native.loadLibrary("c", MemoryLockerLinux.class); /** * This method locks all memory under *nix operating system using kernel function {@code mlockall}. details of this function you * can find on {@see http://www.kernel.org/doc/man-pages/online/pages/man2/mlock.2.html} * * @param flags * determines lock memory on startup or during life of application. * * @return Upon successful completion, the mlockall() function returns a value of zero. Otherwise, no additional memory is locked, * and the function returns a value of -1 and sets errno to indicate the error. The effect of failure of mlockall() on * previously existing locks in the address space is unspecified. If it is supported by the implementation, the * munlockall() function always returns a value of zero. Otherwise, the function returns a value of -1 and sets errno to * indicate the error. */ int mlockall(int flags); }
0true
nativeos_src_main_java_com_orientechnologies_nio_MemoryLockerLinux.java
1,205
public interface OCluster { public static enum ATTRIBUTES { NAME, DATASEGMENT, USE_WAL, RECORD_GROW_FACTOR, RECORD_OVERFLOW_GROW_FACTOR, COMPRESSION } public void configure(OStorage iStorage, int iId, String iClusterName, final String iLocation, int iDataSegmentId, Object... iParameters) throws IOException; public void configure(OStorage iStorage, OStorageClusterConfiguration iConfig) throws IOException; public void create(int iStartSize) throws IOException; public void open() throws IOException; public void close() throws IOException; public void close(boolean flush) throws IOException; public void delete() throws IOException; public OModificationLock getExternalModificationLock(); public void set(ATTRIBUTES iAttribute, Object iValue) throws IOException; public void convertToTombstone(OClusterPosition iPosition) throws IOException; public long getTombstonesCount(); public boolean hasTombstonesSupport(); /** * Truncates the cluster content. All the entries will be removed. * * @throws IOException */ public void truncate() throws IOException; public String getType(); public int getDataSegmentId(); public OPhysicalPosition createRecord(byte[] content, ORecordVersion recordVersion, byte recordType) throws IOException; public boolean deleteRecord(OClusterPosition clusterPosition) throws IOException; public void updateRecord(OClusterPosition clusterPosition, byte[] content, ORecordVersion recordVersion, byte recordType) throws IOException; public ORawBuffer readRecord(OClusterPosition clusterPosition) throws IOException; public boolean exists(); /** * Adds a new entry. */ public boolean addPhysicalPosition(OPhysicalPosition iPPosition) throws IOException; /** * Fills and return the PhysicalPosition object received as parameter with the physical position of logical record iPosition * * @throws IOException */ public OPhysicalPosition getPhysicalPosition(OPhysicalPosition iPPosition) throws IOException; /** * Updates position in data segment (usually on defrag). */ public void updateDataSegmentPosition(OClusterPosition iPosition, int iDataSegmentId, long iDataPosition) throws IOException; /** * Removes the Logical Position entry. */ public void removePhysicalPosition(OClusterPosition iPosition) throws IOException; public void updateRecordType(OClusterPosition iPosition, final byte iRecordType) throws IOException; public void updateVersion(OClusterPosition iPosition, ORecordVersion iVersion) throws IOException; public long getEntries(); public OClusterPosition getFirstPosition() throws IOException; public OClusterPosition getLastPosition() throws IOException; /** * Lets to an external actor to lock the cluster in shared mode. Useful for range queries to avoid atomic locking. * * @see #unlock(); */ public void lock(); /** * Lets to an external actor to unlock the shared mode lock acquired by the lock(). * * @see #lock(); */ public void unlock(); public int getId(); public void synch() throws IOException; public void setSoftlyClosed(boolean softlyClosed) throws IOException; public boolean wasSoftlyClosed() throws IOException; public String getName(); /** * Returns the size of the records contained in the cluster in bytes. * * @return */ public long getRecordsSize() throws IOException; public boolean useWal(); public float recordGrowFactor(); public float recordOverflowGrowFactor(); public String compression(); public boolean isHashBased(); public OClusterEntryIterator absoluteIterator(); public OPhysicalPosition[] higherPositions(OPhysicalPosition position) throws IOException; public OPhysicalPosition[] ceilingPositions(OPhysicalPosition position) throws IOException; public OPhysicalPosition[] lowerPositions(OPhysicalPosition position) throws IOException; public OPhysicalPosition[] floorPositions(OPhysicalPosition position) throws IOException; }
0true
core_src_main_java_com_orientechnologies_orient_core_storage_OCluster.java
1,104
SINGLE_VALUES_DENSE_ENUM { public int numValues() { return 1; } @Override public long nextValue() { return RANDOM.nextInt(16); } },
0true
src_test_java_org_elasticsearch_benchmark_fielddata_LongFieldDataBenchmark.java
1,020
clusterService.add(request.timeout(), new TimeoutClusterStateListener() { @Override public void postAdded() { if (start(true)) { // if we managed to start and perform the operation on the primary, we can remove this listener clusterService.remove(this); } } @Override public void onClose() { clusterService.remove(this); listener.onFailure(new NodeClosedException(nodes.localNode())); } @Override public void clusterChanged(ClusterChangedEvent event) { if (start(true)) { // if we managed to start and perform the operation on the primary, we can remove this listener clusterService.remove(this); } } @Override public void onTimeout(TimeValue timeValue) { // just to be on the safe side, see if we can start it now? if (start(true)) { clusterService.remove(this); return; } clusterService.remove(this); Throwable listenFailure = failure; if (listenFailure == null) { if (shardIt == null) { listenFailure = new UnavailableShardsException(new ShardId(request.index(), -1), "Timeout waiting for [" + timeValue + "], request: " + request.toString()); } else { listenFailure = new UnavailableShardsException(shardIt.shardId(), "[" + shardIt.size() + "] shardIt, [" + shardIt.sizeActive() + "] active : Timeout waiting for [" + timeValue + "], request: " + request.toString()); } } listener.onFailure(listenFailure); } });
0true
src_main_java_org_elasticsearch_action_support_single_instance_TransportInstanceSingleOperationAction.java
330
private static class DummyTransaction extends XaTransaction { private final java.util.List<XaCommand> commandList = new java.util.ArrayList<XaCommand>(); public DummyTransaction( XaLogicalLog log, TransactionState state ) { super( log, state ); setCommitTxId( 0 ); } @Override public void doAddCommand( XaCommand command ) { commandList.add( command ); } @Override public void doPrepare() { } @Override public void doRollback() { } @Override public void doCommit() { } @Override public boolean isReadOnly() { return false; } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_DummyXaDataSource.java
341
return new ReadConfiguration() { @Override public <O> O get(String key, Class<O> datatype) { Preconditions.checkArgument(!entries.containsKey(key) || datatype.isAssignableFrom(entries.get(key).getClass())); return (O)entries.get(key); } @Override public Iterable<String> getKeys(final String prefix) { return Lists.newArrayList(Iterables.filter(entries.keySet(),new Predicate<String>() { @Override public boolean apply(@Nullable String s) { assert s!=null; return StringUtils.isBlank(prefix) || s.startsWith(prefix); } })); } @Override public void close() { //Do nothing } };
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_backend_KCVSConfiguration.java
275
public interface OCommandRequestInternal extends OCommandRequest, OSerializableStream { public Map<Object, Object> getParameters(); public OCommandResultListener getResultListener(); public void setResultListener(OCommandResultListener iListener); public OProgressListener getProgressListener(); public OCommandRequestInternal setProgressListener(OProgressListener iProgressListener); public void reset(); }
0true
core_src_main_java_com_orientechnologies_orient_core_command_OCommandRequestInternal.java
1,109
public class AddToCartException extends Exception { private static final long serialVersionUID = 1L; public AddToCartException() { super(); } public AddToCartException(String message, Throwable cause) { super(message, cause); } public AddToCartException(String message) { super(message); } public AddToCartException(Throwable cause) { super(cause); } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_exception_AddToCartException.java
1,404
public class OMVRBTreeRIDProvider extends OMVRBTreeProviderAbstract<OIdentifiable, OIdentifiable> implements OStringBuilderSerializable { public static final String PERSISTENT_CLASS_NAME = "ORIDs"; private static final long serialVersionUID = 1L; private OMVRBTreeRID tree; private boolean embeddedStreaming = true; // KEEP THE STREAMING MODE private int binaryThreshold = OGlobalConfiguration.MVRBTREE_RID_BINARY_THRESHOLD .getValueAsInteger(); private final StringBuilder buffer = new StringBuilder(); private boolean marshalling = true; protected static final OProfilerMBean PROFILER = Orient.instance().getProfiler(); /** * Copy constructor */ public OMVRBTreeRIDProvider(final OMVRBTreeRIDProvider iSource) { this(null, iSource.getClusterId(), iSource.getRoot()); buffer.append(iSource.buffer); marshalling = false; } public OMVRBTreeRIDProvider(final OStorage iStorage, final int iClusterId, final ORID iRID) { this(iStorage, getDatabase().getClusterNameById(iClusterId)); if (iRID != null) root = (ORecordId) iRID.copy(); marshalling = false; } public OMVRBTreeRIDProvider(final ORID iRID) { this(null, getDatabase().getDefaultClusterId()); if (iRID != null) root = (ORecordId) iRID.copy(); marshalling = false; } public OMVRBTreeRIDProvider(final OStorage iStorage, final int iClusterId) { this(iStorage, getDatabase().getClusterNameById(iClusterId)); marshalling = false; record.unsetDirty(); } public OMVRBTreeRIDProvider(final OStorage iStorage, final int iClusterId, int binaryThreshold) { this(iStorage, getDatabase().getClusterNameById(iClusterId)); marshalling = false; record.unsetDirty(); this.binaryThreshold = binaryThreshold; } public OMVRBTreeRIDProvider(final String iClusterName) { this(null, iClusterName); marshalling = false; } protected OMVRBTreeRIDProvider(final OStorage iStorage, final String iClusterName) { super(new ODocument(), iStorage, iClusterName); ((ODocument) record).field("pageSize", pageSize); getDatabase().getMetadata().getSchema().getOrCreateClass(PERSISTENT_CLASS_NAME); } @Override public OMVRBTreeRIDProvider copy() { final OMVRBTreeRIDProvider copy = new OMVRBTreeRIDProvider(storage, clusterName); copy.setTree(tree); return copy; } public OMVRBTreeRIDEntryProvider getEntry(final ORID iRid) { return new OMVRBTreeRIDEntryProvider(this, iRid); } public OMVRBTreeRIDEntryProvider createEntry() { return new OMVRBTreeRIDEntryProvider(this); } public OStringBuilderSerializable toStream(final StringBuilder iBuffer) throws OSerializationException { final long timer = PROFILER.startChrono(); if (buffer.length() > 0 && getDatabase().getTransaction().isActive() && buffer.indexOf("-") > -1) { // IN TRANSACTION: UNMARSHALL THE BUFFER TO AVOID TO STORE TEMP RIDS lazyUnmarshall(); buffer.setLength(0); } tree.saveAllNewEntries(); if (buffer.length() == 0) // MARSHALL IT try { if (isEmbeddedStreaming()) { marshalling = true; // SERIALIZE AS AN EMBEDDED STRING buffer.append(OStringSerializerHelper.SET_BEGIN); // PERSISTENT RIDS boolean first = true; for (OIdentifiable rid : tree.keySet()) { if (rid instanceof ORecord<?>) { final ORecord<?> record = (ORecord<?>) rid; if (record.isDirty()) record.save(); } if (!first) buffer.append(OStringSerializerHelper.COLLECTION_SEPARATOR); else first = false; rid.getIdentity().toString(buffer); } // TEMPORARY RIDS final IdentityHashMap<ORecord<?>, Object> tempRIDs = tree.getTemporaryEntries(); if (tempRIDs != null && !tempRIDs.isEmpty()) for (ORecord<?> rec : tempRIDs.keySet()) { if (!first) buffer.append(OStringSerializerHelper.COLLECTION_SEPARATOR); else first = false; rec.getIdentity().toString(buffer); } buffer.append(OStringSerializerHelper.SET_END); } else { marshalling = true; buffer.append(OStringSerializerHelper.EMBEDDED_BEGIN); buffer.append(new String(toDocument().toStream())); buffer.append(OStringSerializerHelper.EMBEDDED_END); } } finally { marshalling = false; PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.toStream"), "Serialize a MVRBTreeRID", timer); } iBuffer.append(buffer); return this; } public OSerializableStream fromStream(final byte[] iStream) throws OSerializationException { record.fromStream(iStream); fromDocument((ODocument) record); return this; } public OStringBuilderSerializable fromStream(final StringBuilder iInput) throws OSerializationException { if (iInput != null) { // COPY THE BUFFER: IF THE TREE IS UNTOUCHED RETURN IT buffer.setLength(0); buffer.append(iInput); } return this; } public void lazyUnmarshall() { if (getSize() > 0 || marshalling || buffer.length() == 0) // ALREADY UNMARSHALLED return; marshalling = true; try { final char firstChar = buffer.charAt(0); String value = firstChar == OStringSerializerHelper.SET_BEGIN || firstChar == OStringSerializerHelper.LIST_BEGIN ? buffer .substring(1, buffer.length() - 1) : buffer.toString(); if (firstChar == OStringSerializerHelper.SET_BEGIN || firstChar == OStringSerializerHelper.LIST_BEGIN || firstChar == OStringSerializerHelper.LINK) { setEmbeddedStreaming(true); final StringTokenizer tokenizer = new StringTokenizer(value, ","); while (tokenizer.hasMoreElements()) { final ORecordId rid = new ORecordId(tokenizer.nextToken()); tree.put(rid, rid); } } else { setEmbeddedStreaming(false); value = firstChar == OStringSerializerHelper.EMBEDDED_BEGIN ? value.substring(1, value.length() - 1) : value.toString(); fromStream(value.getBytes()); } } finally { marshalling = false; } } public byte[] toStream() throws OSerializationException { return toDocument().toStream(); } public OMVRBTree<OIdentifiable, OIdentifiable> getTree() { return tree; } public void setTree(final OMVRBTreePersistent<OIdentifiable, OIdentifiable> tree) { this.tree = (OMVRBTreeRID) tree; } @Override public int getSize() { if (embeddedStreaming) return size; else { final OMVRBTreeEntryPersistent<OIdentifiable, OIdentifiable> r = (OMVRBTreeEntryPersistent<OIdentifiable, OIdentifiable>) tree .getRoot(); return r == null ? 0 : (((OMVRBTreeRIDEntryProvider) r.getProvider()).getTreeSize()); } } @Override public boolean setSize(final int iSize) { if (embeddedStreaming) super.setSize(iSize); else { final OMVRBTreeEntryPersistent<OIdentifiable, OIdentifiable> r = (OMVRBTreeEntryPersistent<OIdentifiable, OIdentifiable>) tree .getRoot(); if (r != null) { final OMVRBTreeRIDEntryProvider provider = (OMVRBTreeRIDEntryProvider) r.getProvider(); if (provider != null && provider.setTreeSize(iSize)) r.markDirty(); return true; } } return false; } @Override public boolean setDirty() { if (!marshalling) { if (buffer != null) buffer.setLength(0); if (tree.getOwner() != null) tree.getOwner().setDirty(); return super.setDirty(); } return false; } public ODocument toDocument() { tree.saveAllNewEntries(); // SERIALIZE AS LINK TO THE TREE STRUCTURE final ODocument doc = (ODocument) record; doc.setClassName(PERSISTENT_CLASS_NAME); doc.field("root", root != null ? root : null); doc.field("keySize", keySize); if (tree.getTemporaryEntries() != null && tree.getTemporaryEntries().size() > 0) doc.field("tempEntries", new ArrayList<ORecord<?>>(tree.getTemporaryEntries().keySet())); return doc; } public void fromDocument(final ODocument iDocument) { pageSize = (Integer) iDocument.field("pageSize"); root = iDocument.field("root", OType.LINK); if (iDocument.field("keySize") != null) keySize = iDocument.<Integer> field("keySize"); tree.load(); final Collection<OIdentifiable> tempEntries = iDocument.field("tempEntries"); if (tempEntries != null && !tempEntries.isEmpty()) for (OIdentifiable entry : tempEntries) if (entry != null) tree.put(entry, null); } public boolean isEmbeddedStreaming() { if (embeddedStreaming && !marshalling) { if (getDatabase().getTransaction().isActive()) // FORCE STREAMING BECAUSE TX return true; if (binaryThreshold > 0 && getSize() > binaryThreshold && tree != null) { // CHANGE TO EXTERNAL BINARY tree.setDirtyOwner(); setEmbeddedStreaming(false); } } return embeddedStreaming; } protected void setEmbeddedStreaming(final boolean iValue) { if (embeddedStreaming != iValue) { embeddedStreaming = iValue; if (!iValue) // ASSURE TO SAVE THE SIZE IN THE ROOT NODE setSize(size); } } @Override public boolean updateConfig() { pageSize = OGlobalConfiguration.MVRBTREE_RID_NODE_PAGE_SIZE.getValueAsInteger(); return false; } }
0true
core_src_main_java_com_orientechnologies_orient_core_type_tree_provider_OMVRBTreeRIDProvider.java
213
@Deprecated public class HydratedCacheManagerImpl implements CacheEventListener, HydratedCacheManager, HydratedAnnotationManager { private static final Log LOG = LogFactory.getLog(HydratedCacheManagerImpl.class); private static final HydratedCacheManagerImpl MANAGER = new HydratedCacheManagerImpl(); public static HydratedCacheManagerImpl getInstance() { return MANAGER; } private HydratedCacheManagerImpl() {} private Map<String, HydratedCache> hydratedCacheContainer = new Hashtable<String, HydratedCache>(100); private Map<String, HydrationDescriptor> hydrationDescriptors = new Hashtable<String, HydrationDescriptor>(100); public void addHydratedCache(final HydratedCache cache) { hydratedCacheContainer.put(cache.getCacheRegion() + "_" + cache.getCacheName(), cache); } public HydratedCache removeHydratedCache(final String cacheRegion, final String cacheName) { return hydratedCacheContainer.remove(cacheRegion + "_" + cacheName); } public HydratedCache getHydratedCache(final String cacheRegion, final String cacheName) { if (!containsCache(cacheRegion, cacheName)) { HydratedCache cache = new HydratedCache(cacheRegion, cacheName); addHydratedCache(cache); } return hydratedCacheContainer.get(cacheRegion + "_" + cacheName); } public boolean containsCache(String cacheRegion, String cacheName) { return hydratedCacheContainer.containsKey(cacheRegion + "_" + cacheName); } public HydrationDescriptor getHydrationDescriptor(Object entity) { if (hydrationDescriptors.containsKey(entity.getClass().getName())) { return hydrationDescriptors.get(entity.getClass().getName()); } HydrationDescriptor descriptor = new HydrationDescriptor(); Class<?> topEntityClass = getTopEntityClass(entity); HydrationScanner scanner = new HydrationScanner(topEntityClass, entity.getClass()); scanner.init(); descriptor.setHydratedMutators(scanner.getCacheMutators()); Map<String, Method[]> mutators = scanner.getIdMutators(); if (mutators.size() != 1) { throw new RuntimeException("Broadleaf Commerce Hydrated Cache currently only supports entities with a single @Id annotation."); } Method[] singleMutators = mutators.values().iterator().next(); descriptor.setIdMutators(singleMutators); String cacheRegion = scanner.getCacheRegion(); if (cacheRegion == null || "".equals(cacheRegion)) { cacheRegion = topEntityClass.getName(); } descriptor.setCacheRegion(cacheRegion); hydrationDescriptors.put(entity.getClass().getName(), descriptor); return descriptor; } public Class<?> getTopEntityClass(Object entity) { Class<?> myClass = entity.getClass(); Class<?> superClass = entity.getClass().getSuperclass(); while (superClass != null && superClass.getName().startsWith("org.broadleaf")) { myClass = superClass; superClass = superClass.getSuperclass(); } return myClass; } public Object getHydratedCacheElementItem(String cacheRegion, String cacheName, Serializable elementKey, String elementItemName) { Object response = null; HydratedCache hydratedCache = getHydratedCache(cacheRegion, cacheName); HydratedCacheElement element = hydratedCache.getCacheElement(cacheRegion, cacheName, elementKey); if (element != null) { response = element.getCacheElementItem(elementItemName, elementKey); } return response; } public void addHydratedCacheElementItem(String cacheRegion, String cacheName, Serializable elementKey, String elementItemName, Object elementValue) { HydratedCache hydratedCache = getHydratedCache(cacheRegion, cacheName); HydratedCacheElement element = hydratedCache.getCacheElement(cacheRegion, cacheName, elementKey); if (element == null) { element = new HydratedCacheElement(); hydratedCache.addCacheElement(cacheRegion, cacheName, elementKey, element); } element.putCacheElementItem(elementItemName, elementKey, elementValue); } public void dispose() { if (LOG.isInfoEnabled()) { LOG.info("Disposing of all hydrated cache members"); } hydratedCacheContainer.clear(); } private void removeCache(String cacheRegion, Serializable key) { String cacheName = cacheRegion; if (key instanceof CacheKey) { cacheName = ((CacheKey) key).getEntityOrRoleName(); key = ((CacheKey) key).getKey(); } if (containsCache(cacheRegion, cacheName)) { HydratedCache cache = hydratedCacheContainer.get(cacheRegion + "_" + cacheName); String myKey = cacheRegion + "_" + cacheName + "_" + key; if (cache.containsKey(myKey)) { if (LOG.isInfoEnabled()) { LOG.info("Clearing hydrated cache for cache name: " + cacheRegion + "_" + cacheName + "_" + key); } cache.removeCacheElement(cacheRegion, cacheName, key); } } } private void removeAll(String cacheName) { if (hydratedCacheContainer.containsKey(cacheName)) { if (LOG.isInfoEnabled()) { LOG.info("Clearing all hydrated caches for cache name: " + cacheName); } hydratedCacheContainer.remove(cacheName); } } public void notifyElementEvicted(Ehcache arg0, Element arg1) { removeCache(arg0.getName(), arg1.getKey()); } public void notifyElementExpired(Ehcache arg0, Element arg1) { removeCache(arg0.getName(), arg1.getKey()); } public void notifyElementPut(Ehcache arg0, Element arg1) throws CacheException { //do nothing } public void notifyElementRemoved(Ehcache arg0, Element arg1) throws CacheException { removeCache(arg0.getName(), arg1.getKey()); } public void notifyElementUpdated(Ehcache arg0, Element arg1) throws CacheException { removeCache(arg0.getName(), arg1.getKey()); } public void notifyRemoveAll(Ehcache arg0) { removeAll(arg0.getName()); } @Override public Object clone() throws CloneNotSupportedException { return this; } }
0true
common_src_main_java_org_broadleafcommerce_common_cache_engine_HydratedCacheManagerImpl.java
320
public class OStorageEHClusterConfiguration implements OStorageClusterConfiguration, Serializable { public transient OStorageConfiguration root; public int id; public String name; public String location; public int dataSegmentId; public OStorageEHClusterConfiguration(OStorageConfiguration root, int id, String name, String location, int dataSegmentId) { this.root = root; this.id = id; this.name = name; this.location = location; this.dataSegmentId = dataSegmentId; } @Override public int getId() { return id; } @Override public String getName() { return name; } @Override public String getLocation() { return location; } @Override public int getDataSegmentId() { return dataSegmentId; } }
0true
core_src_main_java_com_orientechnologies_orient_core_config_OStorageEHClusterConfiguration.java
119
public class JMSArchivedPagePublisher implements ArchivedPagePublisher { private JmsTemplate archivePageTemplate; private Destination archivePageDestination; @Override public void processPageArchive(final Page page, final String basePageKey) { archivePageTemplate.send(archivePageDestination, new MessageCreator() { public Message createMessage(Session session) throws JMSException { return session.createTextMessage(basePageKey); } }); } public JmsTemplate getArchivePageTemplate() { return archivePageTemplate; } public void setArchivePageTemplate(JmsTemplate archivePageTemplate) { this.archivePageTemplate = archivePageTemplate; } public Destination getArchivePageDestination() { return archivePageDestination; } public void setArchivePageDestination(Destination archivePageDestination) { this.archivePageDestination = archivePageDestination; } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_message_jms_JMSArchivedPagePublisher.java
38
new Visitor() { @Override public void visit(Tree.StaticMemberOrTypeExpression that) { Tree.TypeArguments tal = that.getTypeArguments(); Integer startIndex = tal==null ? null : tal.getStartIndex(); if (startIndex!=null && startIndex2!=null && startIndex.intValue()==startIndex2.intValue()) { addMemberNameProposal(offset, "", that, result); } super.visit(that); } public void visit(Tree.SimpleType that) { Tree.TypeArgumentList tal = that.getTypeArgumentList(); Integer startIndex = tal==null ? null : tal.getStartIndex(); if (startIndex!=null && startIndex2!=null && startIndex.intValue()==startIndex2.intValue()) { addMemberNameProposal(offset, "", that, result); } super.visit(that); } }.visit(cpc.getRootNode());
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_MemberNameCompletions.java
2,195
public abstract class NoCacheFilter extends Filter { private static final class NoCacheFilterWrapper extends NoCacheFilter { private final Filter delegate; private NoCacheFilterWrapper(Filter delegate) { this.delegate = delegate; } @Override public DocIdSet getDocIdSet(AtomicReaderContext context, Bits acceptDocs) throws IOException { return delegate.getDocIdSet(context, acceptDocs); } @Override public int hashCode() { return delegate.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof NoCacheFilterWrapper) { return delegate.equals(((NoCacheFilterWrapper)obj).delegate); } return false; } @Override public String toString() { return "no_cache(" + delegate + ")"; } } /** * Wraps a filter in a NoCacheFilter or returns it if it already is a NoCacheFilter. */ public static Filter wrap(Filter filter) { if (filter instanceof NoCacheFilter) { return filter; } return new NoCacheFilterWrapper(filter); } }
0true
src_main_java_org_elasticsearch_common_lucene_search_NoCacheFilter.java
243
public interface EditorActionIds { /** * Action definition ID of the Edit -> Correct Indentation action */ public static final String CORRECT_INDENTATION= PLUGIN_ID + ".editor.correctIndentation"; /** * Action definition ID of the Edit -> Terminate Statement action */ public static final String TERMINATE_STATEMENT= PLUGIN_ID + ".editor.terminateStatement"; /** * Action definition ID of the Edit -> Format Block action */ public static final String FORMAT_BLOCK = PLUGIN_ID + ".editor.formatBlock"; /** * Action definition id of the collapse members action */ public static final String FOLDING_COLLAPSE_MEMBERS= PLUGIN_ID + ".editor.folding.collapseMembers"; /** * Action definition id of the collapse comments action */ public static final String FOLDING_COLLAPSE_COMMENTS= PLUGIN_ID + ".editor.folding.collapseComments"; /** * Source menu: id of standard Format global action */ public static final String FORMAT= PLUGIN_ID + ".editor.formatSource"; /** * Action definition ID of the edit -> Go to Matching Fence action */ public static final String GOTO_MATCHING_FENCE= PLUGIN_ID + ".editor.gotoMatchingFence"; /** * Action definition ID of the edit -> Go to Previous Navigation Target action */ public static final String GOTO_PREVIOUS_TARGET= PLUGIN_ID + ".editor.gotoPreviousTarget"; /** * Action definition ID of the edit -> Go to Next Navigation Target action */ public static final String GOTO_NEXT_TARGET= PLUGIN_ID + ".editor.gotoNextTarget"; /** * Action definition ID of the Edit -> Select Enclosing action */ public static final String SELECT_ENCLOSING= PLUGIN_ID + ".editor.selectEnclosing"; /** * Action definition ID of the Edit -> Restore Previous Selection action */ public static final String RESTORE_PREVIOUS= PLUGIN_ID + ".editor.restorePrevious"; /** * Action definition ID of the navigate -> Show Outline action * * @since 0.1 */ public static final String SHOW_OUTLINE= PLUGIN_ID + ".editor.showOutline"; /** * Action definition ID of the Edit -> Toggle Comment action */ public static final String TOGGLE_COMMENT= PLUGIN_ID + ".editor.toggleComment"; public static final String ADD_BLOCK_COMMENT= PLUGIN_ID + ".editor.addBlockComment"; public static final String REMOVE_BLOCK_COMMENT= PLUGIN_ID + ".editor.removeBlockComment"; public static final String SHOW_CEYLON_CODE = PLUGIN_ID + ".editor.code"; public static final String SHOW_CEYLON_HIERARCHY = PLUGIN_ID + ".editor.hierarchy"; public static final String SHOW_CEYLON_REFERENCES = PLUGIN_ID + ".editor.findReferences"; public static final String SHOW_IN_CEYLON_HIERARCHY_VIEW = PLUGIN_ID + ".action.showInHierarchyView"; }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_EditorActionIds.java