Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
1,136
public class OSQLMethodAsFloat extends OAbstractSQLMethod { public static final String NAME = "asfloat"; public OSQLMethodAsFloat() { super(NAME); } @Override public Object execute(OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iMethodParams) { if (ioResult instanceof Number) { ioResult = ((Number) ioResult).floatValue(); } else { ioResult = ioResult != null ? new Float(ioResult.toString().trim()) : null; } return ioResult; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodAsFloat.java
1,459
@Component("blOrderInfoFormValidator") public class OrderInfoFormValidator implements Validator { @SuppressWarnings("rawtypes") public boolean supports(Class clazz) { return clazz.equals(OrderInfoFormValidator.class); } public void validate(Object obj, Errors errors) { OrderInfoForm orderInfoForm = (OrderInfoForm) obj; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "emailAddress", "emailAddress.required"); if (!errors.hasErrors()) { if (!EmailValidator.getInstance().isValid(orderInfoForm.getEmailAddress())) { errors.rejectValue("emailAddress", "emailAddress.invalid", null, null); } } } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_checkout_validator_OrderInfoFormValidator.java
1,554
public interface ProcessContext extends Serializable { /** * Activly informs the workflow process to stop processing * no further activities will be executed * * @return whether or not the stop process call was successful */ public boolean stopProcess(); /** * Is the process stopped * * @return whether or not the process is stopped */ public boolean isStopped(); /** * Provide seed information to this ProcessContext, usually * provided at time of workflow kickoff by the containing * workflow processor. * * @param seedObject - initial seed data for the workflow */ public void setSeedData(Object seedObject); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_workflow_ProcessContext.java
3,536
public class CamelCaseFieldNameTests extends ElasticsearchTestCase { @Test public void testCamelCaseFieldNameStaysAsIs() throws Exception { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .endObject().endObject().string(); DocumentMapper documentMapper = MapperTestUtils.newParser().parse(mapping); ParsedDocument doc = documentMapper.parse("type", "1", XContentFactory.jsonBuilder().startObject() .field("thisIsCamelCase", "value1") .endObject().bytes()); assertThat(documentMapper.mappers().indexName("thisIsCamelCase").isEmpty(), equalTo(false)); assertThat(documentMapper.mappers().indexName("this_is_camel_case"), nullValue()); documentMapper.refreshSource(); documentMapper = MapperTestUtils.newParser().parse(documentMapper.mappingSource().string()); assertThat(documentMapper.mappers().indexName("thisIsCamelCase").isEmpty(), equalTo(false)); assertThat(documentMapper.mappers().indexName("this_is_camel_case"), nullValue()); } }
0true
src_test_java_org_elasticsearch_index_mapper_camelcase_CamelCaseFieldNameTests.java
1,121
public class WanReplicationRef { private String name; private String mergePolicy; private WanReplicationRefReadOnly readOnly; public WanReplicationRef() { } public WanReplicationRef(String name, String mergePolicy) { this.name = name; this.mergePolicy = mergePolicy; } public WanReplicationRef(WanReplicationRef ref) { name = ref.name; mergePolicy = ref.mergePolicy; } public WanReplicationRefReadOnly getAsReadOnly() { if (readOnly == null ) { readOnly = new WanReplicationRefReadOnly(this); } return readOnly; } public String getName() { return name; } public WanReplicationRef setName(String name) { this.name = name; return this; } public String getMergePolicy() { return mergePolicy; } public WanReplicationRef setMergePolicy(String mergePolicy) { this.mergePolicy = mergePolicy; return this; } @Override public String toString() { return "WanReplicationRef{" + "name='" + name + '\'' + ", mergePolicy='" + mergePolicy + '\'' + '}'; } }
0true
hazelcast_src_main_java_com_hazelcast_config_WanReplicationRef.java
1,215
NONE { @Override <T> Recycler<T> build(Recycler.C<T> c, int limit, int availableProcessors) { return none(c); } };
0true
src_main_java_org_elasticsearch_cache_recycler_CacheRecycler.java
61
public class OModificationLock { private volatile boolean veto = false; private volatile boolean throwException = false; private final ConcurrentLinkedQueue<Thread> waiters = new ConcurrentLinkedQueue<Thread>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); /** * Tells the lock that thread is going to perform data modifications in storage. This method allows to perform several data * modifications in parallel. */ public void requestModificationLock() { lock.readLock().lock(); if (!veto) return; if (throwException) { lock.readLock().unlock(); throw new OModificationOperationProhibitedException("Modification requests are prohibited"); } boolean wasInterrupted = false; Thread thread = Thread.currentThread(); waiters.add(thread); while (veto) { LockSupport.park(this); if (Thread.interrupted()) wasInterrupted = true; } waiters.remove(thread); if (wasInterrupted) thread.interrupt(); } /** * Tells the lock that thread is finished to perform to perform modifications in storage. */ public void releaseModificationLock() { lock.readLock().unlock(); } /** * After this method finished it's execution, all threads that are going to perform data modifications in storage should wait till * {@link #allowModifications()} method will be called. This method will wait till all ongoing modifications will be finished. */ public void prohibitModifications() { lock.writeLock().lock(); try { throwException = false; veto = true; } finally { lock.writeLock().unlock(); } } /** * After this method finished it's execution, all threads that are going to perform data modifications in storage should wait till * {@link #allowModifications()} method will be called. This method will wait till all ongoing modifications will be finished. * * @param throwException * If <code>true</code> {@link OModificationOperationProhibitedException} exception will be thrown on * {@link #requestModificationLock()} call. */ public void prohibitModifications(boolean throwException) { lock.writeLock().lock(); try { this.throwException = throwException; veto = true; } finally { lock.writeLock().unlock(); } } /** * After this method finished execution all threads that are waiting to perform data modifications in storage will be awaken and * will be allowed to continue their execution. */ public void allowModifications() { veto = false; for (Thread thread : waiters) LockSupport.unpark(thread); } }
0true
commons_src_main_java_com_orientechnologies_common_concur_lock_OModificationLock.java
2,154
public static final class Iterator extends DocIdSetIterator { private final int maxDoc; private int doc = -1; public Iterator(int maxDoc) { this.maxDoc = maxDoc; } @Override public int docID() { return doc; } @Override public int nextDoc() throws IOException { if (++doc < maxDoc) { return doc; } return doc = NO_MORE_DOCS; } @Override public int advance(int target) throws IOException { doc = target; if (doc < maxDoc) { return doc; } return doc = NO_MORE_DOCS; } @Override public long cost() { return maxDoc; } }
0true
src_main_java_org_elasticsearch_common_lucene_docset_AllDocIdSet.java
59
@SuppressWarnings("serial") static final class ForEachTransformedValueTask<K,V,U> extends BulkTask<K,V,Void> { final Fun<? super V, ? extends U> transformer; final Action<? super U> action; ForEachTransformedValueTask (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t, Fun<? super V, ? extends U> transformer, Action<? super U> action) { super(p, b, i, f, t); this.transformer = transformer; this.action = action; } public final void compute() { final Fun<? super V, ? extends U> transformer; final Action<? super U> action; if ((transformer = this.transformer) != null && (action = this.action) != null) { for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { addToPendingCount(1); new ForEachTransformedValueTask<K,V,U> (this, batch >>>= 1, baseLimit = h, f, tab, transformer, action).fork(); } for (Node<K,V> p; (p = advance()) != null; ) { U u; if ((u = transformer.apply(p.val)) != null) action.apply(u); } propagateCompletion(); } } }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
2,679
public interface Gateway extends LifecycleComponent<Gateway> { String type(); void performStateRecovery(GatewayStateRecoveredListener listener) throws GatewayException; Class<? extends Module> suggestIndexGateway(); void reset() throws Exception; interface GatewayStateRecoveredListener { void onSuccess(ClusterState recoveredState); void onFailure(String message); } }
0true
src_main_java_org_elasticsearch_gateway_Gateway.java
889
public class PromotableFulfillmentGroupAdjustmentImpl extends AbstractPromotionRounding implements PromotableFulfillmentGroupAdjustment, OfferHolder { private static final long serialVersionUID = 1L; protected PromotableCandidateFulfillmentGroupOffer promotableCandidateFulfillmentGroupOffer; protected PromotableFulfillmentGroup promotableFulfillmentGroup; protected Money saleAdjustmentValue; protected Money retailAdjustmentValue; protected Money adjustmentValue; protected boolean appliedToSalePrice; public PromotableFulfillmentGroupAdjustmentImpl( PromotableCandidateFulfillmentGroupOffer promotableCandidateFulfillmentGroupOffer, PromotableFulfillmentGroup fulfillmentGroup) { this.promotableCandidateFulfillmentGroupOffer = promotableCandidateFulfillmentGroupOffer; this.promotableFulfillmentGroup = fulfillmentGroup; computeAdjustmentValues(); } public Offer getOffer() { return promotableCandidateFulfillmentGroupOffer.getOffer(); } /* * Calculates the value of the adjustment for both retail and sale prices. * If either adjustment is greater than the item value, it will be set to the * currentItemValue (e.g. no adjustment can cause a negative value). */ protected void computeAdjustmentValues() { saleAdjustmentValue = new Money(getCurrency()); retailAdjustmentValue = new Money(getCurrency()); Offer offer = promotableCandidateFulfillmentGroupOffer.getOffer(); Money currentPriceDetailSalesValue = promotableFulfillmentGroup.calculatePriceWithAdjustments(true); Money currentPriceDetailRetailValue = promotableFulfillmentGroup.calculatePriceWithAdjustments(false); retailAdjustmentValue = PromotableOfferUtility.computeAdjustmentValue(currentPriceDetailRetailValue, offer.getValue(), this, this); if (offer.getApplyDiscountToSalePrice() == true) { saleAdjustmentValue = PromotableOfferUtility.computeAdjustmentValue(currentPriceDetailSalesValue, offer.getValue(), this, this); } } protected Money computeAdjustmentValue(Money currentPriceDetailValue) { Offer offer = promotableCandidateFulfillmentGroupOffer.getOffer(); OfferDiscountType discountType = offer.getDiscountType(); Money adjustmentValue = new Money(getCurrency()); if (OfferDiscountType.AMOUNT_OFF.equals(discountType)) { adjustmentValue = new Money(offer.getValue(), getCurrency()); } if (OfferDiscountType.FIX_PRICE.equals(discountType)) { adjustmentValue = currentPriceDetailValue; } if (OfferDiscountType.PERCENT_OFF.equals(discountType)) { BigDecimal offerValue = currentPriceDetailValue.getAmount().multiply(offer.getValue().divide(new BigDecimal("100"), 5, RoundingMode.HALF_EVEN)); if (isRoundOfferValues()) { offerValue = offerValue.setScale(roundingScale, roundingMode); } adjustmentValue = new Money(offerValue, getCurrency(), 5); } if (currentPriceDetailValue.lessThan(adjustmentValue)) { adjustmentValue = currentPriceDetailValue; } return adjustmentValue; } @Override public PromotableFulfillmentGroup getPromotableFulfillmentGroup() { return promotableFulfillmentGroup; } @Override public PromotableCandidateFulfillmentGroupOffer getPromotableCandidateFulfillmentGroupOffer() { return promotableCandidateFulfillmentGroupOffer; } @Override public Money getAdjustmentValue() { return adjustmentValue; } public BroadleafCurrency getCurrency() { return promotableFulfillmentGroup.getFulfillmentGroup().getOrder().getCurrency(); } @Override public boolean isCombinable() { Boolean combinable = getOffer().isCombinableWithOtherOffers(); return (combinable != null && combinable); } @Override public boolean isTotalitarian() { Boolean totalitarian = getOffer().isTotalitarianOffer(); return (totalitarian != null && totalitarian.booleanValue()); } @Override public Money getSaleAdjustmentValue() { return saleAdjustmentValue; } @Override public Money getRetailAdjustmentValue() { return retailAdjustmentValue; } @Override public boolean isAppliedToSalePrice() { return appliedToSalePrice; } @Override public void finalizeAdjustment(boolean useSalePrice) { appliedToSalePrice = useSalePrice; if (useSalePrice) { adjustmentValue = saleAdjustmentValue; } else { adjustmentValue = retailAdjustmentValue; } } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_domain_PromotableFulfillmentGroupAdjustmentImpl.java
627
public class GatewayRecoveryStatus { public enum Stage { INIT((byte) 0), INDEX((byte) 1), TRANSLOG((byte) 2), FINALIZE((byte) 3), DONE((byte) 4); private final byte value; Stage(byte value) { this.value = value; } public byte value() { return value; } public static Stage fromValue(byte value) { if (value == 0) { return INIT; } else if (value == 1) { return INDEX; } else if (value == 2) { return TRANSLOG; } else if (value == 3) { return FINALIZE; } else if (value == 4) { return DONE; } throw new ElasticsearchIllegalArgumentException("No stage found for [" + value + ']'); } } final Stage stage; final long startTime; final long time; final long indexSize; final long reusedIndexSize; final long recoveredIndexSize; final long recoveredTranslogOperations; public GatewayRecoveryStatus(Stage stage, long startTime, long time, long indexSize, long reusedIndexSize, long recoveredIndexSize, long recoveredTranslogOperations) { this.stage = stage; this.startTime = startTime; this.time = time; this.indexSize = indexSize; this.reusedIndexSize = reusedIndexSize; this.recoveredIndexSize = recoveredIndexSize; this.recoveredTranslogOperations = recoveredTranslogOperations; } public Stage getStage() { return this.stage; } public long getStartTime() { return this.startTime; } public TimeValue getTime() { return TimeValue.timeValueMillis(time); } public ByteSizeValue getIndexSize() { return new ByteSizeValue(indexSize); } public ByteSizeValue getReusedIndexSize() { return new ByteSizeValue(reusedIndexSize); } public ByteSizeValue getExpectedRecoveredIndexSize() { return new ByteSizeValue(indexSize - reusedIndexSize); } /** * How much of the index has been recovered. */ public ByteSizeValue getRecoveredIndexSize() { return new ByteSizeValue(recoveredIndexSize); } public int getIndexRecoveryProgress() { if (recoveredIndexSize == 0) { if (indexSize != 0 && indexSize == reusedIndexSize) { return 100; } return 0; } return (int) (((double) recoveredIndexSize) / getExpectedRecoveredIndexSize().bytes() * 100); } public long getRecoveredTranslogOperations() { return recoveredTranslogOperations; } }
0true
src_main_java_org_elasticsearch_action_admin_indices_status_GatewayRecoveryStatus.java
1,478
public final class NaturalIdRegionAccessStrategyAdapter implements NaturalIdRegionAccessStrategy { private final AccessDelegate<? extends HazelcastNaturalIdRegion> delegate; public NaturalIdRegionAccessStrategyAdapter(final AccessDelegate<? extends HazelcastNaturalIdRegion> delegate) { this.delegate = delegate; } public boolean afterInsert(final Object key, final Object value) throws CacheException { return afterInsert(key, value, null); } public boolean afterInsert(final Object key, final Object value, final Object version) throws CacheException { return delegate.afterInsert(key, value, version); } public boolean afterUpdate(final Object key, final Object value, final SoftLock lock) throws CacheException { return afterUpdate(key, value, null, null, lock); } public boolean afterUpdate(final Object key, final Object value, final Object currentVersion, final Object previousVersion, final SoftLock lock) throws CacheException { return delegate.afterUpdate(key, value, currentVersion, previousVersion, lock); } public void evict(final Object key) throws CacheException { delegate.evict(key); } public void evictAll() throws CacheException { delegate.evictAll(); } public Object get(final Object key, final long txTimestamp) throws CacheException { return delegate.get(key, txTimestamp); } public NaturalIdRegion getRegion() { return delegate.getHazelcastRegion(); } public boolean insert(final Object key, final Object value) throws CacheException { return insert(key, value, null); } public boolean insert(final Object key, final Object value, final Object version) throws CacheException { return delegate.insert(key, value, version); } public SoftLock lockItem(final Object key, final Object version) throws CacheException { return delegate.lockItem(key, version); } public SoftLock lockRegion() throws CacheException { return delegate.lockRegion(); } public boolean putFromLoad(final Object key, final Object value, final long txTimestamp, final Object version) throws CacheException { return delegate.putFromLoad(key, value, txTimestamp, version); } public boolean putFromLoad(final Object key, final Object value, final long txTimestamp, final Object version, final boolean minimalPutOverride) throws CacheException { return delegate.putFromLoad(key, value, txTimestamp, version, minimalPutOverride); } public void remove(final Object key) throws CacheException { delegate.remove(key); } public void removeAll() throws CacheException { delegate.removeAll(); } public void unlockItem(final Object key, final SoftLock lock) throws CacheException { delegate.unlockItem(key, lock); } public void unlockRegion(final SoftLock lock) throws CacheException { delegate.unlockRegion(lock); } public boolean update(final Object key, final Object value) throws CacheException { return update(key, value, null, null); } public boolean update(final Object key, final Object value, final Object currentVersion, final Object previousVersion) throws CacheException { return delegate.update(key, value, currentVersion, previousVersion); } }
0true
hazelcast-hibernate_hazelcast-hibernate4_src_main_java_com_hazelcast_hibernate_region_NaturalIdRegionAccessStrategyAdapter.java
3,044
static final class BloomFilteredTermsEnum extends TermsEnum { private Terms delegateTerms; private TermsEnum delegateTermsEnum; private TermsEnum reuse; private BloomFilter filter; public BloomFilteredTermsEnum(Terms other, TermsEnum reuse, BloomFilter filter) { this.delegateTerms = other; this.reuse = reuse; this.filter = filter; } void reset(Terms others) { reuse = this.delegateTermsEnum; this.delegateTermsEnum = null; this.delegateTerms = others; } private TermsEnum getDelegate() throws IOException { if (delegateTermsEnum == null) { /* pull the iterator only if we really need it - * this can be a relatively heavy operation depending on the * delegate postings format and they underlying directory * (clone IndexInput) */ delegateTermsEnum = delegateTerms.iterator(reuse); } return delegateTermsEnum; } @Override public final BytesRef next() throws IOException { return getDelegate().next(); } @Override public final Comparator<BytesRef> getComparator() { return delegateTerms.getComparator(); } @Override public final boolean seekExact(BytesRef text) throws IOException { // The magical fail-fast speed up that is the entire point of all of // this code - save a disk seek if there is a match on an in-memory // structure // that may occasionally give a false positive but guaranteed no false // negatives if (!filter.mightContain(text)) { return false; } return getDelegate().seekExact(text); } @Override public final SeekStatus seekCeil(BytesRef text) throws IOException { return getDelegate().seekCeil(text); } @Override public final void seekExact(long ord) throws IOException { getDelegate().seekExact(ord); } @Override public final BytesRef term() throws IOException { return getDelegate().term(); } @Override public final long ord() throws IOException { return getDelegate().ord(); } @Override public final int docFreq() throws IOException { return getDelegate().docFreq(); } @Override public final long totalTermFreq() throws IOException { return getDelegate().totalTermFreq(); } @Override public DocsAndPositionsEnum docsAndPositions(Bits liveDocs, DocsAndPositionsEnum reuse, int flags) throws IOException { return getDelegate().docsAndPositions(liveDocs, reuse, flags); } @Override public DocsEnum docs(Bits liveDocs, DocsEnum reuse, int flags) throws IOException { return getDelegate().docs(liveDocs, reuse, flags); } }
0true
src_main_java_org_elasticsearch_index_codec_postingsformat_BloomFilterPostingsFormat.java
208
public interface HydratedAnnotationManager { public HydrationDescriptor getHydrationDescriptor(Object entity); }
0true
common_src_main_java_org_broadleafcommerce_common_cache_engine_HydratedAnnotationManager.java
1,171
public class OQueryOperatorAnd extends OQueryOperator { public OQueryOperatorAnd() { super("AND", 4, false); } @Override public Object evaluateRecord(final OIdentifiable iRecord, ODocument iCurrentResult, final OSQLFilterCondition iCondition, final Object iLeft, final Object iRight, OCommandContext iContext) { if (iLeft == null) return false; return (Boolean) iLeft && (Boolean) iRight; } @Override public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) { if (iLeft == null || iRight == null) return OIndexReuseType.NO_INDEX; return OIndexReuseType.INDEX_INTERSECTION; } @Override public ORID getBeginRidRange(final Object iLeft, final Object iRight) { final ORID leftRange; final ORID rightRange; if (iLeft instanceof OSQLFilterCondition) leftRange = ((OSQLFilterCondition) iLeft).getBeginRidRange(); else leftRange = null; if (iRight instanceof OSQLFilterCondition) rightRange = ((OSQLFilterCondition) iRight).getBeginRidRange(); else rightRange = null; if (leftRange == null && rightRange == null) return null; else if (leftRange == null) return rightRange; else if (rightRange == null) return leftRange; else return leftRange.compareTo(rightRange) <= 0 ? rightRange : leftRange; } @Override public ORID getEndRidRange(final Object iLeft, final Object iRight) { final ORID leftRange; final ORID rightRange; if (iLeft instanceof OSQLFilterCondition) leftRange = ((OSQLFilterCondition) iLeft).getEndRidRange(); else leftRange = null; if (iRight instanceof OSQLFilterCondition) rightRange = ((OSQLFilterCondition) iRight).getEndRidRange(); else rightRange = null; if (leftRange == null && rightRange == null) return null; else if (leftRange == null) return rightRange; else if (rightRange == null) return leftRange; else return leftRange.compareTo(rightRange) >= 0 ? rightRange : leftRange; } }
0true
core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryOperatorAnd.java
237
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(); } };
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreXaDataSource.java
444
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface AdminPresentationMergeEntry { /** * The type for this property override. The types available are specific to the properties available in * the various admin presentation annotations. See {@link PropertyType} for a comprehensive list of * available values organized by admin presentation annotation type. * * @see PropertyType * @return the property override type */ String propertyType(); /** * The string representation of the override value. Any primitive property can be specified as a string (int, boolean, enum). * The backend override system will be responsible for converting the string representation back * to the appropriate type for use by the admin. The type specific override value properties are provided * for convenience (e.g. doubleOverrideValue()). * * @return The string representation of the property value */ String overrideValue() default ""; /** * Convenience property for specifying a double value override. The target property * must be of this type. This type can also be specified using overrideValue() and the backend will convert. * * @return the property override value in the form of a double */ double doubleOverrideValue() default Double.MIN_VALUE; /** * Convenience property for specifying a float value override. The target property * must be of this type. This type can also be specified using overrideValue() and the backend will convert. * * @return the property override value in the form of a float */ float floatOverrideValue() default Float.MIN_VALUE; /** * Convenience property for specifying a boolean value override. The target property * must be of this type. This type can also be specified using overrideValue() and the backend will convert. * * @return the property override value in the form of a boolean */ boolean booleanOverrideValue() default false; /** * Convenience property for specifying a int value override. The target property * must be of this type. This type can also be specified using overrideValue() and the backend will convert. * * @return the property override value in the form of a int */ int intOverrideValue() default Integer.MIN_VALUE; /** * Convenience property for specifying a long value override. The target property * must be of this type. This type can also be specified using overrideValue() and the backend will convert. * * @return the property override value in the form of a long */ long longOverrideValue() default Long.MIN_VALUE; /** * Convenience property for specifying a string array value override. The target property * must be of this type. * * @return the property override value in the form of a string array */ String[] stringArrayOverrideValue() default {}; /** * Convenience property for specifying a double array value override. The target property * must be of this type. * * @return the property override value in the form of a double array */ double[] doubleArrayOverrideValue() default {}; /** * Convenience property for specifying a float array value override. The target property * must be of this type. * * @return the property override value in the form of a float array */ float[] floatArrayOverrideValue() default {}; /** * Convenience property for specifying a boolean array value override. The target property * must be of this type. * * @return the property override value in the form of a boolean array */ boolean[] booleanArrayOverrideValue() default {}; /** * Convenience property for specifying a int array value override. The target property * must be of this type. * * @return the property override value in the form of a int array */ int[] intArrayOverrideValue() default {}; /** * Convenience property for specifying a long array value override. The target property * must be of this type. * * @return the property override value in the form of a long array */ long[] longArrayOverrideValue() default {}; /** * Property for overriding the validation configuration for a field annotated with the * {@link org.broadleafcommerce.common.presentation.AdminPresentation} annotation. * * @return the validation config override */ ValidationConfiguration[] validationConfigurations() default {}; /** * Property for overriding the operationTypes for an advanced collection. See * {@link org.broadleafcommerce.common.presentation.AdminPresentationCollection}, * {@link org.broadleafcommerce.common.presentation.AdminPresentationAdornedTargetCollection} and * {@link org.broadleafcommerce.common.presentation.AdminPresentationMap} for default values for each type. * * @return the operationType override */ AdminPresentationOperationTypes operationTypes() default @AdminPresentationOperationTypes(addType = OperationType.BASIC, fetchType = OperationType.BASIC, inspectType = OperationType.BASIC, removeType = OperationType.BASIC, updateType = OperationType.BASIC); /** * Property for overriding the filter configuration for a field annotated with the * {@link org.broadleafcommerce.common.presentation.AdminPresentationDataDrivenEnumeration} annotation. * * @return the option filter configuration */ OptionFilterParam[] optionFilterParams() default {}; /** * Property for overriding the map key configuration for a field annotated with the * {@link org.broadleafcommerce.common.presentation.AdminPresentationMap} annotation. * * @return the map key configuration */ AdminPresentationMapKey[] keys() default {}; }
0true
common_src_main_java_org_broadleafcommerce_common_presentation_override_AdminPresentationMergeEntry.java
21
public class DeleteCommandParser implements CommandParser { public TextCommand parser(SocketTextReader socketTextReader, String cmd, int space) { StringTokenizer st = new StringTokenizer(cmd); st.nextToken(); String key = null; int expiration = 0; boolean noReply = false; if (st.hasMoreTokens()) { key = st.nextToken(); } if (st.hasMoreTokens()) { expiration = Integer.parseInt(st.nextToken()); } if (st.hasMoreTokens()) { noReply = "noreply".equals(st.nextToken()); } return new DeleteCommand(key, expiration, noReply); } }
0true
hazelcast_src_main_java_com_hazelcast_ascii_memcache_DeleteCommandParser.java
3,243
public class DoubleScriptDataComparator extends NumberComparatorBase<Double> { public static IndexFieldData.XFieldComparatorSource comparatorSource(SearchScript script) { return new InnerSource(script); } private static class InnerSource extends IndexFieldData.XFieldComparatorSource { private final SearchScript script; private InnerSource(SearchScript script) { this.script = script; } @Override public FieldComparator<? extends Number> newComparator(String fieldname, int numHits, int sortPos, boolean reversed) throws IOException { return new DoubleScriptDataComparator(numHits, script); } @Override public SortField.Type reducedType() { return SortField.Type.DOUBLE; } } private final SearchScript script; private final double[] values; private double bottom; public DoubleScriptDataComparator(int numHits, SearchScript script) { this.script = script; values = new double[numHits]; } @Override public FieldComparator<Double> setNextReader(AtomicReaderContext context) throws IOException { script.setNextReader(context); return this; } @Override public void setScorer(Scorer scorer) { script.setScorer(scorer); } @Override public int compare(int slot1, int slot2) { final double v1 = values[slot1]; final double v2 = values[slot2]; if (v1 > v2) { return 1; } else if (v1 < v2) { return -1; } else { return 0; } } @Override public int compareBottom(int doc) { script.setNextDocId(doc); final double v2 = script.runAsDouble(); if (bottom > v2) { return 1; } else if (bottom < v2) { return -1; } else { return 0; } } @Override public int compareDocToValue(int doc, Double val2) throws IOException { script.setNextDocId(doc); double val1 = script.runAsDouble(); return Double.compare(val1, val2); } @Override public void copy(int slot, int doc) { script.setNextDocId(doc); values[slot] = script.runAsDouble(); } @Override public void setBottom(final int bottom) { this.bottom = values[bottom]; } @Override public Double value(int slot) { return values[slot]; } @Override public void add(int slot, int doc) { script.setNextDocId(doc); values[slot] += script.runAsDouble(); } @Override public void divide(int slot, int divisor) { values[slot] /= divisor; } @Override public void missing(int slot) { values[slot] = Double.MAX_VALUE; } @Override public int compareBottomMissing() { return Double.compare(bottom, Double.MAX_VALUE); } }
1no label
src_main_java_org_elasticsearch_index_fielddata_fieldcomparator_DoubleScriptDataComparator.java
451
static final class Fields { static final XContentBuilderString NODES = new XContentBuilderString("nodes"); static final XContentBuilderString INDICES = new XContentBuilderString("indices"); static final XContentBuilderString UUID = new XContentBuilderString("uuid"); static final XContentBuilderString CLUSTER_NAME = new XContentBuilderString("cluster_name"); static final XContentBuilderString STATUS = new XContentBuilderString("status"); }
0true
src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsResponse.java
2,358
public interface TransportAddress extends Streamable, Serializable { short uniqueAddressTypeId(); }
0true
src_main_java_org_elasticsearch_common_transport_TransportAddress.java
2,650
threadPool.schedule(TimeValue.timeValueMillis(timeout.millis() / 2), ThreadPool.Names.GENERIC, new Runnable() { @Override public void run() { try { sendPings(timeout, null, sendPingsHandler); threadPool.schedule(TimeValue.timeValueMillis(timeout.millis() / 2), ThreadPool.Names.GENERIC, new Runnable() { @Override public void run() { try { sendPings(timeout, TimeValue.timeValueMillis(timeout.millis() / 2), sendPingsHandler); ConcurrentMap<DiscoveryNode, PingResponse> responses = receivedResponses.remove(sendPingsHandler.id()); sendPingsHandler.close(); for (DiscoveryNode node : sendPingsHandler.nodeToDisconnect) { logger.trace("[{}] disconnecting from {}", sendPingsHandler.id(), node); transportService.disconnectFromNode(node); } listener.onPing(responses.values().toArray(new PingResponse[responses.size()])); } catch (EsRejectedExecutionException ex) { logger.debug("Ping execution rejected", ex); } } }); } catch (EsRejectedExecutionException ex) { logger.debug("Ping execution rejected", ex); } } });
0true
src_main_java_org_elasticsearch_discovery_zen_ping_unicast_UnicastZenPing.java
255
private class RowIterator implements KeyIterator { private final Token maximumToken; private final SliceQuery sliceQuery; private final StoreTransaction txh; /** * This RowIterator will use this timestamp for its entire lifetime, * even if the iterator runs more than one distinct slice query while * paging. <b>This field must be in units of milliseconds since * the UNIX Epoch</b>. * <p> * This timestamp is passed to three methods/constructors: * <ul> * <li>{@link org.apache.cassandra.db.Column#isMarkedForDelete(long now)}</li> * <li>{@link org.apache.cassandra.db.ColumnFamily#hasOnlyTombstones(long)}</li> * <li> * the {@link RangeSliceCommand} constructor via the last argument * to {@link CassandraEmbeddedKeyColumnValueStore#getKeySlice(Token, Token, SliceQuery, int, long)} * </li> * </ul> * The second list entry just calls the first and almost doesn't deserve * a mention at present, but maybe the implementation will change in the future. * <p> * When this value needs to be compared to TTL seconds expressed in seconds, * Cassandra internals do the conversion. * Consider {@link ExpiringColumn#isMarkedForDelete(long)}, which is implemented, * as of 2.0.6, by the following one-liner: * <p> * {@code return (int) (now / 1000) >= getLocalDeletionTime()} * <p> * The {@code now / 1000} does the conversion from milliseconds to seconds * (the units of getLocalDeletionTime()). */ private final long nowMillis; private Iterator<Row> keys; private ByteBuffer lastSeenKey = null; private Row currentRow; private int pageSize; private boolean isClosed; public RowIterator(KeyRangeQuery keyRangeQuery, int pageSize, StoreTransaction txh) throws BackendException { this(StorageService.getPartitioner().getToken(keyRangeQuery.getKeyStart().asByteBuffer()), StorageService.getPartitioner().getToken(keyRangeQuery.getKeyEnd().asByteBuffer()), keyRangeQuery, pageSize, txh); } public RowIterator(Token minimum, Token maximum, SliceQuery sliceQuery, int pageSize, StoreTransaction txh) throws BackendException { this.pageSize = pageSize; this.sliceQuery = sliceQuery; this.maximumToken = maximum; this.txh = txh; this.nowMillis = times.getTime().getTimestamp(TimeUnit.MILLISECONDS); this.keys = getRowsIterator(getKeySlice(minimum, maximum, sliceQuery, pageSize, nowMillis)); } @Override public boolean hasNext() { try { return hasNextInternal(); } catch (BackendException e) { throw new RuntimeException(e); } } @Override public StaticBuffer next() { ensureOpen(); if (!hasNext()) throw new NoSuchElementException(); currentRow = keys.next(); ByteBuffer currentKey = currentRow.key.key.duplicate(); try { return StaticArrayBuffer.of(currentKey); } finally { lastSeenKey = currentKey; } } @Override public void close() { isClosed = true; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public RecordIterator<Entry> getEntries() { ensureOpen(); if (sliceQuery == null) throw new IllegalStateException("getEntries() requires SliceQuery to be set."); return new RecordIterator<Entry>() { final Iterator<Entry> columns = CassandraHelper.makeEntryIterator( Iterables.filter(currentRow.cf.getSortedColumns(), new FilterDeletedColumns(nowMillis)), entryGetter, sliceQuery.getSliceEnd(), sliceQuery.getLimit()); //cfToEntries(currentRow.cf, sliceQuery).iterator(); @Override public boolean hasNext() { ensureOpen(); return columns.hasNext(); } @Override public Entry next() { ensureOpen(); return columns.next(); } @Override public void close() { isClosed = true; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } private final boolean hasNextInternal() throws BackendException { ensureOpen(); if (keys == null) return false; boolean hasNext = keys.hasNext(); if (!hasNext && lastSeenKey != null) { Token lastSeenToken = StorageService.getPartitioner().getToken(lastSeenKey.duplicate()); // let's check if we reached key upper bound already so we can skip one useless call to Cassandra if (maximumToken != getMinimumToken() && lastSeenToken.equals(maximumToken)) { return false; } List<Row> newKeys = getKeySlice(StorageService.getPartitioner().getToken(lastSeenKey), maximumToken, sliceQuery, pageSize, nowMillis); keys = getRowsIterator(newKeys, lastSeenKey); hasNext = keys.hasNext(); } return hasNext; } private void ensureOpen() { if (isClosed) throw new IllegalStateException("Iterator has been closed."); } private Iterator<Row> getRowsIterator(List<Row> rows) { if (rows == null) return null; return Iterators.filter(rows.iterator(), new Predicate<Row>() { @Override public boolean apply(@Nullable Row row) { // The hasOnlyTombstones(x) call below ultimately calls Column.isMarkedForDelete(x) return !(row == null || row.cf == null || row.cf.isMarkedForDelete() || row.cf.hasOnlyTombstones(nowMillis)); } }); } private Iterator<Row> getRowsIterator(List<Row> rows, final ByteBuffer exceptKey) { Iterator<Row> rowIterator = getRowsIterator(rows); if (rowIterator == null) return null; return Iterators.filter(rowIterator, new Predicate<Row>() { @Override public boolean apply(@Nullable Row row) { return row != null && !row.key.key.equals(exceptKey); } }); } }
0true
titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_embedded_CassandraEmbeddedKeyColumnValueStore.java
127
public class PageRuleType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, PageRuleType> TYPES = new LinkedHashMap<String, PageRuleType>(); public static final PageRuleType REQUEST = new PageRuleType("REQUEST", "Request"); public static final PageRuleType TIME = new PageRuleType("TIME", "Time"); public static final PageRuleType PRODUCT = new PageRuleType("PRODUCT", "Product"); public static final PageRuleType CUSTOMER = new PageRuleType("CUSTOMER", "Customer"); /** * Allows translation from the passed in String to a <code>PageRuleType</code> * @param type * @return The matching rule type */ public static PageRuleType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public PageRuleType() { //do nothing } /** * Initialize the type and friendlyType * @param <code>type</code> * @param <code>friendlyType</code> */ public PageRuleType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } /** * Sets the type * @param type */ public void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } /** * Gets the type * @return */ @Override public String getType() { return type; } /** * Gets the name of the type * @return */ @Override public String getFriendlyType() { return friendlyType; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } PageRuleType other = (PageRuleType) obj; if (type == null) { if (other.type != null) { return false; } } else if (!type.equals(other.type)) { return false; } return true; } }
1no label
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_service_type_PageRuleType.java
1,592
public class ODistributedStorageTest { @Test public void testSupportedFreezeTrue() { OStorageLocal storage = Mockito.mock(OStorageLocal.class); ODistributedStorage ds = new ODistributedStorage(Mockito.mock(OServer.class), storage); ds.freeze(true); Mockito.verify(storage).freeze(true); } @Test public void testSupportedFreezeFalse() { OStorageLocal storage = Mockito.mock(OStorageLocal.class); ODistributedStorage ds = new ODistributedStorage(Mockito.mock(OServer.class), storage); ds.freeze(false); Mockito.verify(storage).freeze(false); } @Test(expectedExceptions = { UnsupportedOperationException.class }) public void testUnsupportedFreeze() { ODistributedStorage ds = new ODistributedStorage(Mockito.mock(OServer.class), Mockito.mock(OStorageMemory.class)); ds.freeze(false); } @Test public void testSupportedRelease() { OStorageLocal storage = Mockito.mock(OStorageLocal.class); ODistributedStorage ds = new ODistributedStorage(Mockito.mock(OServer.class), storage); ds.release(); Mockito.verify(storage).release(); } @Test(expectedExceptions = { UnsupportedOperationException.class }) public void testUnsupportedRelease() { ODistributedStorage ds = new ODistributedStorage(Mockito.mock(OServer.class), Mockito.mock(OStorageMemory.class)); ds.release(); } }
0true
server_src_test_java_com_orientechnologies_orient_server_distributed_ODistributedStorageTest.java
70
@SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask<K,V> extends BulkTask<K,V,Double> { final ObjectToDouble<Map.Entry<K,V>> transformer; final DoubleByDoubleToDouble reducer; final double basis; double result; MapReduceEntriesToDoubleTask<K,V> rights, nextRight; MapReduceEntriesToDoubleTask (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t, MapReduceEntriesToDoubleTask<K,V> nextRight, ObjectToDouble<Map.Entry<K,V>> transformer, double basis, DoubleByDoubleToDouble reducer) { super(p, b, i, f, t); this.nextRight = nextRight; this.transformer = transformer; this.basis = basis; this.reducer = reducer; } public final Double getRawResult() { return result; } public final void compute() { final ObjectToDouble<Map.Entry<K,V>> transformer; final DoubleByDoubleToDouble reducer; if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) { double r = this.basis; for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { addToPendingCount(1); (rights = new MapReduceEntriesToDoubleTask<K,V> (this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork(); } for (Node<K,V> p; (p = advance()) != null; ) r = reducer.apply(r, transformer.apply(p)); result = r; CountedCompleter<?> c; for (c = firstComplete(); c != null; c = c.nextComplete()) { @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask<K,V> t = (MapReduceEntriesToDoubleTask<K,V>)c, s = t.rights; while (s != null) { t.result = reducer.apply(t.result, s.result); s = t.rights = s.nextRight; } } } } }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
469
indexAliasesService.indicesAliases(updateRequest, new ClusterStateUpdateListener() { @Override public void onResponse(ClusterStateUpdateResponse response) { listener.onResponse(new IndicesAliasesResponse(response.isAcknowledged())); } @Override public void onFailure(Throwable t) { logger.debug("failed to perform aliases", t); listener.onFailure(t); } });
0true
src_main_java_org_elasticsearch_action_admin_indices_alias_TransportIndicesAliasesAction.java
287
public class OScriptManager { protected final String DEF_LANGUAGE = "javascript"; protected ScriptEngineManager scriptEngineManager; protected Map<String, ScriptEngineFactory> engines = new HashMap<String, ScriptEngineFactory>(); protected Map<String, ScriptEngine> sharedEngines = new HashMap<String, ScriptEngine>(); protected String defaultLanguage = DEF_LANGUAGE; protected Map<String, OScriptFormatter> formatters = new HashMap<String, OScriptFormatter>(); protected List<OScriptInjection> injections = new ArrayList<OScriptInjection>(); protected static final Object[] EMPTY_PARAMS = new Object[] {}; protected static final int LINES_AROUND_ERROR = 5; public OScriptManager() { scriptEngineManager = new ScriptEngineManager(); registerSharedEngine(OSQLScriptEngine.NAME, new OSQLScriptEngineFactory().getScriptEngine()); for (ScriptEngineFactory f : scriptEngineManager.getEngineFactories()) { if (f.getParameter("THREADING") != null) // MULTI-THREAD: CACHE IT AS SHARED registerSharedEngine(f.getLanguageName().toLowerCase(), f.getScriptEngine()); else registerEngine(f.getLanguageName().toLowerCase(), f); if (defaultLanguage == null) defaultLanguage = f.getLanguageName(); } if (!existsEngine(DEF_LANGUAGE)) { final ScriptEngine defEngine = scriptEngineManager.getEngineByName(DEF_LANGUAGE); if (defEngine == null) { OLogManager.instance().warn(this, "Cannot find default script language for %s", DEF_LANGUAGE); } else { // GET DIRECTLY THE LANGUAGE BY NAME (DON'T KNOW WHY SOMETIMES DOESN'T RETURN IT WITH getEngineFactories() ABOVE! registerEngine(DEF_LANGUAGE, defEngine.getFactory()); defaultLanguage = DEF_LANGUAGE; } } registerFormatter(OSQLScriptEngine.NAME, new OSQLScriptFormatter()); registerFormatter(DEF_LANGUAGE, new OJSScriptFormatter()); registerFormatter("ruby", new ORubyScriptFormatter()); } public String getFunctionDefinition(final OFunction iFunction) { final OScriptFormatter formatter = formatters.get(iFunction.getLanguage().toLowerCase()); if (formatter == null) throw new IllegalArgumentException("Cannot find script formatter for the language '" + iFunction.getLanguage() + "'"); return formatter.getFunctionDefinition(iFunction); } public String getFunctionInvoke(final OFunction iFunction, final Object[] iArgs) { final OScriptFormatter formatter = formatters.get(iFunction.getLanguage().toLowerCase()); if (formatter == null) throw new IllegalArgumentException("Cannot find script formatter for the language '" + iFunction.getLanguage() + "'"); return formatter.getFunctionInvoke(iFunction, iArgs); } /** * Format the library of functions for a language. * * @param db * Current database instance * @param iLanguage * Language as filter * @return String containing all the functions */ public String getLibrary(final ODatabaseComplex<?> db, final String iLanguage) { if (db == null) // NO DB = NO LIBRARY return null; final StringBuilder code = new StringBuilder(); final Set<String> functions = db.getMetadata().getFunctionLibrary().getFunctionNames(); for (String fName : functions) { final OFunction f = db.getMetadata().getFunctionLibrary().getFunction(fName); if (f.getLanguage() == null) throw new OConfigurationException("Database function '" + fName + "' has no language"); if (f.getLanguage().equalsIgnoreCase(iLanguage)) { final String def = getFunctionDefinition(f); if (def != null) { code.append(def); code.append("\n"); } } } return code.length() == 0 ? null : code.toString(); } public boolean existsEngine(String iLanguage) { if (iLanguage == null) return false; iLanguage = iLanguage.toLowerCase(); return sharedEngines.containsKey(iLanguage) || engines.containsKey(iLanguage); } public ScriptEngine getEngine(final String iLanguage) { if (iLanguage == null) throw new OCommandScriptException("No language was specified"); final String lang = iLanguage.toLowerCase(); ScriptEngine scriptEngine = sharedEngines.get(lang); if (scriptEngine == null) { final ScriptEngineFactory scriptEngineFactory = engines.get(lang); if (scriptEngineFactory == null) throw new OCommandScriptException("Unsupported language: " + iLanguage + ". Supported languages are: " + getSupportedLanguages()); scriptEngine = scriptEngineFactory.getScriptEngine(); } return scriptEngine; } public Iterable<String> getSupportedLanguages() { final HashSet<String> result = new HashSet<String>(); result.addAll(sharedEngines.keySet()); result.addAll(engines.keySet()); return result; } public Bindings bind(final Bindings binding, final ODatabaseRecordTx db, final OCommandContext iContext, final Map<Object, Object> iArgs) { if (db != null) { // BIND FIXED VARIABLES binding.put("db", new OScriptDocumentDatabaseWrapper(db)); binding.put("gdb", new OScriptGraphDatabaseWrapper(db)); binding.put("orient", new OScriptOrientWrapper(db)); } binding.put("util", new OFunctionUtilWrapper(null)); for (OScriptInjection i : injections) i.bind(binding); // BIND CONTEXT VARIABLE INTO THE SCRIPT if (iContext != null) { binding.put("ctx", iContext); for (Entry<String, Object> a : iContext.getVariables().entrySet()) binding.put(a.getKey(), a.getValue()); } // BIND PARAMETERS INTO THE SCRIPT if (iArgs != null) { for (Entry<Object, Object> a : iArgs.entrySet()) binding.put(a.getKey().toString(), a.getValue()); binding.put("params", iArgs.values().toArray()); } else binding.put("params", EMPTY_PARAMS); return binding; } public String getErrorMessage(final ScriptException e, final String lib) { int errorLineNumber = e.getLineNumber(); if (errorLineNumber <= 0) { // FIX TO RHINO: SOMETIMES HAS THE LINE NUMBER INSIDE THE TEXT :-( final String excMessage = e.toString(); final int pos = excMessage.indexOf("<Unknown Source>#"); if (pos > -1) { final int end = excMessage.indexOf(')', pos + "<Unknown Source>#".length()); String lineNumberAsString = excMessage.substring(pos + "<Unknown Source>#".length(), end); errorLineNumber = Integer.parseInt(lineNumberAsString); } } if (errorLineNumber <= 0) { throw new OCommandScriptException("Error on evaluation of the script library. Error: " + e.getMessage() + "\nScript library was:\n" + lib); } else { final StringBuilder code = new StringBuilder(); final Scanner scanner = new Scanner(lib); try { scanner.useDelimiter("\n"); String currentLine = null; String lastFunctionName = "unknown"; for (int currentLineNumber = 1; scanner.hasNext(); currentLineNumber++) { currentLine = scanner.next(); int pos = currentLine.indexOf("function"); if (pos > -1) { final String[] words = OStringParser.getWords(currentLine.substring(pos + "function".length() + 1), " \r\n\t"); if (words.length > 0 && words[0] != "(") lastFunctionName = words[0]; } if (currentLineNumber == errorLineNumber) // APPEND X LINES BEFORE code.append(String.format("%4d: >>> %s\n", currentLineNumber, currentLine)); else if (Math.abs(currentLineNumber - errorLineNumber) <= LINES_AROUND_ERROR) // AROUND: APPEND IT code.append(String.format("%4d: %s\n", currentLineNumber, currentLine)); } code.insert(0, String.format("ScriptManager: error %s.\nFunction %s:\n\n", e.getMessage(), lastFunctionName)); } finally { scanner.close(); } throw new OCommandScriptException(code.toString()); } } /** * Unbinds variables * * @param binding */ public void unbind(Bindings binding) { for (OScriptInjection i : injections) i.unbind(binding); } public void registerInjection(final OScriptInjection iInj) { if (!injections.contains(iInj)) injections.add(iInj); } public void unregisterInjection(final OScriptInjection iInj) { injections.remove(iInj); } public List<OScriptInjection> getInjections() { return injections; } public OScriptManager registerEngine(final String iLanguage, final ScriptEngineFactory iEngine) { engines.put(iLanguage, iEngine); return this; } /** * Registers multi-thread engines can be cached and shared between threads. * * @param iLanguage * Language name * @param iEngine * Engine instance */ public OScriptManager registerSharedEngine(final String iLanguage, final ScriptEngine iEngine) { sharedEngines.put(iLanguage.toLowerCase(), iEngine); return this; } public OScriptManager registerFormatter(final String iLanguage, final OScriptFormatter iFormatterImpl) { formatters.put(iLanguage.toLowerCase(), iFormatterImpl); return this; } }
0true
core_src_main_java_com_orientechnologies_orient_core_command_script_OScriptManager.java
446
new Thread(){ public void run() { for (int i=0; i<maxItems; i++){ queue.offer(i); queue.remove(i); } } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_queue_ClientQueueTest.java
134
public interface TitanConfiguration { /** * Returns a string representation of the provided configuration option or namespace for inspection. * <p /> * An exception is thrown if the path is invalid. * * @param path * @return */ public String get(String path); /** * Sets the configuration option identified by the provided path to the given value. * * @param path * @param value */ public TitanConfiguration set(String path, Object value); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_schema_TitanConfiguration.java
1,256
addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); Iterator it = map.entrySet(new SqlPredicate("year=" + random.nextInt(100))).iterator(); while (it.hasNext()) { it.next(); } } }, 1);
0true
hazelcast_src_main_java_com_hazelcast_examples_AllTest.java
2,185
public class LimitDocIdSet extends MatchDocIdSet { private final int limit; public LimitDocIdSet(int maxDoc, @Nullable Bits acceptDocs, int limit) { super(maxDoc, acceptDocs); this.limit = limit; } @Override protected boolean matchDoc(int doc) { if (++counter > limit) { return false; } return true; } }
0true
src_main_java_org_elasticsearch_common_lucene_search_LimitFilter.java
691
public interface FeaturedProduct extends PromotableProduct { Long getId(); void setId(Long id); Category getCategory(); void setCategory(Category category); Product getProduct(); void setProduct(Product product); void setSequence(Long sequence); Long getSequence(); String getPromotionMessage(); void setPromotionMessage(String promotionMessage); /** * Pass through to getProdcut() to meet the contract for promotable product. * @return */ Product getRelatedProduct(); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_FeaturedProduct.java
5,407
static class SortedUniqueBytesValues extends FilterBytesValues { final BytesRef spare; int[] sortedIds; final BytesRefHash bytes; int numUniqueValues; int pos = Integer.MAX_VALUE; public SortedUniqueBytesValues(BytesValues delegate) { super(delegate); bytes = new BytesRefHash(); spare = new BytesRef(); } @Override public int setDocument(int docId) { final int numValues = super.setDocument(docId); if (numValues == 0) { sortedIds = null; return 0; } bytes.clear(); bytes.reinit(); for (int i = 0; i < numValues; ++i) { bytes.add(super.nextValue(), super.currentValueHash()); } numUniqueValues = bytes.size(); sortedIds = bytes.sort(BytesRef.getUTF8SortedAsUnicodeComparator()); pos = 0; return numUniqueValues; } @Override public BytesRef nextValue() { bytes.get(sortedIds[pos++], spare); return spare; } @Override public int currentValueHash() { return spare.hashCode(); } @Override public Order getOrder() { return Order.BYTES; } }
1no label
src_main_java_org_elasticsearch_search_aggregations_support_FieldDataSource.java
323
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class ClientMapTest { static HazelcastInstance client; static HazelcastInstance server; static TestMapStore flushMapStore = new TestMapStore(); static TestMapStore transientMapStore = new TestMapStore(); @BeforeClass public static void init() { Config config = new Config(); config.getMapConfig("flushMap"). setMapStoreConfig(new MapStoreConfig() .setWriteDelaySeconds(1000) .setImplementation(flushMapStore)); config.getMapConfig("putTransientMap"). setMapStoreConfig(new MapStoreConfig() .setWriteDelaySeconds(1000) .setImplementation(transientMapStore)); server = Hazelcast.newHazelcastInstance(config); client = HazelcastClient.newHazelcastClient(null); } public IMap createMap() { return client.getMap(randomString()); } @AfterClass public static void destroy() { client.shutdown(); Hazelcast.shutdownAll(); } @Test public void testIssue537() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(2); final CountDownLatch nullLatch = new CountDownLatch(2); final IMap map = createMap(); final EntryListener listener = new EntryAdapter() { public void entryAdded(EntryEvent event) { latch.countDown(); } public void entryEvicted(EntryEvent event) { final Object value = event.getValue(); final Object oldValue = event.getOldValue(); if (value != null) { nullLatch.countDown(); } if (oldValue != null) { nullLatch.countDown(); } latch.countDown(); } }; final String id = map.addEntryListener(listener, true); map.put("key1", new GenericEvent("value1"), 2, TimeUnit.SECONDS); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertTrue(nullLatch.await(1, TimeUnit.SECONDS)); map.removeEntryListener(id); map.put("key2", new GenericEvent("value2")); assertEquals(1, map.size()); } @Test public void testContains() throws Exception { final IMap map = createMap(); fillMap(map); assertFalse(map.containsKey("key10")); assertTrue(map.containsKey("key1")); assertFalse(map.containsValue("value10")); assertTrue(map.containsValue("value1")); } @Test public void testGet() { final IMap map = createMap(); fillMap(map); for (int i = 0; i < 10; i++) { Object o = map.get("key" + i); assertEquals("value" + i, o); } } @Test public void testRemoveAndDelete() { final IMap map = createMap(); fillMap(map); assertNull(map.remove("key10")); map.delete("key9"); assertEquals(9, map.size()); for (int i = 0; i < 9; i++) { Object o = map.remove("key" + i); assertEquals("value" + i, o); } assertEquals(0, map.size()); } @Test public void testRemoveIfSame() { final IMap map = createMap(); fillMap(map); assertFalse(map.remove("key2", "value")); assertEquals(10, map.size()); assertTrue(map.remove("key2", "value2")); assertEquals(9, map.size()); } @Test public void testFlush() throws InterruptedException { flushMapStore.latch = new CountDownLatch(1); IMap<Object, Object> map = client.getMap("flushMap"); map.put(1l, "value"); map.flush(); assertOpenEventually(flushMapStore.latch, 5); } @Test public void testGetAllPutAll() { final IMap map = createMap(); Map mm = new HashMap(); for (int i = 0; i < 100; i++) { mm.put(i, i); } map.putAll(mm); assertEquals(map.size(), 100); for (int i = 0; i < 100; i++) { assertEquals(map.get(i), i); } Set ss = new HashSet(); ss.add(1); ss.add(3); Map m2 = map.getAll(ss); assertEquals(m2.size(), 2); assertEquals(m2.get(1), 1); assertEquals(m2.get(3), 3); } @Test public void testAsyncGet() throws Exception { final IMap map = createMap(); fillMap(map); Future f = map.getAsync("key1"); Object o = f.get(); assertEquals("value1", o); } @Test public void testAsyncPut() throws Exception { final IMap map = createMap(); fillMap(map); Future f = map.putAsync("key3", "value"); Object o = f.get(); assertEquals("value3", o); assertEquals("value", map.get("key3")); } @Test public void testAsyncPutWithTtl() throws Exception { final IMap map = createMap(); final CountDownLatch latch = new CountDownLatch(1); map.addEntryListener(new EntryAdapter<String, String>() { public void entryEvicted(EntryEvent<String, String> event) { latch.countDown(); } }, true); Future<String> f1 = map.putAsync("key", "value1", 3, TimeUnit.SECONDS); String f1Val = f1.get(); assertNull(f1Val); assertEquals("value1", map.get("key")); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertNull(map.get("key")); } @Test public void testAsyncRemove() throws Exception { final IMap map = createMap(); fillMap(map); Future f = map.removeAsync("key4"); Object o = f.get(); assertEquals("value4", o); assertEquals(9, map.size()); } @Test public void testTryPutRemove() throws Exception { final IMap map = createMap(); assertTrue(map.tryPut("key1", "value1", 1, TimeUnit.SECONDS)); assertTrue(map.tryPut("key2", "value2", 1, TimeUnit.SECONDS)); map.lock("key1"); map.lock("key2"); final CountDownLatch latch = new CountDownLatch(2); new Thread() { public void run() { boolean result = map.tryPut("key1", "value3", 1, TimeUnit.SECONDS); if (!result) { latch.countDown(); } } }.start(); new Thread() { public void run() { boolean result = map.tryRemove("key2", 1, TimeUnit.SECONDS); if (!result) { latch.countDown(); } } }.start(); assertTrue(latch.await(20, TimeUnit.SECONDS)); assertEquals("value1", map.get("key1")); assertEquals("value2", map.get("key2")); map.forceUnlock("key1"); map.forceUnlock("key2"); } @Test public void testPutTtl() throws Exception { final IMap map = createMap(); map.put("key1", "value1", 1, TimeUnit.SECONDS); assertNotNull(map.get("key1")); Thread.sleep(2000); assertNull(map.get("key1")); } @Test public void testPutIfAbsent() throws Exception { final IMap map = createMap(); assertNull(map.putIfAbsent("key1", "value1")); assertEquals("value1", map.putIfAbsent("key1", "value3")); } @Test public void testPutIfAbsentTtl() throws Exception { final IMap map = createMap(); assertNull(map.putIfAbsent("key1", "value1", 1, TimeUnit.SECONDS)); assertEquals("value1", map.putIfAbsent("key1", "value3", 1, TimeUnit.SECONDS)); Thread.sleep(6000); assertNull(map.putIfAbsent("key1", "value3", 1, TimeUnit.SECONDS)); assertEquals("value3", map.putIfAbsent("key1", "value4", 1, TimeUnit.SECONDS)); } @Test public void testSet() throws Exception { final IMap map = createMap(); map.set("key1", "value1"); assertEquals("value1", map.get("key1")); map.set("key1", "value2"); assertEquals("value2", map.get("key1")); map.set("key1", "value3", 1, TimeUnit.SECONDS); assertEquals("value3", map.get("key1")); Thread.sleep(2000); assertNull(map.get("key1")); } @Test public void testPutTransient() throws InterruptedException { transientMapStore.latch = new CountDownLatch(1); IMap<Object, Object> map = client.getMap("putTransientMap"); map.putTransient(3l, "value1", 100, TimeUnit.SECONDS); map.flush(); assertFalse(transientMapStore.latch.await(5, TimeUnit.SECONDS)); } @Test public void testLock() throws Exception { final IMap map = createMap(); map.put("key1", "value1"); assertEquals("value1", map.get("key1")); map.lock("key1"); final CountDownLatch latch = new CountDownLatch(1); new Thread() { public void run() { map.tryPut("key1", "value2", 1, TimeUnit.SECONDS); latch.countDown(); } }.start(); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertEquals("value1", map.get("key1")); map.forceUnlock("key1"); } @Test public void testLockTtl() throws Exception { final IMap map = createMap(); map.put("key1", "value1"); assertEquals("value1", map.get("key1")); map.lock("key1", 2, TimeUnit.SECONDS); final CountDownLatch latch = new CountDownLatch(1); new Thread() { public void run() { map.tryPut("key1", "value2", 5, TimeUnit.SECONDS); latch.countDown(); } }.start(); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertFalse(map.isLocked("key1")); assertEquals("value2", map.get("key1")); map.forceUnlock("key1"); } @Test public void testLockTtl2() throws Exception { final IMap map = createMap(); map.lock("key1", 3, TimeUnit.SECONDS); final CountDownLatch latch = new CountDownLatch(2); new Thread() { public void run() { if (!map.tryLock("key1")) { latch.countDown(); } try { if (map.tryLock("key1", 5, TimeUnit.SECONDS)) { latch.countDown(); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); assertTrue(latch.await(10, TimeUnit.SECONDS)); map.forceUnlock("key1"); } @Test public void testTryLock() throws Exception { final IMap map = createMap(); final IMap tempMap = map; assertTrue(tempMap.tryLock("key1", 2, TimeUnit.SECONDS)); final CountDownLatch latch = new CountDownLatch(1); new Thread() { public void run() { try { if (!tempMap.tryLock("key1", 2, TimeUnit.SECONDS)) { latch.countDown(); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); assertTrue(latch.await(100, TimeUnit.SECONDS)); assertTrue(tempMap.isLocked("key1")); final CountDownLatch latch2 = new CountDownLatch(1); new Thread() { public void run() { try { if (tempMap.tryLock("key1", 20, TimeUnit.SECONDS)) { latch2.countDown(); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); Thread.sleep(1000); tempMap.unlock("key1"); assertTrue(latch2.await(100, TimeUnit.SECONDS)); assertTrue(tempMap.isLocked("key1")); tempMap.forceUnlock("key1"); } @Test public void testForceUnlock() throws Exception { final IMap map = createMap(); map.lock("key1"); final CountDownLatch latch = new CountDownLatch(1); new Thread() { public void run() { map.forceUnlock("key1"); latch.countDown(); } }.start(); assertTrue(latch.await(100, TimeUnit.SECONDS)); assertFalse(map.isLocked("key1")); } @Test public void testValues() { final IMap map = createMap(); fillMap(map); final Collection values = map.values(new SqlPredicate("this == value1")); assertEquals(1, values.size()); assertEquals("value1", values.iterator().next()); } @Test public void testReplace() throws Exception { final IMap map = createMap(); assertNull(map.replace("key1", "value1")); map.put("key1", "value1"); assertEquals("value1", map.replace("key1", "value2")); assertEquals("value2", map.get("key1")); assertFalse(map.replace("key1", "value1", "value3")); assertEquals("value2", map.get("key1")); assertTrue(map.replace("key1", "value2", "value3")); assertEquals("value3", map.get("key1")); } @Test public void testSubmitToKey() throws Exception { final IMap map = createMap(); map.put(1, 1); Future f = map.submitToKey(1, new IncrementorEntryProcessor()); assertEquals(2, f.get()); assertEquals(2, map.get(1)); } @Test public void testSubmitToNonExistentKey() throws Exception { final IMap map = createMap(); Future f = map.submitToKey(11, new IncrementorEntryProcessor()); assertEquals(1, f.get()); assertEquals(1, map.get(11)); } @Test public void testSubmitToKeyWithCallback() throws Exception { final IMap map = createMap(); map.put(1, 1); final CountDownLatch latch = new CountDownLatch(1); ExecutionCallback executionCallback = new ExecutionCallback() { @Override public void onResponse(Object response) { latch.countDown(); } @Override public void onFailure(Throwable t) { } }; map.submitToKey(1, new IncrementorEntryProcessor(), executionCallback); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertEquals(2, map.get(1)); } @Test public void testListener() throws InterruptedException { final IMap map = createMap(); final CountDownLatch latch1Add = new CountDownLatch(5); final CountDownLatch latch1Remove = new CountDownLatch(2); final CountDownLatch latch2Add = new CountDownLatch(1); final CountDownLatch latch2Remove = new CountDownLatch(1); EntryListener listener1 = new EntryAdapter() { public void entryAdded(EntryEvent event) { latch1Add.countDown(); } public void entryRemoved(EntryEvent event) { latch1Remove.countDown(); } }; EntryListener listener2 = new EntryAdapter() { public void entryAdded(EntryEvent event) { latch2Add.countDown(); } public void entryRemoved(EntryEvent event) { latch2Remove.countDown(); } }; map.addEntryListener(listener1, false); map.addEntryListener(listener2, "key3", true); Thread.sleep(1000); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); map.put("key4", "value4"); map.put("key5", "value5"); map.remove("key1"); map.remove("key3"); assertTrue(latch1Add.await(10, TimeUnit.SECONDS)); assertTrue(latch1Remove.await(10, TimeUnit.SECONDS)); assertTrue(latch2Add.await(5, TimeUnit.SECONDS)); assertTrue(latch2Remove.await(5, TimeUnit.SECONDS)); } @Test public void testPredicateListenerWithPortableKey() throws InterruptedException { final IMap tradeMap = createMap(); final CountDownLatch countDownLatch = new CountDownLatch(1); final AtomicInteger atomicInteger = new AtomicInteger(0); EntryListener listener = new EntryAdapter() { @Override public void entryAdded(EntryEvent event) { atomicInteger.incrementAndGet(); countDownLatch.countDown(); } }; AuthenticationRequest key = new AuthenticationRequest(new UsernamePasswordCredentials("a", "b")); tradeMap.addEntryListener(listener, key, true); AuthenticationRequest key2 = new AuthenticationRequest(new UsernamePasswordCredentials("a", "c")); tradeMap.put(key2, 1); assertFalse(countDownLatch.await(5, TimeUnit.SECONDS)); assertEquals(0, atomicInteger.get()); } @Test public void testBasicPredicate() { final IMap map = createMap(); fillMap(map); final Collection collection = map.values(new SqlPredicate("this == value1")); assertEquals("value1", collection.iterator().next()); final Set set = map.keySet(new SqlPredicate("this == value1")); assertEquals("key1", set.iterator().next()); final Set<Map.Entry<String, String>> set1 = map.entrySet(new SqlPredicate("this == value1")); assertEquals("key1", set1.iterator().next().getKey()); assertEquals("value1", set1.iterator().next().getValue()); } private void fillMap(IMap map) { for (int i = 0; i < 10; i++) { map.put("key" + i, "value" + i); } } /** * Issue #923 */ @Test public void testPartitionAwareKey() { String name = randomString(); PartitionAwareKey key = new PartitionAwareKey("key", "123"); String value = "value"; IMap<Object, Object> map1 = server.getMap(name); map1.put(key, value); assertEquals(value, map1.get(key)); IMap<Object, Object> map2 = client.getMap(name); assertEquals(value, map2.get(key)); } private static class PartitionAwareKey implements PartitionAware, Serializable { private final String key; private final String pk; private PartitionAwareKey(String key, String pk) { this.key = key; this.pk = pk; } @Override public Object getPartitionKey() { return pk; } } @Test public void testExecuteOnKeys() throws Exception { String name = randomString(); IMap<Integer, Integer> map = client.getMap(name); IMap<Integer, Integer> map2 = client.getMap(name); for (int i = 0; i < 10; i++) { map.put(i, 0); } Set keys = new HashSet(); keys.add(1); keys.add(4); keys.add(7); keys.add(9); final Map<Integer, Object> resultMap = map2.executeOnKeys(keys, new IncrementorEntryProcessor()); assertEquals(1, resultMap.get(1)); assertEquals(1, resultMap.get(4)); assertEquals(1, resultMap.get(7)); assertEquals(1, resultMap.get(9)); assertEquals(1, (int) map.get(1)); assertEquals(0, (int) map.get(2)); assertEquals(0, (int) map.get(3)); assertEquals(1, (int) map.get(4)); assertEquals(0, (int) map.get(5)); assertEquals(0, (int) map.get(6)); assertEquals(1, (int) map.get(7)); assertEquals(0, (int) map.get(8)); assertEquals(1, (int) map.get(9)); } /** * Issue #996 */ @Test public void testEntryListener() throws InterruptedException { final CountDownLatch gateAdd = new CountDownLatch(2); final CountDownLatch gateRemove = new CountDownLatch(1); final CountDownLatch gateEvict = new CountDownLatch(1); final CountDownLatch gateUpdate = new CountDownLatch(1); final String mapName = randomString(); final IMap<Object, Object> serverMap = server.getMap(mapName); serverMap.put(3, new Deal(3)); final IMap<Object, Object> clientMap = client.getMap(mapName); assertEquals(1, clientMap.size()); final EntryListener listener = new EntListener(gateAdd, gateRemove, gateEvict, gateUpdate); clientMap.addEntryListener(listener, new SqlPredicate("id=1"), 2, true); clientMap.put(2, new Deal(1)); clientMap.put(2, new Deal(1)); clientMap.remove(2); clientMap.put(2, new Deal(1)); clientMap.evict(2); assertTrue(gateAdd.await(10, TimeUnit.SECONDS)); assertTrue(gateRemove.await(10, TimeUnit.SECONDS)); assertTrue(gateEvict.await(10, TimeUnit.SECONDS)); assertTrue(gateUpdate.await(10, TimeUnit.SECONDS)); } static class EntListener implements EntryListener<Integer, Deal>, Serializable { private final CountDownLatch _gateAdd; private final CountDownLatch _gateRemove; private final CountDownLatch _gateEvict; private final CountDownLatch _gateUpdate; EntListener(CountDownLatch gateAdd, CountDownLatch gateRemove, CountDownLatch gateEvict, CountDownLatch gateUpdate) { _gateAdd = gateAdd; _gateRemove = gateRemove; _gateEvict = gateEvict; _gateUpdate = gateUpdate; } @Override public void entryAdded(EntryEvent<Integer, Deal> arg0) { _gateAdd.countDown(); } @Override public void entryEvicted(EntryEvent<Integer, Deal> arg0) { _gateEvict.countDown(); } @Override public void entryRemoved(EntryEvent<Integer, Deal> arg0) { _gateRemove.countDown(); } @Override public void entryUpdated(EntryEvent<Integer, Deal> arg0) { _gateUpdate.countDown(); } } static class Deal implements Serializable { Integer id; Deal(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } private static class IncrementorEntryProcessor extends AbstractEntryProcessor implements DataSerializable { IncrementorEntryProcessor() { super(true); } public Object process(Map.Entry entry) { Integer value = (Integer) entry.getValue(); if (value == null) { value = 0; } if (value == -1) { entry.setValue(null); return null; } value++; entry.setValue(value); return value; } @Override public void writeData(ObjectDataOutput out) throws IOException { } @Override public void readData(ObjectDataInput in) throws IOException { } public void processBackup(Map.Entry entry) { entry.setValue((Integer) entry.getValue() + 1); } } @Test public void testMapStatistics() throws Exception { String name = randomString(); final LocalMapStats localMapStats = server.getMap(name).getLocalMapStats(); final IMap map = client.getMap(name); final int operationCount = 1000; for (int i = 0; i < operationCount; i++) { map.put(i, i); map.get(i); map.remove(i); } assertEquals("put count", operationCount, localMapStats.getPutOperationCount()); assertEquals("get count", operationCount, localMapStats.getGetOperationCount()); assertEquals("remove count", operationCount, localMapStats.getRemoveOperationCount()); assertTrue("put latency", 0 < localMapStats.getTotalPutLatency()); assertTrue("get latency", 0 < localMapStats.getTotalGetLatency()); assertTrue("remove latency", 0 < localMapStats.getTotalRemoveLatency()); } static class TestMapStore extends MapStoreAdapter<Long, String> { public volatile CountDownLatch latch; @Override public void store(Long key, String value) { if (latch != null) { latch.countDown(); } } @Override public void storeAll(Map<Long, String> map) { if (latch != null) { latch.countDown(); } } @Override public void deleteAll(Collection<Long> keys) { if (latch != null) { latch.countDown(); } } @Override public void delete(Long key) { if (latch != null) { latch.countDown(); } } } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java
1,277
@ClusterScope(scope=Scope.TEST) public class BlockClusterStatsTests extends ElasticsearchIntegrationTest { @Test public void testBlocks() throws Exception { createIndex("foo"); ClusterUpdateSettingsResponse updateSettingsResponse = client().admin().cluster().prepareUpdateSettings().setTransientSettings( ImmutableSettings.settingsBuilder().put("cluster.blocks.read_only", true).build()).get(); assertThat(updateSettingsResponse.isAcknowledged(), is(true)); UpdateSettingsResponse indexSettingsResponse = client().admin().indices().prepareUpdateSettings("foo").setSettings( ImmutableSettings.settingsBuilder().put("index.blocks.read_only", true)).get(); assertThat(indexSettingsResponse.isAcknowledged(), is(true)); ClusterStateResponse clusterStateResponseUnfiltered = client().admin().cluster().prepareState().clear().setBlocks(true).get(); assertThat(clusterStateResponseUnfiltered.getState().blocks().global(), hasSize(1)); assertThat(clusterStateResponseUnfiltered.getState().blocks().indices().size(), is(1)); ClusterStateResponse clusterStateResponse = client().admin().cluster().prepareState().clear().get(); assertThat(clusterStateResponse.getState().blocks().global(), hasSize(0)); assertThat(clusterStateResponse.getState().blocks().indices().size(), is(0)); } }
0true
src_test_java_org_elasticsearch_cluster_BlockClusterStatsTests.java
1,318
public class JDTModule extends LazyModule { private JDTModuleManager moduleManager; private List<IPackageFragmentRoot> packageFragmentRoots; private File artifact; private String repositoryDisplayString = ""; private WeakReference<ExternalModulePhasedUnits> sourceModulePhasedUnits; // Here we have a weak ref on the PhasedUnits because there are already stored as strong references in the TypeChecker phasedUnitsOfDependencies list. // But in the future we might remove the strong reference in the typeChecker and use strong references here, which would be // much more modular (think of several versions of a module imported in a non-shared way in the same projet). private PhasedUnitMap<ExternalPhasedUnit, SoftReference<ExternalPhasedUnit>> binaryModulePhasedUnits; private Properties classesToSources = new Properties(); private Map<String, String> javaImplFilesToCeylonDeclFiles = new HashMap<String, String>(); private String sourceArchivePath = null; private IProject originalProject = null; private JDTModule originalModule = null; private Set<String> originalUnitsToRemove = new LinkedHashSet<>(); private Set<String> originalUnitsToAdd = new LinkedHashSet<>(); private ArtifactResultType artifactType = ArtifactResultType.OTHER; private Exception resolutionException = null; public JDTModule(JDTModuleManager jdtModuleManager, List<IPackageFragmentRoot> packageFragmentRoots) { this.moduleManager = jdtModuleManager; this.packageFragmentRoots = packageFragmentRoots; } private File returnCarFile() { if (isCeylonBinaryArchive()) { return artifact; } if (isSourceArchive()) { return new File(sourceArchivePath.substring(0, sourceArchivePath.length()-ArtifactContext.SRC.length()) + ArtifactContext.CAR); } return null; } synchronized void setArtifact(ArtifactResult artifactResult) { artifact = artifactResult.artifact(); repositoryDisplayString = artifactResult.repositoryDisplayString(); if (artifact.getName().endsWith(ArtifactContext.SRC)) { moduleType = ModuleType.CEYLON_SOURCE_ARCHIVE; } else if(artifact.getName().endsWith(ArtifactContext.CAR)) { moduleType = ModuleType.CEYLON_BINARY_ARCHIVE; } else if(artifact.getName().endsWith(ArtifactContext.JAR)) { moduleType = ModuleType.JAVA_BINARY_ARCHIVE; } artifactType = artifactResult.type(); if (isCeylonBinaryArchive()){ String carPath = artifact.getPath(); sourceArchivePath = carPath.substring(0, carPath.length()-ArtifactContext.CAR.length()) + ArtifactContext.SRC; try { classesToSources = CarUtils.retrieveMappingFile(returnCarFile()); javaImplFilesToCeylonDeclFiles = CarUtils.searchCeylonFilesForJavaImplementations(classesToSources, new File(sourceArchivePath)); } catch (Exception e) { CeylonPlugin.getInstance().getLog().log(new Status(IStatus.WARNING, CeylonPlugin.PLUGIN_ID, "Cannot find the source archive for the Ceylon binary module " + getSignature(), e)); } class BinaryPhasedUnits extends PhasedUnitMap<ExternalPhasedUnit, SoftReference<ExternalPhasedUnit>> { Set<String> sourceCannotBeResolved = new HashSet<String>(); public BinaryPhasedUnits() { String fullPathPrefix = sourceArchivePath + "!/"; for (Object value : classesToSources.values()) { String sourceRelativePath = (String) value; String path = fullPathPrefix + sourceRelativePath; phasedUnitPerPath.put(path, new SoftReference<ExternalPhasedUnit>(null)); relativePathToPath.put(sourceRelativePath, path); } } @Override public ExternalPhasedUnit getPhasedUnit(String path) { if (! phasedUnitPerPath.containsKey(path)) { if (path.endsWith(".ceylon")) { // Case of a Ceylon file with a Java implementation, the classesToSources key is the Java source file. String javaFileRelativePath = getJavaImplementationFile(path.replace(sourceArchivePath + "!/", "")); if (javaFileRelativePath != null) { return super.getPhasedUnit(sourceArchivePath + "!/" + javaFileRelativePath); } } return null; } return super.getPhasedUnit(path); } @Override public ExternalPhasedUnit getPhasedUnitFromRelativePath(String relativePath) { if (relativePath.startsWith("/")) { relativePath = relativePath.substring(1); } if (! relativePathToPath.containsKey(relativePath)) { if (relativePath.endsWith(".ceylon")) { // Case of a Ceylon file with a Java implementation, the classesToSources key is the Java source file. String javaFileRelativePath = getJavaImplementationFile(relativePath); if (javaFileRelativePath != null) { return super.getPhasedUnitFromRelativePath(javaFileRelativePath); } } return null; } return super.getPhasedUnitFromRelativePath(relativePath); } @Override protected ExternalPhasedUnit fromStoredType(SoftReference<ExternalPhasedUnit> storedValue, String path) { ExternalPhasedUnit result = storedValue.get(); if (result == null) { if (!sourceCannotBeResolved.contains(path)) { result = buildPhasedUnitForBinaryUnit(path); if (result != null) { phasedUnitPerPath.put(path, toStoredType(result)); } else { sourceCannotBeResolved.add(path); } } } return result; } @Override protected void addInReturnedList(List<ExternalPhasedUnit> list, ExternalPhasedUnit phasedUnit) { if (phasedUnit != null) { list.add(phasedUnit); } } @Override protected SoftReference<ExternalPhasedUnit> toStoredType(ExternalPhasedUnit phasedUnit) { return new SoftReference<ExternalPhasedUnit>(phasedUnit); } @Override public void removePhasedUnitForRelativePath(String relativePath) { // Don't clean the Package since we are in the binary case String path = relativePathToPath.get(relativePath); relativePathToPath.remove(relativePath); phasedUnitPerPath.remove(path); } }; binaryModulePhasedUnits = new BinaryPhasedUnits(); } if (isSourceArchive()) { sourceArchivePath = artifact.getPath(); try { classesToSources = CarUtils.retrieveMappingFile(returnCarFile()); javaImplFilesToCeylonDeclFiles = CarUtils.searchCeylonFilesForJavaImplementations(classesToSources, artifact); } catch (Exception e) { e.printStackTrace(); } sourceModulePhasedUnits = new WeakReference<ExternalModulePhasedUnits>(null); } try { IJavaProject javaProject = moduleManager.getJavaProject(); if (javaProject != null) { for (IProject refProject : javaProject.getProject().getReferencedProjects()) { if (artifact.getAbsolutePath().contains(CeylonBuilder.getCeylonModulesOutputDirectory(refProject).getAbsolutePath())) { originalProject = refProject; } } } } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (isJavaBinaryArchive()){ String carPath = artifact.getPath(); sourceArchivePath = carPath.substring(0, carPath.length()-ArtifactContext.JAR.length()) + (artifactResult.type().equals(ArtifactResultType.MAVEN) ? ArtifactContext.MAVEN_SRC : ArtifactContext.SRC); } } public String getRepositoryDisplayString() { if (isJDKModule()) { return JDKRepository.JDK_REPOSITORY_DISPLAY_STRING; } return repositoryDisplayString; } synchronized void setSourcePhasedUnits(final ExternalModulePhasedUnits modulePhasedUnits) { sourceModulePhasedUnits = new WeakReference<ExternalModulePhasedUnits>(modulePhasedUnits); } public File getArtifact() { return artifact; } public ArtifactResultType getArtifactType() { return artifactType; } private Properties getClassesToSources() { if (classesToSources.isEmpty() && getNameAsString().equals("java.base")) { for (Map.Entry<Object, Object> entry : ((JDTModule)getLanguageModule()).getClassesToSources().entrySet()) { if (entry.getKey().toString().startsWith("com/redhat/ceylon/compiler/java/language/")) { classesToSources.put(entry.getKey().toString().replace("com/redhat/ceylon/compiler/java/language/", "java/lang/"), entry.getValue().toString()); } } } return classesToSources; } public String toSourceUnitRelativePath(String binaryUnitRelativePath) { return getClassesToSources().getProperty(binaryUnitRelativePath); } public String getJavaImplementationFile(String ceylonFileRelativePath) { String javaFileRelativePath = null; for (Entry<String, String> entry : javaImplFilesToCeylonDeclFiles.entrySet()) { if (entry.getValue().equals(ceylonFileRelativePath)) { javaFileRelativePath = entry.getKey(); } } return javaFileRelativePath; } public String getCeylonDeclarationFile(String sourceUnitRelativePath) { if (sourceUnitRelativePath==null||sourceUnitRelativePath.endsWith(".ceylon")) { return sourceUnitRelativePath; } return javaImplFilesToCeylonDeclFiles.get(sourceUnitRelativePath); } public List<String> toBinaryUnitRelativePaths(String sourceUnitRelativePath) { if (sourceUnitRelativePath == null) { return Collections.emptyList(); } List<String> result = new ArrayList<String>(); for (Entry<Object, Object> entry : classesToSources.entrySet()) { if (sourceUnitRelativePath.equals(entry.getValue())) { result.add((String) entry.getKey()); } } return result; } public synchronized List<IPackageFragmentRoot> getPackageFragmentRoots() { if (packageFragmentRoots.isEmpty() && ! moduleManager.isExternalModuleLoadedFromSource(getNameAsString())) { IJavaProject javaProject = moduleManager.getJavaProject(); if (javaProject != null) { if (this.equals(getLanguageModule())) { IClasspathEntry runtimeClasspathEntry = null; try { for (IClasspathEntry entry : javaProject.getRawClasspath()) { if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER && entry.getPath().segment(0).equals(CeylonLanguageModuleContainer.CONTAINER_ID)) { runtimeClasspathEntry = entry; break; } } if (runtimeClasspathEntry != null) { for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) { if (root.exists() && javaProject.isOnClasspath(root) && root.getRawClasspathEntry().equals(runtimeClasspathEntry)) { packageFragmentRoots.add(root); } } } } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { File jarToSearch = null; try { jarToSearch = returnCarFile(); if (jarToSearch == null) { RepositoryManager repoMgr = CeylonBuilder.getProjectRepositoryManager(javaProject.getProject()); if (repoMgr != null) { jarToSearch = CeylonProjectModulesContainer.getModuleArtifact(repoMgr, this); } } if (jarToSearch != null) { IPackageFragmentRoot root = moduleManager.getJavaProject().getPackageFragmentRoot(jarToSearch.toString()); if (root instanceof JarPackageFragmentRoot) { JarPackageFragmentRoot jarRoot = (JarPackageFragmentRoot) root; if (jarRoot.getJar().getName().equals(jarToSearch.getPath())) { packageFragmentRoots.add(root); } } } } catch (CoreException e) { if (jarToSearch != null) { System.err.println("Exception trying to get Jar file '" + jarToSearch + "' :"); } e.printStackTrace(); } } } } return packageFragmentRoots; } @Override protected JDTModelLoader getModelLoader() { return moduleManager.getModelLoader(); } public JDTModuleManager getModuleManager() { return moduleManager; } @Override public List<Package> getAllPackages() { synchronized (getModelLoader()) { // force-load every package from the module if we can loadAllPackages(new HashSet<String>()); // now delegate return super.getAllPackages(); } } private void loadAllPackages(Set<String> alreadyScannedModules) { Set<String> packageList = listPackages(); for (String packageName : packageList) { getPackage(packageName); } // now force-load other modules for (ModuleImport mi: getImports()) { Module importedModule = mi.getModule(); if(importedModule instanceof JDTModule && alreadyScannedModules.add(importedModule.getNameAsString())){ ((JDTModule)importedModule).loadAllPackages(alreadyScannedModules); } } } private Set<String> listPackages() { Set<String> packageList = new TreeSet<String>(); String name = getNameAsString(); if(JDKUtils.isJDKModule(name)){ packageList.addAll(JDKUtils.getJDKPackagesByModule(name)); }else if(JDKUtils.isOracleJDKModule(name)){ packageList.addAll(JDKUtils.getOracleJDKPackagesByModule(name)); } else if(isJava() || true){ for(IPackageFragmentRoot fragmentRoot : getPackageFragmentRoots()){ if(!fragmentRoot.exists()) continue; IParent parent = fragmentRoot; listPackages(packageList, parent); } } return packageList; } private void listPackages(Set<String> packageList, IParent parent) { try { for (IJavaElement child : parent.getChildren()) { if (child instanceof PackageFragment) { packageList.add(child.getElementName()); listPackages(packageList, (IPackageFragment) child); } } } catch (JavaModelException e) { e.printStackTrace(); } } @Override public void loadPackageList(ArtifactResult artifact) { try { super.loadPackageList(artifact); } catch(Exception e) { CeylonPlugin.getInstance().getLog().log(new Status(IStatus.ERROR, CeylonPlugin.PLUGIN_ID, "Failed loading the package list of module " + getSignature(), e)); } JDTModelLoader modelLoader = getModelLoader(); if (modelLoader != null) { synchronized(modelLoader){ String name = getNameAsString(); for(String pkg : jarPackages){ if(name.equals("ceylon.language") && ! pkg.startsWith("ceylon.language")) { // special case for the language module to hide stuff continue; } modelLoader.findOrCreatePackage(this, pkg); } } } } private ModuleType moduleType; private enum ModuleType { PROJECT_MODULE, CEYLON_SOURCE_ARCHIVE, CEYLON_BINARY_ARCHIVE, JAVA_BINARY_ARCHIVE, SDK_MODULE, UNKNOWN } public void setProjectModule() { moduleType = ModuleType.PROJECT_MODULE; } public boolean isCeylonArchive() { return isCeylonBinaryArchive() || isSourceArchive(); } public boolean isDefaultModule() { return this.equals(moduleManager.getContext().getModules().getDefaultModule()); } public boolean isProjectModule() { return ModuleType.PROJECT_MODULE.equals(moduleType); } public boolean isJDKModule() { synchronized (this) { if (moduleType == null) { if (JDKUtils.isJDKModule(getNameAsString()) || JDKUtils.isOracleJDKModule(getNameAsString())) { moduleType = ModuleType.SDK_MODULE; } } } return ModuleType.SDK_MODULE.equals(moduleType); } public boolean isUnresolved() { return artifact == null && ! isAvailable(); } public boolean isJavaBinaryArchive() { return ModuleType.JAVA_BINARY_ARCHIVE.equals(moduleType); } public boolean isCeylonBinaryArchive() { return ModuleType.CEYLON_BINARY_ARCHIVE.equals(moduleType); } public boolean isSourceArchive() { return ModuleType.CEYLON_SOURCE_ARCHIVE.equals(moduleType); } public synchronized List<? extends PhasedUnit> getPhasedUnits() { PhasedUnitMap<? extends PhasedUnit, ?> phasedUnitMap = null; if (isCeylonBinaryArchive()) { phasedUnitMap = binaryModulePhasedUnits; } if (isSourceArchive()) { phasedUnitMap = sourceModulePhasedUnits.get(); } if (phasedUnitMap != null) { synchronized (phasedUnitMap) { return phasedUnitMap.getPhasedUnits(); } } return Collections.emptyList(); } public ExternalPhasedUnit getPhasedUnit(IPath path) { PhasedUnitMap<? extends PhasedUnit, ?> phasedUnitMap = null; if (isCeylonBinaryArchive()) { phasedUnitMap = binaryModulePhasedUnits; } if (isSourceArchive()) { phasedUnitMap = sourceModulePhasedUnits.get(); } if (phasedUnitMap != null) { IPath sourceArchiveIPath = new Path(sourceArchivePath+"!"); synchronized (phasedUnitMap) { return (ExternalPhasedUnit) phasedUnitMap.getPhasedUnitFromRelativePath(path.makeRelativeTo(sourceArchiveIPath).toString()); } } return null; } public ExternalPhasedUnit getPhasedUnit(String path) { PhasedUnitMap<? extends PhasedUnit, ?> phasedUnitMap = null; if (isCeylonBinaryArchive()) { phasedUnitMap = binaryModulePhasedUnits; } if (isSourceArchive()) { phasedUnitMap = sourceModulePhasedUnits.get(); } if (phasedUnitMap != null) { synchronized (phasedUnitMap) { return (ExternalPhasedUnit) phasedUnitMap.getPhasedUnit(path); } } return null; } public ExternalPhasedUnit getPhasedUnit(VirtualFile file) { PhasedUnitMap<? extends PhasedUnit, ?> phasedUnitMap = null; if (isCeylonBinaryArchive()) { phasedUnitMap = binaryModulePhasedUnits; } if (isSourceArchive()) { phasedUnitMap = sourceModulePhasedUnits.get(); } if (phasedUnitMap != null) { synchronized (phasedUnitMap) { return (ExternalPhasedUnit) phasedUnitMap.getPhasedUnit(file); } } return null; } public ExternalPhasedUnit getPhasedUnitFromRelativePath(String relativePathToSource) { PhasedUnitMap<? extends PhasedUnit, ?> phasedUnitMap = null; if (isCeylonBinaryArchive()) { phasedUnitMap = binaryModulePhasedUnits; } if (isSourceArchive()) { phasedUnitMap = sourceModulePhasedUnits.get(); } if (phasedUnitMap != null) { synchronized (phasedUnitMap) { return (ExternalPhasedUnit) phasedUnitMap.getPhasedUnitFromRelativePath(relativePathToSource); } } return null; } public void removedOriginalUnit(String relativePathToSource) { if (isProjectModule()) { return; } originalUnitsToRemove.add(relativePathToSource); try { if (isCeylonBinaryArchive() || JavaCore.isJavaLikeFileName(relativePathToSource)) { List<String> unitPathsToSearch = new ArrayList<>(); unitPathsToSearch.add(relativePathToSource); unitPathsToSearch.addAll(toBinaryUnitRelativePaths(relativePathToSource)); for (String relativePathOfUnitToRemove : unitPathsToSearch) { Package p = getPackageFromRelativePath(relativePathOfUnitToRemove); if (p != null) { Set<Unit> units = new HashSet<>(); try { for(Declaration d : p.getMembers()) { Unit u = d.getUnit(); if (u.getRelativePath().equals(relativePathOfUnitToRemove)) { units.add(u); } } } catch(Exception e) { e.printStackTrace(); } for (Unit u : units) { try { for (Declaration d : u.getDeclarations()) { d.getMembers(); // Just to fully load the declaration before // the corresponding class is removed (so that // the real removing from the model loader // will not require reading the bindings. } } catch(Exception e) { e.printStackTrace(); } } } } } } catch(Exception e) { e.printStackTrace(); } } public void addedOriginalUnit(String relativePathToSource) { if (isProjectModule()) { return; } originalUnitsToAdd.add(relativePathToSource); } public void refresh() { if (originalUnitsToAdd.size() + originalUnitsToRemove.size() == 0) { // Nothing to refresh return; } try { PhasedUnitMap<? extends PhasedUnit, ?> phasedUnitMap = null; if (isCeylonBinaryArchive()) { JavaModelManager.getJavaModelManager().resetClasspathListCache(); JavaModelManager.getJavaModelManager().getJavaModel().refreshExternalArchives(getPackageFragmentRoots().toArray(new IPackageFragmentRoot[0]), null); phasedUnitMap = binaryModulePhasedUnits; } if (isSourceArchive()) { phasedUnitMap = sourceModulePhasedUnits.get(); } if (phasedUnitMap != null) { synchronized (phasedUnitMap) { for (String relativePathToRemove : originalUnitsToRemove) { if (isCeylonBinaryArchive() || JavaCore.isJavaLikeFileName(relativePathToRemove)) { List<String> unitPathsToSearch = new ArrayList<>(); unitPathsToSearch.add(relativePathToRemove); unitPathsToSearch.addAll(toBinaryUnitRelativePaths(relativePathToRemove)); for (String relativePathOfUnitToRemove : unitPathsToSearch) { Package p = getPackageFromRelativePath(relativePathOfUnitToRemove); if (p != null) { Set<Unit> units = new HashSet<>(); for(Declaration d : p.getMembers()) { Unit u = d.getUnit(); if (u.getRelativePath().equals(relativePathOfUnitToRemove)) { units.add(u); } } for (Unit u : units) { try { p.removeUnit(u); // In the future, when we are sure that we cannot add several unit objects with the // same relative path, we can add a break. } catch(Exception e) { e.printStackTrace(); } } } else { System.out.println("WARNING : The package of the following binary unit (" + relativePathOfUnitToRemove + ") " + "cannot be found in module " + getNameAsString() + artifact != null ? " (artifact=" + artifact.getAbsolutePath() + ")" : ""); } } } phasedUnitMap.removePhasedUnitForRelativePath(relativePathToRemove); } if (isSourceArchive()) { ClosableVirtualFile sourceArchive = null; try { sourceArchive = moduleManager.getContext().getVfs().getFromZipFile(new File(sourceArchivePath)); for (String relativePathToAdd : originalUnitsToAdd) { VirtualFile archiveEntry = null; archiveEntry = searchInSourceArchive( relativePathToAdd, sourceArchive); if (archiveEntry != null) { Package pkg = getPackageFromRelativePath(relativePathToAdd); ((ExternalModulePhasedUnits)phasedUnitMap).parseFile(archiveEntry, sourceArchive, pkg); } } } catch (Exception e) { StringBuilder error = new StringBuilder("Unable to read source artifact from "); error.append(sourceArchive); error.append( "\ndue to connection error: ").append(e.getMessage()); throw e; } finally { if (sourceArchive != null) { sourceArchive.close(); } } } classesToSources = CarUtils.retrieveMappingFile(returnCarFile()); javaImplFilesToCeylonDeclFiles = CarUtils.searchCeylonFilesForJavaImplementations(classesToSources, new File(sourceArchivePath)); originalUnitsToRemove.clear(); originalUnitsToAdd.clear(); } } if (isCeylonBinaryArchive() || isJavaBinaryArchive()) { jarPackages.clear(); loadPackageList(new ArtifactResult() { @Override public VisibilityType visibilityType() { return null; } @Override public String version() { return null; } @Override public ArtifactResultType type() { return null; } @Override public String name() { return null; } @Override public ImportType importType() { return null; } @Override public List<ArtifactResult> dependencies() throws RepositoryException { return null; } @Override public File artifact() throws RepositoryException { return artifact; } @Override public String repositoryDisplayString() { return ""; } @Override public PathFilter filter() { return null; } @Override public Repository repository() { return null; } }); } } catch (Exception e) { e.printStackTrace(); } } private Package getPackageFromRelativePath( String relativePathOfClassToRemove) { List<String> pathElements = Arrays.asList(relativePathOfClassToRemove.split("/")); String packageName = Util.formatPath(pathElements.subList(0, pathElements.size()-1)); Package p = findPackageNoLazyLoading(packageName); return p; } private ExternalPhasedUnit buildPhasedUnitForBinaryUnit(String sourceUnitFullPath) { if (sourceArchivePath == null || sourceUnitFullPath == null) { return null; } if (! sourceUnitFullPath.startsWith(sourceArchivePath)) { return null; } File sourceArchiveFile = new File(sourceArchivePath); if (! sourceArchiveFile.exists()) { return null; } ExternalPhasedUnit phasedUnit = null; String sourceUnitRelativePath = sourceUnitFullPath.replace(sourceArchivePath + "!/", ""); Package pkg = getPackageFromRelativePath(sourceUnitRelativePath); if (pkg != null) { try { JDTModuleManager moduleManager = getModuleManager(); ClosableVirtualFile sourceArchive = null; try { sourceArchive = moduleManager.getContext().getVfs().getFromZipFile(sourceArchiveFile); String ceylonSourceUnitRelativePath = sourceUnitRelativePath; if (sourceUnitRelativePath.endsWith(".java")) { ceylonSourceUnitRelativePath = javaImplFilesToCeylonDeclFiles.get(sourceUnitRelativePath); } VirtualFile archiveEntry = null; if (ceylonSourceUnitRelativePath != null) { archiveEntry = searchInSourceArchive( ceylonSourceUnitRelativePath, sourceArchive); } if (archiveEntry != null) { IProject project = moduleManager.getJavaProject().getProject(); CeylonLexer lexer = new CeylonLexer(NewlineFixingStringStream.fromStream(archiveEntry.getInputStream(), project.getDefaultCharset())); CommonTokenStream tokenStream = new CommonTokenStream(lexer); CeylonParser parser = new CeylonParser(tokenStream); Tree.CompilationUnit cu = parser.compilationUnit(); List<CommonToken> tokens = new ArrayList<CommonToken>(tokenStream.getTokens().size()); tokens.addAll(tokenStream.getTokens()); if(originalProject == null) { phasedUnit = new ExternalPhasedUnit(archiveEntry, sourceArchive, cu, new SingleSourceUnitPackage(pkg, sourceUnitFullPath), moduleManager, CeylonBuilder.getProjectTypeChecker(project), tokens) { @Override protected boolean reuseExistingDescriptorModels() { return true; } }; } else { phasedUnit = new CrossProjectPhasedUnit(archiveEntry, sourceArchive, cu, new SingleSourceUnitPackage(pkg, sourceUnitFullPath), moduleManager, CeylonBuilder.getProjectTypeChecker(project), tokens, originalProject) { @Override protected boolean reuseExistingDescriptorModels() { return true; } }; } } } catch (Exception e) { StringBuilder error = new StringBuilder("Unable to read source artifact from "); error.append(sourceArchive); error.append( "\ndue to connection error: ").append(e.getMessage()); System.err.println(error); } finally { if (sourceArchive != null) { sourceArchive.close(); } } if (phasedUnit != null) { phasedUnit.validateTree(); phasedUnit.visitSrcModulePhase(); phasedUnit.visitRemainingModulePhase(); phasedUnit.scanDeclarations(); phasedUnit.scanTypeDeclarations(); phasedUnit.validateRefinement(); } } catch (Exception e) { e.printStackTrace(); phasedUnit = null; } } return phasedUnit; } private VirtualFile searchInSourceArchive(String sourceUnitRelativePath, ClosableVirtualFile sourceArchive) { VirtualFile archiveEntry; archiveEntry = sourceArchive; for (String part : sourceUnitRelativePath.split("/")) { boolean found = false; for (VirtualFile vf : archiveEntry.getChildren()) { if (part.equals(vf.getName().replace("/", ""))) { archiveEntry = vf; found = true; break; } } if (!found) { archiveEntry = null; break; } } return archiveEntry; } public String getSourceArchivePath() { return sourceArchivePath; } public IProject getOriginalProject() { return originalProject; } public JDTModule getOriginalModule() { if (originalProject != null) { if (originalModule == null) { for (Module m : CeylonBuilder.getProjectModules(originalProject).getListOfModules()) { // TODO : in the future : manage version ?? in case we reference 2 identical projects with different version in the workspace if (m.getNameAsString().equals(getNameAsString())) { assert(m instanceof JDTModule); if (((JDTModule) m).isProjectModule()) { originalModule = (JDTModule) m; break; } } } } return originalModule; } return null; } public boolean containsClass(String className) { return className != null && (classesToSources != null ? classesToSources.containsKey(className) : false); } @Override public List<Package> getPackages() { return super.getPackages(); } @Override public void clearCache(final TypeDeclaration declaration) { clearCacheLocally(declaration); if (getProjectModuleDependencies() != null) { getProjectModuleDependencies().doWithReferencingModules(this, new TraversalAction<Module>() { @Override public void applyOn(Module module) { assert(module instanceof JDTModule); if (module instanceof JDTModule) { ((JDTModule) module).clearCacheLocally(declaration); } } }); getProjectModuleDependencies().doWithTransitiveDependencies(this, new TraversalAction<Module>() { @Override public void applyOn(Module module) { assert(module instanceof JDTModule); if (module instanceof JDTModule) { ((JDTModule) module).clearCacheLocally(declaration); } } }); ((JDTModule)getLanguageModule()).clearCacheLocally(declaration); } } private void clearCacheLocally(final TypeDeclaration declaration) { super.clearCache(declaration); } private ModuleDependencies projectModuleDependencies = null; private ModuleDependencies getProjectModuleDependencies() { if (projectModuleDependencies == null) { IJavaProject javaProject = moduleManager.getJavaProject(); if (javaProject != null) { projectModuleDependencies = CeylonBuilder.getModuleDependenciesForProject(javaProject.getProject()); } } return projectModuleDependencies; } public Iterable<Module> getReferencingModules() { if (getProjectModuleDependencies() != null) { return getProjectModuleDependencies().getReferencingModules(this); } return Collections.emptyList(); } public boolean resolutionFailed() { return resolutionException != null; } public void setResolutionException(Exception resolutionException) { if (resolutionException instanceof RuntimeException) this.resolutionException = resolutionException; } public List<JDTModule> getModuleInReferencingProjects() { if (! isProjectModule()) { return Collections.emptyList(); } IProject project = moduleManager.getJavaProject().getProject(); IProject[] referencingProjects = project.getReferencingProjects(); if (referencingProjects.length == 0) { return Collections.emptyList(); } List<JDTModule> result = new ArrayList<>(); for(IProject referencingProject : referencingProjects) { JDTModule referencingModule = null; Modules referencingProjectModules = CeylonBuilder.getProjectModules(referencingProject); if (referencingProjectModules != null) { for (Module m : referencingProjectModules.getListOfModules()) { if (m.getSignature().equals(getSignature())) { assert(m instanceof JDTModule); referencingModule = (JDTModule) m; break; } } } if (referencingModule != null) { result.add(referencingModule); } } return result; } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_model_JDTModule.java
3,577
public static class Defaults extends NumberFieldMapper.Defaults { public static final FieldType FIELD_TYPE = new FieldType(NumberFieldMapper.Defaults.FIELD_TYPE); static { FIELD_TYPE.freeze(); } public static final Double NULL_VALUE = null; }
0true
src_main_java_org_elasticsearch_index_mapper_core_DoubleFieldMapper.java
2,104
public interface Streamable { void readFrom(StreamInput in) throws IOException; void writeTo(StreamOutput out) throws IOException; }
0true
src_main_java_org_elasticsearch_common_io_stream_Streamable.java
1,404
@XmlRootElement(name = "orderItem") @XmlAccessorType(value = XmlAccessType.FIELD) public class OrderItemWrapper extends BaseWrapper implements APIWrapper<OrderItem> { @XmlElement protected Long id; @XmlElement protected String name; @XmlElement protected Integer quantity; @XmlElement protected Money retailPrice; @XmlElement protected Money salePrice; @XmlElement protected Long orderId; @XmlElement protected Long categoryId; @XmlElement protected Long skuId; @XmlElement protected Long productId; protected Boolean isBundle = Boolean.FALSE; @XmlElement(name = "orderItemAttribute") @XmlElementWrapper(name = "orderItemAttributes") protected List<OrderItemAttributeWrapper> orderItemAttributes; @XmlElement(name = "orderItemPriceDetails") @XmlElementWrapper(name = "orderItemPriceDetails") protected List<OrderItemPriceDetailWrapper> orderItemPriceDetails; //This will only be poulated if this is a BundleOrderItem @XmlElement(name = "bundleItem") @XmlElementWrapper(name = "bundleItems") protected List<OrderItemWrapper> bundleItems; // @XmlElementWrapper(name = "qualifiers") @XmlElement(name = "qualifier") protected List<OrderItemQualifierWrapper> qualifiers; @Override public void wrapDetails(OrderItem model, HttpServletRequest request) { this.id = model.getId(); this.name = model.getName(); this.quantity = model.getQuantity(); this.orderId = model.getOrder().getId(); this.retailPrice = model.getRetailPrice(); this.salePrice = model.getSalePrice(); if (model.getCategory() != null) { this.categoryId = model.getCategory().getId(); } if (model.getOrderItemAttributes() != null && !model.getOrderItemAttributes().isEmpty()) { Map<String, OrderItemAttribute> itemAttributes = model.getOrderItemAttributes(); this.orderItemAttributes = new ArrayList<OrderItemAttributeWrapper>(); Set<String> keys = itemAttributes.keySet(); for (String key : keys) { OrderItemAttributeWrapper orderItemAttributeWrapper = (OrderItemAttributeWrapper) context.getBean(OrderItemAttributeWrapper.class.getName()); orderItemAttributeWrapper.wrapSummary(itemAttributes.get(key), request); this.orderItemAttributes.add(orderItemAttributeWrapper); } } if (model.getOrderItemPriceDetails() != null && !model.getOrderItemPriceDetails().isEmpty()) { this.orderItemPriceDetails = new ArrayList<OrderItemPriceDetailWrapper>(); for (OrderItemPriceDetail orderItemPriceDetail : model.getOrderItemPriceDetails()) { OrderItemPriceDetailWrapper orderItemPriceDetailWrapper = (OrderItemPriceDetailWrapper) context.getBean(OrderItemPriceDetailWrapper.class.getName()); orderItemPriceDetailWrapper.wrapSummary(orderItemPriceDetail, request); this.orderItemPriceDetails.add(orderItemPriceDetailWrapper); } } if (model instanceof DiscreteOrderItem) { DiscreteOrderItem doi = (DiscreteOrderItem) model; this.skuId = doi.getSku().getId(); this.productId = doi.getProduct().getId(); this.isBundle = false; } else if (model instanceof BundleOrderItem) { BundleOrderItem boi = (BundleOrderItem) model; this.skuId = boi.getSku().getId(); this.productId = boi.getProduct().getId(); this.isBundle = true; //Wrap up all the discrete order items for this bundle order item List<DiscreteOrderItem> discreteItems = boi.getDiscreteOrderItems(); if (discreteItems != null && !discreteItems.isEmpty()) { this.bundleItems = new ArrayList<OrderItemWrapper>(); for (DiscreteOrderItem doi : discreteItems) { OrderItemWrapper doiWrapper = (OrderItemWrapper) context.getBean(OrderItemWrapper.class.getName()); doiWrapper.wrapSummary(doi, request); this.bundleItems.add(doiWrapper); } } } if (model.getOrderItemQualifiers() != null && !model.getOrderItemQualifiers().isEmpty()) { this.qualifiers = new ArrayList<OrderItemQualifierWrapper>(); for (OrderItemQualifier qualifier : model.getOrderItemQualifiers()) { OrderItemQualifierWrapper qualifierWrapper = (OrderItemQualifierWrapper) context.getBean(OrderItemQualifierWrapper.class.getName()); qualifierWrapper.wrapSummary(qualifier, request); this.qualifiers.add(qualifierWrapper); } } } @Override public void wrapSummary(OrderItem model, HttpServletRequest request) { wrapDetails(model, request); } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_wrapper_OrderItemWrapper.java
711
public class CountAction extends Action<CountRequest, CountResponse, CountRequestBuilder> { public static final CountAction INSTANCE = new CountAction(); public static final String NAME = "count"; private CountAction() { super(NAME); } @Override public CountResponse newResponse() { return new CountResponse(); } @Override public CountRequestBuilder newRequestBuilder(Client client) { return new CountRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_count_CountAction.java
287
list.getTable().addListener(SWT.MouseMove, new Listener() { @Override public void handleEvent(Event event) { Rectangle bounds = event.getBounds(); TableItem item = list.getTable().getItem(new Point(bounds.x, bounds.y)); if (item!=null) { list.setSelection(new StructuredSelection(item.getData())); } } });
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_RecentFilesPopup.java
683
public class OHashIndexTreeStateStore extends OSingleFileSegment { private static final int RECORD_SIZE = OLocalHashTable.MAX_LEVEL_SIZE * OLongSerializer.LONG_SIZE + 4 * OByteSerializer.BYTE_SIZE; public OHashIndexTreeStateStore(String iPath, String iType) throws IOException { super(iPath, iType); } public OHashIndexTreeStateStore(OStorageLocalAbstract iStorage, OStorageFileConfiguration iConfig) throws IOException { super(iStorage, iConfig); } public OHashIndexTreeStateStore(OStorageLocalAbstract iStorage, OStorageFileConfiguration iConfig, String iType) throws IOException { super(iStorage, iConfig, iType); } public void setHashTreeSize(long hashTreeSize) throws IOException { file.writeHeaderLong(0, hashTreeSize); } public long getHashTreeSize() throws IOException { return file.readHeaderLong(0); } public void setHashTreeTombstone(long hashTreeTombstone) throws IOException { file.writeHeaderLong(OLongSerializer.LONG_SIZE, hashTreeTombstone); } public long getHashTreeTombstone() throws IOException { return file.readHeaderLong(OLongSerializer.LONG_SIZE); } public void setBucketTombstonePointer(long bucketTombstonePointer) throws IOException { file.writeHeaderLong(2 * OLongSerializer.LONG_SIZE, bucketTombstonePointer); } public long getBucketTombstonePointer() throws IOException { return file.readHeaderLong(2 * OLongSerializer.LONG_SIZE); } public void storeTreeState(long[][] hashTree, OHashTreeNodeMetadata[] nodesMetadata) throws IOException { truncate(); file.allocateSpace(hashTree.length * RECORD_SIZE); long filePosition = 0; for (int i = 0; i < hashTree.length; i++) { long[] node = hashTree[i]; byte[] nodeContentBuffer = new byte[RECORD_SIZE]; int offset = 0; if (node != null) { OBooleanSerializer.INSTANCE.serializeNative(true, nodeContentBuffer, offset); offset++; for (long position : node) { OLongSerializer.INSTANCE.serializeNative(position, nodeContentBuffer, offset); offset += OLongSerializer.LONG_SIZE; } OHashTreeNodeMetadata nodeMetadata = nodesMetadata[i]; nodeContentBuffer[offset++] = (byte) nodeMetadata.getMaxLeftChildDepth(); nodeContentBuffer[offset++] = (byte) nodeMetadata.getMaxRightChildDepth(); nodeContentBuffer[offset] = (byte) nodeMetadata.getNodeLocalDepth(); } else { OBooleanSerializer.INSTANCE.serializeNative(false, nodeContentBuffer, offset); } file.write(filePosition, nodeContentBuffer); filePosition += nodeContentBuffer.length; } } public TreeState loadTreeState(int hashTreeSize) throws IOException { OHashTreeNodeMetadata[] hashTreeNodeMetadata = new OHashTreeNodeMetadata[hashTreeSize]; long[][] hashTree = new long[hashTreeSize][]; long filePosition = 0; for (int i = 0; i < hashTreeSize; i++) { byte[] contentBuffer = new byte[RECORD_SIZE]; file.read(filePosition, contentBuffer, contentBuffer.length); int offset = 0; boolean notNullNode = OBooleanSerializer.INSTANCE.deserializeNative(contentBuffer, offset); offset++; if (notNullNode) { long[] node = new long[OLocalHashTable.MAX_LEVEL_SIZE]; for (int n = 0; n < node.length; n++) { node[n] = OLongSerializer.INSTANCE.deserializeNative(contentBuffer, offset); offset += OLongSerializer.LONG_SIZE; } hashTree[i] = node; OHashTreeNodeMetadata nodeMetadata = new OHashTreeNodeMetadata(contentBuffer[offset++], contentBuffer[offset++], contentBuffer[offset]); hashTreeNodeMetadata[i] = nodeMetadata; } else { hashTree[i] = null; hashTreeNodeMetadata[i] = null; hashTreeNodeMetadata[i] = null; } filePosition += RECORD_SIZE; } return new TreeState(hashTree, hashTreeNodeMetadata); } public static class TreeState { private final long[][] hashTree; private final OHashTreeNodeMetadata[] hashTreeNodeMetadata; public TreeState(long[][] hashTree, OHashTreeNodeMetadata[] hashTreeNodeMetadata) { this.hashTree = hashTree; this.hashTreeNodeMetadata = hashTreeNodeMetadata; } public long[][] getHashTree() { return hashTree; } public OHashTreeNodeMetadata[] getHashTreeNodeMetadata() { return hashTreeNodeMetadata; } } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_hashindex_local_OHashIndexTreeStateStore.java
833
public class AbstractOfferServiceExtensionHandler extends AbstractExtensionHandler implements OfferServiceExtensionHandler { public ExtensionResultStatusType applyAdditionalFilters(List<Offer> offers) { return ExtensionResultStatusType.NOT_HANDLED; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_AbstractOfferServiceExtensionHandler.java
2,284
public class LockedRecyclerTests extends AbstractRecyclerTests { @Override protected Recycler<byte[]> newRecycler() { return Recyclers.locked(Recyclers.deque(RECYCLER_C, randomIntBetween(5, 10))); } }
0true
src_test_java_org_elasticsearch_common_recycler_LockedRecyclerTests.java
1,851
public class Merger implements Runnable { Map<MapContainer, Collection<Record>> recordMap; public Merger(Map<MapContainer, Collection<Record>> recordMap) { this.recordMap = recordMap; } public void run() { for (final MapContainer mapContainer : recordMap.keySet()) { Collection<Record> recordList = recordMap.get(mapContainer); String mergePolicyName = mapContainer.getMapConfig().getMergePolicy(); MapMergePolicy mergePolicy = getMergePolicy(mergePolicyName); // todo number of records may be high. below can be optimized a many records can be send in single invocation final MapMergePolicy finalMergePolicy = mergePolicy; for (final Record record : recordList) { // todo too many submission. should submit them in subgroups nodeEngine.getExecutionService().submit("hz:map-merge", new Runnable() { public void run() { final SimpleEntryView entryView = createSimpleEntryView(record.getKey(), toData(record.getValue()), record); MergeOperation operation = new MergeOperation(mapContainer.getName(), record.getKey(), entryView, finalMergePolicy); try { int partitionId = nodeEngine.getPartitionService().getPartitionId(record.getKey()); Future f = nodeEngine.getOperationService().invokeOnPartition(SERVICE_NAME, operation, partitionId); f.get(); } catch (Throwable t) { throw ExceptionUtil.rethrow(t); } } }); } } } }
1no label
hazelcast_src_main_java_com_hazelcast_map_MapService.java
1,271
@Deprecated public class ShippingServiceType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, ShippingServiceType> TYPES = new LinkedHashMap<String, ShippingServiceType>(); public static final ShippingServiceType BANDED_SHIPPING = new ShippingServiceType("BANDED_SHIPPING", "Banded Shipping"); public static final ShippingServiceType USPS = new ShippingServiceType("USPS", "United States Postal Service"); public static final ShippingServiceType FED_EX = new ShippingServiceType("FED_EX", "Federal Express"); public static final ShippingServiceType UPS = new ShippingServiceType("UPS", "United Parcel Service"); public static final ShippingServiceType DHL = new ShippingServiceType("DHL", "DHL"); public static ShippingServiceType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public ShippingServiceType() { //do nothing } public ShippingServiceType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } @Override public String getType() { return type; } @Override public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ShippingServiceType other = (ShippingServiceType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_service_workflow_type_ShippingServiceType.java
307
final class TerminateStatementAction extends Action { private final CeylonEditor editor; private int line; private abstract class Processor extends Visitor implements NaturalVisitor {} TerminateStatementAction(CeylonEditor editor) { super(null); this.editor = editor; } // int count(String s, char c) { // int count=0; // for (int i=0; i<s.length(); i++) { // if (s.charAt(i)==c) count++; // } // return count; // } @Override public void run() { ITextSelection ts = getSelection(editor); String before = editor.getSelectionText(); line = ts.getEndLine(); try { terminateWithSemicolon(); boolean changed; int count=0; do { changed = terminateWithBrace(); count++; } while (changed&&count<5); // IRegion li = editor.getCeylonSourceViewer().getDocument().getLineInformation(line); // editor.getCeylonSourceViewer().getTextWidget().setSelection(li.getOffset()+li.getLength()); if (!editor.getSelectionText().equals(before)) { //if the caret was at the end of the line, //and a semi was added, it winds up selected //so move the caret after the semi IRegion selection = editor.getSelection(); editor.getCeylonSourceViewer().setSelectedRange(selection.getOffset()+1,0); } // change = new DocumentChange("Terminate Statement", doc); // change.setEdit(new MultiTextEdit()); // editor.getParseController().parse(doc, new NullProgressMonitor(), null); // terminateWithParen(doc, change); // change.perform(new NullProgressMonitor()); editor.scheduleParsing(); } catch (Exception e) { e.printStackTrace(); } } private int getCodeEnd(IRegion li, String lineText, List<CommonToken> tokens) { int j=lineText.length()-1; for (; j>=0; j--) { int offset = li.getOffset()+j; if (!skipToken(tokens, offset)) break; } int endOfCodeInLine = li.getOffset()+j; return endOfCodeInLine; } private int getCodeStart(IRegion li, String lineText, List<CommonToken> tokens) { int k=0; for (; k<lineText.length(); k++) { int offset = li.getOffset()+k; if (!skipToken(tokens, offset)) break; } int startOfCodeInLine = li.getOffset()+k; return startOfCodeInLine; } // private void terminateWithParen(final IDocument doc, final TextChange change) // throws Exception { // CompilationUnit rootNode = parse(); // IRegion li = getLineInfo(doc); // String lineText = doc.get(li.getOffset(), li.getLength()); // final List<CommonToken> tokens = editor.getParseController().getTokens(); // final int startOfCodeInLine = getCodeStart(li, lineText, tokens); // final int endOfCodeInLine = getCodeEnd(li, lineText, tokens); // new Visitor() { // @Override // public void visit(Tree.Expression that) { // super.visit(that); // if (that.getStopIndex()<=endOfCodeInLine && // that.getStartIndex()>=startOfCodeInLine) { // if (that.getToken().getType()==CeylonLexer.LPAREN && // that.getEndToken().getType()!=CeylonLexer.RPAREN) { // change.addEdit(new InsertEdit(that.getStopIndex()+1, // ")")); // } // /*try { // String text = doc.get(that.getStartIndex(), // that.getStopIndex()-that.getStartIndex()+1); // StringBuilder terminators = new StringBuilder(); // for (int i=0; i<count(text, '(')-count(text,')'); i++) { // terminators.append(')'); // } // if (terminators.length()!=0) { // change.addEdit(new InsertEdit(that.getStopIndex()+1, // terminators.toString())); // } // } // catch (Exception e) { // e.printStackTrace(); // }*/ // } // } // }.visit(rootNode); // } private boolean terminateWithBrace() throws Exception { IDocument doc = editor.getCeylonSourceViewer().getDocument(); final TextChange change = new DocumentChange("Terminate Statement", doc); change.setEdit(new MultiTextEdit()); CeylonParseController parser = parse(); CompilationUnit rootNode = parser.getRootNode(); IRegion li = getLineInfo(doc); final String lineText = doc.get(li.getOffset(), li.getLength()); final List<CommonToken> tokens = parser.getTokens(); final int startOfCodeInLine = getCodeStart(li, lineText, tokens); final int endOfCodeInLine = getCodeEnd(li, lineText, tokens); new Processor() { @Override public void visit(Tree.Expression that) { super.visit(that); if (that.getStopIndex()<=endOfCodeInLine && that.getStartIndex()>=startOfCodeInLine) { Token et = that.getMainEndToken(); Token st = that.getMainToken(); if (st!=null && st.getType()==CeylonLexer.LPAREN && (et==null || et.getType()!=CeylonLexer.RPAREN)) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(that.getStopIndex()+1, ")")); } } } } @Override public void visit(Tree.ParameterList that) { super.visit(that); terminate(that, CeylonLexer.RPAREN, ")"); } public void visit(Tree.IndexExpression that) { super.visit(that); terminate(that, CeylonLexer.RBRACKET, "]"); } @Override public void visit(Tree.TypeParameterList that) { super.visit(that); terminate(that, CeylonLexer.LARGER_OP, ">"); } @Override public void visit(Tree.TypeArgumentList that) { super.visit(that); terminate(that, CeylonLexer.LARGER_OP, ">"); } @Override public void visit(Tree.PositionalArgumentList that) { super.visit(that); Token t = that.getToken(); if (t!=null && t.getType()==CeylonLexer.LPAREN) { //for infix function syntax terminate(that, CeylonLexer.RPAREN, ")"); } } @Override public void visit(Tree.NamedArgumentList that) { super.visit(that); terminate(that, CeylonLexer.RBRACE, " }"); } @Override public void visit(Tree.SequenceEnumeration that) { super.visit(that); terminate(that, CeylonLexer.RBRACE, " }"); } @Override public void visit(Tree.IterableType that) { super.visit(that); terminate(that, CeylonLexer.RBRACE, "}"); } @Override public void visit(Tree.Tuple that) { super.visit(that); terminate(that, CeylonLexer.RBRACKET, "]"); } @Override public void visit(Tree.TupleType that) { super.visit(that); terminate(that, CeylonLexer.RBRACKET, "]"); } @Override public void visit(Tree.ConditionList that) { super.visit(that); if (!that.getMainToken().getText().startsWith("<missing ")) { terminate(that, CeylonLexer.RPAREN, ")"); } } @Override public void visit(Tree.ForIterator that) { super.visit(that); if (!that.getMainToken().getText().startsWith("<missing ")) { terminate(that, CeylonLexer.RPAREN, ")"); } } @Override public void visit(Tree.ImportMemberOrTypeList that) { super.visit(that); terminate(that, CeylonLexer.RBRACE, " }"); } @Override public void visit(Tree.Import that) { if (that.getImportMemberOrTypeList()==null|| that.getImportMemberOrTypeList() .getMainToken().getText().startsWith("<missing ")) { if (!change.getEdit().hasChildren()) { if (that.getImportPath()!=null && that.getImportPath().getStopIndex()<=endOfCodeInLine) { change.addEdit(new InsertEdit(that.getImportPath().getStopIndex()+1, " { ... }")); } } } super.visit(that); } @Override public void visit(Tree.ImportModule that) { super.visit(that); if (that.getImportPath()!=null) { terminate(that, CeylonLexer.SEMICOLON, ";"); } if (that.getVersion()==null) { if (!change.getEdit().hasChildren()) { if (that.getImportPath()!=null && that.getImportPath().getStopIndex()<=endOfCodeInLine) { change.addEdit(new InsertEdit(that.getImportPath().getStopIndex()+1, " \"1.0.0\"")); } } } } @Override public void visit(Tree.ImportModuleList that) { super.visit(that); terminate(that, CeylonLexer.RBRACE, " }"); } @Override public void visit(Tree.PackageDescriptor that) { super.visit(that); terminate(that, CeylonLexer.SEMICOLON, ";"); } @Override public void visit(Tree.Directive that) { super.visit(that); terminate(that, CeylonLexer.SEMICOLON, ";"); } @Override public void visit(Tree.Body that) { super.visit(that); terminate(that, CeylonLexer.RBRACE, " }"); } @Override public void visit(Tree.MetaLiteral that) { super.visit(that); terminate(that, CeylonLexer.BACKTICK, "`"); } @Override public void visit(Tree.StatementOrArgument that) { super.visit(that); if (/*that instanceof Tree.ExecutableStatement && !(that instanceof Tree.ControlStatement) || that instanceof Tree.AttributeDeclaration || that instanceof Tree.MethodDeclaration || that instanceof Tree.ClassDeclaration || that instanceof Tree.InterfaceDeclaration ||*/ that instanceof Tree.SpecifiedArgument) { terminate(that, CeylonLexer.SEMICOLON, ";"); } } private boolean inLine(Node that) { return that.getStartIndex()>=startOfCodeInLine && that.getStartIndex()<=endOfCodeInLine; } /*private void initiate(Node that, int tokenType, String ch) { if (inLine(that)) { Token mt = that.getMainToken(); if (mt==null || mt.getType()!=tokenType || mt.getText().startsWith("<missing ")) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(that.getStartIndex(), ch)); } } } }*/ private void terminate(Node that, int tokenType, String ch) { if (inLine(that)) { Token et = that.getMainEndToken(); if ((et==null || et.getType()!=tokenType) || that.getStopIndex()>endOfCodeInLine) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(min(endOfCodeInLine,that.getStopIndex())+1, ch)); } } } } @Override public void visit(Tree.AnyClass that) { super.visit(that); if (that.getParameterList()==null) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(that.getIdentifier().getStopIndex()+1, "()")); } } } @Override public void visit(Tree.AnyMethod that) { super.visit(that); if (that.getParameterLists().isEmpty()) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(that.getIdentifier().getStopIndex()+1, "()")); } } } }.visit(rootNode); if (change.getEdit().hasChildren()) { change.perform(new NullProgressMonitor()); return true; } return false; } private boolean terminateWithSemicolon() throws Exception { final IDocument doc = editor.getCeylonSourceViewer().getDocument(); final TextChange change = new DocumentChange("Terminate Statement", doc); change.setEdit(new MultiTextEdit()); CeylonParseController parser = parse(); CompilationUnit rootNode = parser.getRootNode(); IRegion li = getLineInfo(doc); String lineText = doc.get(li.getOffset(), li.getLength()); final List<CommonToken> tokens = parser.getTokens(); //final int startOfCodeInLine = getCodeStart(li, lineText, tokens); final int endOfCodeInLine = getCodeEnd(li, lineText, tokens); if (!doc.get(endOfCodeInLine,1).equals(";")) { new Processor() { @Override public void visit(Tree.Annotation that) { super.visit(that); terminateWithSemicolon(that); } @Override public void visit(Tree.StaticType that) { super.visit(that); terminateWithSemicolon(that); } @Override public void visit(Tree.Expression that) { super.visit(that); terminateWithSemicolon(that); } boolean terminatedInLine(Node node) { return node!=null && node.getStartIndex()<=endOfCodeInLine; } @Override public void visit(Tree.IfClause that) { super.visit(that); if (missingBlock(that.getBlock()) && terminatedInLine(that.getConditionList())) { terminateWithParenAndBaces(that, that.getConditionList()); } } @Override public void visit(Tree.ElseClause that) { super.visit(that); if (missingBlock(that.getBlock())) { terminateWithBaces(that); } } @Override public void visit(Tree.ForClause that) { super.visit(that); if (missingBlock(that.getBlock()) && terminatedInLine(that.getForIterator())) { terminateWithParenAndBaces(that, that.getForIterator()); } } @Override public void visit(Tree.WhileClause that) { super.visit(that); if (missingBlock(that.getBlock()) && terminatedInLine(that.getConditionList())) { terminateWithParenAndBaces(that, that.getConditionList()); } } @Override public void visit(Tree.CaseClause that) { super.visit(that); if (missingBlock(that.getBlock()) && terminatedInLine(that.getCaseItem())) { terminateWithParenAndBaces(that, that.getCaseItem()); } } @Override public void visit(Tree.TryClause that) { super.visit(that); if (missingBlock(that.getBlock())) { terminateWithBaces(that); } } @Override public void visit(Tree.CatchClause that) { super.visit(that); if (missingBlock(that.getBlock()) && terminatedInLine(that.getCatchVariable())) { terminateWithParenAndBaces(that, that.getCatchVariable()); } } @Override public void visit(Tree.FinallyClause that) { super.visit(that); if (missingBlock(that.getBlock())) { terminateWithBaces(that); } } @Override public void visit(Tree.StatementOrArgument that) { if (that instanceof Tree.ExecutableStatement && !(that instanceof Tree.ControlStatement) || that instanceof Tree.AttributeDeclaration || that instanceof Tree.ImportModule || that instanceof Tree.TypeAliasDeclaration || that instanceof Tree.SpecifiedArgument) { terminateWithSemicolon(that); } if (that instanceof Tree.MethodDeclaration) { MethodDeclaration md = (Tree.MethodDeclaration) that; if (md.getSpecifierExpression()==null) { List<ParameterList> pl = md.getParameterLists(); if (md.getIdentifier()!=null && terminatedInLine(md.getIdentifier())) { terminateWithParenAndBaces(that, pl.isEmpty() ? null : pl.get(pl.size()-1)); } } else { terminateWithSemicolon(that); } } if (that instanceof Tree.ClassDeclaration) { ClassDeclaration cd = (Tree.ClassDeclaration) that; if (cd.getClassSpecifier()==null) { terminateWithParenAndBaces(that, cd.getParameterList()); } else { terminateWithSemicolon(that); } } if (that instanceof Tree.InterfaceDeclaration) { Tree.InterfaceDeclaration id = (Tree.InterfaceDeclaration) that; if (id.getTypeSpecifier()==null) { terminateWithBaces(that); } else { terminateWithSemicolon(that); } } super.visit(that); } private void terminateWithParenAndBaces(Node that, Node subnode) { try { if (that.getStartIndex()<=endOfCodeInLine && that.getStopIndex()>=endOfCodeInLine) { if (subnode==null || subnode.getStartIndex()>endOfCodeInLine) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(endOfCodeInLine+1, "() {}")); } } else { Token et = that.getEndToken(); Token set = subnode.getEndToken(); if (set==null || set.getType()!=CeylonLexer.RPAREN || subnode.getStopIndex()>endOfCodeInLine) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(endOfCodeInLine+1, ") {}")); } } else if (et==null || et.getType()!=CeylonLexer.RBRACE || that.getStopIndex()>endOfCodeInLine) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(endOfCodeInLine+1, " {}")); } } } } } catch (Exception e) { e.printStackTrace(); } } private void terminateWithBaces(Node that) { try { if (that.getStartIndex()<=endOfCodeInLine && that.getStopIndex()>=endOfCodeInLine) { Token et = that.getEndToken(); if (et==null || et.getType()!=CeylonLexer.SEMICOLON && et.getType()!=CeylonLexer.RBRACE || that.getStopIndex()>endOfCodeInLine) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(endOfCodeInLine+1, " {}")); } } } } catch (Exception e) { e.printStackTrace(); } } private void terminateWithSemicolon(Node that) { try { if (that.getStartIndex()<=endOfCodeInLine && that.getStopIndex()>=endOfCodeInLine) { Token et = that.getEndToken(); if (et==null || et.getType()!=CeylonLexer.SEMICOLON || that.getStopIndex()>endOfCodeInLine) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(endOfCodeInLine+1, ";")); } } } } catch (Exception e) { e.printStackTrace(); } } protected boolean missingBlock(Block block) { return block==null || block.getMainToken()==null || block.getMainToken() .getText().startsWith("<missing"); } }.visit(rootNode); if (change.getEdit().hasChildren()) { change.perform(new NullProgressMonitor()); return true; } } return false; } private IRegion getLineInfo(final IDocument doc) throws BadLocationException { return doc.getLineInformation(line); } private boolean skipToken(List<CommonToken> tokens, int offset) { int ti = Nodes.getTokenIndexAtCharacter(tokens, offset); if (ti<0) ti=-ti; int type = tokens.get(ti).getType(); return type==CeylonLexer.WS || type==CeylonLexer.MULTI_COMMENT || type==CeylonLexer.LINE_COMMENT; } private CeylonParseController parse() { CeylonParseController cpc = new CeylonParseController(); cpc.initialize(editor.getParseController().getPath(), editor.getParseController().getProject(), null); cpc.parse(editor.getCeylonSourceViewer().getDocument(), new NullProgressMonitor(), null); return cpc; } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_TerminateStatementAction.java
3,493
public abstract class FieldMapperListener { public static class Aggregator extends FieldMapperListener { public final List<FieldMapper> mappers = new ArrayList<FieldMapper>(); @Override public void fieldMapper(FieldMapper fieldMapper) { mappers.add(fieldMapper); } } public abstract void fieldMapper(FieldMapper fieldMapper); public void fieldMappers(Iterable<FieldMapper> fieldMappers) { for (FieldMapper mapper : fieldMappers) { fieldMapper(mapper); } } }
0true
src_main_java_org_elasticsearch_index_mapper_FieldMapperListener.java
1,368
public abstract class OTransactionAbstract implements OTransaction { protected final ODatabaseRecordTx database; protected TXSTATUS status = TXSTATUS.INVALID; protected OTransactionAbstract(final ODatabaseRecordTx iDatabase) { database = iDatabase; } public boolean isActive() { return status != TXSTATUS.INVALID; } public TXSTATUS getStatus() { return status; } public ODatabaseRecordTx getDatabase() { return database; } public static void updateCacheFromEntries(final OTransaction tx, final Iterable<? extends ORecordOperation> entries, final boolean updateStrategy) { final OLevel1RecordCache dbCache = tx.getDatabase().getLevel1Cache(); for (ORecordOperation txEntry : entries) { if (!updateStrategy) // ALWAYS REMOVE THE RECORD FROM CACHE dbCache.deleteRecord(txEntry.getRecord().getIdentity()); else if (txEntry.type == ORecordOperation.DELETED) // DELETION dbCache.deleteRecord(txEntry.getRecord().getIdentity()); else if (txEntry.type == ORecordOperation.UPDATED || txEntry.type == ORecordOperation.CREATED) // UDPATE OR CREATE dbCache.updateRecord(txEntry.getRecord()); } } protected void invokeCommitAgainstListeners() { // WAKE UP LISTENERS for (ODatabaseListener listener : ((ODatabaseRaw) database.getUnderlying()).browseListeners()) try { listener.onBeforeTxCommit(database.getUnderlying()); } catch (Throwable t) { OLogManager.instance().error(this, "Error on commit callback against listener: " + listener, t); } } protected void invokeRollbackAgainstListeners() { // WAKE UP LISTENERS for (ODatabaseListener listener : ((ODatabaseRaw) database.getUnderlying()).browseListeners()) try { listener.onBeforeTxRollback(database.getUnderlying()); } catch (Throwable t) { OLogManager.instance().error(this, "Error on rollback callback against listener: " + listener, t); } } }
1no label
core_src_main_java_com_orientechnologies_orient_core_tx_OTransactionAbstract.java
312
new OConfigurationChangeCallback() { public void change(final Object iCurrentValue, final Object iNewValue) { Orient.instance().getProfiler().setAutoDump((Integer) iNewValue); } }),
0true
core_src_main_java_com_orientechnologies_orient_core_config_OGlobalConfiguration.java
76
public interface StaticAssetDescription extends Serializable { public Long getId(); public void setId(Long id); public String getDescription(); public void setDescription(String description); public String getLongDescription(); public void setLongDescription(String longDescription); public StaticAssetDescription cloneEntity(); public AdminAuditable getAuditable(); public void setAuditable(AdminAuditable auditable); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_domain_StaticAssetDescription.java
1,494
@SuppressWarnings("serial") public class OObjectNotDetachedException extends RuntimeException { public OObjectNotDetachedException() { super(); } public OObjectNotDetachedException(String message, Throwable cause) { super(message, cause); } public OObjectNotDetachedException(String message) { super(message); } public OObjectNotDetachedException(Throwable cause) { super(cause); } }
0true
object_src_main_java_com_orientechnologies_orient_object_db_OObjectNotDetachedException.java
1,375
public abstract class CheckoutEndpoint extends BaseEndpoint { private static final Log LOG = LogFactory.getLog(CheckoutEndpoint.class); @Resource(name="blCheckoutService") protected CheckoutService checkoutService; //This service is backed by the entire payment workflow configured in the application context. //It is the entry point for engaging the payment workflow @Resource(name="blCompositePaymentService") protected CompositePaymentService compositePaymentService; @Resource(name="blOrderService") protected OrderService orderService; //This should only be called for modules that need to engage the workflow directly without doing a complete checkout. //e.g. PayPal for doing an authorize and retrieving the redirect: url to PayPal public PaymentResponseItemWrapper executePayment(HttpServletRequest request, PaymentReferenceMapWrapper mapWrapper) { Order cart = CartState.getCart(); if (cart != null) { try { Map<PaymentInfo, Referenced> payments = new HashMap<PaymentInfo, Referenced>(); PaymentInfo paymentInfo = mapWrapper.getPaymentInfoWrapper().unwrap(request, context); Referenced referenced = mapWrapper.getReferencedWrapper().unwrap(request, context); payments.put(paymentInfo, referenced); CompositePaymentResponse compositePaymentResponse = compositePaymentService.executePayment(cart, payments); PaymentResponseItem responseItem = compositePaymentResponse.getPaymentResponse().getResponseItems().get(paymentInfo); PaymentResponseItemWrapper paymentResponseItemWrapper = context.getBean(PaymentResponseItemWrapper.class); paymentResponseItemWrapper.wrapDetails(responseItem, request); return paymentResponseItemWrapper; } catch (PaymentException e) { throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR) .type(MediaType.TEXT_PLAIN).entity("An error occured with payment.").build()); } } throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) .type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build()); } public OrderWrapper performCheckout(HttpServletRequest request, List<PaymentReferenceMapWrapper> mapWrappers) { Order cart = CartState.getCart(); if (cart != null) { try { if (mapWrappers != null && !mapWrappers.isEmpty()) { Map<PaymentInfo, Referenced> payments = new HashMap<PaymentInfo, Referenced>(); orderService.removePaymentsFromOrder(cart, PaymentInfoType.CREDIT_CARD); for (PaymentReferenceMapWrapper mapWrapper : mapWrappers) { PaymentInfo paymentInfo = mapWrapper.getPaymentInfoWrapper().unwrap(request, context); paymentInfo.setOrder(cart); Referenced referenced = mapWrapper.getReferencedWrapper().unwrap(request, context); if (cart.getPaymentInfos() == null) { cart.setPaymentInfos(new ArrayList<PaymentInfo>()); } cart.getPaymentInfos().add(paymentInfo); payments.put(paymentInfo, referenced); } CheckoutResponse response = checkoutService.performCheckout(cart, payments); Order order = response.getOrder(); OrderWrapper wrapper = (OrderWrapper) context.getBean(OrderWrapper.class.getName()); wrapper.wrapDetails(order, request); return wrapper; } } catch (CheckoutException e) { cart.setStatus(OrderStatus.IN_PROCESS); try { orderService.save(cart, false); } catch (PricingException e1) { LOG.error("An unexpected error occured saving / pricing the cart.", e1); } throw new WebApplicationException(e, Response.status(Response.Status.INTERNAL_SERVER_ERROR) .type(MediaType.TEXT_PLAIN).entity("An error occured during checkout.").build()); } } throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) .type(MediaType.TEXT_PLAIN).entity("Cart could not be found").build()); } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_endpoint_checkout_CheckoutEndpoint.java
244
{ @Override public NeoStore instance() { return getNeoStore(); } }, persistenceCache, schemaCache, providerMap, labelScanStore, readOnly ));
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreXaDataSource.java
2,718
class AllocateDangledRequestHandler extends BaseTransportRequestHandler<AllocateDangledRequest> { public static final String ACTION = "/gateway/local/allocate_dangled"; @Override public AllocateDangledRequest newInstance() { return new AllocateDangledRequest(); } @Override public void messageReceived(final AllocateDangledRequest request, final TransportChannel channel) throws Exception { String[] indexNames = new String[request.indices.length]; for (int i = 0; i < request.indices.length; i++) { indexNames[i] = request.indices[i].index(); } clusterService.submitStateUpdateTask("allocation dangled indices " + Arrays.toString(indexNames), new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { if (currentState.blocks().disableStatePersistence()) { return currentState; } MetaData.Builder metaData = MetaData.builder(currentState.metaData()); ClusterBlocks.Builder blocks = ClusterBlocks.builder().blocks(currentState.blocks()); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(currentState.routingTable()); boolean importNeeded = false; StringBuilder sb = new StringBuilder(); for (IndexMetaData indexMetaData : request.indices) { if (currentState.metaData().hasIndex(indexMetaData.index())) { continue; } importNeeded = true; metaData.put(indexMetaData, false); blocks.addBlocks(indexMetaData); routingTableBuilder.addAsRecovery(indexMetaData); sb.append("[").append(indexMetaData.index()).append("/").append(indexMetaData.state()).append("]"); } if (!importNeeded) { return currentState; } logger.info("auto importing dangled indices {} from [{}]", sb.toString(), request.fromNode); ClusterState updatedState = ClusterState.builder(currentState).metaData(metaData).blocks(blocks).routingTable(routingTableBuilder).build(); // now, reroute RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder(updatedState).routingTable(routingTableBuilder).build()); return ClusterState.builder(updatedState).routingResult(routingResult).build(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); try { channel.sendResponse(t); } catch (Exception e) { logger.error("failed send response for allocating dangled", e); } } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { try { channel.sendResponse(new AllocateDangledResponse(true)); } catch (IOException e) { logger.error("failed send response for allocating dangled", e); } } }); } @Override public String executor() { return ThreadPool.Names.SAME; } }
0true
src_main_java_org_elasticsearch_gateway_local_state_meta_LocalAllocateDangledIndices.java
3,556
public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { BooleanFieldMapper.Builder builder = booleanField(name); parseField(builder, name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String propName = Strings.toUnderscoreCase(entry.getKey()); Object propNode = entry.getValue(); if (propName.equals("null_value")) { builder.nullValue(nodeBooleanValue(propNode)); } } return builder; } }
0true
src_main_java_org_elasticsearch_index_mapper_core_BooleanFieldMapper.java
5,959
public class SuggestBuilder implements ToXContent { private final String name; private String globalText; private final List<SuggestionBuilder<?>> suggestions = new ArrayList<SuggestionBuilder<?>>(); public SuggestBuilder() { this.name = null; } public SuggestBuilder(String name) { this.name = name; } /** * Sets the text to provide suggestions for. The suggest text is a required option that needs * to be set either via this setter or via the {@link org.elasticsearch.search.suggest.SuggestBuilder.SuggestionBuilder#setText(String)} method. * <p/> * The suggest text gets analyzed by the suggest analyzer or the suggest field search analyzer. * For each analyzed token, suggested terms are suggested if possible. */ public SuggestBuilder setText(String globalText) { this.globalText = globalText; return this; } /** * Adds an {@link org.elasticsearch.search.suggest.SuggestBuilder.TermSuggestionBuilder} instance under a user defined name. * The order in which the <code>Suggestions</code> are added, is the same as in the response. */ public SuggestBuilder addSuggestion(SuggestionBuilder<?> suggestion) { suggestions.add(suggestion); return this; } /** * Returns all suggestions with the defined names. */ public List<SuggestionBuilder<?>> getSuggestion() { return suggestions; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { if(name == null) { builder.startObject(); } else { builder.startObject(name); } if (globalText != null) { builder.field("text", globalText); } for (SuggestionBuilder<?> suggestion : suggestions) { builder = suggestion.toXContent(builder, params); } builder.endObject(); return builder; } /** * Convenience factory method. * * @param name The name of this suggestion. This is a required parameter. */ public static TermSuggestionBuilder termSuggestion(String name) { return new TermSuggestionBuilder(name); } /** * Convenience factory method. * * @param name The name of this suggestion. This is a required parameter. */ public static PhraseSuggestionBuilder phraseSuggestion(String name) { return new PhraseSuggestionBuilder(name); } public static abstract class SuggestionBuilder<T> implements ToXContent { private String name; private String suggester; private String text; private String field; private String analyzer; private Integer size; private Integer shardSize; public SuggestionBuilder(String name, String suggester) { this.name = name; this.suggester = suggester; } /** * Same as in {@link SuggestBuilder#setText(String)}, but in the suggestion scope. */ @SuppressWarnings("unchecked") public T text(String text) { this.text = text; return (T) this; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(name); if (text != null) { builder.field("text", text); } builder.startObject(suggester); if (analyzer != null) { builder.field("analyzer", analyzer); } if (field != null) { builder.field("field", field); } if (size != null) { builder.field("size", size); } if (shardSize != null) { builder.field("shard_size", shardSize); } builder = innerToXContent(builder, params); builder.endObject(); builder.endObject(); return builder; } protected abstract XContentBuilder innerToXContent(XContentBuilder builder, Params params) throws IOException; /** * Sets from what field to fetch the candidate suggestions from. This is an * required option and needs to be set via this setter or * {@link org.elasticsearch.search.suggest.SuggestBuilder.TermSuggestionBuilder#setField(String)} * method */ @SuppressWarnings("unchecked") public T field(String field) { this.field = field; return (T)this; } /** * Sets the analyzer to analyse to suggest text with. Defaults to the search * analyzer of the suggest field. */ @SuppressWarnings("unchecked") public T analyzer(String analyzer) { this.analyzer = analyzer; return (T)this; } /** * Sets the maximum suggestions to be returned per suggest text term. */ @SuppressWarnings("unchecked") public T size(int size) { if (size <= 0) { throw new ElasticsearchIllegalArgumentException("Size must be positive"); } this.size = size; return (T)this; } /** * Sets the maximum number of suggested term to be retrieved from each * individual shard. During the reduce phase the only the top N suggestions * are returned based on the <code>size</code> option. Defaults to the * <code>size</code> option. * <p/> * Setting this to a value higher than the `size` can be useful in order to * get a more accurate document frequency for suggested terms. Due to the * fact that terms are partitioned amongst shards, the shard level document * frequencies of suggestions may not be precise. Increasing this will make * these document frequencies more precise. */ @SuppressWarnings("unchecked") public T shardSize(Integer shardSize) { this.shardSize = shardSize; return (T)this; } } }
1no label
src_main_java_org_elasticsearch_search_suggest_SuggestBuilder.java
3,311
public abstract class Operation implements DataSerializable { // serialized private String serviceName; private int partitionId = -1; private int replicaIndex; private long callId; private boolean validateTarget = true; private long invocationTime = -1; private long callTimeout = Long.MAX_VALUE; private long waitTimeout = -1; private String callerUuid; private String executorName; // injected private transient NodeEngine nodeEngine; private transient Object service; private transient Address callerAddress; private transient Connection connection; private transient ResponseHandler responseHandler; private transient long startTime; public boolean isUrgent() { return this instanceof UrgentSystemOperation; } // runs before wait-support public abstract void beforeRun() throws Exception; // runs after wait-support, supposed to do actual operation public abstract void run() throws Exception; // runs after backups, before wait-notify public abstract void afterRun() throws Exception; public abstract boolean returnsResponse(); public abstract Object getResponse(); public String getServiceName() { return serviceName; } public final Operation setServiceName(String serviceName) { this.serviceName = serviceName; return this; } public final int getPartitionId() { return partitionId; } public final Operation setPartitionId(int partitionId) { this.partitionId = partitionId; return this; } public final int getReplicaIndex() { return replicaIndex; } public final Operation setReplicaIndex(int replicaIndex) { if (replicaIndex < 0 || replicaIndex >= InternalPartition.MAX_REPLICA_COUNT) { throw new IllegalArgumentException("Replica index is out of range [0-" + (InternalPartition.MAX_REPLICA_COUNT - 1) + "]"); } this.replicaIndex = replicaIndex; return this; } public String getExecutorName() { return executorName; } public void setExecutorName(String executorName) { this.executorName = executorName; } public final long getCallId() { return callId; } // Accessed using OperationAccessor final Operation setCallId(long callId) { this.callId = callId; return this; } public boolean validatesTarget() { return validateTarget; } public final Operation setValidateTarget(boolean validateTarget) { this.validateTarget = validateTarget; return this; } public final NodeEngine getNodeEngine() { return nodeEngine; } public final Operation setNodeEngine(NodeEngine nodeEngine) { this.nodeEngine = nodeEngine; return this; } public final <T> T getService() { if (service == null) { // one might have overridden getServiceName() method... final String name = serviceName != null ? serviceName : getServiceName(); service = ((NodeEngineImpl) nodeEngine).getService(name); if (service == null) { if (nodeEngine.isActive()) { throw new HazelcastException("Service with name '" + name + "' not found!"); } else { throw new RetryableHazelcastException("HazelcastInstance[" + nodeEngine.getThisAddress() + "] is not active!"); } } } return (T) service; } public final Operation setService(Object service) { this.service = service; return this; } public final Address getCallerAddress() { return callerAddress; } // Accessed using OperationAccessor final Operation setCallerAddress(Address callerAddress) { this.callerAddress = callerAddress; return this; } public final Connection getConnection() { return connection; } // Accessed using OperationAccessor final Operation setConnection(Connection connection) { this.connection = connection; return this; } public final Operation setResponseHandler(ResponseHandler responseHandler) { this.responseHandler = responseHandler; return this; } public final ResponseHandler getResponseHandler() { return responseHandler; } public final long getStartTime() { return startTime; } // Accessed using OperationAccessor final Operation setStartTime(long startTime) { this.startTime = startTime; return this; } public final long getInvocationTime() { return invocationTime; } // Accessed using OperationAccessor final Operation setInvocationTime(long invocationTime) { this.invocationTime = invocationTime; return this; } public final long getCallTimeout() { return callTimeout; } // Accessed using OperationAccessor final Operation setCallTimeout(long callTimeout) { this.callTimeout = callTimeout; return this; } public final long getWaitTimeout() { return waitTimeout; } public final void setWaitTimeout(long timeout) { this.waitTimeout = timeout; } public ExceptionAction onException(Throwable throwable) { return (throwable instanceof RetryableException) ? ExceptionAction.RETRY_INVOCATION : ExceptionAction.THROW_EXCEPTION; } public String getCallerUuid() { return callerUuid; } public Operation setCallerUuid(String callerUuid) { this.callerUuid = callerUuid; return this; } protected final ILogger getLogger() { final NodeEngine ne = nodeEngine; return ne != null ? ne.getLogger(getClass()) : Logger.getLogger(getClass()); } public void logError(Throwable e) { final ILogger logger = getLogger(); if (e instanceof RetryableException) { final Level level = returnsResponse() ? Level.FINEST : Level.WARNING; if (logger.isLoggable(level)) { logger.log(level, e.getClass().getName() + ": " + e.getMessage()); } } else if (e instanceof OutOfMemoryError) { try { logger.log(Level.SEVERE, e.getMessage(), e); } catch (Throwable ignored) { } } else { final Level level = nodeEngine != null && nodeEngine.isActive() ? Level.SEVERE : Level.FINEST; if (logger.isLoggable(level)) { logger.log(level, e.getMessage(), e); } } } @Override public final void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(serviceName); out.writeInt(partitionId); out.writeInt(replicaIndex); out.writeLong(callId); out.writeBoolean(validateTarget); out.writeLong(invocationTime); out.writeLong(callTimeout); out.writeLong(waitTimeout); out.writeUTF(callerUuid); out.writeUTF(executorName); writeInternal(out); } @Override public final void readData(ObjectDataInput in) throws IOException { serviceName = in.readUTF(); partitionId = in.readInt(); replicaIndex = in.readInt(); callId = in.readLong(); validateTarget = in.readBoolean(); invocationTime = in.readLong(); callTimeout = in.readLong(); waitTimeout = in.readLong(); callerUuid = in.readUTF(); executorName = in.readUTF(); readInternal(in); } protected abstract void writeInternal(ObjectDataOutput out) throws IOException; protected abstract void readInternal(ObjectDataInput in) throws IOException; }
1no label
hazelcast_src_main_java_com_hazelcast_spi_Operation.java
4,485
threadPool.generic().execute(new Runnable() { @Override public void run() { // create a new recovery status, and process... RecoveryStatus recoveryStatus = new RecoveryStatus(request.recoveryId(), indexShard); onGoingRecoveries.put(recoveryStatus.recoveryId, recoveryStatus); doRecovery(request, recoveryStatus, listener); } });
1no label
src_main_java_org_elasticsearch_indices_recovery_RecoveryTarget.java
2,176
public class AndFilter extends Filter { private final List<? extends Filter> filters; public AndFilter(List<? extends Filter> filters) { this.filters = filters; } public List<? extends Filter> filters() { return filters; } @Override public DocIdSet getDocIdSet(AtomicReaderContext context, Bits acceptDocs) throws IOException { if (filters.size() == 1) { return filters.get(0).getDocIdSet(context, acceptDocs); } DocIdSet[] sets = new DocIdSet[filters.size()]; for (int i = 0; i < filters.size(); i++) { DocIdSet set = filters.get(i).getDocIdSet(context, acceptDocs); if (DocIdSets.isEmpty(set)) { // none matching for this filter, we AND, so return EMPTY return null; } sets[i] = set; } return new AndDocIdSet(sets); } @Override public int hashCode() { int hash = 7; hash = 31 * hash + (null == filters ? 0 : filters.hashCode()); return hash; } @Override public boolean equals(Object obj) { if (this == obj) return true; if ((obj == null) || (obj.getClass() != this.getClass())) return false; AndFilter other = (AndFilter) obj; return equalFilters(filters, other.filters); } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (Filter filter : filters) { if (builder.length() > 0) { builder.append(' '); } builder.append('+'); builder.append(filter); } return builder.toString(); } private boolean equalFilters(List<? extends Filter> filters1, List<? extends Filter> filters2) { return (filters1 == filters2) || ((filters1 != null) && filters1.equals(filters2)); } }
0true
src_main_java_org_elasticsearch_common_lucene_search_AndFilter.java
195
public interface LoggableTransaction extends BaseTransaction { public void logMutations(DataOutput out); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_LoggableTransaction.java
1,574
@ManagedDescription("ISet") public class SetMBean extends HazelcastMBean<ISet> { private final AtomicLong totalAddedItemCount = new AtomicLong(); private final AtomicLong totalRemovedItemCount = new AtomicLong(); private final String registrationId; protected SetMBean(ISet managedObject, ManagementService service) { super(managedObject, service); objectName = service.createObjectName("ISet", managedObject.getName()); ItemListener itemListener = new ItemListener() { public void itemAdded(ItemEvent item) { totalAddedItemCount.incrementAndGet(); } public void itemRemoved(ItemEvent item) { totalRemovedItemCount.incrementAndGet(); } }; registrationId = managedObject.addItemListener(itemListener, false); } @ManagedAnnotation(value = "clear", operation = true) @ManagedDescription("Clear Set") public void clear() { managedObject.clear(); } @ManagedAnnotation("name") @ManagedDescription("Name of the DistributedObject") public String getName() { return managedObject.getName(); } @ManagedAnnotation("partitionKey") @ManagedDescription("the partitionKey") public String getPartitionKey() { return managedObject.getPartitionKey(); } @ManagedAnnotation("totalAddedItemCount") public long getTotalAddedItemCount() { return totalAddedItemCount.get(); } @ManagedAnnotation("totalRemovedItemCount") public long getTotalRemovedItemCount() { return totalRemovedItemCount.get(); } @Override public void preDeregister() throws Exception { super.preDeregister(); try { managedObject.removeItemListener(registrationId); } catch (Exception ignored) { } } }
0true
hazelcast_src_main_java_com_hazelcast_jmx_SetMBean.java
1,384
public class HazelcastLocalCacheRegionFactory extends AbstractHazelcastCacheRegionFactory implements RegionFactory { public static final int serialVersionUID = 1; private transient CleanupService cleanupService; public HazelcastLocalCacheRegionFactory() { } public HazelcastLocalCacheRegionFactory(final HazelcastInstance instance) { super(instance); } public HazelcastLocalCacheRegionFactory(final Properties properties) { super(properties); } public CollectionRegion buildCollectionRegion(final String regionName, final Properties properties, final CacheDataDescription metadata) throws CacheException { final HazelcastCollectionRegion<LocalRegionCache> region = new HazelcastCollectionRegion<LocalRegionCache>(instance, regionName, properties, metadata, new LocalRegionCache(regionName, instance, metadata)); cleanupService.registerCache(region.getCache()); return region; } public EntityRegion buildEntityRegion(final String regionName, final Properties properties, final CacheDataDescription metadata) throws CacheException { final HazelcastEntityRegion<LocalRegionCache> region = new HazelcastEntityRegion<LocalRegionCache>(instance, regionName, properties, metadata, new LocalRegionCache(regionName, instance, metadata)); cleanupService.registerCache(region.getCache()); return region; } public TimestampsRegion buildTimestampsRegion(final String regionName, final Properties properties) throws CacheException { return new HazelcastTimestampsRegion<LocalRegionCache>(instance, regionName, properties, new TimestampsRegionCache(regionName, instance)); } @Override public void start(final Settings settings, final Properties properties) throws CacheException { super.start(settings, properties); cleanupService = new CleanupService(instance.getName()); } @Override public void stop() { cleanupService.stop(); super.stop(); } }
0true
hazelcast-hibernate_hazelcast-hibernate4_src_main_java_com_hazelcast_hibernate_HazelcastLocalCacheRegionFactory.java
220
{ @Override public LockElement acquireReadLock( Object resource ) { try { Transaction tx = getTransaction(); lockManager.getReadLock( resource, tx ); return new LockElement( resource, tx, LockType.READ, lockManager ); } catch ( Exception e ) { throw launderedException( e ); } } @Override public LockElement acquireWriteLock( Object resource ) { try { Transaction tx = getTransaction(); lockManager.getWriteLock( resource, tx ); return new LockElement( resource, tx, LockType.WRITE, lockManager ); } catch ( SystemException e ) { throw launderedException( e ); } } @Override public TxIdGenerator getTxIdGenerator() { return txIdGenerator; } };
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_PlaceboTm.java
1,592
public class FilterAndSortCriteria { private static final long serialVersionUID = 1L; public static final String SORT_PROPERTY_PARAMETER = "sortProperty"; public static final String SORT_DIRECTION_PARAMETER = "sortDirection"; public static final String START_INDEX_PARAMETER = "startIndex"; public static final String MAX_INDEX_PARAMETER = "maxIndex"; public static final String IS_NULL_FILTER_VALUE = new String("BLC_SPECIAL_FILTER_VALUE:NULL").intern(); protected String propertyId; protected List<String> filterValues = new ArrayList<String>(); protected SortDirection sortDirection; public FilterAndSortCriteria(String propertyId) { this.propertyId = propertyId; } public FilterAndSortCriteria(String propertyId, String filterValue) { this.propertyId = propertyId; setFilterValue(filterValue); } public FilterAndSortCriteria(String propertyId, List<String> filterValues) { this.propertyId = propertyId; setFilterValues(filterValues); } public String getPropertyId() { return propertyId; } public void setPropertyId(String propertyId) { this.propertyId = propertyId; } public void clearFilterValues() { filterValues.clear(); } public void setFilterValue(String value) { clearFilterValues(); filterValues.add(value); } public List<String> getFilterValues() { // We want values that are NOT special return BLCCollectionUtils.selectList(filterValues, getPredicateForSpecialValues(false)); } public List<String> getSpecialFilterValues() { // We want values that ARE special return BLCCollectionUtils.selectList(filterValues, getPredicateForSpecialValues(true)); } public void setFilterValues(List<String> filterValues) { this.filterValues = filterValues; } public Boolean getSortAscending() { return (sortDirection == null) ? null : SortDirection.ASCENDING.equals(sortDirection); } public void setSortAscending(Boolean sortAscending) { this.sortDirection = (sortAscending) ? SortDirection.ASCENDING : SortDirection.DESCENDING; } public SortDirection getSortDirection() { return sortDirection; } public void setSortDirection(SortDirection sortDirection) { this.sortDirection = sortDirection; } public boolean hasSpecialFilterValue() { // We want values that ARE special return CollectionUtils.exists(filterValues, getPredicateForSpecialValues(true)); } protected TypedPredicate<String> getPredicateForSpecialValues(final boolean inclusive) { return new TypedPredicate<String>() { @Override public boolean eval(String value) { // Note that this static String is the result of a call to String.intern(). This means that we are // safe to compare with == while still allowing the user to specify a filter for the actual value of this // string. if (inclusive) { return IS_NULL_FILTER_VALUE == value; } else { return IS_NULL_FILTER_VALUE != value; } } }; } }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_FilterAndSortCriteria.java
1,078
public enum ValueCollectionType { SET, LIST }
0true
hazelcast_src_main_java_com_hazelcast_config_MultiMapConfig.java
330
map.addEntryListener(new EntryAdapter<String, String>() { public void entryEvicted(EntryEvent<String, String> event) { latch.countDown(); } }, true);
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java
392
public interface Media extends Serializable { public Long getId(); public void setId(Long id); public String getUrl(); public void setUrl(String url); public String getTitle(); public void setTitle(String title); public String getAltText(); public void setAltText(String altText); public String getTags(); public void setTags(String tags); }
0true
common_src_main_java_org_broadleafcommerce_common_media_domain_Media.java
1,514
public interface NodeContext { AddressPicker createAddressPicker(Node node); Joiner createJoiner(Node node); ConnectionManager createConnectionManager(Node node, ServerSocketChannel serverSocketChannel); }
0true
hazelcast_src_main_java_com_hazelcast_instance_NodeContext.java
1,708
runnable = new Runnable() { public void run() { try { map.tryLock(null, 1, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } } };
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
978
public interface OObjectSerializerHelperInterface { public ODocument toStream(final Object iPojo, final ODocument iRecord, final OEntityManager iEntityManager, final OClass schemaClass, final OUserObject2RecordHandler iObj2RecHandler, final ODatabaseObject db, final boolean iSaveOnlyDirty); public String getDocumentBoundField(final Class<?> iClass); public Object getFieldValue(final Object iPojo, final String iProperty); public void invokeCallback(final Object iPojo, final ODocument iDocument, final Class<?> iAnnotation); }
0true
core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_object_OObjectSerializerHelperInterface.java
3,038
public static class CustomBloomFilterFactory extends BloomFilterFactory { private final float desiredMaxSaturation; private final float saturationLimit; public CustomBloomFilterFactory() { this(Defaults.MAX_SATURATION, Defaults.SATURATION_LIMIT); } CustomBloomFilterFactory(float desiredMaxSaturation, float saturationLimit) { this.desiredMaxSaturation = desiredMaxSaturation; this.saturationLimit = saturationLimit; } @Override public FuzzySet getSetForField(SegmentWriteState state, FieldInfo info) { //Assume all of the docs have a unique term (e.g. a primary key) and we hope to maintain a set with desiredMaxSaturation% of bits set return FuzzySet.createSetBasedOnQuality(state.segmentInfo.getDocCount(), desiredMaxSaturation); } @Override public boolean isSaturated(FuzzySet bloomFilter, FieldInfo fieldInfo) { // Don't bother saving bitsets if > saturationLimit % of bits are set - we don't want to // throw any more memory at this problem. return bloomFilter.getSaturation() > saturationLimit; } }
0true
src_main_java_org_elasticsearch_index_codec_postingsformat_BloomFilterLucenePostingsFormatProvider.java
865
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() { @Override public void run() { for (final AtomicArray.Entry<DfsSearchResult> entry : firstResults.asList()) { DfsSearchResult dfsResult = entry.value; DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId()); if (node.id().equals(nodes.localNodeId())) { QuerySearchRequest querySearchRequest = new QuerySearchRequest(request, dfsResult.id(), dfs); executeQuery(entry.index, dfsResult, counter, querySearchRequest, node); } } } });
0true
src_main_java_org_elasticsearch_action_search_type_TransportSearchDfsQueryThenFetchAction.java
1,479
class Hibernate3CacheEntrySerializer implements StreamSerializer<CacheEntry> { private static final Unsafe UNSAFE = UnsafeHelper.UNSAFE; private static final long DISASSEMBLED_STATE_OFFSET; private static final long SUBCLASS_OFFSET; private static final long LAZY_PROPERTIES_ARE_UNFETCHED; private static final long VERSION_OFFSET; private static final Class<?>[] CONSTRUCTOR_ARG_TYPES = {Serializable[].class, String.class, boolean.class, Object.class}; private static final Constructor<CacheEntry> CACHE_ENTRY_CONSTRUCTOR; static { try { Class<CacheEntry> cacheEntryClass = CacheEntry.class; Field disassembledState = cacheEntryClass.getDeclaredField("disassembledState"); DISASSEMBLED_STATE_OFFSET = UNSAFE.objectFieldOffset(disassembledState); Field subclass = cacheEntryClass.getDeclaredField("subclass"); SUBCLASS_OFFSET = UNSAFE.objectFieldOffset(subclass); Field lazyPropertiesAreUnfetched = cacheEntryClass.getDeclaredField("lazyPropertiesAreUnfetched"); LAZY_PROPERTIES_ARE_UNFETCHED = UNSAFE.objectFieldOffset(lazyPropertiesAreUnfetched); Field version = cacheEntryClass.getDeclaredField("version"); VERSION_OFFSET = UNSAFE.objectFieldOffset(version); CACHE_ENTRY_CONSTRUCTOR = cacheEntryClass.getDeclaredConstructor(CONSTRUCTOR_ARG_TYPES); CACHE_ENTRY_CONSTRUCTOR.setAccessible(true); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void write(ObjectDataOutput out, CacheEntry object) throws IOException { try { Serializable[] disassembledState = (Serializable[]) UNSAFE.getObject(object, DISASSEMBLED_STATE_OFFSET); String subclass = (String) UNSAFE.getObject(object, SUBCLASS_OFFSET); boolean lazyPropertiesAreUnfetched = UNSAFE.getBoolean(object, LAZY_PROPERTIES_ARE_UNFETCHED); Object version = UNSAFE.getObject(object, VERSION_OFFSET); out.writeInt(disassembledState.length); for (Serializable state : disassembledState) { out.writeObject(state); } out.writeUTF(subclass); out.writeBoolean(lazyPropertiesAreUnfetched); out.writeObject(version); } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } throw new IOException(e); } } @Override public CacheEntry read(ObjectDataInput in) throws IOException { try { int length = in.readInt(); Serializable[] disassembledState = new Serializable[length]; for (int i = 0; i < length; i++) { disassembledState[i] = in.readObject(); } String subclass = in.readUTF(); boolean lazyPropertiesAreUnfetched = in.readBoolean(); Object version = in.readObject(); return CACHE_ENTRY_CONSTRUCTOR.newInstance(disassembledState, subclass, lazyPropertiesAreUnfetched, version); } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } throw new IOException(e); } } @Override public int getTypeId() { return SerializationConstants.HIBERNATE3_TYPE_HIBERNATE_CACHE_ENTRY; } @Override public void destroy() { } }
0true
hazelcast-hibernate_hazelcast-hibernate3_src_main_java_com_hazelcast_hibernate_serialization_Hibernate3CacheEntrySerializer.java
471
public interface ClientExecutionService { void executeInternal(Runnable command); <T> ICompletableFuture<T> submitInternal(Callable<T> command); void execute(Runnable command); ICompletableFuture<?> submit(Runnable task); <T> ICompletableFuture<T> submit(Callable<T> task); ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit); ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit); ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long period, TimeUnit unit); ExecutorService getAsyncExecutor(); }
0true
hazelcast-client_src_main_java_com_hazelcast_client_spi_ClientExecutionService.java
839
public class TransportClearScrollAction extends TransportAction<ClearScrollRequest, ClearScrollResponse> { private final ClusterService clusterService; private final SearchServiceTransportAction searchServiceTransportAction; @Inject public TransportClearScrollAction(Settings settings, TransportService transportService, ThreadPool threadPool, ClusterService clusterService, SearchServiceTransportAction searchServiceTransportAction) { super(settings, threadPool); this.clusterService = clusterService; this.searchServiceTransportAction = searchServiceTransportAction; transportService.registerHandler(ClearScrollAction.NAME, new TransportHandler()); } @Override protected void doExecute(ClearScrollRequest request, final ActionListener<ClearScrollResponse> listener) { new Async(request, listener, clusterService.state()).run(); } private class Async { final DiscoveryNodes nodes; final CountDown expectedOps; final ClearScrollRequest request; final List<Tuple<String, Long>[]> contexts = new ArrayList<Tuple<String, Long>[]>(); final AtomicReference<Throwable> expHolder; final ActionListener<ClearScrollResponse> listener; private Async(ClearScrollRequest request, ActionListener<ClearScrollResponse> listener, ClusterState clusterState) { int expectedOps = 0; this.nodes = clusterState.nodes(); if (request.getScrollIds().size() == 1 && "_all".equals(request.getScrollIds().get(0))) { expectedOps = nodes.size(); } else { for (String parsedScrollId : request.getScrollIds()) { Tuple<String, Long>[] context = parseScrollId(parsedScrollId).getContext(); expectedOps += context.length; this.contexts.add(context); } } this.request = request; this.listener = listener; this.expHolder = new AtomicReference<Throwable>(); this.expectedOps = new CountDown(expectedOps); } public void run() { if (expectedOps.isCountedDown()) { listener.onResponse(new ClearScrollResponse(true)); return; } if (contexts.isEmpty()) { for (final DiscoveryNode node : nodes) { searchServiceTransportAction.sendClearAllScrollContexts(node, request, new ActionListener<Boolean>() { @Override public void onResponse(Boolean success) { onFreedContext(); } @Override public void onFailure(Throwable e) { onFailedFreedContext(e, node); } }); } } else { for (Tuple<String, Long>[] context : contexts) { for (Tuple<String, Long> target : context) { final DiscoveryNode node = nodes.get(target.v1()); if (node == null) { onFreedContext(); continue; } searchServiceTransportAction.sendFreeContext(node, target.v2(), request, new ActionListener<Boolean>() { @Override public void onResponse(Boolean success) { onFreedContext(); } @Override public void onFailure(Throwable e) { onFailedFreedContext(e, node); } }); } } } } void onFreedContext() { if (expectedOps.countDown()) { boolean succeeded = expHolder.get() == null; listener.onResponse(new ClearScrollResponse(succeeded)); } } void onFailedFreedContext(Throwable e, DiscoveryNode node) { logger.warn("Clear SC failed on node[{}]", e, node); if (expectedOps.countDown()) { listener.onResponse(new ClearScrollResponse(false)); } else { expHolder.set(e); } } } class TransportHandler extends BaseTransportRequestHandler<ClearScrollRequest> { @Override public ClearScrollRequest newInstance() { return new ClearScrollRequest(); } @Override public void messageReceived(final ClearScrollRequest request, final TransportChannel channel) throws Exception { // no need to use threaded listener, since we just send a response request.listenerThreaded(false); execute(request, new ActionListener<ClearScrollResponse>() { @Override public void onResponse(ClearScrollResponse response) { try { channel.sendResponse(response); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(e); } catch (Exception e1) { logger.warn("Failed to send error response for action [clear_sc] and request [" + request + "]", e1); } } }); } @Override public String executor() { return ThreadPool.Names.SAME; } } }
1no label
src_main_java_org_elasticsearch_action_search_TransportClearScrollAction.java
323
public class JavaUILabelProvider implements ILabelProvider, IColorProvider, IStyledLabelProvider { protected ListenerList fListeners = new ListenerList(); protected JavaElementImageProvider fImageLabelProvider; protected StorageLabelProvider fStorageLabelProvider; private ArrayList<ILabelDecorator> fLabelDecorators; private int fImageFlags; private long fTextFlags; /** * Creates a new label provider with default flags. */ public JavaUILabelProvider() { this(JavaElementLabels.ALL_DEFAULT, JavaElementImageProvider.OVERLAY_ICONS); } /** * @param textFlags Flags defined in <code>JavaElementLabels</code>. * @param imageFlags Flags defined in <code>JavaElementImageProvider</code>. */ public JavaUILabelProvider(long textFlags, int imageFlags) { fImageLabelProvider= new JavaElementImageProvider(); fLabelDecorators= null; fStorageLabelProvider= new StorageLabelProvider(); fImageFlags= imageFlags; fTextFlags= textFlags; } /** * Adds a decorator to the label provider * @param decorator the decorator to add */ public void addLabelDecorator(ILabelDecorator decorator) { if (fLabelDecorators == null) { fLabelDecorators= new ArrayList<ILabelDecorator>(2); } fLabelDecorators.add(decorator); } /** * Sets the textFlags. * @param textFlags The textFlags to set */ public final void setTextFlags(long textFlags) { fTextFlags= textFlags; } /** * Sets the imageFlags * @param imageFlags The imageFlags to set */ public final void setImageFlags(int imageFlags) { fImageFlags= imageFlags; } /** * Gets the image flags. * Can be overwritten by super classes. * @return Returns a int */ public final int getImageFlags() { return fImageFlags; } /** * Gets the text flags. * @return Returns a int */ public final long getTextFlags() { return fTextFlags; } /** * Evaluates the image flags for a element. * Can be overwritten by super classes. * @param element the element to compute the image flags for * @return Returns a int */ protected int evaluateImageFlags(Object element) { return getImageFlags(); } /** * Evaluates the text flags for a element. Can be overwritten by super classes. * @param element the element to compute the text flags for * @return Returns a int */ protected long evaluateTextFlags(Object element) { return getTextFlags(); } protected Image decorateImage(Image image, Object element) { if (fLabelDecorators != null && image != null) { for (int i= 0; i < fLabelDecorators.size(); i++) { ILabelDecorator decorator= fLabelDecorators.get(i); image= decorator.decorateImage(image, element); } } return image; } /* (non-Javadoc) * @see ILabelProvider#getImage */ public Image getImage(Object element) { Image result= fImageLabelProvider.getImageLabel(element, evaluateImageFlags(element)); if (result == null && (element instanceof IStorage)) { result= fStorageLabelProvider.getImage(element); } return decorateImage(result, element); } protected String decorateText(String text, Object element) { if (fLabelDecorators != null && text.length() > 0) { for (int i= 0; i < fLabelDecorators.size(); i++) { ILabelDecorator decorator= fLabelDecorators.get(i); String decorated= decorator.decorateText(text, element); if (decorated != null) { text= decorated; } } } return text; } /* (non-Javadoc) * @see ILabelProvider#getText */ public String getText(Object element) { String result= JavaElementLabels.getTextLabel(element, evaluateTextFlags(element)); if (result.length() == 0 && (element instanceof IStorage)) { result= fStorageLabelProvider.getText(element); } return decorateText(result, element); } public StyledString getStyledText(Object element) { StyledString string= JavaElementLabels.getStyledTextLabel(element, (evaluateTextFlags(element) | JavaElementLabels.COLORIZE)); if (string.length() == 0 && (element instanceof IStorage)) { string= new StyledString(fStorageLabelProvider.getText(element)); } String decorated= decorateText(string.getString(), element); if (decorated != null) { return StyledCellLabelProvider.styleDecoratedString(decorated, StyledString.DECORATIONS_STYLER, string); } return string; } /* (non-Javadoc) * @see IBaseLabelProvider#dispose */ public void dispose() { if (fLabelDecorators != null) { for (int i= 0; i < fLabelDecorators.size(); i++) { ILabelDecorator decorator= fLabelDecorators.get(i); decorator.dispose(); } fLabelDecorators= null; } fStorageLabelProvider.dispose(); fImageLabelProvider.dispose(); } /* (non-Javadoc) * @see IBaseLabelProvider#addListener(ILabelProviderListener) */ public void addListener(ILabelProviderListener listener) { if (fLabelDecorators != null) { for (int i= 0; i < fLabelDecorators.size(); i++) { ILabelDecorator decorator= fLabelDecorators.get(i); decorator.addListener(listener); } } fListeners.add(listener); } /* (non-Javadoc) * @see IBaseLabelProvider#isLabelProperty(Object, String) */ public boolean isLabelProperty(Object element, String property) { return true; } /* (non-Javadoc) * @see IBaseLabelProvider#removeListener(ILabelProviderListener) */ public void removeListener(ILabelProviderListener listener) { if (fLabelDecorators != null) { for (int i= 0; i < fLabelDecorators.size(); i++) { ILabelDecorator decorator= fLabelDecorators.get(i); decorator.removeListener(listener); } } fListeners.remove(listener); } public static ILabelDecorator[] getDecorators(boolean errortick, ILabelDecorator extra) { if (errortick) { if (extra == null) { return new ILabelDecorator[] {}; } else { return new ILabelDecorator[] { extra }; } } if (extra != null) { return new ILabelDecorator[] { extra }; } return null; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object) */ public Color getForeground(Object element) { return null; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object) */ public Color getBackground(Object element) { return null; } /** * Fires a label provider changed event to all registered listeners * Only listeners registered at the time this method is called are notified. * * @param event a label provider changed event * * @see ILabelProviderListener#labelProviderChanged */ protected void fireLabelProviderChanged(final LabelProviderChangedEvent event) { Object[] listeners = fListeners.getListeners(); for (int i = 0; i < listeners.length; ++i) { final ILabelProviderListener l = (ILabelProviderListener) listeners[i]; SafeRunner.run(new SafeRunnable() { public void run() { l.labelProviderChanged(event); } }); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_explorer_JavaUILabelProvider.java
1,449
public class GetProductsByCategoryIdTei extends TagExtraInfo { @Override public VariableInfo[] getVariableInfo(TagData tagData) { List<VariableInfo> infos = new ArrayList<VariableInfo>(2); String variableName = tagData.getAttributeString("var"); infos.add(new VariableInfo(variableName, String.class.getName(), true, VariableInfo.NESTED)); variableName = tagData.getAttributeString("categoryId"); if (variableName != null) { variableName = GetProductsByCategoryIdTag.toVariableName(variableName); infos.add(new VariableInfo(variableName, String.class.getName(), true, VariableInfo.NESTED)); } return infos.toArray(new VariableInfo[infos.size()]); } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_catalog_taglib_tei_GetProductsByCategoryIdTei.java
2,766
public class NettyHttpChannel implements HttpChannel { private final NettyHttpServerTransport transport; private final Channel channel; private final org.jboss.netty.handler.codec.http.HttpRequest request; public NettyHttpChannel(NettyHttpServerTransport transport, Channel channel, org.jboss.netty.handler.codec.http.HttpRequest request) { this.transport = transport; this.channel = channel; this.request = request; } @Override public void sendResponse(RestResponse response) { // Decide whether to close the connection or not. boolean http10 = request.getProtocolVersion().equals(HttpVersion.HTTP_1_0); boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(HttpHeaders.Names.CONNECTION)) || (http10 && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.headers().get(HttpHeaders.Names.CONNECTION))); // Build the response object. HttpResponseStatus status = getStatus(response.status()); org.jboss.netty.handler.codec.http.HttpResponse resp; if (http10) { resp = new DefaultHttpResponse(HttpVersion.HTTP_1_0, status); if (!close) { resp.headers().add(HttpHeaders.Names.CONNECTION, "Keep-Alive"); } } else { resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status); } if (RestUtils.isBrowser(request.headers().get(HttpHeaders.Names.USER_AGENT))) { if (transport.settings().getAsBoolean("http.cors.enabled", true)) { // Add support for cross-origin Ajax requests (CORS) resp.headers().add("Access-Control-Allow-Origin", transport.settings().get("http.cors.allow-origin", "*")); if (request.getMethod() == HttpMethod.OPTIONS) { // Allow Ajax requests based on the CORS "preflight" request resp.headers().add("Access-Control-Max-Age", transport.settings().getAsInt("http.cors.max-age", 1728000)); resp.headers().add("Access-Control-Allow-Methods", transport.settings().get("http.cors.allow-methods", "OPTIONS, HEAD, GET, POST, PUT, DELETE")); resp.headers().add("Access-Control-Allow-Headers", transport.settings().get("http.cors.allow-headers", "X-Requested-With, Content-Type, Content-Length")); } } } String opaque = request.headers().get("X-Opaque-Id"); if (opaque != null) { resp.headers().add("X-Opaque-Id", opaque); } // Add all custom headers Map<String, List<String>> customHeaders = response.getHeaders(); if (customHeaders != null) { for (Map.Entry<String, List<String>> headerEntry : customHeaders.entrySet()) { for (String headerValue : headerEntry.getValue()) { resp.headers().add(headerEntry.getKey(), headerValue); } } } // Convert the response content to a ChannelBuffer. ChannelBuffer buf; try { if (response instanceof XContentRestResponse) { // if its a builder based response, and it was created with a CachedStreamOutput, we can release it // after we write the response, and no need to do an extra copy because its not thread safe XContentBuilder builder = ((XContentRestResponse) response).builder(); if (response.contentThreadSafe()) { buf = builder.bytes().toChannelBuffer(); } else { buf = builder.bytes().copyBytesArray().toChannelBuffer(); } } else { if (response.contentThreadSafe()) { buf = ChannelBuffers.wrappedBuffer(response.content(), response.contentOffset(), response.contentLength()); } else { buf = ChannelBuffers.copiedBuffer(response.content(), response.contentOffset(), response.contentLength()); } } } catch (IOException e) { throw new HttpException("Failed to convert response to bytes", e); } if (response.prefixContent() != null || response.suffixContent() != null) { ChannelBuffer prefixBuf = ChannelBuffers.EMPTY_BUFFER; if (response.prefixContent() != null) { prefixBuf = ChannelBuffers.copiedBuffer(response.prefixContent(), response.prefixContentOffset(), response.prefixContentLength()); } ChannelBuffer suffixBuf = ChannelBuffers.EMPTY_BUFFER; if (response.suffixContent() != null) { suffixBuf = ChannelBuffers.copiedBuffer(response.suffixContent(), response.suffixContentOffset(), response.suffixContentLength()); } buf = ChannelBuffers.wrappedBuffer(prefixBuf, buf, suffixBuf); } resp.setContent(buf); resp.headers().add(HttpHeaders.Names.CONTENT_TYPE, response.contentType()); resp.headers().add(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf.readableBytes())); if (transport.resetCookies) { String cookieString = request.headers().get(HttpHeaders.Names.COOKIE); if (cookieString != null) { CookieDecoder cookieDecoder = new CookieDecoder(); Set<Cookie> cookies = cookieDecoder.decode(cookieString); if (!cookies.isEmpty()) { // Reset the cookies if necessary. CookieEncoder cookieEncoder = new CookieEncoder(true); for (Cookie cookie : cookies) { cookieEncoder.addCookie(cookie); } resp.headers().add(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); } } } // Write the response. ChannelFuture future = channel.write(resp); // Close the connection after the write operation is done if necessary. if (close) { future.addListener(ChannelFutureListener.CLOSE); } } private HttpResponseStatus getStatus(RestStatus status) { switch (status) { case CONTINUE: return HttpResponseStatus.CONTINUE; case SWITCHING_PROTOCOLS: return HttpResponseStatus.SWITCHING_PROTOCOLS; case OK: return HttpResponseStatus.OK; case CREATED: return HttpResponseStatus.CREATED; case ACCEPTED: return HttpResponseStatus.ACCEPTED; case NON_AUTHORITATIVE_INFORMATION: return HttpResponseStatus.NON_AUTHORITATIVE_INFORMATION; case NO_CONTENT: return HttpResponseStatus.NO_CONTENT; case RESET_CONTENT: return HttpResponseStatus.RESET_CONTENT; case PARTIAL_CONTENT: return HttpResponseStatus.PARTIAL_CONTENT; case MULTI_STATUS: // no status for this?? return HttpResponseStatus.INTERNAL_SERVER_ERROR; case MULTIPLE_CHOICES: return HttpResponseStatus.MULTIPLE_CHOICES; case MOVED_PERMANENTLY: return HttpResponseStatus.MOVED_PERMANENTLY; case FOUND: return HttpResponseStatus.FOUND; case SEE_OTHER: return HttpResponseStatus.SEE_OTHER; case NOT_MODIFIED: return HttpResponseStatus.NOT_MODIFIED; case USE_PROXY: return HttpResponseStatus.USE_PROXY; case TEMPORARY_REDIRECT: return HttpResponseStatus.TEMPORARY_REDIRECT; case BAD_REQUEST: return HttpResponseStatus.BAD_REQUEST; case UNAUTHORIZED: return HttpResponseStatus.UNAUTHORIZED; case PAYMENT_REQUIRED: return HttpResponseStatus.PAYMENT_REQUIRED; case FORBIDDEN: return HttpResponseStatus.FORBIDDEN; case NOT_FOUND: return HttpResponseStatus.NOT_FOUND; case METHOD_NOT_ALLOWED: return HttpResponseStatus.METHOD_NOT_ALLOWED; case NOT_ACCEPTABLE: return HttpResponseStatus.NOT_ACCEPTABLE; case PROXY_AUTHENTICATION: return HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED; case REQUEST_TIMEOUT: return HttpResponseStatus.REQUEST_TIMEOUT; case CONFLICT: return HttpResponseStatus.CONFLICT; case GONE: return HttpResponseStatus.GONE; case LENGTH_REQUIRED: return HttpResponseStatus.LENGTH_REQUIRED; case PRECONDITION_FAILED: return HttpResponseStatus.PRECONDITION_FAILED; case REQUEST_ENTITY_TOO_LARGE: return HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE; case REQUEST_URI_TOO_LONG: return HttpResponseStatus.REQUEST_URI_TOO_LONG; case UNSUPPORTED_MEDIA_TYPE: return HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE; case REQUESTED_RANGE_NOT_SATISFIED: return HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE; case EXPECTATION_FAILED: return HttpResponseStatus.EXPECTATION_FAILED; case UNPROCESSABLE_ENTITY: return HttpResponseStatus.BAD_REQUEST; case LOCKED: return HttpResponseStatus.BAD_REQUEST; case FAILED_DEPENDENCY: return HttpResponseStatus.BAD_REQUEST; case INTERNAL_SERVER_ERROR: return HttpResponseStatus.INTERNAL_SERVER_ERROR; case NOT_IMPLEMENTED: return HttpResponseStatus.NOT_IMPLEMENTED; case BAD_GATEWAY: return HttpResponseStatus.BAD_GATEWAY; case SERVICE_UNAVAILABLE: return HttpResponseStatus.SERVICE_UNAVAILABLE; case GATEWAY_TIMEOUT: return HttpResponseStatus.GATEWAY_TIMEOUT; case HTTP_VERSION_NOT_SUPPORTED: return HttpResponseStatus.HTTP_VERSION_NOT_SUPPORTED; default: return HttpResponseStatus.INTERNAL_SERVER_ERROR; } } }
1no label
src_main_java_org_elasticsearch_http_netty_NettyHttpChannel.java
3,326
public static class Builder implements IndexFieldData.Builder { @Override public IndexFieldData<FSTBytesAtomicFieldData> build(Index index, @IndexSettings Settings indexSettings, FieldMapper<?> mapper, IndexFieldDataCache cache, CircuitBreakerService breakerService) { return new FSTBytesIndexFieldData(index, indexSettings, mapper.names(), mapper.fieldDataType(), cache, breakerService); } }
0true
src_main_java_org_elasticsearch_index_fielddata_plain_FSTBytesIndexFieldData.java
1,621
public class OTxTask extends OAbstractReplicatedTask { private static final long serialVersionUID = 1L; private List<OAbstractRecordReplicatedTask> tasks = new ArrayList<OAbstractRecordReplicatedTask>(); public OTxTask() { } public void add(final OAbstractRecordReplicatedTask iTask) { tasks.add(iTask); } @Override public Object execute(final OServer iServer, ODistributedServerManager iManager, final ODatabaseDocumentTx database) throws Exception { ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, "committing transaction against db=%s...", database.getName()); ODatabaseRecordThreadLocal.INSTANCE.set(database); try { database.begin(); for (OAbstractRecordReplicatedTask task : tasks) { task.execute(iServer, iManager, database); } database.commit(); } catch (ONeedRetryException e) { return Boolean.FALSE; } catch (OTransactionException e) { return Boolean.FALSE; } catch (Exception e) { OLogManager.instance().error(this, "Error on distirbuted transaction commit", e); return Boolean.FALSE; } return Boolean.TRUE; } @Override public QUORUM_TYPE getQuorumType() { return QUORUM_TYPE.WRITE; } @Override public OFixTxTask getFixTask(final ODistributedRequest iRequest, final ODistributedResponse iBadResponse, final ODistributedResponse iGoodResponse) { final OFixTxTask fixTask = new OFixTxTask(); for (OAbstractRecordReplicatedTask t : tasks) { final ORecordId rid = t.getRid(); final ORecordInternal<?> rec = rid.getRecord(); if (rec == null) fixTask.add(new ODeleteRecordTask(rid, null)); else { final ORecordVersion v = rec.getRecordVersion(); v.setRollbackMode(); fixTask.add(new OUpdateRecordTask(rid, rec.toStream(), v, rec.getRecordType())); } } return fixTask; } @Override public void writeExternal(final ObjectOutput out) throws IOException { out.writeInt(tasks.size()); for (OAbstractRecordReplicatedTask task : tasks) out.writeObject(task); } @Override public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { final int size = in.readInt(); for (int i = 0; i < size; ++i) tasks.add((OAbstractRecordReplicatedTask) in.readObject()); } @Override public String getName() { return "tx"; } @Override public String getPayload() { return null; } }
1no label
server_src_main_java_com_orientechnologies_orient_server_distributed_task_OTxTask.java
3,667
public static class Defaults extends AbstractFieldMapper.Defaults { public static final String NAME = IdFieldMapper.NAME; public static final String INDEX_NAME = IdFieldMapper.NAME; public static final FieldType FIELD_TYPE = new FieldType(AbstractFieldMapper.Defaults.FIELD_TYPE); static { FIELD_TYPE.setIndexed(false); FIELD_TYPE.setStored(false); FIELD_TYPE.setOmitNorms(true); FIELD_TYPE.setIndexOptions(IndexOptions.DOCS_ONLY); FIELD_TYPE.freeze(); } public static final String PATH = null; }
0true
src_main_java_org_elasticsearch_index_mapper_internal_IdFieldMapper.java
1,809
interface ConstructionProxyFactory<T> { /** * Gets a construction proxy for the given constructor. */ ConstructionProxy<T> create(); }
0true
src_main_java_org_elasticsearch_common_inject_ConstructionProxyFactory.java
2,525
static final MapFactory ORDERED_MAP_FACTORY = new MapFactory() { @Override public Map<String, Object> newMap() { return new LinkedHashMap<String, Object>(); } };
0true
src_main_java_org_elasticsearch_common_xcontent_support_AbstractXContentParser.java
2,897
public class NumericDateTokenizer extends NumericTokenizer { public NumericDateTokenizer(Reader reader, int precisionStep, char[] buffer, DateTimeFormatter dateTimeFormatter) throws IOException { super(reader, new NumericTokenStream(precisionStep), buffer, dateTimeFormatter); } @Override protected void setValue(NumericTokenStream tokenStream, String value) { tokenStream.setLongValue(((DateTimeFormatter) extra).parseMillis(value)); } }
0true
src_main_java_org_elasticsearch_index_analysis_NumericDateTokenizer.java
1,651
public class OverrideViaAnnotationRequest { private final Class<?> requestedEntity; private final Boolean parentExcluded; private final DynamicEntityDao dynamicEntityDao; private final String prefix; public OverrideViaAnnotationRequest(Class<?> requestedEntity, Boolean parentExcluded, DynamicEntityDao dynamicEntityDao, String prefix) { this.requestedEntity = requestedEntity; this.parentExcluded = parentExcluded; this.dynamicEntityDao = dynamicEntityDao; this.prefix = prefix; } public Class<?> getRequestedEntity() { return requestedEntity; } public Boolean getParentExcluded() { return parentExcluded; } public DynamicEntityDao getDynamicEntityDao() { return dynamicEntityDao; } public String getPrefix() { return prefix; } }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_dao_provider_metadata_request_OverrideViaAnnotationRequest.java
575
public interface CacheItemRequest { public int key(); }
0true
common_src_main_java_org_broadleafcommerce_common_vendor_service_cache_CacheItemRequest.java
1,190
public class BulkUdpModule extends AbstractModule { @Override protected void configure() { bind(BulkUdpService.class).asEagerSingleton(); } }
0true
src_main_java_org_elasticsearch_bulk_udp_BulkUdpModule.java
2,615
return transportService.submitRequest(masterNode, JoinRequestRequestHandler.ACTION, new JoinRequest(node, true), new FutureTransportResponseHandler<JoinResponse>() { @Override public JoinResponse newInstance() { return new JoinResponse(); } }).txGet(timeout.millis(), TimeUnit.MILLISECONDS).clusterState;
0true
src_main_java_org_elasticsearch_discovery_zen_membership_MembershipAction.java
492
public class ServerCookie { private static final String tspecials = ",; "; private static final String tspecials2 = "()<>@,;:\\\"/[]?={} \t"; private static final String tspecials2NoSlash = "()<>@,;:\\\"[]?={} \t"; // Other fields private static final String OLD_COOKIE_PATTERN = "EEE, dd-MMM-yyyy HH:mm:ss z"; private static final ThreadLocal<DateFormat> OLD_COOKIE_FORMAT = new ThreadLocal<DateFormat>() { protected DateFormat initialValue() { DateFormat df = new SimpleDateFormat(OLD_COOKIE_PATTERN, Locale.US); df.setTimeZone(TimeZone.getTimeZone("GMT")); return df; } }; private static final String ancientDate; static { ancientDate = OLD_COOKIE_FORMAT.get().format(new Date(10000)); } /** * If set to true, we parse cookies according to the servlet spec, */ public static final boolean STRICT_SERVLET_COMPLIANCE = false; /** * If set to false, we don't use the IE6/7 Max-Age/Expires work around */ public static final boolean ALWAYS_ADD_EXPIRES = true; // TODO RFC2965 fields also need to be passed public static void appendCookieValue( StringBuffer headerBuf, int version, String name, String value, String path, String domain, String comment, int maxAge, boolean isSecure, boolean isHttpOnly) { StringBuffer buf = new StringBuffer(); // Servlet implementation checks name buf.append( name ); buf.append("="); // Servlet implementation does not check anything else version = maybeQuote2(version, buf, value,true); // Add version 1 specific information if (version == 1) { // Version=1 ... required buf.append ("; Version=1"); // Comment=comment if ( comment!=null ) { buf.append ("; Comment="); maybeQuote2(version, buf, comment); } } // Add domain information, if present if (domain!=null) { buf.append("; Domain="); maybeQuote2(version, buf, domain); } // Max-Age=secs ... or use old "Expires" format // TODO RFC2965 Discard if (maxAge >= 0) { if (version > 0) { buf.append ("; Max-Age="); buf.append (maxAge); } // IE6, IE7 and possibly other browsers don't understand Max-Age. // They do understand Expires, even with V1 cookies! if (version == 0 || ALWAYS_ADD_EXPIRES) { // Wdy, DD-Mon-YY HH:MM:SS GMT ( Expires Netscape format ) buf.append ("; Expires="); // To expire immediately we need to set the time in past if (maxAge == 0) buf.append( ancientDate ); else OLD_COOKIE_FORMAT.get().format( new Date(System.currentTimeMillis() + maxAge*1000L), buf, new FieldPosition(0)); } } // Path=path if (path!=null) { buf.append ("; Path="); if (version==0) { maybeQuote2(version, buf, path); } else { maybeQuote2(version, buf, path, ServerCookie.tspecials2NoSlash, false); } } // Secure if (isSecure) { buf.append ("; Secure"); } // HttpOnly if (isHttpOnly) { buf.append("; HttpOnly"); } headerBuf.append(buf); } public static int maybeQuote2 (int version, StringBuffer buf, String value) { return maybeQuote2(version,buf,value,false); } public static int maybeQuote2 (int version, StringBuffer buf, String value, boolean allowVersionSwitch) { return maybeQuote2(version,buf,value,null,allowVersionSwitch); } public static int maybeQuote2 (int version, StringBuffer buf, String value, String literals, boolean allowVersionSwitch) { if (value==null || value.length()==0) { buf.append("\"\""); }else if (containsCTL(value,version)) throw new IllegalArgumentException("Control character in cookie value, consider BASE64 encoding your value"); else if (alreadyQuoted(value)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,1,value.length()-1)); buf.append('"'); } else if (allowVersionSwitch && (!STRICT_SERVLET_COMPLIANCE) && version==0 && !isToken2(value, literals)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,0,value.length())); buf.append('"'); version = 1; } else if (version==0 && !isToken(value,literals)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,0,value.length())); buf.append('"'); } else if (version==1 && !isToken2(value,literals)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,0,value.length())); buf.append('"'); }else { buf.append(value); } return version; } public static boolean containsCTL(String value, int version) { if( value==null) return false; int len = value.length(); for (int i = 0; i < len; i++) { char c = value.charAt(i); if (c < 0x20 || c >= 0x7f) { if (c == 0x09) continue; //allow horizontal tabs return true; } } return false; } public static boolean alreadyQuoted (String value) { if (value==null || value.length()==0) return false; return (value.charAt(0)=='\"' && value.charAt(value.length()-1)=='\"'); } /** * Escapes any double quotes in the given string. * * @param s the input string * @param beginIndex start index inclusive * @param endIndex exclusive * @return The (possibly) escaped string */ private static String escapeDoubleQuotes(String s, int beginIndex, int endIndex) { if (s == null || s.length() == 0 || s.indexOf('"') == -1) { return s; } StringBuffer b = new StringBuffer(); for (int i = beginIndex; i < endIndex; i++) { char c = s.charAt(i); if (c == '\\' ) { b.append(c); //ignore the character after an escape, just append it if (++i>=endIndex) throw new IllegalArgumentException("Invalid escape character in cookie value."); b.append(s.charAt(i)); } else if (c == '"') b.append('\\').append('"'); else b.append(c); } return b.toString(); } /* * Tests a string and returns true if the string counts as a * reserved token in the Java language. * * @param value the <code>String</code> to be tested * * @return <code>true</code> if the <code>String</code> is a reserved * token; <code>false</code> if it is not */ public static boolean isToken(String value) { return isToken(value,null); } public static boolean isToken(String value, String literals) { String tspecials = (literals==null?ServerCookie.tspecials:literals); if( value==null) return true; int len = value.length(); for (int i = 0; i < len; i++) { char c = value.charAt(i); if (tspecials.indexOf(c) != -1) return false; } return true; } public static boolean isToken2(String value) { return isToken2(value,null); } public static boolean isToken2(String value, String literals) { String tspecials2 = (literals==null?ServerCookie.tspecials2:literals); if( value==null) return true; int len = value.length(); for (int i = 0; i < len; i++) { char c = value.charAt(i); if (tspecials2.indexOf(c) != -1) return false; } return true; } }
0true
common_src_main_java_org_broadleafcommerce_common_security_util_ServerCookie.java
1,275
@Repository("blReviewDetailDao") public class ReviewDetailDaoImpl implements ReviewDetailDao { @PersistenceContext(unitName = "blPU") protected EntityManager em; @Resource(name="blEntityConfiguration") protected EntityConfiguration entityConfiguration; public ReviewDetail readReviewDetailById(Long reviewId) { return em.find(ReviewDetailImpl.class, reviewId); } public ReviewDetail saveReviewDetail(ReviewDetail reviewDetail) { return em.merge(reviewDetail); } @Override public ReviewDetail readReviewByCustomerAndItem(Customer customer, String itemId) { final Query query = em.createNamedQuery("BC_READ_REVIEW_DETAIL_BY_CUSTOMER_ID_AND_ITEM_ID"); query.setParameter("customerId", customer.getId()); query.setParameter("itemId", itemId); ReviewDetail reviewDetail = null; try { reviewDetail = (ReviewDetail) query.getSingleResult(); } catch (NoResultException nre) { //ignore } return reviewDetail; } public ReviewDetail create() { return (ReviewDetail) entityConfiguration.createEntityInstance(ReviewDetail.class.getName()); } public ReviewFeedback createFeedback() { return (ReviewFeedback) entityConfiguration.createEntityInstance(ReviewFeedback.class.getName()); } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_rating_dao_ReviewDetailDaoImpl.java
2,955
public class ThaiAnalyzerProvider extends AbstractIndexAnalyzerProvider<ThaiAnalyzer> { private final ThaiAnalyzer analyzer; @Inject public ThaiAnalyzerProvider(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); analyzer = new ThaiAnalyzer(version, Analysis.parseStopWords(env, settings, ThaiAnalyzer.getDefaultStopSet(), version)); } @Override public ThaiAnalyzer get() { return this.analyzer; } }
0true
src_main_java_org_elasticsearch_index_analysis_ThaiAnalyzerProvider.java
1,827
@Component("blBasicFieldTypeValidator") public class BasicFieldTypeValidator implements PopulateValueRequestValidator { @Override public PropertyValidationResult validate(PopulateValueRequest populateValueRequest, Serializable instance) { switch(populateValueRequest.getMetadata().getFieldType()) { case INTEGER: try { if (int.class.isAssignableFrom(populateValueRequest.getReturnType()) || Integer.class.isAssignableFrom(populateValueRequest.getReturnType())) { Integer.parseInt(populateValueRequest.getRequestedValue()); } else if (byte.class.isAssignableFrom(populateValueRequest.getReturnType()) || Byte.class.isAssignableFrom(populateValueRequest.getReturnType())) { Byte.parseByte(populateValueRequest.getRequestedValue()); } else if (short.class.isAssignableFrom(populateValueRequest.getReturnType()) || Short.class.isAssignableFrom(populateValueRequest.getReturnType())) { Short.parseShort(populateValueRequest.getRequestedValue()); } else if (long.class.isAssignableFrom(populateValueRequest.getReturnType()) || Long.class.isAssignableFrom(populateValueRequest.getReturnType())) { Long.parseLong(populateValueRequest.getRequestedValue()); } } catch (NumberFormatException e) { return new PropertyValidationResult(false, "Field must be an valid number"); } break; case DECIMAL: try { if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType())) { new BigDecimal(populateValueRequest.getRequestedValue()); } else { Double.parseDouble(populateValueRequest.getRequestedValue()); } } catch (NumberFormatException e) { return new PropertyValidationResult(false, "Field must be a valid decimal"); } break; case MONEY: try { if (BigDecimal.class.isAssignableFrom(populateValueRequest.getReturnType()) || Money.class.isAssignableFrom(populateValueRequest.getReturnType())) { new BigDecimal(populateValueRequest.getRequestedValue()); } else if (Double.class.isAssignableFrom(populateValueRequest.getReturnType())) { Double.parseDouble(populateValueRequest.getRequestedValue()); } } catch (NumberFormatException e) { return new PropertyValidationResult(false, "Field must be a valid number"); } break; case DATE: try { populateValueRequest.getDataFormatProvider().getSimpleDateFormatter().parse(populateValueRequest.getRequestedValue()); } catch (ParseException e) { return new PropertyValidationResult(false, "Field must be a date of the format: " + populateValueRequest.getDataFormatProvider().getSimpleDateFormatter().toPattern()); } break; case FOREIGN_KEY: case ADDITIONAL_FOREIGN_KEY: if (Collection.class.isAssignableFrom(populateValueRequest.getReturnType())) { Collection collection; try { collection = (Collection) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName()); } catch (FieldNotAvailableException e) { return new PropertyValidationResult(false, "External entity cannot be added to the specified collection at " + populateValueRequest.getProperty().getName()); } catch (IllegalAccessException e) { return new PropertyValidationResult(false, "External entity cannot be added to the specified collection at " + populateValueRequest.getProperty().getName()); } } else if (Map.class.isAssignableFrom(populateValueRequest.getReturnType())) { return new PropertyValidationResult(false, "External entity cannot be added to a map at " + populateValueRequest.getProperty().getName()); } case ID: if (populateValueRequest.getSetId()) { switch (populateValueRequest.getMetadata().getSecondaryType()) { case INTEGER: Long.valueOf(populateValueRequest.getRequestedValue()); break; default: //do nothing } } default: return new PropertyValidationResult(true); } return new PropertyValidationResult(true); } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_validation_BasicFieldTypeValidator.java
803
public interface OClass extends Comparable<OClass> { public static enum ATTRIBUTES { NAME, SHORTNAME, SUPERCLASS, OVERSIZE, STRICTMODE, ADDCLUSTER, REMOVECLUSTER, CUSTOM, ABSTRACT } public static enum INDEX_TYPE { UNIQUE(true), NOTUNIQUE(true), FULLTEXT(true), DICTIONARY(false), PROXY(true), UNIQUE_HASH_INDEX(true), NOTUNIQUE_HASH_INDEX( true), FULLTEXT_HASH_INDEX(true), DICTIONARY_HASH_INDEX(false); private final boolean automaticIndexable; INDEX_TYPE(boolean iValue) { automaticIndexable = iValue; } public boolean isAutomaticIndexable() { return automaticIndexable; } } public <T> T newInstance() throws InstantiationException, IllegalAccessException; public boolean isAbstract(); public OClass setAbstract(boolean iAbstract); public boolean isStrictMode(); public OClass setStrictMode(boolean iMode); public OClass getSuperClass(); public OClass setSuperClass(OClass iSuperClass); public String getName(); public String getStreamableName(); public Collection<OProperty> declaredProperties(); public Collection<OProperty> properties(); public Collection<OProperty> getIndexedProperties(); public OProperty getProperty(final String iPropertyName); public OProperty createProperty(final String iPropertyName, final OType iType); public OProperty createProperty(final String iPropertyName, final OType iType, final OClass iLinkedClass); public OProperty createProperty(final String iPropertyName, final OType iType, final OType iLinkedType); public void dropProperty(final String iPropertyName); public boolean existsProperty(final String iPropertyName); public Class<?> getJavaClass(); public int getDefaultClusterId(); public int[] getClusterIds(); public OClass addClusterId(final int iId); public OClass removeClusterId(final int iId); public int[] getPolymorphicClusterIds(); public Iterator<OClass> getBaseClasses(); public long getSize(); /** * Returns the oversize factor. Oversize is used to extend the record size by a factor to avoid defragmentation upon updates. 0 or * 1.0 means no oversize. * * @return Oversize factor * @see #setOverSize(float) */ public float getOverSize(); /** * Sets the oversize factor. Oversize is used to extend the record size by a factor to avoid defragmentation upon updates. 0 or * 1.0 means no oversize. Default is 0. * * @return Oversize factor * @see #getOverSize() */ public OClass setOverSize(final float overSize); /** * Returns the number of the records of this class considering also subclasses (polymorphic). */ public long count(); /** * Returns the number of the records of this class and based on polymorphic parameter it consider or not the subclasses. */ public long count(final boolean iPolymorphic); /** * Truncates all the clusters the class uses. * * @throws IOException */ public void truncate() throws IOException; /** * Tells if the current instance extends the passed schema class (iClass). * * @param iClassName * @return true if the current instance extends the passed schema class (iClass). * @see #isSuperClassOf(OClass) */ public boolean isSubClassOf(final String iClassName); /** * Returns true if the current instance extends the passed schema class (iClass). * * @param iClass * @return * @see #isSuperClassOf(OClass) */ public boolean isSubClassOf(final OClass iClass); /** * Returns true if the passed schema class (iClass) extends the current instance. * * @param iClass * @return Returns true if the passed schema class extends the current instance * @see #isSubClassOf(OClass) */ public boolean isSuperClassOf(final OClass iClass); public String getShortName(); public OClass setShortName(final String shortName); public Object get(ATTRIBUTES iAttribute); public OClass set(ATTRIBUTES attribute, Object iValue); /** * Creates database index that is based on passed in field names. Given index will be added into class instance and associated * with database index. * * @param fields * Field names from which index will be created. * @param iName * Database index name * @param iType * Index type. * * @return Class index registered inside of given class ans associated with database index. */ public OIndex<?> createIndex(String iName, INDEX_TYPE iType, String... fields); /** * Creates database index that is based on passed in field names. Given index will be added into class instance and associated * with database index. * * @param fields * Field names from which index will be created. * @param iName * Database index name * @param iType * Index type. * * @return Class index registered inside of given class ans associated with database index. */ public OIndex<?> createIndex(String iName, String iType, String... fields); /** * Creates database index that is based on passed in field names. Given index will be added into class instance. * * @param fields * Field names from which index will be created. * @param iName * Database index name. * @param iType * Index type. * @param iProgressListener * Progress listener. * * @return Class index registered inside of given class ans associated with database index. */ public OIndex<?> createIndex(String iName, INDEX_TYPE iType, OProgressListener iProgressListener, String... fields); /** * Creates database index that is based on passed in field names. Given index will be added into class instance. * * @param fields * Field names from which index will be created. * @param iName * Database index name. * @param iType * Index type. * @param iProgressListener * Progress listener. * * @return Class index registered inside of given class ans associated with database index. */ public OIndex<?> createIndex(String iName, String iType, OProgressListener iProgressListener, String... fields); /** * Returns list of indexes that contain passed in fields names as their first keys. Order of fields does not matter. * * All indexes sorted by their count of parameters in ascending order. If there are indexes for the given set of fields in super * class they will be taken into account. * * * * @param fields * Field names. * * @return list of indexes that contain passed in fields names as their first keys. * * @see com.orientechnologies.orient.core.index.OIndexDefinition#getParamCount() */ public Set<OIndex<?>> getInvolvedIndexes(Collection<String> fields); /** * * * @param fields * Field names. * @return <code>true</code> if given fields are contained as first key fields in class indexes. * * @see #getInvolvedIndexes(java.util.Collection) */ public Set<OIndex<?>> getInvolvedIndexes(String... fields); /** * Returns list of indexes that contain passed in fields names as their first keys. Order of fields does not matter. * * Indexes that related only to the given class will be returned. * * * * @param fields * Field names. * * @return list of indexes that contain passed in fields names as their first keys. * * @see com.orientechnologies.orient.core.index.OIndexDefinition#getParamCount() */ public Set<OIndex<?>> getClassInvolvedIndexes(Collection<String> fields); /** * * * @param fields * Field names. * @return list of indexes that contain passed in fields names as their first keys. * * @see #getClassInvolvedIndexes(java.util.Collection) */ public Set<OIndex<?>> getClassInvolvedIndexes(String... fields); /** * Indicates whether given fields are contained as first key fields in class indexes. Order of fields does not matter. If there * are indexes for the given set of fields in super class they will be taken into account. * * @param fields * Field names. * * @return <code>true</code> if given fields are contained as first key fields in class indexes. */ public boolean areIndexed(Collection<String> fields); /** * @param fields * Field names. * @return <code>true</code> if given fields are contained as first key fields in class indexes. * @see #areIndexed(java.util.Collection) */ public boolean areIndexed(String... fields); /** * Returns index instance by database index name. * * @param iName * Database index name. * @return Index instance. */ public OIndex<?> getClassIndex(String iName); /** * @return All indexes for given class. */ public Set<OIndex<?>> getClassIndexes(); /** * @return All indexes for given class and its super classes. */ public Set<OIndex<?>> getIndexes(); public abstract void setDefaultClusterId(final int iDefaultClusterId); public String getCustom(final String iName); public OClassImpl setCustom(final String iName, final String iValue); public void removeCustom(final String iName); public void clearCustom(); public Set<String> getCustomKeys(); }
0true
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OClass.java
2,875
public class KeepFilterFactoryTests extends ElasticsearchTokenStreamTestCase { private static final String RESOURCE = "org/elasticsearch/index/analysis/keep_analysis.json"; @Test public void testLoadWithoutSettings() { AnalysisService analysisService = AnalysisTestsHelper.createAnalysisServiceFromClassPath(RESOURCE); TokenFilterFactory tokenFilter = analysisService.tokenFilter("keep"); Assert.assertNull(tokenFilter); } @Test public void testLoadOverConfiguredSettings() { Settings settings = ImmutableSettings.settingsBuilder() .put("index.analysis.filter.broken_keep_filter.type", "keep") .put("index.analysis.filter.broken_keep_filter.keep_words_path", "does/not/exists.txt") .put("index.analysis.filter.broken_keep_filter.keep_words", "[\"Hello\", \"worlD\"]") .build(); try { AnalysisTestsHelper.createAnalysisServiceFromSettings(settings); Assert.fail("path and array are configured"); } catch (Exception e) { assertThat(e.getCause(), instanceOf(ElasticsearchIllegalArgumentException.class)); } } @Test public void testKeepWordsPathSettings() { Settings settings = ImmutableSettings.settingsBuilder() .put("index.analysis.filter.non_broken_keep_filter.type", "keep") .put("index.analysis.filter.non_broken_keep_filter.keep_words_path", "does/not/exists.txt") .build(); try { // test our none existing setup is picked up AnalysisTestsHelper.createAnalysisServiceFromSettings(settings); fail("expected an exception due to non existent keep_words_path"); } catch (Throwable e) { assertThat(e.getCause(), instanceOf(FailedToResolveConfigException.class)); } settings = ImmutableSettings.settingsBuilder().put(settings) .put("index.analysis.filter.non_broken_keep_filter.keep_words", new String[]{"test"}) .build(); try { // test our none existing setup is picked up AnalysisTestsHelper.createAnalysisServiceFromSettings(settings); fail("expected an exception indicating that you can't use [keep_words_path] with [keep_words] "); } catch (Throwable e) { assertThat(e.getCause(), instanceOf(ElasticsearchIllegalArgumentException.class)); } } @Test public void testCaseInsensitiveMapping() throws IOException { AnalysisService analysisService = AnalysisTestsHelper.createAnalysisServiceFromClassPath(RESOURCE); TokenFilterFactory tokenFilter = analysisService.tokenFilter("my_keep_filter"); assertThat(tokenFilter, instanceOf(KeepWordFilterFactory.class)); String source = "hello small world"; String[] expected = new String[]{"hello", "world"}; Tokenizer tokenizer = new WhitespaceTokenizer(TEST_VERSION_CURRENT, new StringReader(source)); assertTokenStreamContents(tokenFilter.create(tokenizer), expected, new int[]{1, 2}); } @Test public void testCaseSensitiveMapping() throws IOException { AnalysisService analysisService = AnalysisTestsHelper.createAnalysisServiceFromClassPath(RESOURCE); TokenFilterFactory tokenFilter = analysisService.tokenFilter("my_case_sensitive_keep_filter"); assertThat(tokenFilter, instanceOf(KeepWordFilterFactory.class)); String source = "Hello small world"; String[] expected = new String[]{"Hello"}; Tokenizer tokenizer = new WhitespaceTokenizer(TEST_VERSION_CURRENT, new StringReader(source)); assertTokenStreamContents(tokenFilter.create(tokenizer), expected, new int[]{1}); } }
0true
src_test_java_org_elasticsearch_index_analysis_KeepFilterFactoryTests.java
330
public class PluginsInfo implements Streamable, Serializable, ToXContent { static final class Fields { static final XContentBuilderString PLUGINS = new XContentBuilderString("plugins"); } private List<PluginInfo> infos; public PluginsInfo() { infos = new ArrayList<PluginInfo>(); } public PluginsInfo(int size) { infos = new ArrayList<PluginInfo>(size); } public List<PluginInfo> getInfos() { return infos; } public void add(PluginInfo info) { infos.add(info); } public static PluginsInfo readPluginsInfo(StreamInput in) throws IOException { PluginsInfo infos = new PluginsInfo(); infos.readFrom(in); return infos; } @Override public void readFrom(StreamInput in) throws IOException { int plugins_size = in.readInt(); for (int i = 0; i < plugins_size; i++) { infos.add(PluginInfo.readPluginInfo(in)); } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeInt(infos.size()); for (PluginInfo plugin : infos) { plugin.writeTo(out); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startArray(Fields.PLUGINS); for (PluginInfo pluginInfo : infos) { pluginInfo.toXContent(builder, params); } builder.endArray(); return builder; } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_info_PluginsInfo.java
359
future.andThen(new ExecutionCallback<Integer>() { @Override public void onResponse(Integer response) { result[0] = response.intValue(); semaphore.release(); } @Override public void onFailure(Throwable t) { semaphore.release(); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_ClientMapReduceTest.java
2,573
clusterService.submitStateUpdateTask("zen-disco-node_failed(" + node + "), reason " + reason, Priority.URGENT, new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { DiscoveryNodes.Builder builder = DiscoveryNodes.builder(currentState.nodes()) .remove(node.id()); latestDiscoNodes = builder.build(); currentState = ClusterState.builder(currentState).nodes(latestDiscoNodes).build(); // check if we have enough master nodes, if not, we need to move into joining the cluster again if (!electMaster.hasEnoughMasterNodes(currentState.nodes())) { return rejoin(currentState, "not enough master nodes"); } // eagerly run reroute to remove dead nodes from routing table RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder(currentState).build()); return ClusterState.builder(currentState).routingResult(routingResult).build(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { sendInitialStateEventIfNeeded(); } });
1no label
src_main_java_org_elasticsearch_discovery_zen_ZenDiscovery.java