Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
1,679
public class FsImmutableBlobContainer extends AbstractFsBlobContainer implements ImmutableBlobContainer { public FsImmutableBlobContainer(FsBlobStore blobStore, BlobPath blobPath, File path) { super(blobStore, blobPath, path); } @Override public void writeBlob(final String blobName, final InputStream is, final long sizeInBytes, final WriterListener listener) { blobStore.executor().execute(new Runnable() { @Override public void run() { File file = new File(path, blobName); RandomAccessFile raf; try { raf = new RandomAccessFile(file, "rw"); // clean the file if it exists raf.setLength(0); } catch (Exception e) { listener.onFailure(e); return; } try { try { long bytesWritten = 0; byte[] buffer = new byte[blobStore.bufferSizeInBytes()]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { raf.write(buffer, 0, bytesRead); bytesWritten += bytesRead; } if (bytesWritten != sizeInBytes) { listener.onFailure(new ElasticsearchIllegalStateException("[" + blobName + "]: wrote [" + bytesWritten + "], expected to write [" + sizeInBytes + "]")); return; } } finally { try { is.close(); } catch (IOException ex) { // do nothing } try { raf.close(); } catch (IOException ex) { // do nothing } } FileSystemUtils.syncFile(file); listener.onCompleted(); } catch (Exception e) { // just on the safe size, try and delete it on failure try { if (file.exists()) { file.delete(); } } catch (Exception e1) { // ignore } listener.onFailure(e); } } }); } @Override public void writeBlob(String blobName, InputStream is, long sizeInBytes) throws IOException { BlobStores.syncWriteBlob(this, blobName, is, sizeInBytes); } }
0true
src_main_java_org_elasticsearch_common_blobstore_fs_FsImmutableBlobContainer.java
1,620
public class SecurityConfig { private String ceilingEntityFullyQualifiedName; private List<EntityOperationType> requiredTypes; private List<String> permissions = new ArrayList<String>(); private List<String> roles = new ArrayList<String>(); public String getCeilingEntityFullyQualifiedName() { return ceilingEntityFullyQualifiedName; } public void setCeilingEntityFullyQualifiedName( String ceilingEntityFullyQualifiedName) { this.ceilingEntityFullyQualifiedName = ceilingEntityFullyQualifiedName; } public List<EntityOperationType> getRequiredTypes() { return requiredTypes; } public void setRequiredTypes(List<EntityOperationType> requiredTypes) { this.requiredTypes = requiredTypes; } public List<String> getPermissions() { return permissions; } public void setPermissions(List<String> permissions) { this.permissions = permissions; } public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_security_SecurityConfig.java
43
public interface BiFun<A,B,T> { T apply(A a, B b); }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
518
public class OFetchException extends OException { private static final long serialVersionUID = 7247597939953323863L; public OFetchException(String message, Throwable cause) { super(message, cause); } public OFetchException(String message) { super(message); } }
0true
core_src_main_java_com_orientechnologies_orient_core_exception_OFetchException.java
1,032
public interface OrderItemContainer { List<? extends OrderItem> getOrderItems(); /** * Returns true if the contained items can be discounted. * @return */ boolean getAllowDiscountsOnChildItems(); /** * Returns true if pricing operations are at the container level (as opposed to being * the sum of the contained items) * @return */ boolean isPricingAtContainerLevel(); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_OrderItemContainer.java
1,507
public static class EntityObjectVersion { @OId private ORID rid; @OVersion private Object version; public EntityObjectVersion() { } public ORID getRid() { return rid; } public Object getVersion() { return version; } }
0true
object_src_test_java_com_orientechnologies_orient_object_enhancement_OVersionSerializationTest.java
5,306
public class LongTerms extends InternalTerms { public static final Type TYPE = new Type("terms", "lterms"); public static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() { @Override public LongTerms readResult(StreamInput in) throws IOException { LongTerms buckets = new LongTerms(); buckets.readFrom(in); return buckets; } }; public static void registerStreams() { AggregationStreams.registerStream(STREAM, TYPE.stream()); } static class Bucket extends InternalTerms.Bucket { long term; public Bucket(long term, long docCount, InternalAggregations aggregations) { super(docCount, aggregations); this.term = term; } @Override public String getKey() { return String.valueOf(term); } @Override public Text getKeyAsText() { return new StringText(String.valueOf(term)); } @Override public Number getKeyAsNumber() { return term; } @Override int compareTerm(Terms.Bucket other) { return Longs.compare(term, other.getKeyAsNumber().longValue()); } } private ValueFormatter valueFormatter; LongTerms() {} // for serialization public LongTerms(String name, InternalOrder order, ValueFormatter valueFormatter, int requiredSize, long minDocCount, Collection<InternalTerms.Bucket> buckets) { super(name, order, requiredSize, minDocCount, buckets); this.valueFormatter = valueFormatter; } @Override public Type type() { return TYPE; } @Override public InternalTerms reduce(ReduceContext reduceContext) { List<InternalAggregation> aggregations = reduceContext.aggregations(); if (aggregations.size() == 1) { InternalTerms terms = (InternalTerms) aggregations.get(0); terms.trimExcessEntries(reduceContext.cacheRecycler()); return terms; } InternalTerms reduced = null; Recycler.V<LongObjectOpenHashMap<List<Bucket>>> buckets = null; for (InternalAggregation aggregation : aggregations) { InternalTerms terms = (InternalTerms) aggregation; if (terms instanceof UnmappedTerms) { continue; } if (reduced == null) { reduced = terms; } if (buckets == null) { buckets = reduceContext.cacheRecycler().longObjectMap(terms.buckets.size()); } for (Terms.Bucket bucket : terms.buckets) { List<Bucket> existingBuckets = buckets.v().get(((Bucket) bucket).term); if (existingBuckets == null) { existingBuckets = new ArrayList<Bucket>(aggregations.size()); buckets.v().put(((Bucket) bucket).term, existingBuckets); } existingBuckets.add((Bucket) bucket); } } if (reduced == null) { // there are only unmapped terms, so we just return the first one (no need to reduce) return (UnmappedTerms) aggregations.get(0); } // TODO: would it be better to sort the backing array buffer of the hppc map directly instead of using a PQ? final int size = Math.min(requiredSize, buckets.v().size()); BucketPriorityQueue ordered = new BucketPriorityQueue(size, order.comparator(null)); Object[] internalBuckets = buckets.v().values; boolean[] states = buckets.v().allocated; for (int i = 0; i < states.length; i++) { if (states[i]) { List<LongTerms.Bucket> sameTermBuckets = (List<LongTerms.Bucket>) internalBuckets[i]; final InternalTerms.Bucket b = sameTermBuckets.get(0).reduce(sameTermBuckets, reduceContext.cacheRecycler()); if (b.getDocCount() >= minDocCount) { ordered.insertWithOverflow(b); } } } buckets.release(); InternalTerms.Bucket[] list = new InternalTerms.Bucket[ordered.size()]; for (int i = ordered.size() - 1; i >= 0; i--) { list[i] = (Bucket) ordered.pop(); } reduced.buckets = Arrays.asList(list); return reduced; } @Override public void readFrom(StreamInput in) throws IOException { this.name = in.readString(); this.order = InternalOrder.Streams.readOrder(in); this.valueFormatter = ValueFormatterStreams.readOptional(in); this.requiredSize = readSize(in); this.minDocCount = in.readVLong(); int size = in.readVInt(); List<InternalTerms.Bucket> buckets = new ArrayList<InternalTerms.Bucket>(size); for (int i = 0; i < size; i++) { buckets.add(new Bucket(in.readLong(), in.readVLong(), InternalAggregations.readAggregations(in))); } this.buckets = buckets; this.bucketMap = null; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(name); InternalOrder.Streams.writeOrder(order, out); ValueFormatterStreams.writeOptional(valueFormatter, out); writeSize(requiredSize, out); out.writeVLong(minDocCount); out.writeVInt(buckets.size()); for (InternalTerms.Bucket bucket : buckets) { out.writeLong(((Bucket) bucket).term); out.writeVLong(bucket.getDocCount()); ((InternalAggregations) bucket.getAggregations()).writeTo(out); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(name); builder.startArray(CommonFields.BUCKETS); for (InternalTerms.Bucket bucket : buckets) { builder.startObject(); builder.field(CommonFields.KEY, ((Bucket) bucket).term); if (valueFormatter != null) { builder.field(CommonFields.KEY_AS_STRING, valueFormatter.format(((Bucket) bucket).term)); } builder.field(CommonFields.DOC_COUNT, bucket.getDocCount()); ((InternalAggregations) bucket.getAggregations()).toXContentInternal(builder, params); builder.endObject(); } builder.endArray(); builder.endObject(); return builder; } }
1no label
src_main_java_org_elasticsearch_search_aggregations_bucket_terms_LongTerms.java
256
public static interface Provider { StoreRateLimiting rateLimiting(); }
0true
src_main_java_org_apache_lucene_store_StoreRateLimiting.java
1,015
@SuppressWarnings({"unchecked", "rawtypes"}) public class OChainedIndexProxy<T> implements OIndex<T> { private final OIndex<T> index; private final List<OIndex<?>> indexChain; private final OIndex<?> lastIndex; private final boolean isOneValue; /** * Create proxies that support maximum number of different operations. In case when several different indexes which support * different operations (e.g. indexes of {@code UNIQUE} and {@code FULLTEXT} types) are possible, the creates the only one index * of each type. * * @param index - the index which proxies created for * @param longChain - property chain from the query, which should be evaluated * @param database - current database instance * @return proxies needed to process query. */ public static <T> Collection<OChainedIndexProxy<T>> createdProxy(OIndex<T> index, OSQLFilterItemField.FieldChain longChain, ODatabaseComplex<?> database) { Collection<OChainedIndexProxy<T>> proxies = new ArrayList<OChainedIndexProxy<T>>(); for (List<OIndex<?>> indexChain : getIndexesForChain(index, longChain, database)) { proxies.add(new OChainedIndexProxy<T>(index, indexChain)); } return proxies; } private OChainedIndexProxy(OIndex<T> index, List<OIndex<?>> indexChain) { this.index = index; this.indexChain = Collections.unmodifiableList(indexChain); lastIndex = indexChain.get(indexChain.size() - 1); isOneValue = isAllOneValue(indexChain); } private boolean isAllOneValue(List<OIndex<?>> indexChain) { for (OIndex<?> oIndex : indexChain) { if (!(oIndex.getInternal() instanceof OIndexOneValue)) return false; } return true; } public String getDatabaseName() { return index.getDatabaseName(); } public List<String> getIndexNames() { final ArrayList<String> names = new ArrayList<String>(indexChain.size()); for (OIndex<?> oIndex : indexChain) { names.add(oIndex.getName()); } return names; } @Override public String getName() { final StringBuilder res = new StringBuilder("IndexChain{"); final List<String> indexNames = getIndexNames(); for (int i = 0; i < indexNames.size(); i++) { String indexName = indexNames.get(i); if (i > 0) res.append(", "); res.append(indexName); } res.append("}"); return res.toString(); } /** * {@inheritDoc} */ @Override public T get(Object iKey) { final Object lastIndexResult = lastIndex.get(iKey); final Set<OIdentifiable> result = new HashSet<OIdentifiable>(); applyTailIndexes(lastIndexResult, new IndexValuesResultListener() { @Override public boolean addResult(OIdentifiable value) { result.add(value); return true; } }); if (isOneValue) return (T) (result.isEmpty() ? null : result.iterator().next()); return (T) result; } public long count(Object iKey) { return index.count(iKey); } /** * {@inheritDoc} */ @Override public Collection<OIdentifiable> getValuesBetween(Object iRangeFrom, Object iRangeTo) { final Set<OIdentifiable> result = new HashSet<OIdentifiable>(); final Object lastIndexValuesBetween = lastIndex.getValuesBetween(iRangeFrom, iRangeTo); applyTailIndexes(lastIndexValuesBetween, new IndexValuesResultListener() { @Override public boolean addResult(OIdentifiable value) { result.add(value); return true; } }); return result; } /** * {@inheritDoc} */ @Override public Collection<OIdentifiable> getValuesBetween(Object iRangeFrom, boolean iFromInclusive, Object iRangeTo, boolean iToInclusive) { final Set<OIdentifiable> result = new HashSet<OIdentifiable>(); final Object lastIndexValuesBetween = lastIndex.getValuesBetween(iRangeFrom, iFromInclusive, iRangeTo, iToInclusive); applyTailIndexes(lastIndexValuesBetween, new IndexValuesResultListener() { @Override public boolean addResult(OIdentifiable value) { result.add(value); return true; } }); return result; } /** * {@inheritDoc} */ @Override public void getValuesBetween(Object iRangeFrom, boolean iFromInclusive, Object iRangeTo, boolean iToInclusive, IndexValuesResultListener resultListener) { final Object result = lastIndex.getValuesBetween(iRangeFrom, iFromInclusive, iRangeTo, iToInclusive); applyTailIndexes(result, resultListener); } @Override public long count(final Object iRangeFrom, final boolean iFromInclusive, final Object iRangeTo, final boolean iToInclusive, final int maxValuesToFetch) { return lastIndex.count(iRangeFrom, iFromInclusive, iRangeTo, iToInclusive, maxValuesToFetch); } /** * {@inheritDoc} */ @Override public Collection<OIdentifiable> getValuesMajor(Object fromKey, boolean isInclusive) { final Set<OIdentifiable> result = new HashSet<OIdentifiable>(); final Object lastIndexValuesMajor = lastIndex.getValuesMajor(fromKey, isInclusive); applyTailIndexes(lastIndexValuesMajor, new IndexValuesResultListener() { @Override public boolean addResult(OIdentifiable value) { result.add(value); return true; } }); return result; } /** * {@inheritDoc} */ @Override public void getValuesMajor(Object fromKey, boolean isInclusive, IndexValuesResultListener resultListener) { final Object result = lastIndex.getValuesMajor(fromKey, isInclusive); applyTailIndexes(result, resultListener); } /** * {@inheritDoc} */ @Override public Collection<OIdentifiable> getValuesMinor(Object toKey, boolean isInclusive) { final Set<OIdentifiable> result = new HashSet<OIdentifiable>(); final Object lastIndexValuesMinor = lastIndex.getValuesMinor(toKey, isInclusive); applyTailIndexes(lastIndexValuesMinor, new IndexValuesResultListener() { @Override public boolean addResult(OIdentifiable value) { result.add(value); return true; } }); return result; } /** * {@inheritDoc} */ @Override public void getValuesMinor(Object toKey, boolean isInclusive, IndexValuesResultListener resultListener) { final Object result = lastIndex.getValuesMinor(toKey, isInclusive); applyTailIndexes(result, resultListener); } /** * {@inheritDoc} */ @Override public Collection<OIdentifiable> getValues(Collection<?> iKeys) { final Set<OIdentifiable> result = new HashSet<OIdentifiable>(); final Object lastIndexResult = lastIndex.getValues(iKeys); applyTailIndexes(lastIndexResult, new IndexValuesResultListener() { @Override public boolean addResult(OIdentifiable value) { result.add(value); return true; } }); return result; } /** * {@inheritDoc} */ @Override public void getValues(Collection<?> iKeys, IndexValuesResultListener resultListener) { final Object result = lastIndex.getValues(iKeys); applyTailIndexes(result, resultListener); } /** * Returns internal index of last chain index, because proxy applicable to all operations that last index applicable. */ public OIndexInternal<T> getInternal() { return (OIndexInternal<T>) lastIndex.getInternal(); } /** * {@inheritDoc} */ public OIndexDefinition getDefinition() { return lastIndex.getDefinition(); } private void applyTailIndexes(final Object result, IndexValuesResultListener resultListener) { final OIndex<?> previousIndex = indexChain.get(indexChain.size() - 2); Set<Comparable> currentKeys = prepareKeys(previousIndex, result); for (int j = indexChain.size() - 2; j > 0; j--) { Set<Comparable> newKeys = new TreeSet<Comparable>(); final OIndex<?> currentIndex = indexChain.get(j); for (Comparable currentKey : currentKeys) { final Object currentResult = currentIndex.get(currentKey); final Set<Comparable> preparedKeys; preparedKeys = prepareKeys(indexChain.get(j - 1), currentResult); newKeys.addAll(preparedKeys); } updateStatistic(currentIndex); currentKeys = newKeys; } applyMainIndex(currentKeys, resultListener); } private Set<Comparable> convertResult(Object result, Class<?> targetType) { final Set<Comparable> newKeys; if (result instanceof Set) { newKeys = new TreeSet<Comparable>(); for (Object o : ((Set) result)) { newKeys.add((Comparable) OType.convert(o, targetType)); } return newKeys; } else { return Collections.singleton((Comparable) OType.convert(result, targetType)); } } /** * Make type conversion of keys for specific index. * * @param index - index for which keys prepared for. * @param keys - which should be prepared. * @return keys converted to necessary type. */ private Set<Comparable> prepareKeys(OIndex<?> index, Object keys) { final Class<?> targetType = index.getKeyTypes()[0].getDefaultJavaType(); return convertResult(keys, targetType); } private void applyMainIndex(Iterable<Comparable> currentKeys, IndexValuesResultListener resultListener) { keysLoop: for (Comparable key : currentKeys) { final T result = index.get(index.getDefinition().createValue(key)); if (result instanceof Set) { for (T o : (Set<T>) result) { if (!resultListener.addResult((OIdentifiable) o)) break keysLoop; } } else { if (!resultListener.addResult((OIdentifiable) result)) break; } } updateStatistic(index); } private static Iterable<List<OIndex<?>>> getIndexesForChain(OIndex<?> index, OSQLFilterItemField.FieldChain fieldChain, ODatabaseComplex<?> database) { List<OIndex<?>> baseIndexes = prepareBaseIndexes(index, fieldChain, database); Collection<OIndex<?>> lastIndexes = prepareLastIndexVariants(index, fieldChain, database); Collection<List<OIndex<?>>> result = new ArrayList<List<OIndex<?>>>(); for (OIndex<?> lastIndex : lastIndexes) { final List<OIndex<?>> indexes = new ArrayList<OIndex<?>>(fieldChain.getItemCount()); indexes.addAll(baseIndexes); indexes.add(lastIndex); result.add(indexes); } return result; } private static Collection<OIndex<?>> prepareLastIndexVariants(OIndex<?> index, OSQLFilterItemField.FieldChain fieldChain, ODatabaseComplex<?> database) { OClass oClass = database.getMetadata().getSchema().getClass(index.getDefinition().getClassName()); for (int i = 0; i < fieldChain.getItemCount() - 1; i++) { oClass = oClass.getProperty(fieldChain.getItemName(i)).getLinkedClass(); } final Set<OIndex<?>> involvedIndexes = new TreeSet<OIndex<?>>(new Comparator<OIndex<?>>() { public int compare(OIndex<?> o1, OIndex<?> o2) { return o1.getDefinition().getParamCount() - o2.getDefinition().getParamCount(); } }); involvedIndexes.addAll(oClass.getInvolvedIndexes(fieldChain.getItemName(fieldChain.getItemCount() - 1))); final Collection<Class<? extends OIndex>> indexTypes = new HashSet<Class<? extends OIndex>>(3); final Collection<OIndex<?>> result = new ArrayList<OIndex<?>>(); for (OIndex<?> involvedIndex : involvedIndexes) { if (!indexTypes.contains(involvedIndex.getInternal().getClass())) { result.add(involvedIndex); indexTypes.add(involvedIndex.getInternal().getClass()); } } return result; } private static List<OIndex<?>> prepareBaseIndexes(OIndex<?> index, OSQLFilterItemField.FieldChain fieldChain, ODatabaseComplex<?> database) { List<OIndex<?>> result = new ArrayList<OIndex<?>>(fieldChain.getItemCount() - 1); result.add(index); OClass oClass = database.getMetadata().getSchema().getClass(index.getDefinition().getClassName()); oClass = oClass.getProperty(fieldChain.getItemName(0)).getLinkedClass(); for (int i = 1; i < fieldChain.getItemCount() - 1; i++) { final Set<OIndex<?>> involvedIndexes = oClass.getInvolvedIndexes(fieldChain.getItemName(i)); final OIndex<?> bestIndex = findBestIndex(involvedIndexes); result.add(bestIndex); oClass = oClass.getProperty(fieldChain.getItemName(i)).getLinkedClass(); } return result; } private static OIndex<?> findBestIndex(Iterable<OIndex<?>> involvedIndexes) { OIndex<?> bestIndex = null; for (OIndex<?> index : involvedIndexes) { bestIndex = index; OIndexInternal<?> bestInternalIndex = index.getInternal(); if (bestInternalIndex instanceof OIndexUnique || bestInternalIndex instanceof OIndexNotUnique) { return index; } } return bestIndex; } /** * Register statistic information about usage of index in {@link OProfiler}. * * @param index which usage is registering. */ private void updateStatistic(OIndex<?> index) { final OProfilerMBean profiler = Orient.instance().getProfiler(); if (profiler.isRecording()) { Orient.instance().getProfiler() .updateCounter(profiler.getDatabaseMetric(index.getDatabaseName(), "query.indexUsed"), "Used index in query", +1); final int paramCount = index.getDefinition().getParamCount(); if (paramCount > 1) { final String profiler_prefix = profiler.getDatabaseMetric(index.getDatabaseName(), "query.compositeIndexUsed"); profiler.updateCounter(profiler_prefix, "Used composite index in query", +1); profiler.updateCounter(profiler_prefix + "." + paramCount, "Used composite index in query with " + paramCount + " params", +1); } } } public void checkEntry(final OIdentifiable iRecord, final Object iKey) { index.checkEntry(iRecord, iKey); } // // Following methods are not allowed for proxy. // @Override public OIndex<T> create(String name, OIndexDefinition indexDefinition, String clusterIndexName, Set<String> clustersToIndex, boolean rebuild, OProgressListener progressListener) { throw new UnsupportedOperationException("Not allowed operation"); } @Override public Collection<ODocument> getEntriesMajor(Object fromKey, boolean isInclusive) { throw new UnsupportedOperationException("Not allowed operation"); } @Override public void getEntriesMajor(Object fromKey, boolean isInclusive, IndexEntriesResultListener resultListener) { throw new UnsupportedOperationException("Not allowed operation"); } @Override public Collection<ODocument> getEntriesMinor(Object toKey, boolean isInclusive) { throw new UnsupportedOperationException("Not allowed operation"); } @Override public void getEntriesMinor(Object toKey, boolean isInclusive, IndexEntriesResultListener resultListener) { throw new UnsupportedOperationException("Not allowed operation"); } @Override public Collection<ODocument> getEntriesBetween(Object iRangeFrom, Object iRangeTo, boolean iInclusive) { throw new UnsupportedOperationException("Not allowed operation"); } @Override public void getEntriesBetween(Object iRangeFrom, Object iRangeTo, boolean iInclusive, IndexEntriesResultListener resultListener) { throw new UnsupportedOperationException("Not allowed operation"); } @Override public Collection<ODocument> getEntriesBetween(Object iRangeFrom, Object iRangeTo) { throw new UnsupportedOperationException("Not allowed operation"); } @Override public Collection<ODocument> getEntries(Collection<?> iKeys) { throw new UnsupportedOperationException("Not allowed operation"); } public void getEntries(Collection<?> iKeys, IndexEntriesResultListener resultListener) { throw new UnsupportedOperationException("Not allowed operation"); } public boolean contains(Object iKey) { throw new UnsupportedOperationException("Not allowed operation"); } public void unload() { throw new UnsupportedOperationException("Not allowed operation"); } public OType[] getKeyTypes() { throw new UnsupportedOperationException("Not allowed operation"); } public Iterator<Map.Entry<Object, T>> iterator() { throw new UnsupportedOperationException("Not allowed operation"); } public Iterator<Map.Entry<Object, T>> inverseIterator() { throw new UnsupportedOperationException("Not allowed operation"); } public Iterator<OIdentifiable> valuesIterator() { throw new UnsupportedOperationException("Not allowed operation"); } public Iterator<OIdentifiable> valuesInverseIterator() { throw new UnsupportedOperationException("Not allowed operation"); } public OIndex<T> put(Object iKey, OIdentifiable iValue) { throw new UnsupportedOperationException("Not allowed operation"); } public boolean remove(Object key) { throw new UnsupportedOperationException("Not allowed operation"); } public boolean remove(Object iKey, OIdentifiable iRID) { throw new UnsupportedOperationException("Not allowed operation"); } public int remove(OIdentifiable iRID) { throw new UnsupportedOperationException("Not allowed operation"); } public OIndex<T> clear() { throw new UnsupportedOperationException("Not allowed operation"); } public Iterable<Object> keys() { throw new UnsupportedOperationException("Not allowed operation"); } public long getSize() { throw new UnsupportedOperationException("Not allowed operation"); } public long getKeySize() { throw new UnsupportedOperationException("Not allowed operation"); } @Override public void flush() { throw new UnsupportedOperationException("Not allowed operation"); } public OIndex<T> delete() { throw new UnsupportedOperationException("Not allowed operation"); } @Override public void deleteWithoutIndexLoad(String indexName) { throw new UnsupportedOperationException("Not allowed operation"); } public String getType() { throw new UnsupportedOperationException("Not allowed operation"); } public boolean isAutomatic() { throw new UnsupportedOperationException("Not allowed operation"); } public long rebuild() { throw new UnsupportedOperationException("Not allowed operation"); } public long rebuild(OProgressListener iProgressListener) { throw new UnsupportedOperationException("Not allowed operation"); } public ODocument getConfiguration() { throw new UnsupportedOperationException("Not allowed operation"); } public ORID getIdentity() { throw new UnsupportedOperationException("Not allowed operation"); } public void commit(ODocument iDocument) { throw new UnsupportedOperationException("Not allowed operation"); } public Set<String> getClusters() { throw new UnsupportedOperationException("Not allowed operation"); } public boolean supportsOrderedIterations() { return false; } @Override public boolean isRebuiding() { return false; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_OChainedIndexProxy.java
1,806
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class LocalMapStatsTest extends HazelcastTestSupport { private final String name = "fooMap"; @Test public void testLastAccessTime() throws InterruptedException { final TimeUnit timeUnit = TimeUnit.NANOSECONDS; final long startTime = timeUnit.toMillis(System.nanoTime()); HazelcastInstance h1 = createHazelcastInstance(); IMap<String, String> map1 = h1.getMap(name); String key = "key"; map1.put(key, "value"); long lastUpdateTime = map1.getLocalMapStats().getLastUpdateTime(); assertTrue(lastUpdateTime >= startTime); Thread.sleep(5); map1.put(key, "value2"); long lastUpdateTime2 = map1.getLocalMapStats().getLastUpdateTime(); assertTrue(lastUpdateTime2 > lastUpdateTime); } }
0true
hazelcast_src_test_java_com_hazelcast_map_LocalMapStatsTest.java
203
public class HydratedSetup { private static final Log LOG = LogFactory.getLog(HydratedSetup.class); private static Map<String, String> inheritanceHierarchyRoots = Collections.synchronizedMap(new HashMap<String, String>()); private static String getInheritanceHierarchyRoot(Class<?> myEntityClass) { String myEntityName = myEntityClass.getName(); if (inheritanceHierarchyRoots.containsKey(myEntityName)) { return inheritanceHierarchyRoots.get(myEntityName); } Class<?> currentClass = myEntityClass; boolean eof = false; while (!eof) { Class<?> superclass = currentClass.getSuperclass(); if (superclass.equals(Object.class) || !superclass.isAnnotationPresent(Entity.class)) { eof = true; } else { currentClass = superclass; } } if (!currentClass.isAnnotationPresent(Cache.class)) { currentClass = myEntityClass; } inheritanceHierarchyRoots.put(myEntityName, currentClass.getName()); return inheritanceHierarchyRoots.get(myEntityName); } public static void populateFromCache(Object entity) { populateFromCache(entity, null); } public static void populateFromCache(Object entity, String propertyName) { HydratedCacheManager manager = HydratedCacheEventListenerFactory.getConfiguredManager(); HydrationDescriptor descriptor = ((HydratedAnnotationManager) manager).getHydrationDescriptor(entity); if (!MapUtils.isEmpty(descriptor.getHydratedMutators())) { Method[] idMutators = descriptor.getIdMutators(); String cacheRegion = descriptor.getCacheRegion(); for (String field : descriptor.getHydratedMutators().keySet()) { if (StringUtils.isEmpty(propertyName) || field.equals(propertyName)) { try { Serializable entityId = (Serializable) idMutators[0].invoke(entity); Object hydratedItem = manager.getHydratedCacheElementItem(cacheRegion, getInheritanceHierarchyRoot(entity.getClass()), entityId, field); if (hydratedItem == null) { Method factoryMethod = entity.getClass().getMethod(descriptor.getHydratedMutators().get(field).getFactoryMethod(), new Class[]{}); Object fieldVal = factoryMethod.invoke(entity); manager.addHydratedCacheElementItem(cacheRegion, getInheritanceHierarchyRoot(entity.getClass()), entityId, field, fieldVal); hydratedItem = fieldVal; } descriptor.getHydratedMutators().get(field).getMutators()[1].invoke(entity, hydratedItem); } catch (InvocationTargetException e) { if (e.getTargetException() != null && e.getTargetException() instanceof CacheFactoryException) { LOG.warn("Unable to setup the hydrated cache for an entity. " + e.getTargetException().getMessage()); } else { throw new RuntimeException("There was a problem while replacing a hydrated cache item - field("+field+") : entity("+entity.getClass().getName()+')', e); } } catch (Exception e) { throw new RuntimeException("There was a problem while replacing a hydrated cache item - field("+field+") : entity("+entity.getClass().getName()+')', e); } } } } } public static void addCacheItem(String cacheRegion, String cacheName, Serializable elementKey, String elementItemName, Object elementValue) { HydratedCacheManager manager = HydratedCacheEventListenerFactory.getConfiguredManager(); manager.addHydratedCacheElementItem(cacheRegion, cacheName, elementKey, elementItemName, elementValue); } public static Object getCacheItem(String cacheRegion, String cacheName, Serializable elementKey, String elementItemName) { HydratedCacheManager manager = HydratedCacheEventListenerFactory.getConfiguredManager(); return manager.getHydratedCacheElementItem(cacheRegion, cacheName, elementKey, elementItemName); } public static EntityManager retrieveBoundEntityManager() { Map<Object, Object> resources = TransactionSynchronizationManager.getResourceMap(); for (Map.Entry<Object, Object> entry : resources.entrySet()) { if (entry.getKey() instanceof EntityManagerFactory) { EntityManagerFactory emf = (EntityManagerFactory) entry.getKey(); //return the entityManager from the first found return ((EntityManagerHolder) entry.getValue()).getEntityManager(); } } throw new RuntimeException("Unable to restore skus from hydrated cache. Please make sure that the OpenEntityManagerInViewFilter is configured in web.xml for the blPU persistence unit."); } }
0true
common_src_main_java_org_broadleafcommerce_common_cache_HydratedSetup.java
165
public class SpecifyTypeProposal implements ICompletionProposal, ICompletionProposalExtension6 { private final ProducedType infType; private final String desc; private final Tree.Type typeNode; private CeylonEditor editor; private final Tree.CompilationUnit rootNode; private Point selection; private SpecifyTypeProposal(String desc, Tree.Type type, Tree.CompilationUnit cu, ProducedType infType, CeylonEditor editor) { this.desc = desc; this.typeNode = type; this.rootNode = cu; this.infType = infType; this.editor = editor; } @Override public void apply(IDocument document) { int offset = typeNode.getStartIndex(); int length = typeNode.getStopIndex()-offset+1; if (editor==null) { IEditorPart ed = EditorUtil.getCurrentEditor(); if (ed instanceof CeylonEditor) { editor = (CeylonEditor) ed; } } if (editor==null) { if (typeNode instanceof Tree.LocalModifier) { DocumentChange change = new DocumentChange("Specify Type", document); change.setEdit(new MultiTextEdit()); try { HashSet<Declaration> decs = new HashSet<Declaration>(); importType(decs, infType, rootNode); int il = applyImports(change, decs, rootNode, document); String typeName = infType.getProducedTypeName(rootNode.getUnit()); change.addEdit(new ReplaceEdit(offset, length, typeName)); change.perform(new NullProgressMonitor()); offset += il; length = typeName.length(); selection = new Point(offset, length); } catch (Exception e) { e.printStackTrace(); } } } else { LinkedModeModel linkedModeModel = new LinkedModeModel(); ProposalPosition linkedPosition = getTypeProposals(document, offset, length, infType, rootNode, null); try { LinkedMode.addLinkedPosition(linkedModeModel, linkedPosition); LinkedMode.installLinkedMode(editor, document, linkedModeModel, this, new DeleteBlockingExitPolicy(document), NO_STOP, -1); } catch (BadLocationException e) { e.printStackTrace(); } } } static void addSpecifyTypeProposal(Tree.CompilationUnit cu, Node node, Collection<ICompletionProposal> proposals, CeylonEditor editor) { for (SpecifyTypeProposal proposal: createProposals(cu, node, editor)) { proposals.add(proposal); } } public static List<SpecifyTypeProposal> createProposals(Tree.CompilationUnit cu, Node node, CeylonEditor editor) { final Tree.Type type = (Tree.Type) node; InferredType result = inferType(cu, type); List<SpecifyTypeProposal> list = new ArrayList<SpecifyTypeProposal>(2); ProducedType declaredType = type.getTypeModel(); if (!isTypeUnknown(declaredType)) { if (!isTypeUnknown(result.generalizedType) && (isTypeUnknown(result.inferredType) || !result.generalizedType.isSubtypeOf(result.inferredType)) && !result.generalizedType.isSubtypeOf(declaredType)) { list.add(new SpecifyTypeProposal("Widen type to", type, cu, result.generalizedType, editor)); } if (!isTypeUnknown(result.inferredType)) { if (!result.inferredType.isSubtypeOf(declaredType)) { list.add(new SpecifyTypeProposal("Change type to", type, cu, result.inferredType, editor)); } else if (!declaredType.isSubtypeOf(result.inferredType)) { list.add(new SpecifyTypeProposal("Narrow type to", type, cu, result.inferredType, editor)); } } if (type instanceof Tree.LocalModifier) { list.add(new SpecifyTypeProposal("Declare explicit type", type, cu, declaredType, editor)); } } else { if (!isTypeUnknown(result.inferredType)) { list.add(new SpecifyTypeProposal("Declare type", type, cu, result.inferredType, editor)); } if (!isTypeUnknown(result.generalizedType) && (isTypeUnknown(result.inferredType) || !result.generalizedType.isSubtypeOf(result.inferredType))) { list.add(new SpecifyTypeProposal("Declare type", type, cu, result.generalizedType, editor)); } } return list; } static InferredType inferType(Tree.CompilationUnit cu, final Tree.Type type) { InferTypeVisitor itv = new InferTypeVisitor(type.getUnit()) { @Override public void visit(Tree.TypedDeclaration that) { if (that.getType()==type) { dec = that.getDeclarationModel(); // union(that.getType().getTypeModel()); } super.visit(that); } }; itv.visit(cu); return itv.result; } @Override public StyledString getStyledDisplayString() { return Highlights.styleProposal(getDisplayString(), false); } @Override public Point getSelection(IDocument document) { return selection; } @Override public String getAdditionalProposalInfo() { return null; } @Override public String getDisplayString() { String type = infType.getProducedTypeName(rootNode.getUnit()); return desc + " '" + type + "'"; } @Override public Image getImage() { return REVEAL; } @Override public IContextInformation getContextInformation() { return null; } static void addTypingProposals(Collection<ICompletionProposal> proposals, IFile file, Tree.CompilationUnit cu, Node node, Tree.Declaration decNode, CeylonEditor editor) { if (decNode instanceof Tree.TypedDeclaration && !(decNode instanceof Tree.ObjectDefinition) && !(decNode instanceof Tree.Variable)) { Tree.Type type = ((Tree.TypedDeclaration) decNode).getType(); if (type instanceof Tree.LocalModifier || type instanceof Tree.StaticType) { addSpecifyTypeProposal(cu, type, proposals, editor); } } else if (node instanceof Tree.LocalModifier || node instanceof Tree.StaticType) { addSpecifyTypeProposal(cu, node, proposals, editor); } if (node instanceof Tree.MemberOrTypeExpression) { addSpecifyTypeArgumentsProposal(cu, node, proposals, file); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_SpecifyTypeProposal.java
956
public abstract class AbstractIsLockedRequest extends KeyBasedClientRequest { protected Data key; private long threadId; public AbstractIsLockedRequest() { } public AbstractIsLockedRequest(Data key) { this.key = key; } protected AbstractIsLockedRequest(Data key, long threadId) { this(key); this.threadId = threadId; } protected String getName() { return (String) getClientEngine().toObject(key); } @Override protected final Operation prepareOperation() { return new IsLockedOperation(getNamespace(), key, threadId); } @Override protected final Object getKey() { return key; } protected abstract ObjectNamespace getNamespace(); @Override public final String getServiceName() { return LockService.SERVICE_NAME; } @Override public void write(PortableWriter writer) throws IOException { writer.writeLong("tid", threadId); ObjectDataOutput out = writer.getRawDataOutput(); key.writeData(out); } @Override public void read(PortableReader reader) throws IOException { threadId = reader.readLong("tid"); ObjectDataInput in = reader.getRawDataInput(); key = new Data(); key.readData(in); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_lock_client_AbstractIsLockedRequest.java
191
public class TimeDTO { @AdminPresentation(excluded = true) private Calendar cal; @AdminPresentation(friendlyName = "TimeDTO_Hour_Of_Day", fieldType = SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration = "org.broadleafcommerce.common.time.HourOfDayType") private Integer hour; @AdminPresentation(friendlyName = "TimeDTO_Day_Of_Week", fieldType = SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration = "org.broadleafcommerce.common.time.DayOfWeekType") private Integer dayOfWeek; @AdminPresentation(friendlyName = "TimeDTO_Month", fieldType = SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration = "org.broadleafcommerce.common.time.MonthType") private Integer month; @AdminPresentation(friendlyName = "TimeDTO_Day_Of_Month", fieldType = SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration = "org.broadleafcommerce.common.time.DayOfMonthType") private Integer dayOfMonth; @AdminPresentation(friendlyName = "TimeDTO_Minute", fieldType = SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration = "org.broadleafcommerce.common.time.MinuteType") private Integer minute; @AdminPresentation(friendlyName = "TimeDTO_Date") private Date date; public TimeDTO() { cal = SystemTime.asCalendar(); } public TimeDTO(Calendar cal) { this.cal = cal; } /** * @return int representing the hour of day as 0 - 23 */ public HourOfDayType getHour() { if (hour == null) { hour = cal.get(Calendar.HOUR_OF_DAY); } return HourOfDayType.getInstance(hour.toString()); } /** * @return int representing the day of week using Calendar.DAY_OF_WEEK values. * 1 = Sunday, 7 = Saturday */ public DayOfWeekType getDayOfWeek() { if (dayOfWeek == null) { dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); } return DayOfWeekType.getInstance(dayOfWeek.toString()); } /** * @return the current day of the month (1-31). */ public DayOfMonthType getDayOfMonth() { if (dayOfMonth == null) { dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); } return DayOfMonthType.getInstance(dayOfMonth.toString()); } /** * @return int representing the current month (1-12) */ public MonthType getMonth() { if (month == null) { month = cal.get(Calendar.MONTH); } return MonthType.getInstance(month.toString()); } public MinuteType getMinute() { if (minute == null) { minute = cal.get(Calendar.MINUTE); } return MinuteType.getInstance(minute.toString()); } public Date getDate() { if (date == null) { date = cal.getTime(); } return date; } public void setCal(Calendar cal) { this.cal = cal; } public void setHour(HourOfDayType hour) { this.hour = Integer.valueOf(hour.getType()); ; } public void setDayOfWeek(DayOfWeekType dayOfWeek) { this.dayOfWeek = Integer.valueOf(dayOfWeek.getType()); } public void setMonth(MonthType month) { this.month = Integer.valueOf(month.getType()); } public void setDayOfMonth(DayOfMonthType dayOfMonth) { this.dayOfMonth = Integer.valueOf(dayOfMonth.getType()); } public void setDate(Date date) { this.date = date; } public void setMinute(MinuteType minute) { this.minute = Integer.valueOf(minute.getType()); ; } }
0true
common_src_main_java_org_broadleafcommerce_common_TimeDTO.java
3,307
public abstract class DoubleArrayAtomicFieldData extends AbstractAtomicNumericFieldData { public static DoubleArrayAtomicFieldData empty(int numDocs) { return new Empty(numDocs); } private final int numDocs; protected long size = -1; public DoubleArrayAtomicFieldData(int numDocs) { super(true); this.numDocs = numDocs; } @Override public void close() { } @Override public int getNumDocs() { return numDocs; } static class Empty extends DoubleArrayAtomicFieldData { Empty(int numDocs) { super(numDocs); } @Override public LongValues getLongValues() { return LongValues.EMPTY; } @Override public DoubleValues getDoubleValues() { return DoubleValues.EMPTY; } @Override public boolean isMultiValued() { return false; } @Override public boolean isValuesOrdered() { return false; } @Override public long getNumberUniqueValues() { return 0; } @Override public long getMemorySizeInBytes() { return 0; } @Override public BytesValues getBytesValues(boolean needsHashes) { return BytesValues.EMPTY; } @Override public ScriptDocValues getScriptValues() { return ScriptDocValues.EMPTY; } } public static class WithOrdinals extends DoubleArrayAtomicFieldData { private final BigDoubleArrayList values; private final Ordinals ordinals; public WithOrdinals(BigDoubleArrayList values, int numDocs, Ordinals ordinals) { super(numDocs); this.values = values; this.ordinals = ordinals; } @Override public boolean isMultiValued() { return ordinals.isMultiValued(); } @Override public boolean isValuesOrdered() { return true; } @Override public long getNumberUniqueValues() { return ordinals.getNumOrds(); } @Override public long getMemorySizeInBytes() { if (size == -1) { size = RamUsageEstimator.NUM_BYTES_INT/*size*/ + RamUsageEstimator.NUM_BYTES_INT/*numDocs*/ + values.sizeInBytes() + ordinals.getMemorySizeInBytes(); } return size; } @Override public LongValues getLongValues() { return new LongValues(values, ordinals.ordinals()); } @Override public DoubleValues getDoubleValues() { return new DoubleValues(values, ordinals.ordinals()); } static class LongValues extends org.elasticsearch.index.fielddata.LongValues.WithOrdinals { private final BigDoubleArrayList values; LongValues(BigDoubleArrayList values, Ordinals.Docs ordinals) { super(ordinals); this.values = values; } @Override public final long getValueByOrd(long ord) { assert ord != Ordinals.MISSING_ORDINAL; return (long) values.get(ord); } } static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues.WithOrdinals { private final BigDoubleArrayList values; DoubleValues(BigDoubleArrayList values, Ordinals.Docs ordinals) { super(ordinals); this.values = values; } @Override public double getValueByOrd(long ord) { assert ord != Ordinals.MISSING_ORDINAL; return values.get(ord); } } } /** * A single valued case, where not all values are "set", so we have a FixedBitSet that * indicates which values have an actual value. */ public static class SingleFixedSet extends DoubleArrayAtomicFieldData { private final BigDoubleArrayList values; private final FixedBitSet set; private final long numOrds; public SingleFixedSet(BigDoubleArrayList values, int numDocs, FixedBitSet set, long numOrds) { super(numDocs); this.values = values; this.set = set; this.numOrds = numOrds; } @Override public boolean isMultiValued() { return false; } @Override public boolean isValuesOrdered() { return false; } @Override public long getNumberUniqueValues() { return numOrds; } @Override public long getMemorySizeInBytes() { if (size == -1) { size = RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.sizeInBytes() + RamUsageEstimator.sizeOf(set.getBits()); } return size; } @Override public LongValues getLongValues() { return new LongValues(values, set); } @Override public DoubleValues getDoubleValues() { return new DoubleValues(values, set); } static class LongValues extends org.elasticsearch.index.fielddata.LongValues { private final BigDoubleArrayList values; private final FixedBitSet set; LongValues(BigDoubleArrayList values, FixedBitSet set) { super(false); this.values = values; this.set = set; } @Override public int setDocument(int docId) { this.docId = docId; return set.get(docId) ? 1 : 0; } @Override public long nextValue() { return (long) values.get(docId); } } static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues { private final BigDoubleArrayList values; private final FixedBitSet set; DoubleValues(BigDoubleArrayList values, FixedBitSet set) { super(false); this.values = values; this.set = set; } @Override public int setDocument(int docId) { this.docId = docId; return set.get(docId) ? 1 : 0; } @Override public double nextValue() { return values.get(docId); } } } /** * Assumes all the values are "set", and docId is used as the index to the value array. */ public static class Single extends DoubleArrayAtomicFieldData { private final BigDoubleArrayList values; private final long numOrds; /** * Note, here, we assume that there is no offset by 1 from docId, so position 0 * is the value for docId 0. */ public Single(BigDoubleArrayList values, int numDocs, long numOrds) { super(numDocs); this.values = values; this.numOrds = numOrds; } @Override public boolean isMultiValued() { return false; } @Override public boolean isValuesOrdered() { return false; } @Override public long getNumberUniqueValues() { return numOrds; } @Override public long getMemorySizeInBytes() { if (size == -1) { size = RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.sizeInBytes(); } return size; } @Override public LongValues getLongValues() { return new LongValues(values); } @Override public DoubleValues getDoubleValues() { return new DoubleValues(values); } static final class LongValues extends DenseLongValues { private final BigDoubleArrayList values; LongValues(BigDoubleArrayList values) { super(false); this.values = values; } @Override public long nextValue() { return (long) values.get(docId); } } static final class DoubleValues extends DenseDoubleValues { private final BigDoubleArrayList values; DoubleValues(BigDoubleArrayList values) { super(false); this.values = values; } @Override public double nextValue() { return values.get(docId); } } } }
1no label
src_main_java_org_elasticsearch_index_fielddata_plain_DoubleArrayAtomicFieldData.java
1,685
blobContainer.writeBlob(blobName, is, sizeInBytes, new ImmutableBlobContainer.WriterListener() { @Override public void onCompleted() { latch.countDown(); } @Override public void onFailure(Throwable t) { failure.set(t); latch.countDown(); } });
0true
src_main_java_org_elasticsearch_common_blobstore_support_BlobStores.java
207
Callable<Object> response = new Callable<Object>() { public Object call() throws Exception { Boolean result; try { OStorageRemoteThreadLocal.INSTANCE.get().sessionId = sessionId; beginResponse(network); result = network.readByte() == 1; } finally { endResponse(network); OStorageRemoteThreadLocal.INSTANCE.get().sessionId = -1; } iCallback.call(iRid, result); return null; } };
0true
client_src_main_java_com_orientechnologies_orient_client_remote_OStorageRemote.java
638
public class PeerRecoveryStatus { 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 PeerRecoveryStatus(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_PeerRecoveryStatus.java
226
public final class SimpleNeoStoreProvider implements NeoStoreProvider { private NeoStore neoStore; public SimpleNeoStoreProvider( NeoStore neoStore ) { this.neoStore = neoStore; } @Override public NeoStore evaluate() { return neoStore; } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_SimpleNeoStoreProvider.java
80
@SuppressWarnings("serial") static final class MapReduceMappingsToLongTask<K,V> extends BulkTask<K,V,Long> { final ObjectByObjectToLong<? super K, ? super V> transformer; final LongByLongToLong reducer; final long basis; long result; MapReduceMappingsToLongTask<K,V> rights, nextRight; MapReduceMappingsToLongTask (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t, MapReduceMappingsToLongTask<K,V> nextRight, ObjectByObjectToLong<? super K, ? super V> transformer, long basis, LongByLongToLong reducer) { super(p, b, i, f, t); this.nextRight = nextRight; this.transformer = transformer; this.basis = basis; this.reducer = reducer; } public final Long getRawResult() { return result; } public final void compute() { final ObjectByObjectToLong<? super K, ? super V> transformer; final LongByLongToLong reducer; if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) { long r = this.basis; for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { addToPendingCount(1); (rights = new MapReduceMappingsToLongTask<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.key, p.val)); result = r; CountedCompleter<?> c; for (c = firstComplete(); c != null; c = c.nextComplete()) { @SuppressWarnings("unchecked") MapReduceMappingsToLongTask<K,V> t = (MapReduceMappingsToLongTask<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
210
public static class Command extends LogEntry { private final XaCommand command; Command( int identifier, XaCommand command ) { super( identifier ); this.command = command; } public XaCommand getXaCommand() { return command; } @Override public String toString() { return "Command[" + getIdentifier() + ", " + command + "]"; } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogEntry.java
531
@SuppressWarnings("serial") public class OValidationException extends RuntimeException { public OValidationException(String string) { super(string); } public OValidationException(String message, Throwable cause) { super(message, cause); } }
0true
core_src_main_java_com_orientechnologies_orient_core_exception_OValidationException.java
2,367
public class ByteSizeUnitTests extends ElasticsearchTestCase { @Test public void testBytes() { assertThat(BYTES.toBytes(1), equalTo(1l)); assertThat(BYTES.toKB(1024), equalTo(1l)); assertThat(BYTES.toMB(1024 * 1024), equalTo(1l)); assertThat(BYTES.toGB(1024 * 1024 * 1024), equalTo(1l)); } @Test public void testKB() { assertThat(KB.toBytes(1), equalTo(1024l)); assertThat(KB.toKB(1), equalTo(1l)); assertThat(KB.toMB(1024), equalTo(1l)); assertThat(KB.toGB(1024 * 1024), equalTo(1l)); } @Test public void testMB() { assertThat(MB.toBytes(1), equalTo(1024l * 1024)); assertThat(MB.toKB(1), equalTo(1024l)); assertThat(MB.toMB(1), equalTo(1l)); assertThat(MB.toGB(1024), equalTo(1l)); } @Test public void testGB() { assertThat(GB.toBytes(1), equalTo(1024l * 1024 * 1024)); assertThat(GB.toKB(1), equalTo(1024l * 1024)); assertThat(GB.toMB(1), equalTo(1024l)); assertThat(GB.toGB(1), equalTo(1l)); } @Test public void testTB() { assertThat(TB.toBytes(1), equalTo(1024l * 1024 * 1024 * 1024)); assertThat(TB.toKB(1), equalTo(1024l * 1024 * 1024)); assertThat(TB.toMB(1), equalTo(1024l * 1024)); assertThat(TB.toGB(1), equalTo(1024l)); assertThat(TB.toTB(1), equalTo(1l)); } @Test public void testPB() { assertThat(PB.toBytes(1), equalTo(1024l * 1024 * 1024 * 1024 * 1024)); assertThat(PB.toKB(1), equalTo(1024l * 1024 * 1024 * 1024)); assertThat(PB.toMB(1), equalTo(1024l * 1024 * 1024)); assertThat(PB.toGB(1), equalTo(1024l * 1024)); assertThat(PB.toTB(1), equalTo(1024l)); assertThat(PB.toPB(1), equalTo(1l)); } }
0true
src_test_java_org_elasticsearch_common_unit_ByteSizeUnitTests.java
416
static final class Fields { static final XContentBuilderString SNAPSHOTS = new XContentBuilderString("snapshots"); }
0true
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_get_GetSnapshotsResponse.java
2,986
static final class Fields { static final XContentBuilderString FILTER_CACHE = new XContentBuilderString("filter_cache"); static final XContentBuilderString MEMORY_SIZE = new XContentBuilderString("memory_size"); static final XContentBuilderString MEMORY_SIZE_IN_BYTES = new XContentBuilderString("memory_size_in_bytes"); static final XContentBuilderString EVICTIONS = new XContentBuilderString("evictions"); }
0true
src_main_java_org_elasticsearch_index_cache_filter_FilterCacheStats.java
954
private class TransportHandler extends BaseTransportRequestHandler<Request> { @Override public Request newInstance() { return newRequest(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void messageReceived(final Request request, final TransportChannel channel) throws Exception { // we just send back a response, no need to fork a listener request.listenerThreaded(false); execute(request, new ActionListener<Response>() { @Override public void onResponse(Response 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 response", e1); } } }); } }
0true
src_main_java_org_elasticsearch_action_support_master_TransportMasterNodeOperationAction.java
402
add(store, "expiring-doc1", new HashMap<String, Object>() {{ put(NAME, "first"); put(TIME, 1L); put(WEIGHT, 10.2d); }}, true, 2);
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexProviderTest.java
2,050
public class EntrySetOperationFactory implements OperationFactory { String name; public EntrySetOperationFactory() { } public EntrySetOperationFactory(String name) { this.name = name; } @Override public Operation createOperation() { return new MapEntrySetOperation(name); } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); } @Override public void readData(ObjectDataInput in) throws IOException { name = in.readUTF(); } }
0true
hazelcast_src_main_java_com_hazelcast_map_operation_EntrySetOperationFactory.java
3,268
public static class Docs implements Ordinals.Docs { private final DocIdOrdinals parent; private final LongsRef longsScratch = new LongsRef(new long[1], 0, 1); private int docId = -1; private long currentOrdinal = -1; public Docs(DocIdOrdinals parent) { this.parent = parent; } @Override public Ordinals ordinals() { return parent; } @Override public int getNumDocs() { return parent.getNumDocs(); } @Override public long getNumOrds() { return parent.getNumOrds(); } @Override public long getMaxOrd() { return parent.getMaxOrd(); } @Override public boolean isMultiValued() { return false; } @Override public long getOrd(int docId) { return currentOrdinal = docId + 1; } @Override public LongsRef getOrds(int docId) { longsScratch.longs[0] = currentOrdinal = docId + 1; return longsScratch; } @Override public long nextOrd() { assert docId >= 0; currentOrdinal = docId + 1; docId = -1; return currentOrdinal; } @Override public int setDocument(int docId) { this.docId = docId; return 1; } @Override public long currentOrd() { return currentOrdinal; } }
0true
src_main_java_org_elasticsearch_index_fielddata_ordinals_DocIdOrdinals.java
434
map.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { changed.value = true; } });
0true
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedMapTest.java
918
public interface LockResource { Data getKey(); boolean isLocked(); boolean isLockedBy(String owner, long threadId); String getOwner(); boolean isTransactional(); long getThreadId(); int getLockCount(); long getAcquireTime(); long getRemainingLeaseTime(); }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_lock_LockResource.java
2,401
final class BigIntArray extends AbstractBigArray implements IntArray { private int[][] pages; /** Constructor. */ public BigIntArray(long size, PageCacheRecycler recycler, boolean clearOnResize) { super(INT_PAGE_SIZE, recycler, clearOnResize); this.size = size; pages = new int[numPages(size)][]; for (int i = 0; i < pages.length; ++i) { pages[i] = newIntPage(i); } } @Override public int get(long index) { final int pageIndex = pageIndex(index); final int indexInPage = indexInPage(index); return pages[pageIndex][indexInPage]; } @Override public int set(long index, int value) { final int pageIndex = pageIndex(index); final int indexInPage = indexInPage(index); final int[] page = pages[pageIndex]; final int ret = page[indexInPage]; page[indexInPage] = value; return ret; } @Override public int increment(long index, int inc) { final int pageIndex = pageIndex(index); final int indexInPage = indexInPage(index); return pages[pageIndex][indexInPage] += inc; } @Override protected int numBytesPerElement() { return RamUsageEstimator.NUM_BYTES_INT; } /** Change the size of this array. Content between indexes <code>0</code> and <code>min(size(), newSize)</code> will be preserved. */ public void resize(long newSize) { final int numPages = numPages(newSize); if (numPages > pages.length) { pages = Arrays.copyOf(pages, ArrayUtil.oversize(numPages, RamUsageEstimator.NUM_BYTES_OBJECT_REF)); } for (int i = numPages - 1; i >= 0 && pages[i] == null; --i) { pages[i] = newIntPage(i); } for (int i = numPages; i < pages.length && pages[i] != null; ++i) { pages[i] = null; releasePage(i); } this.size = newSize; } }
0true
src_main_java_org_elasticsearch_common_util_BigIntArray.java
581
class ShardOptimizeResponse extends BroadcastShardOperationResponse { ShardOptimizeResponse() { } public ShardOptimizeResponse(String index, int shardId) { super(index, shardId); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_optimize_ShardOptimizeResponse.java
36
public class TitanGraphQueryTestSuite extends GraphQueryTestSuite { public TitanGraphQueryTestSuite(final GraphTest graphTest) { super(graphTest); } @Override public void testGraphQueryForVertices() { TitanGraph g = (TitanGraph) graphTest.generateGraph(); if (g.getRelationType("age") == null) { TitanManagement mgmt = g.getManagementSystem(); mgmt.makePropertyKey("age").dataType(Integer.class).cardinality(Cardinality.SINGLE).make(); mgmt.commit(); } g.shutdown(); super.testGraphQueryForVertices(); } @Override public void testGraphQueryForEdges() { TitanGraph g = (TitanGraph) graphTest.generateGraph(); if (g.getRelationType("weight") == null) { TitanManagement mgmt = g.getManagementSystem(); mgmt.makePropertyKey("weight").dataType(Double.class).cardinality(Cardinality.SINGLE).make(); mgmt.commit(); } g.shutdown(); super.testGraphQueryForEdges(); } }
0true
titan-test_src_main_java_com_thinkaurelius_titan_blueprints_TitanGraphQueryTestSuite.java
526
public class FlushRequestBuilder extends BroadcastOperationRequestBuilder<FlushRequest, FlushResponse, FlushRequestBuilder> { public FlushRequestBuilder(IndicesAdminClient indicesClient) { super((InternalIndicesAdminClient) indicesClient, new FlushRequest()); } public FlushRequestBuilder setFull(boolean full) { request.full(full); return this; } @Override protected void doExecute(ActionListener<FlushResponse> listener) { ((IndicesAdminClient) client).flush(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_flush_FlushRequestBuilder.java
3,638
public static class Names { public static final String LAT = "lat"; public static final String LAT_SUFFIX = "." + LAT; public static final String LON = "lon"; public static final String LON_SUFFIX = "." + LON; public static final String GEOHASH = "geohash"; public static final String GEOHASH_SUFFIX = "." + GEOHASH; }
0true
src_main_java_org_elasticsearch_index_mapper_geo_GeoPointFieldMapper.java
2,638
public class ClassDefinitionImpl extends BinaryClassDefinition implements ClassDefinition { private final List<FieldDefinition> fieldDefinitions = new ArrayList<FieldDefinition>(); private final Map<String, FieldDefinition> fieldDefinitionsMap = new HashMap<String, FieldDefinition>(); private final Set<ClassDefinition> nestedClassDefinitions = new HashSet<ClassDefinition>(); public ClassDefinitionImpl() { } public ClassDefinitionImpl(int factoryId, int classId) { this.factoryId = factoryId; this.classId = classId; } public void addFieldDef(FieldDefinition fd) { fieldDefinitions.add(fd); fieldDefinitionsMap.put(fd.getName(), fd); } public void addClassDef(ClassDefinition cd) { nestedClassDefinitions.add(cd); } public FieldDefinition get(String name) { return fieldDefinitionsMap.get(name); } public FieldDefinition get(int fieldIndex) { return fieldDefinitions.get(fieldIndex); } public Set<ClassDefinition> getNestedClassDefinitions() { return nestedClassDefinitions; } public boolean hasField(String fieldName) { return fieldDefinitionsMap.containsKey(fieldName); } public Set<String> getFieldNames() { return new HashSet<String>(fieldDefinitionsMap.keySet()); } public FieldType getFieldType(String fieldName) { final FieldDefinition fd = get(fieldName); if (fd != null) { return fd.getType(); } throw new IllegalArgumentException(); } public int getFieldClassId(String fieldName) { final FieldDefinition fd = get(fieldName); if (fd != null) { return fd.getClassId(); } throw new IllegalArgumentException(); } public void writeData(ObjectDataOutput out) throws IOException { out.writeInt(factoryId); out.writeInt(classId); out.writeInt(version); out.writeInt(fieldDefinitions.size()); for (FieldDefinition fieldDefinition : fieldDefinitions) { fieldDefinition.writeData(out); } out.writeInt(nestedClassDefinitions.size()); for (ClassDefinition classDefinition : nestedClassDefinitions) { classDefinition.writeData(out); } } public void readData(ObjectDataInput in) throws IOException { factoryId = in.readInt(); classId = in.readInt(); version = in.readInt(); int size = in.readInt(); for (int i = 0; i < size; i++) { FieldDefinitionImpl fieldDefinition = new FieldDefinitionImpl(); fieldDefinition.readData(in); addFieldDef(fieldDefinition); } size = in.readInt(); for (int i = 0; i < size; i++) { ClassDefinitionImpl classDefinition = new ClassDefinitionImpl(); classDefinition.readData(in); addClassDef(classDefinition); } } public int getFieldCount() { return fieldDefinitions.size(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClassDefinitionImpl that = (ClassDefinitionImpl) o; if (classId != that.classId) { return false; } if (version != that.version) { return false; } return true; } @Override public int hashCode() { int result = classId; result = 31 * result + version; return result; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("ClassDefinition"); sb.append("{factoryId=").append(factoryId); sb.append(", classId=").append(classId); sb.append(", version=").append(version); sb.append(", fieldDefinitions=").append(fieldDefinitions); sb.append('}'); return sb.toString(); } }
1no label
hazelcast_src_main_java_com_hazelcast_nio_serialization_ClassDefinitionImpl.java
1,399
@SuppressWarnings("unchecked") public class OMVRBTreeMapEntryProvider<K, V> extends OMVRBTreeEntryDataProviderAbstract<K, V> { /** * Current version of serialization format for single MVRBTree node. Versions have negative numbers for backward compatibility * with previous format that does not have version number, but first value in serialized content was non-negative integer. */ private static final int CURRENT_VERSION = -1; private static final OProfilerMBean PROFILER = Orient.instance().getProfiler(); private static final long serialVersionUID = 1L; protected K[] keys; protected V[] values; protected int[] serializedKeys; protected int[] serializedValues; private byte[] buffer; public OMVRBTreeMapEntryProvider(final OMVRBTreeMapProvider<K, V> iTreeDataProvider) { super(iTreeDataProvider, OMemoryStream.DEF_SIZE); keys = (K[]) new Object[pageSize]; values = (V[]) new Object[pageSize]; serializedKeys = new int[pageSize]; serializedValues = new int[pageSize]; } public OMVRBTreeMapEntryProvider(final OMVRBTreeMapProvider<K, V> iTreeDataProvider, final ORID iRID) { super(iTreeDataProvider, iRID); } public K getKeyAt(final int iIndex) { K k = keys[iIndex]; if (k == null) try { PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.unserializeKey"), "Deserialize a MVRBTree entry key", 1); k = (K) keyFromStream(iIndex); if (iIndex == 0 || iIndex == size || ((OMVRBTreeMapProvider<K, V>) treeDataProvider).keepKeysInMemory) // KEEP THE UNMARSHALLED KEY IN MEMORY. TO OPTIMIZE FIRST AND LAST ITEM ARE ALWAYS KEPT IN MEMORY TO SPEEDUP FREQUENT // NODE CHECKING OF BOUNDS keys[iIndex] = k; } catch (IOException e) { OLogManager.instance().error(this, "Cannot lazy load the key #" + iIndex + " in tree node " + this, e, OSerializationException.class); } return k; } public V getValueAt(final int iIndex) { V v = values[iIndex]; if (v == null) try { PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.unserializeValue"), "Deserialize a MVRBTree entry value", 1); v = (V) valueFromStream(iIndex); if (((OMVRBTreeMapProvider<K, V>) treeDataProvider).keepValuesInMemory) // KEEP THE UNMARSHALLED VALUE IN MEMORY values[iIndex] = v; } catch (IOException e) { OLogManager.instance().error(this, "Cannot lazy load the value #" + iIndex + " in tree node " + this, e, OSerializationException.class); } return v; } public boolean setValueAt(int iIndex, final V iValue) { values[iIndex] = iValue; serializedValues[iIndex] = 0; return setDirty(); } public boolean insertAt(final int iIndex, final K iKey, final V iValue) { if (iIndex < size) { // MOVE RIGHT TO MAKE ROOM FOR THE ITEM System.arraycopy(keys, iIndex, keys, iIndex + 1, size - iIndex); System.arraycopy(values, iIndex, values, iIndex + 1, size - iIndex); System.arraycopy(serializedKeys, iIndex, serializedKeys, iIndex + 1, size - iIndex); System.arraycopy(serializedValues, iIndex, serializedValues, iIndex + 1, size - iIndex); } keys[iIndex] = iKey; values[iIndex] = iValue; serializedKeys[iIndex] = 0; serializedValues[iIndex] = 0; size++; return setDirty(); } public boolean removeAt(final int iIndex) { if (iIndex == size - 1) { // LAST ONE: JUST REMOVE IT } else if (iIndex > -1) { // SHIFT LEFT THE VALUES System.arraycopy(keys, iIndex + 1, keys, iIndex, size - iIndex - 1); System.arraycopy(values, iIndex + 1, values, iIndex, size - iIndex - 1); System.arraycopy(serializedKeys, iIndex + 1, serializedKeys, iIndex, size - iIndex - 1); System.arraycopy(serializedValues, iIndex + 1, serializedValues, iIndex, size - iIndex - 1); } // FREE RESOURCES size--; serializedKeys[size] = 0; serializedValues[size] = 0; keys[size] = null; values[size] = null; return setDirty(); } /** * @TODO Optimize by copying only real data and not the entire source buffer. */ public boolean copyDataFrom(final OMVRBTreeEntryDataProvider<K, V> iFrom, final int iStartPosition) { final OMVRBTreeMapEntryProvider<K, V> parent = (OMVRBTreeMapEntryProvider<K, V>) iFrom; size = iFrom.getSize() - iStartPosition; System.arraycopy(parent.serializedKeys, iStartPosition, serializedKeys, 0, size); System.arraycopy(parent.serializedValues, iStartPosition, serializedValues, 0, size); System.arraycopy(parent.keys, iStartPosition, keys, 0, size); System.arraycopy(parent.values, iStartPosition, values, 0, size); if (buffer == null && parent.buffer == null) { stream = null; return setDirty(); } if (parent.buffer == null) { buffer = null; stream = null; return setDirty(); } if (buffer == null || buffer.length < parent.buffer.length) buffer = new byte[parent.buffer.length]; System.arraycopy(parent.buffer, 0, buffer, 0, parent.buffer.length); if (buffer == null) stream = null; else { if (stream != null) stream.setSource(buffer); else stream = new OMemoryStream(buffer); } return setDirty(); } public boolean truncate(final int iNewSize) { // TRUNCATE PARENT Arrays.fill(serializedKeys, iNewSize, pageSize, 0); Arrays.fill(serializedValues, iNewSize, pageSize, 0); Arrays.fill(keys, iNewSize, size, null); Arrays.fill(values, iNewSize, size, null); size = iNewSize; return setDirty(); } public boolean copyFrom(final OMVRBTreeEntryDataProvider<K, V> iSource) { final OMVRBTreeMapEntryProvider<K, V> source = (OMVRBTreeMapEntryProvider<K, V>) iSource; serializedKeys = new int[source.serializedKeys.length]; System.arraycopy(source.serializedKeys, 0, serializedKeys, 0, source.serializedKeys.length); serializedValues = new int[source.serializedValues.length]; System.arraycopy(source.serializedValues, 0, serializedValues, 0, source.serializedValues.length); keys = (K[]) new Object[source.keys.length]; System.arraycopy(source.keys, 0, keys, 0, source.keys.length); values = (V[]) new Object[source.values.length]; System.arraycopy(source.values, 0, values, 0, source.values.length); size = source.size; if (buffer == null && source.buffer == null) { stream = null; return setDirty(); } if (source.buffer == null) { buffer = null; stream = null; return setDirty(); } if (buffer == null || buffer.length < source.buffer.length) buffer = new byte[source.buffer.length]; System.arraycopy(source.buffer, 0, buffer, 0, source.buffer.length); if (buffer == null) stream = null; else { if (stream != null) stream.setSource(buffer); else stream = new OMemoryStream(buffer); } return setDirty(); } @Override public void delete() { super.delete(); // FORCE REMOVING OF K/V AND SEIALIZED K/V AS WELL keys = null; values = null; serializedKeys = null; serializedValues = null; } @Override public void clear() { super.clear(); buffer = null; keys = null; values = null; serializedKeys = null; serializedValues = null; } public OSerializableStream fromStream(byte[] iStream) throws OSerializationException { final long timer = PROFILER.startChrono(); try { // @COMPATIBILITY BEFORE 1.0 if (OIntegerSerializer.INSTANCE.deserialize(iStream, 0) >= 0) { OLogManager.instance().warn( this, "Previous version of serialization format was found for node with id " + record.getIdentity() + " conversion to new format will be performed." + " It will take some time. If this message is shown constantly please recreate indexes."); iStream = convertIntoNewSerializationFormat(iStream); OLogManager.instance().warn(this, "Conversion of data to new serialization format for node " + record.getIdentity() + " was finished. "); } if (((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer instanceof OBinarySerializer) fromStreamUsingBinarySerializer(iStream); else fromStreamUsingBinaryStreamSerializer(iStream); return this; } catch (IOException e) { throw new OSerializationException("Can not unmarshall tree node with id ", e); } finally { PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.entry.fromStream"), "Deserialize a MVRBTree entry", timer); } } public byte[] toStream() throws OSerializationException { final long timer = PROFILER.startChrono(); try { if (((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer instanceof OBinarySerializer) toStreamUsingBinarySerializer(); else toStreamUsingBinaryStreamSerializer(); record.fromStream(buffer); return buffer; } catch (IOException e) { throw new OSerializationException("Cannot marshall RB+Tree node", e); } finally { PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.entry.toStream"), "Serialize a MVRBTree entry", timer); } } private void toStreamUsingBinarySerializer() { int bufferSize = 2 * OIntegerSerializer.INT_SIZE; bufferSize += OLinkSerializer.INSTANCE.getObjectSize(parentRid) * 3; bufferSize += OBooleanSerializer.BOOLEAN_SIZE; bufferSize += OIntegerSerializer.INT_SIZE; for (int i = 0; i < size; ++i) bufferSize += getKeySize(i); for (int i = 0; i < size; ++i) bufferSize += getBinaryValueSize(i); byte[] outBuffer = new byte[bufferSize]; int offset = serializeMetadata(outBuffer, size, pageSize, parentRid, leftRid, rightRid, color); for (int i = 0; i < size; i++) { offset = serializeKey(outBuffer, offset, i); } for (int i = 0; i < size; i++) { offset = serializeBinaryValue(outBuffer, offset, i); } buffer = outBuffer; } private int serializeMetadata(byte[] newBuffer, int iSize, int iPageSize, ORID iParentId, ORID iLeftRid, ORID iRightRid, boolean iColor) { int offset = 0; OIntegerSerializer.INSTANCE.serialize(CURRENT_VERSION, newBuffer, offset); offset += OIntegerSerializer.INT_SIZE; OIntegerSerializer.INSTANCE.serialize(iPageSize, newBuffer, offset); offset += OIntegerSerializer.INT_SIZE; OLinkSerializer.INSTANCE.serialize(iParentId, newBuffer, offset); offset += OLinkSerializer.INSTANCE.getObjectSize(iParentId); OLinkSerializer.INSTANCE.serialize(iLeftRid, newBuffer, offset); offset += OLinkSerializer.INSTANCE.getObjectSize(iLeftRid); OLinkSerializer.INSTANCE.serialize(iRightRid, newBuffer, offset); offset += OLinkSerializer.INSTANCE.getObjectSize(iRightRid); OBooleanSerializer.INSTANCE.serialize(iColor, newBuffer, offset); offset += OBooleanSerializer.BOOLEAN_SIZE; OIntegerSerializer.INSTANCE.serialize(iSize, newBuffer, offset); offset += OIntegerSerializer.INT_SIZE; return offset; } private int deserializeMetadata(byte[] inBuffer) { int offset = 0; int currentVersion = OIntegerSerializer.INSTANCE.deserialize(inBuffer, offset); offset += OIntegerSerializer.INT_SIZE; if (currentVersion != CURRENT_VERSION) throw new OSerializationException("MVRBTree node is stored using " + currentVersion + " version of serialization format but current version is " + CURRENT_VERSION + "."); pageSize = OIntegerSerializer.INSTANCE.deserialize(inBuffer, offset); offset += OIntegerSerializer.INT_SIZE; parentRid = OLinkSerializer.INSTANCE.deserialize(inBuffer, offset); offset += OLinkSerializer.INSTANCE.getObjectSize(parentRid); leftRid = OLinkSerializer.INSTANCE.deserialize(inBuffer, offset); offset += OLinkSerializer.INSTANCE.getObjectSize(leftRid); rightRid = OLinkSerializer.INSTANCE.deserialize(inBuffer, offset); offset += OLinkSerializer.INSTANCE.getObjectSize(rightRid); color = OBooleanSerializer.INSTANCE.deserialize(inBuffer, offset); offset += OBooleanSerializer.BOOLEAN_SIZE; size = OIntegerSerializer.INSTANCE.deserialize(inBuffer, offset); offset += OIntegerSerializer.INT_SIZE; if (size > pageSize) throw new OConfigurationException("Loaded index with page size set to " + pageSize + " while the loaded was built with: " + size); return offset; } private int serializeBinaryValue(byte[] newBuffer, int offset, int i) { final OBinarySerializer<V> valueSerializer = (OBinarySerializer<V>) ((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer; if (serializedValues[i] <= 0) { PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.serializeValue"), "Serialize a MVRBTree entry value", 1); valueSerializer.serialize(values[i], newBuffer, offset); offset += valueSerializer.getObjectSize(values[i]); } else { final int size = valueSerializer.getObjectSize(buffer, serializedValues[i]); System.arraycopy(buffer, serializedValues[i], newBuffer, offset, size); serializedValues[i] = offset; offset += size; } return offset; } private int serializeKey(byte[] newBuffer, int offset, int i) { final OBinarySerializer<K> keySerializer = ((OMVRBTreeMapProvider<K, V>) treeDataProvider).keySerializer; if (serializedKeys[i] <= 0) { PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.serializeKey"), "Serialize a MVRBTree entry key", 1); keySerializer.serialize(keys[i], newBuffer, offset); offset += keySerializer.getObjectSize(keys[i]); } else { final int size = keySerializer.getObjectSize(buffer, serializedKeys[i]); System.arraycopy(buffer, serializedKeys[i], newBuffer, offset, size); serializedKeys[i] = offset; offset += size; } return offset; } private int getKeySize(final int iIndex) { final OBinarySerializer<K> serializer = ((OMVRBTreeMapProvider<K, V>) treeDataProvider).keySerializer; if (serializedKeys[iIndex] <= 0) return serializer.getObjectSize(keys[iIndex]); return serializer.getObjectSize(buffer, serializedKeys[iIndex]); } private int getBinaryValueSize(final int iIndex) { final OBinarySerializer<V> serializer = (OBinarySerializer<V>) ((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer; if (serializedValues[iIndex] <= 0) return serializer.getObjectSize(values[iIndex]); return serializer.getObjectSize(buffer, serializedValues[iIndex]); } private void toStreamUsingBinaryStreamSerializer() throws IOException { int bufferSize = 2 * OIntegerSerializer.INT_SIZE; bufferSize += OLinkSerializer.INSTANCE.getObjectSize(parentRid) * 3; bufferSize += OBooleanSerializer.BOOLEAN_SIZE; bufferSize += OIntegerSerializer.INT_SIZE; for (int i = 0; i < size; ++i) bufferSize += getKeySize(i); final byte[] outBuffer = new byte[bufferSize * 2]; int offset = serializeMetadata(outBuffer, size, pageSize, parentRid, leftRid, rightRid, color); for (int i = 0; i < size; i++) { offset = serializeKey(outBuffer, offset, i); } final OMemoryStream outStream = new OMemoryStream(outBuffer); try { outStream.jump(offset); for (int i = 0; i < size; ++i) serializedValues[i] = outStream.set(serializeStreamValue(i)); buffer = outStream.toByteArray(); } finally { outStream.close(); } if (stream == null) stream = new OMemoryStream(buffer); else stream.setSource(buffer); } private void fromStreamUsingBinarySerializer(final byte[] inBuffer) { int offset = deserializeMetadata(inBuffer); serializedKeys = new int[pageSize]; keys = (K[]) new Object[pageSize]; final OBinarySerializer<K> keySerializer = ((OMVRBTreeMapProvider<K, V>) treeDataProvider).keySerializer; if (keySerializer == null) throw new IllegalStateException("key serializer wasn't found"); for (int i = 0; i < size; i++) { serializedKeys[i] = offset; offset += keySerializer.getObjectSize(inBuffer, offset); } serializedValues = new int[pageSize]; values = (V[]) new Object[pageSize]; final OBinarySerializer<V> valueSerializer = (OBinarySerializer<V>) ((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer; if (valueSerializer == null) throw new IllegalStateException("value serializer wasn't found"); for (int i = 0; i < size; i++) { serializedValues[i] = offset; offset += valueSerializer.getObjectSize(inBuffer, offset); } buffer = inBuffer; } private void fromStreamUsingBinaryStreamSerializer(final byte[] inBuffer) { int offset = deserializeMetadata(inBuffer); serializedKeys = new int[pageSize]; keys = (K[]) new Object[pageSize]; final OBinarySerializer<K> keySerializer = ((OMVRBTreeMapProvider<K, V>) treeDataProvider).keySerializer; for (int i = 0; i < size; i++) { serializedKeys[i] = offset; offset += keySerializer.getObjectSize(inBuffer, offset); } serializedValues = new int[pageSize]; values = (V[]) new Object[pageSize]; if (stream == null) stream = new OMemoryStream(inBuffer); else stream.setSource(inBuffer); stream.jump(offset); for (int i = 0; i < size; i++) { serializedValues[i] = stream.getAsByteArrayOffset(); } buffer = inBuffer; } /** * Serialize only the new values or the changed. * */ protected byte[] serializeStreamValue(final int iIndex) throws IOException { if (serializedValues[iIndex] <= 0) { // NEW OR MODIFIED: MARSHALL CONTENT PROFILER.updateCounter(PROFILER.getProcessMetric("mvrbtree.entry.serializeValue"), "Serialize a MVRBTree entry value", 1); return ((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer.toStream(values[iIndex]); } // RETURN ORIGINAL CONTENT return stream.getAsByteArray(serializedValues[iIndex]); } protected Object keyFromStream(final int iIndex) throws IOException { return ((OMVRBTreeMapProvider<K, V>) treeDataProvider).keySerializer.deserialize(buffer, serializedKeys[iIndex]); } protected Object valueFromStream(final int iIndex) throws IOException { final OStreamSerializer valueSerializer = ((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer; if (valueSerializer instanceof OBinarySerializer) return ((OBinarySerializer<V>) valueSerializer).deserialize(buffer, serializedValues[iIndex]); return valueSerializer.fromStream(stream.getAsByteArray(serializedValues[iIndex])); } private byte[] convertIntoNewSerializationFormat(byte[] stream) throws IOException { final OMemoryStream oldStream = new OMemoryStream(stream); try { int oldPageSize = oldStream.getAsInteger(); ORecordId oldParentRid = new ORecordId().fromStream(oldStream.getAsByteArrayFixed(ORecordId.PERSISTENT_SIZE)); ORecordId oldLeftRid = new ORecordId().fromStream(oldStream.getAsByteArrayFixed(ORecordId.PERSISTENT_SIZE)); ORecordId oldRightRid = new ORecordId().fromStream(oldStream.getAsByteArrayFixed(ORecordId.PERSISTENT_SIZE)); boolean oldColor = oldStream.getAsBoolean(); int oldSize = oldStream.getAsInteger(); if (oldSize > oldPageSize) throw new OConfigurationException("Loaded index with page size set to " + oldPageSize + " while the loaded was built with: " + oldSize); K[] oldKeys = (K[]) new Object[oldPageSize]; for (int i = 0; i < oldSize; ++i) { oldKeys[i] = (K) ((OMVRBTreeMapProvider<K, V>) treeDataProvider).streamKeySerializer.fromStream(oldStream.getAsByteArray()); } V[] oldValues = (V[]) new Object[oldPageSize]; for (int i = 0; i < oldSize; ++i) { oldValues[i] = (V) ((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer.fromStream(oldStream.getAsByteArray()); } byte[] result; if (((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer instanceof OBinarySerializer) result = convertNewSerializationFormatBinarySerializer(oldSize, oldPageSize, oldParentRid, oldLeftRid, oldRightRid, oldColor, oldKeys, oldValues); else result = convertNewSerializationFormatStreamSerializer(oldSize, oldPageSize, oldParentRid, oldLeftRid, oldRightRid, oldColor, oldKeys, oldValues); return result; } finally { oldStream.close(); } } private byte[] convertNewSerializationFormatBinarySerializer(int oldSize, int oldPageSize, ORecordId oldParentRid, ORecordId oldLeftRid, ORecordId oldRightRid, boolean oldColor, K[] oldKeys, V[] oldValues) { int bufferSize = 2 * OIntegerSerializer.INT_SIZE; bufferSize += OLinkSerializer.INSTANCE.getObjectSize(oldParentRid) * 3; bufferSize += OBooleanSerializer.BOOLEAN_SIZE; bufferSize += OIntegerSerializer.INT_SIZE; final OBinarySerializer<K> keySerializer = ((OMVRBTreeMapProvider<K, V>) treeDataProvider).keySerializer; final OBinarySerializer<V> valueSerializer = (OBinarySerializer<V>) ((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer; for (int i = 0; i < oldSize; ++i) bufferSize += keySerializer.getObjectSize(oldKeys[i]); for (int i = 0; i < oldSize; ++i) bufferSize += valueSerializer.getObjectSize(oldValues[i]); byte[] outBuffer = new byte[bufferSize]; int offset = serializeMetadata(outBuffer, oldSize, oldPageSize, oldParentRid, oldLeftRid, oldRightRid, oldColor); for (int i = 0; i < oldSize; i++) { keySerializer.serialize(oldKeys[i], outBuffer, offset); offset += keySerializer.getObjectSize(oldKeys[i]); } for (int i = 0; i < oldSize; i++) { valueSerializer.serialize(oldValues[i], outBuffer, offset); offset += valueSerializer.getObjectSize(oldValues[i]); } return outBuffer; } private byte[] convertNewSerializationFormatStreamSerializer(int oldSize, int oldPageSize, ORecordId oldParentRid, ORecordId oldLeftRid, ORecordId oldRightRid, boolean oldColor, K[] oldKeys, V[] oldValues) throws IOException { int bufferSize = 2 * OIntegerSerializer.INT_SIZE; bufferSize += OLinkSerializer.INSTANCE.getObjectSize(oldParentRid) * 3; bufferSize += OBooleanSerializer.BOOLEAN_SIZE; bufferSize += OIntegerSerializer.INT_SIZE; final OBinarySerializer<K> keySerializer = ((OMVRBTreeMapProvider<K, V>) treeDataProvider).keySerializer; final OStreamSerializer valueSerializer = ((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer; for (int i = 0; i < oldSize; ++i) bufferSize += keySerializer.getObjectSize(oldKeys[i]); final byte[] outBuffer = new byte[bufferSize * 2]; int offset = serializeMetadata(outBuffer, oldSize, oldPageSize, oldParentRid, oldLeftRid, oldRightRid, oldColor); for (int i = 0; i < oldSize; i++) { keySerializer.serialize(oldKeys[i], outBuffer, offset); offset += keySerializer.getObjectSize(oldKeys[i]); } final OMemoryStream outStream = new OMemoryStream(outBuffer); try { outStream.jump(offset); for (int i = 0; i < oldSize; ++i) outStream.set(valueSerializer.toStream(oldValues[i])); return outStream.toByteArray(); } finally { outStream.close(); } } }
0true
core_src_main_java_com_orientechnologies_orient_core_type_tree_provider_OMVRBTreeMapEntryProvider.java
3,235
list = new SlicedObjectList<String>(values.isMultiValued() ? new String[10] : new String[1]) { @Override public void grow(int newLength) { assert offset == 0; // NOTE: senseless if offset != 0 if (values.length >= newLength) { return; } final String[] current = values; values = new String[ArrayUtil.oversize(newLength, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; System.arraycopy(current, 0, values, 0, current.length); } };
0true
src_main_java_org_elasticsearch_index_fielddata_ScriptDocValues.java
1,939
static class DelegatingInvocationHandler<T> implements InvocationHandler { T delegate; public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (delegate == null) { throw new IllegalStateException("This is a proxy used to support" + " circular references involving constructors. The object we're" + " proxying is not constructed yet. Please wait until after" + " injection has completed to use this object."); } try { // This appears to be not test-covered return method.invoke(delegate, args); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw e.getTargetException(); } } void setDelegate(T delegate) { this.delegate = delegate; } }
0true
src_main_java_org_elasticsearch_common_inject_internal_ConstructionContext.java
1,623
public class OAutomaticBackup extends OServerPluginAbstract { public enum VARIABLES { DBNAME, DATE } private Date firstTime = null; private long delay = -1; private String targetDirectory = "backup"; private String targetFileName; private Set<String> includeDatabases = new HashSet<String>(); private Set<String> excludeDatabases = new HashSet<String>(); private OServer serverInstance; @Override public void config(final OServer iServer, final OServerParameterConfiguration[] iParams) { serverInstance = iServer; for (OServerParameterConfiguration param : iParams) { if (param.name.equalsIgnoreCase("enabled")) { if (!Boolean.parseBoolean(param.value)) // DISABLE IT return; } else if (param.name.equalsIgnoreCase("delay")) delay = OIOUtils.getTimeAsMillisecs(param.value); else if (param.name.equalsIgnoreCase("firsttime")) { try { firstTime = OIOUtils.getTodayWithTime(param.value); } catch (ParseException e) { throw new OConfigurationException("Parameter 'firstTime' has invalid format, expected: HH:mm:ss", e); } } else if (param.name.equalsIgnoreCase("target.directory")) targetDirectory = param.value; else if (param.name.equalsIgnoreCase("db.include") && param.value.trim().length() > 0) for (String db : param.value.split(",")) includeDatabases.add(db); else if (param.name.equalsIgnoreCase("db.exclude") && param.value.trim().length() > 0) for (String db : param.value.split(",")) excludeDatabases.add(db); else if (param.name.equalsIgnoreCase("target.fileName")) targetFileName = param.value; } if (delay <= 0) throw new OConfigurationException("Cannot find mandatory parameter 'delay'"); if (!targetDirectory.endsWith("/")) targetDirectory += "/"; final File filePath = new File(targetDirectory); if (filePath.exists()) { if (!filePath.isDirectory()) throw new OConfigurationException("Parameter 'path' points to a file, not a directory"); } else // CREATE BACKUP FOLDER(S) IF ANY filePath.mkdirs(); OLogManager.instance().info(this, "Automatic backup plugin installed and active: delay=%dms, firstTime=%s, targetDirectory=%s", delay, firstTime, targetDirectory); final TimerTask timerTask = new TimerTask() { @Override public void run() { OLogManager.instance().info(this, "[OAutomaticBackup] Scanning databases to backup..."); int ok = 0, errors = 0; final Map<String, String> databaseNames = serverInstance.getAvailableStorageNames(); for (final Entry<String, String> dbName : databaseNames.entrySet()) { boolean include; if (includeDatabases.size() > 0) include = includeDatabases.contains(dbName.getKey()); else include = true; if (excludeDatabases.contains(dbName.getKey())) include = false; if (include) { final String fileName = (String) OVariableParser.resolveVariables(targetFileName, OSystemVariableResolver.VAR_BEGIN, OSystemVariableResolver.VAR_END, new OVariableParserListener() { @Override public String resolve(final String iVariable) { if (iVariable.equalsIgnoreCase(VARIABLES.DBNAME.toString())) return dbName.getKey(); else if (iVariable.startsWith(VARIABLES.DATE.toString())) { return new SimpleDateFormat(iVariable.substring(VARIABLES.DATE.toString().length() + 1)).format(new Date()); } // NOT FOUND throw new IllegalArgumentException("Variable '" + iVariable + "' wasn't found"); } }); final String exportFilePath = targetDirectory + fileName; ODatabaseDocumentTx db = null; try { db = new ODatabaseDocumentTx(dbName.getValue()); db.setProperty(ODatabase.OPTIONS.SECURITY.toString(), Boolean.FALSE); db.open("admin", "aaa"); final long begin = System.currentTimeMillis(); db.backup(new FileOutputStream(exportFilePath), null, null); OLogManager.instance().info( this, "[OAutomaticBackup] - Backup of database '" + dbName.getValue() + "' completed in " + (System.currentTimeMillis() - begin) + "ms"); ok++; } catch (Exception e) { OLogManager.instance().error(this, "[OAutomaticBackup] - Error on exporting database '" + dbName.getValue() + "' to file: " + exportFilePath, e); errors++; } finally { if (db != null) db.close(); } } } OLogManager.instance().info(this, "[OAutomaticBackup] Backup finished: %d ok, %d errors", ok, errors); } }; if (firstTime == null) Orient.instance().getTimer().schedule(timerTask, delay, delay); else Orient.instance().getTimer().schedule(timerTask, firstTime, delay); } @Override public String getName() { return "automaticBackup"; } }
0true
server_src_main_java_com_orientechnologies_orient_server_handler_OAutomaticBackup.java
797
public interface CandidateOffer extends Serializable { public Long getId(); public void setId(Long id); public Offer getOffer(); public void setOffer(Offer offer); public int getPriority(); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_CandidateOffer.java
2,982
static class EntriesStats { public final long sizeInBytes; public final long count; public EntriesStats(long sizeInBytes, long count) { this.sizeInBytes = sizeInBytes; this.count = count; } }
0true
src_main_java_org_elasticsearch_index_cache_filter_FilterCache.java
1,133
public interface ClientService { /** * Returns all connected clients to this member. * * @return all connected clients to this member. */ Collection<Client> getConnectedClients(); /** * @param clientListener ClientListener * * @return returns registration id. */ String addClientListener(ClientListener clientListener); /** * @param registrationId Id of listener registration. * * @return true if registration is removed, false otherwise */ boolean removeClientListener(String registrationId); }
0true
hazelcast_src_main_java_com_hazelcast_core_ClientService.java
595
public class ContainerShapeType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, ContainerShapeType> TYPES = new LinkedHashMap<String, ContainerShapeType>(); public static ContainerShapeType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public ContainerShapeType() { //do nothing } public ContainerShapeType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } else { throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName()); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ContainerShapeType other = (ContainerShapeType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
common_src_main_java_org_broadleafcommerce_common_vendor_service_type_ContainerShapeType.java
32
public class StateMachines implements MessageProcessor, MessageSource { private final Logger logger = LoggerFactory.getLogger( StateMachines.class ); private final MessageSender sender; private DelayedDirectExecutor executor; private Executor stateMachineExecutor; private Timeouts timeouts; private final Map<Class<? extends MessageType>, StateMachine> stateMachines = new LinkedHashMap<Class<? extends MessageType>, StateMachine>(); private final List<MessageProcessor> outgoingProcessors = new ArrayList<MessageProcessor>(); private final OutgoingMessageHolder outgoing; // This is used to ensure fairness of message delivery private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock( true ); private final String instanceIdHeaderValue; public StateMachines( MessageSource source, final MessageSender sender, Timeouts timeouts, DelayedDirectExecutor executor, Executor stateMachineExecutor, InstanceId instanceId ) { this.sender = sender; this.executor = executor; this.stateMachineExecutor = stateMachineExecutor; this.timeouts = timeouts; this.instanceIdHeaderValue = instanceId.toString(); outgoing = new OutgoingMessageHolder(); timeouts.addMessageProcessor( this ); source.addMessageProcessor( this ); } public Timeouts getTimeouts() { return timeouts; } public synchronized void addStateMachine( StateMachine stateMachine ) { stateMachines.put( stateMachine.getMessageType(), stateMachine ); } public synchronized void removeStateMachine( StateMachine stateMachine ) { stateMachines.remove( stateMachine.getMessageType() ); } public Iterable<StateMachine> getStateMachines() { return stateMachines.values(); } @Override public void addMessageProcessor( MessageProcessor messageProcessor ) { outgoingProcessors.add( messageProcessor ); } public OutgoingMessageHolder getOutgoing() { return outgoing; } @Override public boolean process( final Message<? extends MessageType> message ) { stateMachineExecutor.execute( new Runnable() { OutgoingMessageHolder temporaryOutgoing = new OutgoingMessageHolder(); @Override public void run() { lock.writeLock().lock(); try { // Lock timeouts while we are processing the message synchronized ( timeouts ) { StateMachine stateMachine = stateMachines.get( message.getMessageType().getClass() ); if ( stateMachine == null ) { return; // No StateMachine registered for this MessageType type - Ignore this } stateMachine.handle( message, temporaryOutgoing ); Message<? extends MessageType> tempMessage; while ((tempMessage = temporaryOutgoing.nextOutgoingMessage()) != null) { outgoing.offer( tempMessage ); } // Process and send messages // Allow state machines to send messages to each other as well in this loop Message<? extends MessageType> outgoingMessage; List<Message<? extends MessageType>> toSend = new LinkedList<Message<? extends MessageType>>(); try { while ( ( outgoingMessage = outgoing.nextOutgoingMessage() ) != null ) { message.copyHeadersTo( outgoingMessage, CONVERSATION_ID, CREATED_BY ); for ( MessageProcessor outgoingProcessor : outgoingProcessors ) { try { if ( !outgoingProcessor.process( outgoingMessage ) ) { break; } } catch ( Throwable e ) { logger.warn( "Outgoing message processor threw exception", e ); } } if ( outgoingMessage.hasHeader( Message.TO ) ) { outgoingMessage.setHeader( Message.INSTANCE_ID, instanceIdHeaderValue ); toSend.add( outgoingMessage ); } else { // Deliver internally if possible StateMachine internalStatemachine = stateMachines.get( outgoingMessage.getMessageType() .getClass() ); if ( internalStatemachine != null ) { internalStatemachine.handle( (Message) outgoingMessage, temporaryOutgoing ); while ((tempMessage = temporaryOutgoing.nextOutgoingMessage()) != null) { outgoing.offer( tempMessage ); } } } } if ( !toSend.isEmpty() ) // the check is necessary, sender may not have started yet { sender.process( toSend ); } } catch ( Exception e ) { logger.warn( "Error processing message " + message, e ); } } } finally { lock.writeLock().unlock(); } // Before returning, process delayed executions so that they are done before returning // This will effectively trigger all notifications created by contexts executor.drain(); } } ); return true; } public void addStateTransitionListener( StateTransitionListener stateTransitionListener ) { for ( StateMachine stateMachine : stateMachines.values() ) { stateMachine.addStateTransitionListener( stateTransitionListener ); } } public void removeStateTransitionListener( StateTransitionListener stateTransitionListener ) { for ( StateMachine stateMachine : stateMachines.values() ) { stateMachine.removeStateTransitionListener( stateTransitionListener ); } } @Override public String toString() { List<String> states = new ArrayList<String>(); for ( StateMachine stateMachine : stateMachines.values() ) { states.add( stateMachine.getState().getClass().getSuperclass().getSimpleName() + ":" + stateMachine .getState().toString() ); } return states.toString(); } public StateMachine getStateMachine( Class<? extends MessageType> messageType ) { return stateMachines.get( messageType ); } private class OutgoingMessageHolder implements MessageHolder { private Deque<Message<? extends MessageType>> outgoingMessages = new ArrayDeque<Message<? extends MessageType>>(); @Override public synchronized void offer( Message<? extends MessageType> message ) { outgoingMessages.addFirst( message ); } public synchronized Message<? extends MessageType> nextOutgoingMessage() { return outgoingMessages.pollFirst(); } } }
1no label
enterprise_cluster_src_main_java_org_neo4j_cluster_StateMachines.java
126
class FixMultilineStringIndentationProposal extends CorrectionProposal { public static void addFixMultilineStringIndentation( Collection<ICompletionProposal> proposals, IFile file, Tree.CompilationUnit cu, Node node) { if (node instanceof Tree.StringLiteral) { TextFileChange change = new TextFileChange("Fix Multiline String", file); IDocument doc = EditorUtil.getDocument(change); Tree.StringLiteral literal = (Tree.StringLiteral) node; int offset = literal.getStartIndex(); int length = literal.getStopIndex() - literal.getStartIndex() + 1; Token token = literal.getToken(); int indentation = token.getCharPositionInLine() + getStartQuoteLength(token.getType()); String text = getFixedText(token.getText(), indentation, doc); if (text!=null) { change.setEdit(new ReplaceEdit(offset, length, text)); FixMultilineStringIndentationProposal proposal = new FixMultilineStringIndentationProposal(change); if (!proposals.contains(proposal)) { proposals.add(proposal); } } } } private static String getFixedText(String text, int indentation, IDocument doc) { StringBuilder result = new StringBuilder(); for (String line: text.split("\n|\r\n?")) { if (result.length() == 0) { //the first line of the string result.append(line); } else { for (int i = 0; i<indentation; i++) { //fix the indentation result.append(" "); if (line.startsWith(" ")) { line = line.substring(1); } } //the non-whitespace content result.append(line); } result.append(Indents.getDefaultLineDelimiter(doc)); } result.setLength(result.length()-1); return result.toString(); } private static int getStartQuoteLength(int type) { int startQuoteLength = -1; if (type == STRING_LITERAL || type== ASTRING_LITERAL || type == STRING_START) { startQuoteLength = 1; } else if (type == STRING_MID || type == STRING_END) { startQuoteLength = 2; } else if (type == VERBATIM_STRING || type == AVERBATIM_STRING) { startQuoteLength = 3; } return startQuoteLength; } private FixMultilineStringIndentationProposal(TextFileChange change) { super("Fix multiline string indentation", change, null); } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ChangeMultilineStringIndentionProposal.java
1,225
public class ShippingRateDataProvider { @DataProvider(name = "basicShippingRates") public static Object[][] provideBasicShippingRates(){ ShippingRateImpl sr = new ShippingRateImpl(); sr.setFeeType("SHIPPING"); sr.setFeeSubType("ALL"); sr.setFeeBand(1); sr.setBandUnitQuantity(BigDecimal.valueOf(29.99)); sr.setBandResultQuantity(BigDecimal.valueOf(8.5)); sr.setBandResultPercent(0); ShippingRateImpl sr2 = new ShippingRateImpl(); sr2.setFeeType("SHIPPING"); sr2.setFeeSubType("ALL"); sr2.setFeeBand(2); sr2.setBandUnitQuantity(BigDecimal.valueOf(999999.99)); sr2.setBandResultQuantity(BigDecimal.valueOf(8.5)); sr2.setBandResultPercent(0); return new Object[][] {{sr, sr2}}; } }
0true
integration_src_test_java_org_broadleafcommerce_core_pricing_ShippingRateDataProvider.java
22
public interface Fun<A,T> { T apply(A a); }
0true
src_main_java_jsr166e_CompletableFuture.java
1,588
class ApplySettings implements NodeSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { ImmutableMap<String, String> requireMap = settings.getByPrefix(CLUSTER_ROUTING_REQUIRE_GROUP).getAsMap(); if (!requireMap.isEmpty()) { clusterRequireFilters = DiscoveryNodeFilters.buildFromKeyValue(AND, requireMap); } ImmutableMap<String, String> includeMap = settings.getByPrefix(CLUSTER_ROUTING_INCLUDE_GROUP).getAsMap(); if (!includeMap.isEmpty()) { clusterIncludeFilters = DiscoveryNodeFilters.buildFromKeyValue(OR, includeMap); } ImmutableMap<String, String> excludeMap = settings.getByPrefix(CLUSTER_ROUTING_EXCLUDE_GROUP).getAsMap(); if (!excludeMap.isEmpty()) { clusterExcludeFilters = DiscoveryNodeFilters.buildFromKeyValue(OR, excludeMap); } } }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_decider_FilterAllocationDecider.java
265
public class ElasticsearchException extends RuntimeException { /** * Construct a <code>ElasticsearchException</code> with the specified detail message. * * @param msg the detail message */ public ElasticsearchException(String msg) { super(msg); } /** * Construct a <code>ElasticsearchException</code> with the specified detail message * and nested exception. * * @param msg the detail message * @param cause the nested exception */ public ElasticsearchException(String msg, Throwable cause) { super(msg, cause); } /** * Returns the rest status code associated with this exception. */ public RestStatus status() { Throwable cause = unwrapCause(); if (cause == this) { return RestStatus.INTERNAL_SERVER_ERROR; } else if (cause instanceof ElasticsearchException) { return ((ElasticsearchException) cause).status(); } else if (cause instanceof IllegalArgumentException) { return RestStatus.BAD_REQUEST; } else { return RestStatus.INTERNAL_SERVER_ERROR; } } /** * Unwraps the actual cause from the exception for cases when the exception is a * {@link ElasticsearchWrapperException}. * * @see org.elasticsearch.ExceptionsHelper#unwrapCause(Throwable) */ public Throwable unwrapCause() { return ExceptionsHelper.unwrapCause(this); } /** * Return the detail message, including the message from the nested exception * if there is one. */ public String getDetailedMessage() { if (getCause() != null) { StringBuilder sb = new StringBuilder(); sb.append(toString()).append("; "); if (getCause() instanceof ElasticsearchException) { sb.append(((ElasticsearchException) getCause()).getDetailedMessage()); } else { sb.append(getCause()); } return sb.toString(); } else { return super.toString(); } } /** * Retrieve the innermost cause of this exception, if none, returns the current exception. */ public Throwable getRootCause() { Throwable rootCause = this; Throwable cause = getCause(); while (cause != null && cause != rootCause) { rootCause = cause; cause = cause.getCause(); } return rootCause; } /** * Retrieve the most specific cause of this exception, that is, * either the innermost cause (root cause) or this exception itself. * <p>Differs from {@link #getRootCause()} in that it falls back * to the present exception if there is no root cause. * * @return the most specific cause (never <code>null</code>) */ public Throwable getMostSpecificCause() { Throwable rootCause = getRootCause(); return (rootCause != null ? rootCause : this); } /** * Check whether this exception contains an exception of the given type: * either it is of the given class itself or it contains a nested cause * of the given type. * * @param exType the exception type to look for * @return whether there is a nested exception of the specified type */ public boolean contains(Class exType) { if (exType == null) { return false; } if (exType.isInstance(this)) { return true; } Throwable cause = getCause(); if (cause == this) { return false; } if (cause instanceof ElasticsearchException) { return ((ElasticsearchException) cause).contains(exType); } else { while (cause != null) { if (exType.isInstance(cause)) { return true; } if (cause.getCause() == cause) { break; } cause = cause.getCause(); } return false; } } }
0true
src_main_java_org_elasticsearch_ElasticsearchException.java
1,134
public class CartOperationProcessContextFactory implements ProcessContextFactory { /** * Creates the necessary context for cart operations */ public ProcessContext createContext(Object seedData) throws WorkflowException { if (!(seedData instanceof CartOperationRequest)){ throw new WorkflowException("Seed data instance is incorrect. " + "Required class is " + CartOperationRequest.class.getName() + " " + "but found class: " + seedData.getClass().getName()); } CartOperationContext context = new CartOperationContext(); context.setSeedData(seedData); return context; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_workflow_CartOperationProcessContextFactory.java
2,043
public interface LinkedKeyBinding<T> extends Binding<T> { /** * Returns the linked key used to resolve injections. That binding can be retrieved from an * injector using {@link org.elasticsearch.common.inject.Injector#getBinding(Key) Injector.getBinding(key)}. */ Key<? extends T> getLinkedKey(); }
0true
src_main_java_org_elasticsearch_common_inject_spi_LinkedKeyBinding.java
2,047
public interface PrivateElements extends Element { /** * Returns the configuration information in this private environment. */ List<Element> getElements(); /** * Returns the child injector that hosts these private elements, or null if the elements haven't * been used to create an injector. */ Injector getInjector(); /** * Returns the unique exposed keys for these private elements. */ Set<Key<?>> getExposedKeys(); /** * Returns an arbitrary object containing information about the "place" where this key was * exposed. Used by Guice in the production of descriptive error messages. * <p/> * <p>Tools might specially handle types they know about; {@code StackTraceElement} is a good * example. Tools should simply call {@code toString()} on the source object if the type is * unfamiliar. * * @param key one of the keys exposed by this module. */ Object getExposedSource(Key<?> key); }
0true
src_main_java_org_elasticsearch_common_inject_spi_PrivateElements.java
2,112
future.andThen(new ExecutionCallback<Data>() { @Override public void onResponse(Data response) { if (nearCacheEnabled) { int partitionId = nodeEngine.getPartitionService().getPartitionId(key); if (!nodeEngine.getPartitionService().getPartitionOwner(partitionId) .equals(nodeEngine.getClusterService().getThisAddress()) || mapConfig.getNearCacheConfig().isCacheLocalEntries()) { mapService.putNearCache(name, key, response); } } } @Override public void onFailure(Throwable t) { } });
1no label
hazelcast_src_main_java_com_hazelcast_map_proxy_MapProxySupport.java
17
public interface DataBufferEnv { public int getNumOfBufferPartitions(); public int getCurrentBufferPartition(); public long getBufferTime(); public long getBufferPartitionOverlap(); public int previousBufferPartition(int currentPartition); public int getConcurrencyDegree(); public int getBufferWriteThreadPoolSize(); public void closeAndRestartEnvironment(); public void restartEnvironment(boolean isReadOnly); public int nextBufferPartition(); public DataBufferEnv advanceBufferPartition(); public Object clone(); public Object cloneMetaBuffer(); public Properties getConfigProperties(); public LOS getLOS(); public void flush(); }
0true
timeSequenceFeedAggregator_src_main_java_gov_nasa_arc_mct_buffer_config_DataBufferEnv.java
116
public interface Gather<S,M> { /** * Gathers the adjacent vertex's state and the connecting edge's properties into a single object * to be combined by a corresponding {@link Combiner} as configured in {@link OLAPQueryBuilder#edges(Gather, Combiner)}. * * @param state State of the adjacent vertex * @param edge Edge connecting to the adjacent vertex * @param dir Direction of the edge from the perspective of the current/central vertex * @return An object of type M which gathers the state and edge properties */ public M apply(S state, TitanEdge edge, Direction dir); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_olap_Gather.java
450
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) { changed.value = true; } });
0true
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedSetTest.java
491
client.getClientExecutionService().executeInternal(new Runnable() { @Override public void run() { for (MembershipListener listener : listeners.values()) { listener.memberAttributeChanged(event); } } });
1no label
hazelcast-client_src_main_java_com_hazelcast_client_spi_impl_ClientClusterServiceImpl.java
669
sbTree.loadEntriesMinor(toKey, isInclusive, new OTreeInternal.RangeResultListener<Object, V>() { @Override public boolean addResult(Map.Entry<Object, V> entry) { final Object key = entry.getKey(); final V value = entry.getValue(); return addToEntriesResult(transformer, entriesResultListener, key, value); } });
0true
core_src_main_java_com_orientechnologies_orient_core_index_engine_OSBTreeIndexEngine.java
441
public class KCVMutation extends Mutation<Entry,StaticBuffer> { public KCVMutation(List<Entry> additions, List<StaticBuffer> deletions) { super(additions, deletions); } @Override public void consolidate() { super.consolidate(KCVEntryMutation.ENTRY2COLUMN_FCT, Functions.<StaticBuffer>identity()); } @Override public boolean isConsolidated() { return super.isConsolidated(KCVEntryMutation.ENTRY2COLUMN_FCT, Functions.<StaticBuffer>identity()); } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_KCVMutation.java
1,249
public class FulfillmentEstimationResponse { protected Map<? extends FulfillmentOption, Money> fulfillmentOptionPrices; public Map<? extends FulfillmentOption, Money> getFulfillmentOptionPrices() { return fulfillmentOptionPrices; } public void setFulfillmentOptionPrices(Map<? extends FulfillmentOption, Money> fulfillmentOptionPrices) { this.fulfillmentOptionPrices = fulfillmentOptionPrices; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_service_fulfillment_provider_FulfillmentEstimationResponse.java
1,585
public enum Allocation { NONE, NEW_PRIMARIES, PRIMARIES, ALL; public static Allocation parse(String strValue) { if (strValue == null) { return null; } else { strValue = strValue.toUpperCase(Locale.ROOT); try { return Allocation.valueOf(strValue); } catch (IllegalArgumentException e) { throw new ElasticsearchIllegalArgumentException("Illegal allocation.enable value [" + strValue + "]"); } } } }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_decider_EnableAllocationDecider.java
1,577
public class BasicFieldMetadata extends FieldMetadata { private static final long serialVersionUID = 1L; protected SupportedFieldType fieldType; protected SupportedFieldType secondaryType = SupportedFieldType.INTEGER; protected Integer length; protected Boolean required; protected Boolean unique; protected Integer scale; protected Integer precision; protected Boolean mutable; protected String foreignKeyProperty; protected String foreignKeyClass; protected String foreignKeyDisplayValueProperty; protected Boolean foreignKeyCollection; protected MergedPropertyType mergedPropertyType; protected String[][] enumerationValues; protected String enumerationClass; protected Boolean isDerived; //@AdminPresentation derived fields protected String name; protected VisibilityEnum visibility; protected String group; protected Integer groupOrder; protected Boolean groupCollapsed; protected SupportedFieldType explicitFieldType; protected Boolean largeEntry; protected Boolean prominent; protected Integer gridOrder; protected String columnWidth; protected String broadleafEnumeration; protected Boolean readOnly; protected Map<String, Map<String, String>> validationConfigurations = new HashMap<String, Map<String, String>>(5); protected Boolean requiredOverride; protected String tooltip; protected String helpText; protected String hint; protected String lookupDisplayProperty; protected Boolean forcePopulateChildProperties; protected String optionListEntity; protected String optionValueFieldName; protected String optionDisplayFieldName; protected Boolean optionCanEditValues; protected String[][] optionFilterParams; protected String[] customCriteria; protected Boolean useServerSideInspectionCache; protected Boolean toOneLookupCreatedViaAnnotation; protected String ruleIdentifier; protected LookupType lookupType; protected Boolean translatable; //for MapFields protected String mapFieldValueClass; protected Boolean searchable; protected String manyToField; public SupportedFieldType getFieldType() { return fieldType; } public void setFieldType(SupportedFieldType fieldType) { this.fieldType = fieldType; } public SupportedFieldType getSecondaryType() { return secondaryType; } public void setSecondaryType(SupportedFieldType secondaryType) { this.secondaryType = secondaryType; } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } public Boolean getRequired() { return required; } public void setRequired(Boolean required) { this.required = required; } public Integer getScale() { return scale; } public void setScale(Integer scale) { this.scale = scale; } public Integer getPrecision() { return precision; } public void setPrecision(Integer precision) { this.precision = precision; } public Boolean getUnique() { return unique; } public void setUnique(Boolean unique) { this.unique = unique; } public Boolean getMutable() { return mutable; } public void setMutable(Boolean mutable) { this.mutable = mutable; } public String getForeignKeyProperty() { return foreignKeyProperty; } public void setForeignKeyProperty(String foreignKeyProperty) { this.foreignKeyProperty = foreignKeyProperty; } public String getForeignKeyClass() { return foreignKeyClass; } public void setForeignKeyClass(String foreignKeyClass) { this.foreignKeyClass = foreignKeyClass; } public Boolean getForeignKeyCollection() { return foreignKeyCollection; } public void setForeignKeyCollection(Boolean foreignKeyCollection) { this.foreignKeyCollection = foreignKeyCollection; } public MergedPropertyType getMergedPropertyType() { return mergedPropertyType; } public void setMergedPropertyType(MergedPropertyType mergedPropertyType) { this.mergedPropertyType = mergedPropertyType; } public String[][] getEnumerationValues() { return enumerationValues; } public void setEnumerationValues(String[][] enumerationValues) { this.enumerationValues = enumerationValues; } public String getForeignKeyDisplayValueProperty() { return foreignKeyDisplayValueProperty; } public void setForeignKeyDisplayValueProperty(String foreignKeyDisplayValueProperty) { this.foreignKeyDisplayValueProperty = foreignKeyDisplayValueProperty; } public String getEnumerationClass() { return enumerationClass; } public void setEnumerationClass(String enumerationClass) { this.enumerationClass = enumerationClass; } public Boolean getIsDerived() { return isDerived; } public void setDerived(Boolean isDerived) { this.isDerived = isDerived; } public String getName() { return name; } public void setName(String name) { this.name = name; } public SupportedFieldType getExplicitFieldType() { return explicitFieldType; } public void setExplicitFieldType(SupportedFieldType fieldType) { this.explicitFieldType = fieldType; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public Boolean isLargeEntry() { return largeEntry; } public void setLargeEntry(Boolean largeEntry) { this.largeEntry = largeEntry; } public Boolean isProminent() { return prominent; } public void setProminent(Boolean prominent) { this.prominent = prominent; } public String getColumnWidth() { return columnWidth; } public void setColumnWidth(String columnWidth) { this.columnWidth = columnWidth; } public String getBroadleafEnumeration() { return broadleafEnumeration; } public void setBroadleafEnumeration(String broadleafEnumeration) { this.broadleafEnumeration = broadleafEnumeration; } public Boolean getReadOnly() { return readOnly; } public void setReadOnly(Boolean readOnly) { this.readOnly = readOnly; } public Integer getGroupOrder() { return groupOrder; } public void setGroupOrder(Integer groupOrder) { this.groupOrder = groupOrder; } public Integer getGridOrder() { return gridOrder; } public void setGridOrder(Integer gridOrder) { this.gridOrder = gridOrder; } /** * @return the validation configurations for this property keyed by the fully-qualified name of the * {@link PropertyValidator} implementation */ public Map<String, Map<String, String>> getValidationConfigurations() { return validationConfigurations; } public void setValidationConfigurations(Map<String, Map<String, String>> validationConfigurations) { this.validationConfigurations = validationConfigurations; } public Boolean getRequiredOverride() { return requiredOverride; } public void setRequiredOverride(Boolean requiredOverride) { this.requiredOverride = requiredOverride; } public Boolean getGroupCollapsed() { return groupCollapsed; } public void setGroupCollapsed(Boolean groupCollapsed) { this.groupCollapsed = groupCollapsed; } public String getTooltip() { return tooltip; } public void setTooltip(String tooltip) { this.tooltip = tooltip; } public String getHelpText() { return helpText; } public void setHelpText(String helpText) { this.helpText = helpText; } public String getHint() { return hint; } public void setHint(String hint) { this.hint = hint; } public VisibilityEnum getVisibility() { return visibility; } public void setVisibility(VisibilityEnum visibility) { this.visibility = visibility; } public String getLookupDisplayProperty() { return lookupDisplayProperty; } public void setLookupDisplayProperty(String lookupDisplayProperty) { this.lookupDisplayProperty = lookupDisplayProperty; } public Boolean getForcePopulateChildProperties() { return forcePopulateChildProperties; } public void setForcePopulateChildProperties(Boolean forcePopulateChildProperties) { this.forcePopulateChildProperties = forcePopulateChildProperties; } public Boolean getOptionCanEditValues() { return optionCanEditValues; } public void setOptionCanEditValues(Boolean optionCanEditValues) { this.optionCanEditValues = optionCanEditValues; } public String getOptionDisplayFieldName() { return optionDisplayFieldName; } public void setOptionDisplayFieldName(String optionDisplayFieldName) { this.optionDisplayFieldName = optionDisplayFieldName; } public String getOptionListEntity() { return optionListEntity; } public void setOptionListEntity(String optionListEntity) { this.optionListEntity = optionListEntity; } public String getOptionValueFieldName() { return optionValueFieldName; } public void setOptionValueFieldName(String optionValueFieldName) { this.optionValueFieldName = optionValueFieldName; } public String[][] getOptionFilterParams() { return optionFilterParams; } public void setOptionFilterParams(String[][] optionFilterParams) { this.optionFilterParams = optionFilterParams; } public String[] getCustomCriteria() { return customCriteria; } public void setCustomCriteria(String[] customCriteria) { this.customCriteria = customCriteria; } public Boolean getUseServerSideInspectionCache() { return useServerSideInspectionCache; } public void setUseServerSideInspectionCache(Boolean useServerSideInspectionCache) { this.useServerSideInspectionCache = useServerSideInspectionCache; } public Boolean getToOneLookupCreatedViaAnnotation() { return toOneLookupCreatedViaAnnotation; } public void setToOneLookupCreatedViaAnnotation(Boolean toOneLookupCreatedViaAnnotation) { this.toOneLookupCreatedViaAnnotation = toOneLookupCreatedViaAnnotation; } public String getRuleIdentifier() { return ruleIdentifier; } public void setRuleIdentifier(String ruleIdentifier) { this.ruleIdentifier = ruleIdentifier; } public String getMapFieldValueClass() { return mapFieldValueClass; } public void setMapFieldValueClass(String mapFieldValueClass) { this.mapFieldValueClass = mapFieldValueClass; } public LookupType getLookupType() { return lookupType; } public Boolean getSearchable() { return searchable; } public void setSearchable(Boolean searchable) { this.searchable = searchable; } public String getManyToField() { return manyToField; } public void setManyToField(String manyToField) { this.manyToField = manyToField; } public void setLookupType(LookupType lookupType) { this.lookupType = lookupType; } public Boolean getTranslatable() { return translatable; } public void setTranslatable(Boolean translatable) { this.translatable = translatable; } @Override public FieldMetadata cloneFieldMetadata() { BasicFieldMetadata metadata = new BasicFieldMetadata(); metadata.fieldType = fieldType; metadata.secondaryType = secondaryType; metadata.length = length; metadata.required = required; metadata.unique = unique; metadata.scale = scale; metadata.precision = precision; metadata.mutable = mutable; metadata.foreignKeyProperty = foreignKeyProperty; metadata.foreignKeyClass = foreignKeyClass; metadata.foreignKeyDisplayValueProperty = foreignKeyDisplayValueProperty; metadata.foreignKeyCollection = foreignKeyCollection; metadata.mergedPropertyType = mergedPropertyType; metadata.enumerationClass = enumerationClass; if (enumerationValues != null) { metadata.enumerationValues = new String[enumerationValues.length][]; for (int j=0;j<enumerationValues.length;j++) { metadata.enumerationValues[j] = new String[enumerationValues[j].length]; System.arraycopy(enumerationValues[j], 0, metadata.enumerationValues[j], 0, enumerationValues[j].length); } } metadata.name = name; metadata.visibility = visibility; metadata.group = group; metadata.groupOrder = groupOrder; metadata.groupCollapsed = groupCollapsed; metadata.setTab(getTab()); metadata.setTabOrder(getTabOrder()); metadata.explicitFieldType = explicitFieldType; metadata.largeEntry = largeEntry; metadata.prominent = prominent; metadata.gridOrder = gridOrder; metadata.columnWidth = columnWidth; metadata.broadleafEnumeration = broadleafEnumeration; metadata.readOnly = readOnly; metadata.requiredOverride = requiredOverride; metadata.tooltip = tooltip; metadata.helpText = helpText; metadata.hint = hint; for (Map.Entry<String, Map<String, String>> entry : validationConfigurations.entrySet()) { Map<String, String> clone = new HashMap<String, String>(entry.getValue().size()); for (Map.Entry<String, String> entry2 : entry.getValue().entrySet()) { clone.put(entry2.getKey(), entry2.getValue()); } metadata.validationConfigurations.put(entry.getKey(), clone); } metadata.lookupDisplayProperty = lookupDisplayProperty; metadata.forcePopulateChildProperties = forcePopulateChildProperties; metadata.optionListEntity = optionListEntity; metadata.optionCanEditValues = optionCanEditValues; metadata.optionDisplayFieldName = optionDisplayFieldName; metadata.optionValueFieldName = optionValueFieldName; if (optionFilterParams != null) { metadata.optionFilterParams = new String[optionFilterParams.length][]; for (int j=0;j<optionFilterParams.length;j++) { metadata.optionFilterParams[j] = new String[optionFilterParams[j].length]; System.arraycopy(optionFilterParams[j], 0, metadata.optionFilterParams[j], 0, optionFilterParams[j].length); } } metadata.customCriteria = customCriteria; metadata.useServerSideInspectionCache = useServerSideInspectionCache; metadata.toOneLookupCreatedViaAnnotation = toOneLookupCreatedViaAnnotation; metadata.ruleIdentifier = ruleIdentifier; metadata.mapFieldValueClass = mapFieldValueClass; metadata.searchable = searchable; metadata.manyToField = manyToField; metadata.lookupType = lookupType; metadata.translatable = translatable; metadata.isDerived = isDerived; metadata = (BasicFieldMetadata) populate(metadata); return metadata; } @Override public void accept(MetadataVisitor visitor) { visitor.visit(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BasicFieldMetadata)) { return false; } if (!super.equals(o)) { return false; } BasicFieldMetadata metadata = (BasicFieldMetadata) o; if (broadleafEnumeration != null ? !broadleafEnumeration.equals(metadata.broadleafEnumeration) : metadata.broadleafEnumeration != null) { return false; } if (columnWidth != null ? !columnWidth.equals(metadata.columnWidth) : metadata.columnWidth != null) { return false; } if (enumerationClass != null ? !enumerationClass.equals(metadata.enumerationClass) : metadata.enumerationClass != null) { return false; } if (explicitFieldType != metadata.explicitFieldType) { return false; } if (fieldType != metadata.fieldType) { return false; } if (foreignKeyClass != null ? !foreignKeyClass.equals(metadata.foreignKeyClass) : metadata.foreignKeyClass != null) { return false; } if (foreignKeyCollection != null ? !foreignKeyCollection.equals(metadata.foreignKeyCollection) : metadata.foreignKeyCollection != null) { return false; } if (foreignKeyDisplayValueProperty != null ? !foreignKeyDisplayValueProperty.equals(metadata.foreignKeyDisplayValueProperty) : metadata.foreignKeyDisplayValueProperty != null) { return false; } if (foreignKeyProperty != null ? !foreignKeyProperty.equals(metadata.foreignKeyProperty) : metadata.foreignKeyProperty != null) { return false; } if (group != null ? !group.equals(metadata.group) : metadata.group != null) { return false; } if (groupCollapsed != null ? !groupCollapsed.equals(metadata.groupCollapsed) : metadata.groupCollapsed != null) { return false; } if (groupOrder != null ? !groupOrder.equals(metadata.groupOrder) : metadata.groupOrder != null) { return false; } if (helpText != null ? !helpText.equals(metadata.helpText) : metadata.helpText != null) { return false; } if (hint != null ? !hint.equals(metadata.hint) : metadata.hint != null) { return false; } if (largeEntry != null ? !largeEntry.equals(metadata.largeEntry) : metadata.largeEntry != null) { return false; } if (length != null ? !length.equals(metadata.length) : metadata.length != null) { return false; } if (lookupDisplayProperty != null ? !lookupDisplayProperty.equals(metadata.lookupDisplayProperty) : metadata.lookupDisplayProperty != null) { return false; } if (forcePopulateChildProperties != null ? !forcePopulateChildProperties.equals(metadata.forcePopulateChildProperties) : metadata.forcePopulateChildProperties != null) { return false; } if (mergedPropertyType != metadata.mergedPropertyType) { return false; } if (mutable != null ? !mutable.equals(metadata.mutable) : metadata.mutable != null) { return false; } if (name != null ? !name.equals(metadata.name) : metadata.name != null) { return false; } if (optionCanEditValues != null ? !optionCanEditValues.equals(metadata.optionCanEditValues) : metadata.optionCanEditValues != null) { return false; } if (optionDisplayFieldName != null ? !optionDisplayFieldName.equals(metadata.optionDisplayFieldName) : metadata.optionDisplayFieldName != null) { return false; } if (optionListEntity != null ? !optionListEntity.equals(metadata.optionListEntity) : metadata.optionListEntity != null) { return false; } if (optionValueFieldName != null ? !optionValueFieldName.equals(metadata.optionValueFieldName) : metadata.optionValueFieldName != null) { return false; } if (precision != null ? !precision.equals(metadata.precision) : metadata.precision != null) { return false; } if (prominent != null ? !prominent.equals(metadata.prominent) : metadata.prominent != null) { return false; } if (gridOrder != null ? !gridOrder.equals(metadata.gridOrder) : metadata.gridOrder != null) { return false; } if (readOnly != null ? !readOnly.equals(metadata.readOnly) : metadata.readOnly != null) { return false; } if (required != null ? !required.equals(metadata.required) : metadata.required != null) { return false; } if (requiredOverride != null ? !requiredOverride.equals(metadata.requiredOverride) : metadata.requiredOverride != null) { return false; } if (scale != null ? !scale.equals(metadata.scale) : metadata.scale != null) { return false; } if (secondaryType != metadata.secondaryType) { return false; } if (tooltip != null ? !tooltip.equals(metadata.tooltip) : metadata.tooltip != null) { return false; } if (unique != null ? !unique.equals(metadata.unique) : metadata.unique != null) { return false; } if (validationConfigurations != null ? !validationConfigurations.equals(metadata.validationConfigurations) : metadata.validationConfigurations != null) { return false; } if (visibility != metadata.visibility) { return false; } if (ruleIdentifier != null ? !ruleIdentifier.equals(metadata.ruleIdentifier) : metadata.ruleIdentifier != null) { return false; } if (mapFieldValueClass != null ? !mapFieldValueClass.equals(metadata.mapFieldValueClass) : metadata.mapFieldValueClass != null) { return false; } if (searchable != null ? !searchable.equals(metadata.searchable) : metadata.searchable != null) { return false; } if (manyToField != null ? !manyToField.equals(metadata.manyToField) : metadata.manyToField != null) { return false; } if (lookupType != null ? !lookupType.equals(metadata.lookupType) : metadata.lookupType != null) { return false; } if (isDerived != null ? !isDerived.equals(metadata.isDerived) : metadata.isDerived != null) { return false; } return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (fieldType != null ? fieldType.hashCode() : 0); result = 31 * result + (secondaryType != null ? secondaryType.hashCode() : 0); result = 31 * result + (length != null ? length.hashCode() : 0); result = 31 * result + (required != null ? required.hashCode() : 0); result = 31 * result + (unique != null ? unique.hashCode() : 0); result = 31 * result + (scale != null ? scale.hashCode() : 0); result = 31 * result + (precision != null ? precision.hashCode() : 0); result = 31 * result + (mutable != null ? mutable.hashCode() : 0); result = 31 * result + (foreignKeyProperty != null ? foreignKeyProperty.hashCode() : 0); result = 31 * result + (foreignKeyClass != null ? foreignKeyClass.hashCode() : 0); result = 31 * result + (foreignKeyDisplayValueProperty != null ? foreignKeyDisplayValueProperty.hashCode() : 0); result = 31 * result + (foreignKeyCollection != null ? foreignKeyCollection.hashCode() : 0); result = 31 * result + (mergedPropertyType != null ? mergedPropertyType.hashCode() : 0); result = 31 * result + (enumerationClass != null ? enumerationClass.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (visibility != null ? visibility.hashCode() : 0); result = 31 * result + (group != null ? group.hashCode() : 0); result = 31 * result + (groupOrder != null ? groupOrder.hashCode() : 0); result = 31 * result + (groupCollapsed != null ? groupCollapsed.hashCode() : 0); result = 31 * result + (explicitFieldType != null ? explicitFieldType.hashCode() : 0); result = 31 * result + (largeEntry != null ? largeEntry.hashCode() : 0); result = 31 * result + (prominent != null ? prominent.hashCode() : 0); result = 31 * result + (gridOrder != null ? gridOrder.hashCode() : 0); result = 31 * result + (columnWidth != null ? columnWidth.hashCode() : 0); result = 31 * result + (broadleafEnumeration != null ? broadleafEnumeration.hashCode() : 0); result = 31 * result + (readOnly != null ? readOnly.hashCode() : 0); result = 31 * result + (validationConfigurations != null ? validationConfigurations.hashCode() : 0); result = 31 * result + (requiredOverride != null ? requiredOverride.hashCode() : 0); result = 31 * result + (tooltip != null ? tooltip.hashCode() : 0); result = 31 * result + (helpText != null ? helpText.hashCode() : 0); result = 31 * result + (hint != null ? hint.hashCode() : 0); result = 31 * result + (lookupDisplayProperty != null ? lookupDisplayProperty.hashCode() : 0); result = 31 * result + (forcePopulateChildProperties != null ? forcePopulateChildProperties.hashCode() : 0); result = 31 * result + (optionListEntity != null ? optionListEntity.hashCode() : 0); result = 31 * result + (optionValueFieldName != null ? optionValueFieldName.hashCode() : 0); result = 31 * result + (optionDisplayFieldName != null ? optionDisplayFieldName.hashCode() : 0); result = 31 * result + (optionCanEditValues != null ? optionCanEditValues.hashCode() : 0); result = 31 * result + (ruleIdentifier != null ? ruleIdentifier.hashCode() : 0); result = 31 * result + (mapFieldValueClass != null ? mapFieldValueClass.hashCode() : 0); result = 31 * result + (searchable != null ? searchable.hashCode() : 0); result = 31 * result + (manyToField != null ? manyToField.hashCode() : 0); result = 31 * result + (lookupType != null ? lookupType.hashCode() : 0); result = 31 * result + (isDerived != null ? isDerived.hashCode() : 0); return result; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_BasicFieldMetadata.java
321
public class TransportNodesHotThreadsAction extends TransportNodesOperationAction<NodesHotThreadsRequest, NodesHotThreadsResponse, TransportNodesHotThreadsAction.NodeRequest, NodeHotThreads> { @Inject public TransportNodesHotThreadsAction(Settings settings, ClusterName clusterName, ThreadPool threadPool, ClusterService clusterService, TransportService transportService) { super(settings, clusterName, threadPool, clusterService, transportService); } @Override protected String executor() { return ThreadPool.Names.GENERIC; } @Override protected String transportAction() { return NodesHotThreadsAction.NAME; } @Override protected NodesHotThreadsResponse newResponse(NodesHotThreadsRequest request, AtomicReferenceArray responses) { final List<NodeHotThreads> nodes = Lists.newArrayList(); for (int i = 0; i < responses.length(); i++) { Object resp = responses.get(i); if (resp instanceof NodeHotThreads) { nodes.add((NodeHotThreads) resp); } } return new NodesHotThreadsResponse(clusterName, nodes.toArray(new NodeHotThreads[nodes.size()])); } @Override protected NodesHotThreadsRequest newRequest() { return new NodesHotThreadsRequest(); } @Override protected NodeRequest newNodeRequest() { return new NodeRequest(); } @Override protected NodeRequest newNodeRequest(String nodeId, NodesHotThreadsRequest request) { return new NodeRequest(nodeId, request); } @Override protected NodeHotThreads newNodeResponse() { return new NodeHotThreads(); } @Override protected NodeHotThreads nodeOperation(NodeRequest request) throws ElasticsearchException { HotThreads hotThreads = new HotThreads() .busiestThreads(request.request.threads) .type(request.request.type) .interval(request.request.interval) .threadElementsSnapshotCount(request.request.snapshots); try { return new NodeHotThreads(clusterService.localNode(), hotThreads.detect()); } catch (Exception e) { throw new ElasticsearchException("failed to detect hot threads", e); } } @Override protected boolean accumulateExceptions() { return false; } static class NodeRequest extends NodeOperationRequest { NodesHotThreadsRequest request; NodeRequest() { } NodeRequest(String nodeId, NodesHotThreadsRequest request) { super(request, nodeId); this.request = request; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); request = new NodesHotThreadsRequest(); request.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); request.writeTo(out); } } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_hotthreads_TransportNodesHotThreadsAction.java
3,558
public class ByteFieldMapper extends NumberFieldMapper<Byte> { public static final String CONTENT_TYPE = "byte"; 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 Byte NULL_VALUE = null; } public static class Builder extends NumberFieldMapper.Builder<Builder, ByteFieldMapper> { protected Byte nullValue = Defaults.NULL_VALUE; public Builder(String name) { super(name, new FieldType(Defaults.FIELD_TYPE)); builder = this; } public Builder nullValue(byte nullValue) { this.nullValue = nullValue; return this; } @Override public ByteFieldMapper build(BuilderContext context) { fieldType.setOmitNorms(fieldType.omitNorms() && boost == 1.0f); ByteFieldMapper fieldMapper = new ByteFieldMapper(buildNames(context), precisionStep, boost, fieldType, docValues, nullValue, ignoreMalformed(context), coerce(context), postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo); fieldMapper.includeInAll(includeInAll); return fieldMapper; } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { ByteFieldMapper.Builder builder = byteField(name); parseNumberField(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(nodeByteValue(propNode)); } } return builder; } } private Byte nullValue; private String nullValueAsString; protected ByteFieldMapper(Names names, int precisionStep, float boost, FieldType fieldType, Boolean docValues, Byte nullValue, Explicit<Boolean> ignoreMalformed, Explicit<Boolean> coerce, PostingsFormatProvider postingsProvider, DocValuesFormatProvider docValuesProvider, SimilarityProvider similarity, Loading normsLoading, @Nullable Settings fieldDataSettings, Settings indexSettings, MultiFields multiFields, CopyTo copyTo) { super(names, precisionStep, boost, fieldType, docValues, ignoreMalformed, coerce, new NamedAnalyzer("_byte/" + precisionStep, new NumericIntegerAnalyzer(precisionStep)), new NamedAnalyzer("_byte/max", new NumericIntegerAnalyzer(Integer.MAX_VALUE)), postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings, indexSettings, multiFields, copyTo); this.nullValue = nullValue; this.nullValueAsString = nullValue == null ? null : nullValue.toString(); } @Override public FieldType defaultFieldType() { return Defaults.FIELD_TYPE; } @Override public FieldDataType defaultFieldDataType() { return new FieldDataType("byte"); } @Override protected int maxPrecisionStep() { return 32; } @Override public Byte value(Object value) { if (value == null) { return null; } if (value instanceof Number) { return ((Number) value).byteValue(); } if (value instanceof BytesRef) { return ((BytesRef) value).bytes[((BytesRef) value).offset]; } return Byte.parseByte(value.toString()); } @Override public BytesRef indexedValueForSearch(Object value) { BytesRef bytesRef = new BytesRef(); NumericUtils.intToPrefixCoded(parseValue(value), 0, bytesRef); // 0 because of exact match return bytesRef; } private byte parseValue(Object value) { if (value instanceof Number) { return ((Number) value).byteValue(); } if (value instanceof BytesRef) { return Byte.parseByte(((BytesRef) value).utf8ToString()); } return Byte.parseByte(value.toString()); } private int parseValueAsInt(Object value) { return parseValue(value); } @Override public Query fuzzyQuery(String value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions) { byte iValue = Byte.parseByte(value); byte iSim = fuzziness.asByte(); return NumericRangeQuery.newIntRange(names.indexName(), precisionStep, iValue - iSim, iValue + iSim, true, true); } @Override public Query termQuery(Object value, @Nullable QueryParseContext context) { int iValue = parseValue(value); return NumericRangeQuery.newIntRange(names.indexName(), precisionStep, iValue, iValue, true, true); } @Override public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return NumericRangeQuery.newIntRange(names.indexName(), precisionStep, lowerTerm == null ? null : parseValueAsInt(lowerTerm), upperTerm == null ? null : parseValueAsInt(upperTerm), includeLower, includeUpper); } @Override public Filter termFilter(Object value, @Nullable QueryParseContext context) { int iValue = parseValueAsInt(value); return NumericRangeFilter.newIntRange(names.indexName(), precisionStep, iValue, iValue, true, true); } @Override public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return NumericRangeFilter.newIntRange(names.indexName(), precisionStep, lowerTerm == null ? null : parseValueAsInt(lowerTerm), upperTerm == null ? null : parseValueAsInt(upperTerm), includeLower, includeUpper); } @Override public Filter rangeFilter(IndexFieldDataService fieldData, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return NumericRangeFieldDataFilter.newByteRange((IndexNumericFieldData) fieldData.getForField(this), lowerTerm == null ? null : parseValue(lowerTerm), upperTerm == null ? null : parseValue(upperTerm), includeLower, includeUpper); } @Override public Filter nullValueFilter() { if (nullValue == null) { return null; } return NumericRangeFilter.newIntRange(names.indexName(), precisionStep, nullValue.intValue(), nullValue.intValue(), true, true); } @Override protected boolean customBoost() { return true; } @Override protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException { byte value; float boost = this.boost; if (context.externalValueSet()) { Object externalValue = context.externalValue(); if (externalValue == null) { if (nullValue == null) { return; } value = nullValue; } else if (externalValue instanceof String) { String sExternalValue = (String) externalValue; if (sExternalValue.length() == 0) { if (nullValue == null) { return; } value = nullValue; } else { value = Byte.parseByte(sExternalValue); } } else { value = ((Number) externalValue).byteValue(); } if (context.includeInAll(includeInAll, this)) { context.allEntries().addText(names.fullName(), Byte.toString(value), boost); } } else { XContentParser parser = context.parser(); if (parser.currentToken() == XContentParser.Token.VALUE_NULL || (parser.currentToken() == XContentParser.Token.VALUE_STRING && parser.textLength() == 0)) { if (nullValue == null) { return; } value = nullValue; if (nullValueAsString != null && (context.includeInAll(includeInAll, this))) { context.allEntries().addText(names.fullName(), nullValueAsString, boost); } } else if (parser.currentToken() == XContentParser.Token.START_OBJECT) { XContentParser.Token token; String currentFieldName = null; Byte objValue = nullValue; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else { if ("value".equals(currentFieldName) || "_value".equals(currentFieldName)) { if (parser.currentToken() != XContentParser.Token.VALUE_NULL) { objValue = (byte) parser.shortValue(coerce.value()); } } else if ("boost".equals(currentFieldName) || "_boost".equals(currentFieldName)) { boost = parser.floatValue(); } else { throw new ElasticsearchIllegalArgumentException("unknown property [" + currentFieldName + "]"); } } } if (objValue == null) { // no value return; } value = objValue; } else { value = (byte) parser.shortValue(coerce.value()); if (context.includeInAll(includeInAll, this)) { context.allEntries().addText(names.fullName(), parser.text(), boost); } } } if (fieldType.indexed() || fieldType.stored()) { CustomByteNumericField field = new CustomByteNumericField(this, value, fieldType); field.setBoost(boost); fields.add(field); } if (hasDocValues()) { addDocValue(context, value); } } @Override protected String contentType() { return CONTENT_TYPE; } @Override public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException { super.merge(mergeWith, mergeContext); if (!this.getClass().equals(mergeWith.getClass())) { return; } if (!mergeContext.mergeFlags().simulate()) { this.nullValue = ((ByteFieldMapper) mergeWith).nullValue; this.nullValueAsString = ((ByteFieldMapper) mergeWith).nullValueAsString; } } @Override protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException { super.doXContentBody(builder, includeDefaults, params); if (includeDefaults || precisionStep != Defaults.PRECISION_STEP) { builder.field("precision_step", precisionStep); } if (includeDefaults || nullValue != null) { builder.field("null_value", nullValue); } if (includeInAll != null) { builder.field("include_in_all", includeInAll); } else if (includeDefaults) { builder.field("include_in_all", false); } } public static class CustomByteNumericField extends CustomNumericField { private final byte number; private final NumberFieldMapper mapper; public CustomByteNumericField(NumberFieldMapper mapper, byte number, FieldType fieldType) { super(mapper, number, fieldType); this.mapper = mapper; this.number = number; } @Override public TokenStream tokenStream(Analyzer analyzer) { if (fieldType().indexed()) { return mapper.popCachedStream().setIntValue(number); } return null; } @Override public String numericAsString() { return Byte.toString(number); } } }
0true
src_main_java_org_elasticsearch_index_mapper_core_ByteFieldMapper.java
2,420
public interface ObjectArray<T> extends BigArray { /** * Get an element given its index. */ public abstract T get(long index); /** * Set a value at the given index and return the previous value. */ public abstract T set(long index, T value); }
0true
src_main_java_org_elasticsearch_common_util_ObjectArray.java
600
ex.execute(new Runnable() { public void run() { if (sleep) { try { Thread.sleep((int) (1000 * Math.random())); } catch (InterruptedException ignored) { } } HazelcastInstance h = nodeFactory.newHazelcastInstance(config); map.put(index, h); latch.countDown(); } });
0true
hazelcast_src_test_java_com_hazelcast_cluster_JoinStressTest.java
118
static final class Submitter { int seed; Submitter(int s) { seed = s; } }
0true
src_main_java_jsr166e_ForkJoinPool.java
2,652
sendPingsHandler.executor().execute(new Runnable() { @Override public void run() { try { if (sendPingsHandler.isClosed()) { return; } // connect to the node, see if we manage to do it, if not, bail if (!nodeFoundByAddress) { logger.trace("[{}] connecting (light) to {}", sendPingsHandler.id(), nodeToSend); transportService.connectToNodeLight(nodeToSend); } else { logger.trace("[{}] connecting to {}", sendPingsHandler.id(), nodeToSend); transportService.connectToNode(nodeToSend); } logger.trace("[{}] connected to {}", sendPingsHandler.id(), node); if (receivedResponses.containsKey(sendPingsHandler.id())) { // we are connected and still in progress, send the ping request sendPingRequestToNode(sendPingsHandler.id(), timeout, pingRequest, latch, node, nodeToSend); } else { // connect took too long, just log it and bail latch.countDown(); logger.trace("[{}] connect to {} was too long outside of ping window, bailing", sendPingsHandler.id(), node); } } catch (ConnectTransportException e) { // can't connect to the node logger.trace("[{}] failed to connect to {}", e, sendPingsHandler.id(), nodeToSend); latch.countDown(); } } });
0true
src_main_java_org_elasticsearch_discovery_zen_ping_unicast_UnicastZenPing.java
1,853
class MapSizeEstimator<T extends Record> implements SizeEstimator<T> { private volatile long size; public long getSize() { return size; } public void add(long size) { this.size += size; } public void reset() { size = 0; } public long getCost(T record) { if (record == null) { return 0L; } final long cost = record.getCost(); if (cost == 0L) { return cost; } final int numberOfIntegers = 4; // entry size in CHM long refSize = numberOfIntegers * ((Integer.SIZE / Byte.SIZE)); return refSize + cost; } }
0true
hazelcast_src_main_java_com_hazelcast_map_MapSizeEstimator.java
2,638
private class Receiver implements Runnable { private volatile boolean running = true; public void stop() { running = false; } @Override public void run() { while (running) { try { int id = -1; DiscoveryNode requestingNodeX = null; ClusterName clusterName = null; Map<String, Object> externalPingData = null; XContentType xContentType = null; synchronized (receiveMutex) { try { multicastSocket.receive(datagramPacketReceive); } catch (SocketTimeoutException ignore) { continue; } catch (Exception e) { if (running) { if (multicastSocket.isClosed()) { logger.warn("multicast socket closed while running, restarting..."); // for some reason, the socket got closed on us while we are still running // make a best effort in trying to start the multicast socket again... threadPool.generic().execute(new Runnable() { @Override public void run() { MulticastZenPing.this.stop(); MulticastZenPing.this.start(); } }); running = false; return; } else { logger.warn("failed to receive packet, throttling...", e); Thread.sleep(500); } } continue; } try { boolean internal = false; if (datagramPacketReceive.getLength() > 4) { int counter = 0; for (; counter < INTERNAL_HEADER.length; counter++) { if (datagramPacketReceive.getData()[datagramPacketReceive.getOffset() + counter] != INTERNAL_HEADER[counter]) { break; } } if (counter == INTERNAL_HEADER.length) { internal = true; } } if (internal) { StreamInput input = CachedStreamInput.cachedHandles(new BytesStreamInput(datagramPacketReceive.getData(), datagramPacketReceive.getOffset() + INTERNAL_HEADER.length, datagramPacketReceive.getLength(), true)); Version version = Version.readVersion(input); input.setVersion(version); id = input.readInt(); clusterName = ClusterName.readClusterName(input); requestingNodeX = readNode(input); } else { xContentType = XContentFactory.xContentType(datagramPacketReceive.getData(), datagramPacketReceive.getOffset(), datagramPacketReceive.getLength()); if (xContentType != null) { // an external ping externalPingData = XContentFactory.xContent(xContentType) .createParser(datagramPacketReceive.getData(), datagramPacketReceive.getOffset(), datagramPacketReceive.getLength()) .mapAndClose(); } else { throw new ElasticsearchIllegalStateException("failed multicast message, probably message from previous version"); } } } catch (Exception e) { logger.warn("failed to read requesting data from {}", e, datagramPacketReceive.getSocketAddress()); continue; } } if (externalPingData != null) { handleExternalPingRequest(externalPingData, xContentType, datagramPacketReceive.getSocketAddress()); } else { handleNodePingRequest(id, requestingNodeX, clusterName); } } catch (Exception e) { if (running) { logger.warn("unexpected exception in multicast receiver", e); } } } } @SuppressWarnings("unchecked") private void handleExternalPingRequest(Map<String, Object> externalPingData, XContentType contentType, SocketAddress remoteAddress) { if (externalPingData.containsKey("response")) { // ignoring responses sent over the multicast channel logger.trace("got an external ping response (ignoring) from {}, content {}", remoteAddress, externalPingData); return; } if (multicastSocket == null) { logger.debug("can't send ping response, no socket, from {}, content {}", remoteAddress, externalPingData); return; } Map<String, Object> request = (Map<String, Object>) externalPingData.get("request"); if (request == null) { logger.warn("malformed external ping request, no 'request' element from {}, content {}", remoteAddress, externalPingData); return; } String clusterName = request.containsKey("cluster_name") ? request.get("cluster_name").toString() : request.containsKey("clusterName") ? request.get("clusterName").toString() : null; if (clusterName == null) { logger.warn("malformed external ping request, missing 'cluster_name' element within request, from {}, content {}", remoteAddress, externalPingData); return; } if (!clusterName.equals(MulticastZenPing.this.clusterName.value())) { logger.trace("got request for cluster_name {}, but our cluster_name is {}, from {}, content {}", clusterName, MulticastZenPing.this.clusterName.value(), remoteAddress, externalPingData); return; } if (logger.isTraceEnabled()) { logger.trace("got external ping request from {}, content {}", remoteAddress, externalPingData); } try { DiscoveryNode localNode = nodesProvider.nodes().localNode(); XContentBuilder builder = XContentFactory.contentBuilder(contentType); builder.startObject().startObject("response"); builder.field("cluster_name", MulticastZenPing.this.clusterName.value()); builder.startObject("version").field("number", version.number()).field("snapshot_build", version.snapshot).endObject(); builder.field("transport_address", localNode.address().toString()); if (nodesProvider.nodeService() != null) { for (Map.Entry<String, String> attr : nodesProvider.nodeService().attributes().entrySet()) { builder.field(attr.getKey(), attr.getValue()); } } builder.startObject("attributes"); for (Map.Entry<String, String> attr : localNode.attributes().entrySet()) { builder.field(attr.getKey(), attr.getValue()); } builder.endObject(); builder.endObject().endObject(); synchronized (sendMutex) { BytesReference bytes = builder.bytes(); datagramPacketSend.setData(bytes.array(), bytes.arrayOffset(), bytes.length()); multicastSocket.send(datagramPacketSend); if (logger.isTraceEnabled()) { logger.trace("sending external ping response {}", builder.string()); } } } catch (Exception e) { logger.warn("failed to send external multicast response", e); } } private void handleNodePingRequest(int id, DiscoveryNode requestingNodeX, ClusterName clusterName) { if (!pingEnabled) { return; } DiscoveryNodes discoveryNodes = nodesProvider.nodes(); final DiscoveryNode requestingNode = requestingNodeX; if (requestingNode.id().equals(discoveryNodes.localNodeId())) { // that's me, ignore return; } if (!clusterName.equals(MulticastZenPing.this.clusterName)) { if (logger.isTraceEnabled()) { logger.trace("[{}] received ping_request from [{}], but wrong cluster_name [{}], expected [{}], ignoring", id, requestingNode, clusterName, MulticastZenPing.this.clusterName); } return; } // don't connect between two client nodes, no need for that... if (!discoveryNodes.localNode().shouldConnectTo(requestingNode)) { if (logger.isTraceEnabled()) { logger.trace("[{}] received ping_request from [{}], both are client nodes, ignoring", id, requestingNode, clusterName); } return; } final MulticastPingResponse multicastPingResponse = new MulticastPingResponse(); multicastPingResponse.id = id; multicastPingResponse.pingResponse = new PingResponse(discoveryNodes.localNode(), discoveryNodes.masterNode(), clusterName); if (logger.isTraceEnabled()) { logger.trace("[{}] received ping_request from [{}], sending {}", id, requestingNode, multicastPingResponse.pingResponse); } if (!transportService.nodeConnected(requestingNode)) { // do the connect and send on a thread pool threadPool.generic().execute(new Runnable() { @Override public void run() { // connect to the node if possible try { transportService.connectToNode(requestingNode); transportService.sendRequest(requestingNode, MulticastPingResponseRequestHandler.ACTION, multicastPingResponse, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleException(TransportException exp) { logger.warn("failed to receive confirmation on sent ping response to [{}]", exp, requestingNode); } }); } catch (Exception e) { logger.warn("failed to connect to requesting node {}", e, requestingNode); } } }); } else { transportService.sendRequest(requestingNode, MulticastPingResponseRequestHandler.ACTION, multicastPingResponse, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleException(TransportException exp) { logger.warn("failed to receive confirmation on sent ping response to [{}]", exp, requestingNode); } }); } } }
0true
src_main_java_org_elasticsearch_discovery_zen_ping_multicast_MulticastZenPing.java
506
public class SiteResolutionType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, SiteResolutionType> TYPES = new LinkedHashMap<String, SiteResolutionType>(); public static final SiteResolutionType DOMAIN = new SiteResolutionType("DOMAIN", "Domain"); public static final SiteResolutionType DOMAIN_PREFIX = new SiteResolutionType("DOMAIN_PREFIX", "Domain Prefix"); public static SiteResolutionType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public SiteResolutionType() { //do nothing } public SiteResolutionType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } @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; SiteResolutionType other = (SiteResolutionType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
common_src_main_java_org_broadleafcommerce_common_site_service_type_SiteResolutionType.java
16
class CommandExecutor implements Runnable { final TextCommand command; CommandExecutor(TextCommand command) { this.command = command; } @Override public void run() { try { TextCommandType type = command.getType(); TextCommandProcessor textCommandProcessor = textCommandProcessors[type.getValue()]; textCommandProcessor.handle(command); } catch (Throwable e) { logger.warning(e); } } }
0true
hazelcast_src_main_java_com_hazelcast_ascii_TextCommandServiceImpl.java
295
public abstract class BroadleafException extends Exception implements RootCauseAccessor { private Throwable rootCause; public BroadleafException() { super(); } public BroadleafException(String message, Throwable cause) { super(message, cause); if (cause != null) { rootCause = findRootCause(cause); } else { rootCause = this; } } private Throwable findRootCause(Throwable cause) { Throwable rootCause = cause; while (rootCause != null && rootCause.getCause() != null) { rootCause = rootCause.getCause(); } return rootCause; } public BroadleafException(String message) { super(message); this.rootCause = this; } public BroadleafException(Throwable cause) { super(cause); if (cause != null) { rootCause = findRootCause(cause); } } public Throwable getRootCause() { return rootCause; } public String getRootCauseMessage() { if (rootCause != null) { return rootCause.getMessage(); } else { return getMessage(); } } }
0true
common_src_main_java_org_broadleafcommerce_common_exception_BroadleafException.java
1,237
@Deprecated public interface ShippingService { public FulfillmentGroup calculateShippingForFulfillmentGroup(FulfillmentGroup fulfillmentGroup) throws FulfillmentPriceException; }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_service_ShippingService.java
346
fViewer.getControl().addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent event) { fActionSet.handleKeyEvent(event); } });
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_explorer_PackageExplorerPart.java
1,781
@Component("blMapStructurePersistenceModule") @Scope("prototype") public class MapStructurePersistenceModule extends BasicPersistenceModule { private static final Log LOG = LogFactory.getLog(MapStructurePersistenceModule.class); @Override public boolean isCompatible(OperationType operationType) { return OperationType.MAP.equals(operationType); } @Override public void extractProperties(Class<?>[] inheritanceLine, Map<MergedPropertyType, Map<String, FieldMetadata>> mergedProperties, List<Property> properties) throws NumberFormatException { if (mergedProperties.get(MergedPropertyType.MAPSTRUCTUREKEY) != null) { extractPropertiesFromMetadata(inheritanceLine, mergedProperties.get(MergedPropertyType.MAPSTRUCTUREKEY), properties, false, MergedPropertyType.MAPSTRUCTUREKEY); } if (mergedProperties.get(MergedPropertyType.MAPSTRUCTUREVALUE) != null) { extractPropertiesFromMetadata(inheritanceLine, mergedProperties.get(MergedPropertyType.MAPSTRUCTUREVALUE), properties, false, MergedPropertyType.MAPSTRUCTUREVALUE); } } protected Entity[] getMapRecords(Serializable record, MapStructure mapStructure, Map<String, FieldMetadata> ceilingMergedProperties, Map<String, FieldMetadata> valueMergedProperties, Property symbolicIdProperty) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException, IllegalArgumentException, ClassNotFoundException, NoSuchFieldException { //compile a list of mapKeys that were used as mapFields List<String> mapFieldKeys = new ArrayList<String>(); String mapProperty = mapStructure.getMapProperty(); for (Map.Entry<String, FieldMetadata> entry : ceilingMergedProperties.entrySet()) { if (entry.getKey().startsWith(mapProperty + FieldManager.MAPFIELDSEPARATOR)) { mapFieldKeys.add(entry.getKey().substring(entry.getKey().indexOf(FieldManager.MAPFIELDSEPARATOR) + FieldManager.MAPFIELDSEPARATOR.length(), entry.getKey().length())); } } Collections.sort(mapFieldKeys); FieldManager fieldManager = getFieldManager(); Map map; try { map = (Map) fieldManager.getFieldValue(record, mapProperty); } catch (FieldNotAvailableException e) { throw new IllegalArgumentException(e); } List<Entity> entities = new ArrayList<Entity>(map.size()); for (Object key : map.keySet()) { if (key instanceof String && mapFieldKeys.contains(key)) { continue; } Entity entityItem = new Entity(); entityItem.setType(new String[]{record.getClass().getName()}); entities.add(entityItem); List<Property> props = new ArrayList<Property>(); Property propertyItem = new Property(); propertyItem.setName(mapStructure.getKeyPropertyName()); props.add(propertyItem); String strVal; if (Date.class.isAssignableFrom(key.getClass())) { strVal = getSimpleDateFormatter().format((Date) key); } else if (Timestamp.class.isAssignableFrom(key.getClass())) { strVal = getSimpleDateFormatter().format(new Date(((Timestamp) key).getTime())); } else if (Calendar.class.isAssignableFrom(key.getClass())) { strVal = getSimpleDateFormatter().format(((Calendar) key).getTime()); } else if (Double.class.isAssignableFrom(key.getClass())) { strVal = getDecimalFormatter().format(key); } else if (BigDecimal.class.isAssignableFrom(key.getClass())) { strVal = getDecimalFormatter().format(key); } else { strVal = key.toString(); } propertyItem.setValue(strVal); PersistentClass persistentClass = persistenceManager.getDynamicEntityDao().getPersistentClass(mapStructure.getValueClassName()); if (persistentClass == null) { Property temp = new Property(); temp.setName(((SimpleValueMapStructure) mapStructure).getValuePropertyName()); temp.setValue(String.valueOf(map.get(key))); props.add(temp); } else { extractPropertiesFromPersistentEntity(valueMergedProperties, (Serializable) map.get(key), props); } if (symbolicIdProperty != null) { props.add(symbolicIdProperty); } Property[] properties = new Property[props.size()]; properties = props.toArray(properties); entityItem.setProperties(properties); } return entities.toArray(new Entity[entities.size()]); } @Override public void updateMergedProperties(PersistencePackage persistencePackage, Map<MergedPropertyType, Map<String, FieldMetadata>> allMergedProperties) throws ServiceException { String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname(); try { PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective(); MapStructure mapStructure = (MapStructure) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE); if (mapStructure != null) { PersistentClass persistentClass = persistenceManager.getDynamicEntityDao().getPersistentClass(mapStructure.getKeyClassName()); Map<String, FieldMetadata> keyMergedProperties; if (persistentClass == null) { keyMergedProperties = persistenceManager.getDynamicEntityDao().getPropertiesForPrimitiveClass( mapStructure.getKeyPropertyName(), mapStructure.getKeyPropertyFriendlyName(), Class.forName(mapStructure.getKeyClassName()), Class.forName(ceilingEntityFullyQualifiedClassname), MergedPropertyType.MAPSTRUCTUREKEY ); } else { keyMergedProperties = persistenceManager.getDynamicEntityDao().getMergedProperties( mapStructure.getKeyClassName(), new Class[]{Class.forName(mapStructure.getKeyClassName())}, null, new String[]{}, new ForeignKey[]{}, MergedPropertyType.MAPSTRUCTUREKEY, persistencePerspective.getPopulateToOneFields(), persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(), persistencePerspective.getConfigurationKey(), "" ); } allMergedProperties.put(MergedPropertyType.MAPSTRUCTUREKEY, keyMergedProperties); persistentClass = persistenceManager.getDynamicEntityDao().getPersistentClass(mapStructure.getValueClassName()); Map<String, FieldMetadata> valueMergedProperties; if (persistentClass == null) { if (!SimpleValueMapStructure.class.isAssignableFrom(mapStructure.getClass())) { throw new IllegalStateException("The map structure was determined to not be a simple value, but the system was unable to identify the entity designated for the map structure value(" + mapStructure.getValueClassName() + ")"); } valueMergedProperties = persistenceManager.getDynamicEntityDao().getPropertiesForPrimitiveClass( ((SimpleValueMapStructure) mapStructure).getValuePropertyName(), ((SimpleValueMapStructure) mapStructure).getValuePropertyFriendlyName(), Class.forName(mapStructure.getValueClassName()), Class.forName(ceilingEntityFullyQualifiedClassname), MergedPropertyType.MAPSTRUCTUREVALUE ); } else { valueMergedProperties = persistenceManager.getDynamicEntityDao().getMergedProperties( mapStructure.getValueClassName(), new Class[]{Class.forName(mapStructure.getValueClassName())}, null, new String[]{}, new ForeignKey[]{}, MergedPropertyType.MAPSTRUCTUREVALUE, persistencePerspective.getPopulateToOneFields(), persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(), persistencePerspective.getConfigurationKey(), "" ); } allMergedProperties.put(MergedPropertyType.MAPSTRUCTUREVALUE, valueMergedProperties); //clear out all but the primary key field from the owning entity // Iterator<Map.Entry<String, FieldMetadata>> itr = allMergedProperties.get(MergedPropertyType.PRIMARY).entrySet().iterator(); // while (itr.hasNext()) { // Map.Entry<String, FieldMetadata> entry = itr.next(); // if (!(entry.getValue() instanceof BasicFieldMetadata) || !SupportedFieldType.ID.equals(((BasicFieldMetadata) entry.getValue()).getFieldType())) { // itr.remove(); // } // } } } catch (Exception e) { throw new ServiceException("Unable to fetch results for " + ceilingEntityFullyQualifiedClassname, e); } } @Override public Entity add(PersistencePackage persistencePackage) throws ServiceException { String[] customCriteria = persistencePackage.getCustomCriteria(); if (customCriteria != null && customCriteria.length > 0) { LOG.warn("custom persistence handlers and custom criteria not supported for add types other than BASIC"); } PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective(); Entity entity = persistencePackage.getEntity(); MapStructure mapStructure = (MapStructure) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE); if (!mapStructure.getMutable()) { throw new SecurityServiceException("Field not mutable"); } try { Map<String, FieldMetadata> ceilingMergedProperties = getSimpleMergedProperties(entity.getType()[0], persistencePerspective); String mapKey = entity.findProperty(mapStructure.getKeyPropertyName()).getValue(); if (StringUtils.isEmpty(mapKey)) { entity.addValidationError(mapStructure.getKeyPropertyName(), RequiredPropertyValidator.ERROR_MESSAGE); LOG.debug("No key property passed in for map, failing validation"); } if (ceilingMergedProperties.containsKey(mapStructure.getMapProperty() + FieldManager.MAPFIELDSEPARATOR + mapKey)) { throw new ServiceException("\"" + mapKey + "\" is a reserved property name."); } Serializable instance = persistenceManager.getDynamicEntityDao().retrieve(Class.forName(entity.getType() [0]), Long.valueOf(entity.findProperty("symbolicId").getValue())); Assert.isTrue(instance != null, "Entity not found"); FieldManager fieldManager = getFieldManager(); Map map = (Map) fieldManager.getFieldValue(instance, mapStructure.getMapProperty()); if (map.containsKey(mapKey)) { entity.addValidationError(mapStructure.getKeyPropertyName(), "keyExistsValidationError"); } PersistentClass persistentClass = persistenceManager.getDynamicEntityDao().getPersistentClass(mapStructure.getValueClassName()); Map<String, FieldMetadata> valueUnfilteredMergedProperties; if (persistentClass == null) { valueUnfilteredMergedProperties = persistenceManager.getDynamicEntityDao().getPropertiesForPrimitiveClass( ((SimpleValueMapStructure) mapStructure).getValuePropertyName(), ((SimpleValueMapStructure) mapStructure).getValuePropertyFriendlyName(), Class.forName(mapStructure.getValueClassName()), Class.forName(entity.getType()[0]), MergedPropertyType.MAPSTRUCTUREVALUE ); } else { valueUnfilteredMergedProperties = persistenceManager.getDynamicEntityDao().getMergedProperties( mapStructure.getValueClassName(), new Class[]{Class.forName(mapStructure.getValueClassName())}, null, new String[]{}, new ForeignKey[]{}, MergedPropertyType.MAPSTRUCTUREVALUE, persistencePerspective.getPopulateToOneFields(), persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(), persistencePerspective.getConfigurationKey(), "" ); } Map<String, FieldMetadata> valueMergedProperties = filterOutCollectionMetadata(valueUnfilteredMergedProperties); if (persistentClass != null) { Serializable valueInstance = (Serializable) Class.forName(mapStructure.getValueClassName()).newInstance(); valueInstance = createPopulatedInstance(valueInstance, entity, valueMergedProperties, false); if (valueInstance instanceof ValueAssignable) { //This is likely a OneToMany map (see productAttributes) whose map key is actually the name field from //the mapped entity. ((ValueAssignable) valueInstance).setName(entity.findProperty(mapStructure.getKeyPropertyName()).getValue()); } if (mapStructure.getManyToField() != null) { //Need to fulfill a bi-directional association back to the parent entity fieldManager.setFieldValue(valueInstance, mapStructure.getManyToField(), instance); } valueInstance = persistenceManager.getDynamicEntityDao().persist(valueInstance); /* * TODO this map manipulation code currently assumes the key value is a String. This should be widened to accept * additional types of primitive objects. */ map.put(mapKey, valueInstance); } else { String propertyName = ((SimpleValueMapStructure) mapStructure).getValuePropertyName(); String value = entity.findProperty(propertyName).getValue(); Object convertedPrimitive = convertPrimitiveBasedOnType(propertyName, value, valueMergedProperties); map.put(mapKey, convertedPrimitive); } Entity[] responses = getMapRecords(instance, mapStructure, ceilingMergedProperties, valueMergedProperties, entity.findProperty("symbolicId")); for (Entity response : responses) { if (response.findProperty(mapStructure.getKeyPropertyName()).getValue().equals(persistencePackage.getEntity().findProperty(mapStructure.getKeyPropertyName()).getValue())) { return response; } } return responses[0]; } catch (Exception e) { throw new ServiceException("Problem updating entity : " + e.getMessage(), e); } } protected Object convertPrimitiveBasedOnType(String valuePropertyName, String value, Map<String, FieldMetadata> valueMergedProperties) throws ParseException { switch(((BasicFieldMetadata) valueMergedProperties.get(valuePropertyName)).getFieldType()) { case BOOLEAN : return Boolean.parseBoolean(value); case DATE : return getSimpleDateFormatter().parse(value); case DECIMAL : return new BigDecimal(value); case MONEY : return new Money(value); case INTEGER : return Integer.parseInt(value); default : return value; } } @Override public Entity update(PersistencePackage persistencePackage) throws ServiceException { String[] customCriteria = persistencePackage.getCustomCriteria(); if (customCriteria != null && customCriteria.length > 0) { LOG.warn("custom persistence handlers and custom criteria not supported for update types other than BASIC"); } PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective(); Entity entity = persistencePackage.getEntity(); MapStructure mapStructure = (MapStructure) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE); if (!mapStructure.getMutable()) { throw new SecurityServiceException("Field not mutable"); } try { Map<String, FieldMetadata> ceilingMergedProperties = getSimpleMergedProperties(entity.getType()[0], persistencePerspective); String mapKey = entity.findProperty(mapStructure.getKeyPropertyName()).getValue(); if (ceilingMergedProperties.containsKey(mapStructure.getMapProperty() + FieldManager.MAPFIELDSEPARATOR + mapKey)) { throw new ServiceException("\"" + mapKey + "\" is a reserved property name."); } Serializable instance = persistenceManager.getDynamicEntityDao().retrieve(Class.forName(entity.getType()[0]), Long.valueOf(entity.findProperty("symbolicId").getValue())); Assert.isTrue(instance != null, "Entity not found"); FieldManager fieldManager = getFieldManager(); Map map = (Map) fieldManager.getFieldValue(instance, mapStructure.getMapProperty()); PersistentClass persistentClass = persistenceManager.getDynamicEntityDao().getPersistentClass(mapStructure.getValueClassName()); Map<String, FieldMetadata> valueUnfilteredMergedProperties; if (persistentClass == null) { valueUnfilteredMergedProperties = persistenceManager.getDynamicEntityDao().getPropertiesForPrimitiveClass( ((SimpleValueMapStructure) mapStructure).getValuePropertyName(), ((SimpleValueMapStructure) mapStructure).getValuePropertyFriendlyName(), Class.forName(mapStructure.getValueClassName()), Class.forName(entity.getType()[0]), MergedPropertyType.MAPSTRUCTUREVALUE ); } else { valueUnfilteredMergedProperties = persistenceManager.getDynamicEntityDao().getMergedProperties( mapStructure.getValueClassName(), new Class[]{Class.forName(mapStructure.getValueClassName())}, null, new String[]{}, new ForeignKey[]{}, MergedPropertyType.MAPSTRUCTUREVALUE, persistencePerspective.getPopulateToOneFields(), persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(), persistencePerspective.getConfigurationKey(), "" ); } Map<String, FieldMetadata> valueMergedProperties = filterOutCollectionMetadata(valueUnfilteredMergedProperties); if (StringUtils.isEmpty(mapKey)) { entity.addValidationError(mapStructure.getKeyPropertyName(), RequiredPropertyValidator.ERROR_MESSAGE); LOG.debug("No key property passed in for map, failing validation"); } if (persistentClass != null) { Serializable valueInstance = (Serializable) map.get(entity.findProperty("priorKey").getValue()); if (map.get(mapKey) != null && !map.get(mapKey).equals(valueInstance)) { entity.addValidationError(mapStructure.getKeyPropertyName(), "keyExistsValidationError"); } if (StringUtils.isNotBlank(mapStructure.getMapKeyValueProperty())) { Property p = entity.findProperty("key"); Property newP = new Property(); newP.setName(mapStructure.getMapKeyValueProperty()); newP.setValue(p.getValue()); newP.setIsDirty(p.getIsDirty()); entity.addProperty(newP); } //allow validation on other properties in order to show key validation errors along with all the other properties //validation errors valueInstance = createPopulatedInstance(valueInstance, entity, valueMergedProperties, false); if (StringUtils.isNotEmpty(mapKey) && !entity.isValidationFailure()) { if (!entity.findProperty("priorKey").getValue().equals(mapKey)) { map.remove(entity.findProperty("priorKey").getValue()); } /* * TODO this map manipulation code currently assumes the key value is a String. This should be widened to accept * additional types of primitive objects. */ map.put(entity.findProperty(mapStructure.getKeyPropertyName()).getValue(), valueInstance); } } else { if (StringUtils.isNotEmpty(mapKey) && !entity.isValidationFailure()) { map.put(entity.findProperty(mapStructure.getKeyPropertyName()).getValue(), entity.findProperty(((SimpleValueMapStructure) mapStructure).getValuePropertyName()).getValue()); } } instance = persistenceManager.getDynamicEntityDao().merge(instance); Entity[] responses = getMapRecords(instance, mapStructure, ceilingMergedProperties, valueMergedProperties, entity.findProperty("symbolicId")); for (Entity response : responses) { if (response.findProperty(mapStructure.getKeyPropertyName()).getValue().equals(persistencePackage.getEntity().findProperty(mapStructure.getKeyPropertyName()).getValue())) { return response; } } return responses[0]; } catch (Exception e) { throw new ServiceException("Problem updating entity : " + e.getMessage(), e); } } @Override public void remove(PersistencePackage persistencePackage) throws ServiceException { String[] customCriteria = persistencePackage.getCustomCriteria(); if (customCriteria != null && customCriteria.length > 0) { LOG.warn("custom persistence handlers and custom criteria not supported for remove types other than BASIC"); } PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective(); Entity entity = persistencePackage.getEntity(); MapStructure mapStructure = (MapStructure) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE); if (!mapStructure.getMutable()) { throw new SecurityServiceException("Field not mutable"); } try { Map<String, FieldMetadata> ceilingMergedProperties = getSimpleMergedProperties(entity.getType()[0], persistencePerspective); String mapKey = entity.findProperty(mapStructure.getKeyPropertyName()).getValue(); if (ceilingMergedProperties.containsKey(mapStructure.getMapProperty() + FieldManager.MAPFIELDSEPARATOR + mapKey)) { throw new ServiceException("\"" + mapKey + "\" is a reserved property name."); } Serializable instance = persistenceManager.getDynamicEntityDao().retrieve(Class.forName(entity.getType()[0]), Long.valueOf(entity.findProperty("symbolicId").getValue())); Assert.isTrue(instance != null, "Entity not found"); FieldManager fieldManager = getFieldManager(); Map map = (Map) fieldManager.getFieldValue(instance, mapStructure.getMapProperty()); Object value = map.remove(entity.findProperty("priorKey").getValue()); if (mapStructure.getDeleteValueEntity()) { persistenceManager.getDynamicEntityDao().remove((Serializable) value); } } catch (Exception e) { throw new ServiceException("Problem removing entity : " + e.getMessage(), e); } } @Override public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto) throws ServiceException { Entity[] payload; int totalRecords; String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname(); if (StringUtils.isEmpty(persistencePackage.getFetchTypeFullyQualifiedClassname())) { persistencePackage.setFetchTypeFullyQualifiedClassname(ceilingEntityFullyQualifiedClassname); } try { PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective(); Class<?>[] entities = persistenceManager.getPolymorphicEntities(ceilingEntityFullyQualifiedClassname); Map<String, FieldMetadata> mergedProperties = persistenceManager.getDynamicEntityDao().getMergedProperties( ceilingEntityFullyQualifiedClassname, entities, (ForeignKey) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.FOREIGNKEY), persistencePerspective.getAdditionalNonPersistentProperties(), persistencePerspective.getAdditionalForeignKeys(), MergedPropertyType.PRIMARY, persistencePerspective.getPopulateToOneFields(), persistencePerspective.getIncludeFields(), persistencePerspective.getExcludeFields(), persistencePerspective.getConfigurationKey(), "" ); MapStructure mapStructure = (MapStructure) persistencePerspective.getPersistencePerspectiveItems().get(PersistencePerspectiveItemType.MAPSTRUCTURE); PersistentClass persistentClass = persistenceManager.getDynamicEntityDao().getPersistentClass(mapStructure.getValueClassName()); Map<String, FieldMetadata> valueUnfilteredMergedProperties; if (persistentClass == null) { valueUnfilteredMergedProperties = persistenceManager.getDynamicEntityDao().getPropertiesForPrimitiveClass( ((SimpleValueMapStructure) mapStructure).getValuePropertyName(), ((SimpleValueMapStructure) mapStructure).getValuePropertyFriendlyName(), Class.forName(mapStructure.getValueClassName()), Class.forName(ceilingEntityFullyQualifiedClassname), MergedPropertyType.MAPSTRUCTUREVALUE ); } else { valueUnfilteredMergedProperties = persistenceManager.getDynamicEntityDao().getMergedProperties( mapStructure.getValueClassName(), new Class[]{Class.forName(mapStructure.getValueClassName())}, null, new String[]{}, new ForeignKey[]{}, MergedPropertyType.MAPSTRUCTUREVALUE, false, new String[]{}, new String[]{}, null, "" ); } Map<String, FieldMetadata> valueMergedProperties = filterOutCollectionMetadata(valueUnfilteredMergedProperties); List<FilterMapping> filterMappings = getFilterMappings(persistencePerspective, cto, persistencePackage .getFetchTypeFullyQualifiedClassname(), mergedProperties); totalRecords = getTotalRecords(persistencePackage.getFetchTypeFullyQualifiedClassname(), filterMappings); if (totalRecords > 1) { throw new ServiceException("Queries to retrieve an entity containing a MapStructure must return only 1 entity. Your query returned ("+totalRecords+") values."); } List<Serializable> records = getPersistentRecords(persistencePackage.getFetchTypeFullyQualifiedClassname(), filterMappings, cto.getFirstResult(), cto.getMaxResults()); Map<String, FieldMetadata> ceilingMergedProperties = getSimpleMergedProperties(ceilingEntityFullyQualifiedClassname, persistencePerspective); payload = getMapRecords(records.get(0), mapStructure, ceilingMergedProperties, valueMergedProperties, null); } catch (Exception e) { throw new ServiceException("Unable to fetch results for " + ceilingEntityFullyQualifiedClassname, e); } DynamicResultSet results = new DynamicResultSet(null, payload, payload.length); return results; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_MapStructurePersistenceModule.java
2,788
public class VersionTypeTests extends ElasticsearchTestCase { @Test public void testInternalVersionConflict() throws Exception { assertFalse(VersionType.INTERNAL.isVersionConflict(10, Versions.MATCH_ANY)); // if we don't have a version in the index we accept everything assertFalse(VersionType.INTERNAL.isVersionConflict(Versions.NOT_SET, 10)); assertFalse(VersionType.INTERNAL.isVersionConflict(Versions.NOT_SET, Versions.MATCH_ANY)); // if we didn't find a version (but the index does support it), we don't like it unless MATCH_ANY assertTrue(VersionType.INTERNAL.isVersionConflict(Versions.NOT_FOUND, Versions.NOT_FOUND)); assertTrue(VersionType.INTERNAL.isVersionConflict(Versions.NOT_FOUND, 10)); assertFalse(VersionType.INTERNAL.isVersionConflict(Versions.NOT_FOUND, Versions.MATCH_ANY)); // and the stupid usual case assertFalse(VersionType.INTERNAL.isVersionConflict(10, 10)); assertTrue(VersionType.INTERNAL.isVersionConflict(9, 10)); assertTrue(VersionType.INTERNAL.isVersionConflict(10, 9)); // Old indexing code, dictating behavior // if (expectedVersion != Versions.MATCH_ANY && currentVersion != Versions.NOT_SET) { // // an explicit version is provided, see if there is a conflict // // if we did not find anything, and a version is provided, so we do expect to find a doc under that version // // this is important, since we don't allow to preset a version in order to handle deletes // if (currentVersion == Versions.NOT_FOUND) { // throw new VersionConflictEngineException(shardId, index.type(), index.id(), Versions.NOT_FOUND, expectedVersion); // } else if (expectedVersion != currentVersion) { // throw new VersionConflictEngineException(shardId, index.type(), index.id(), currentVersion, expectedVersion); // } // } // updatedVersion = (currentVersion == Versions.NOT_SET || currentVersion == Versions.NOT_FOUND) ? 1 : currentVersion + 1; } @Test public void testExternalVersionConflict() throws Exception { assertFalse(VersionType.EXTERNAL.isVersionConflict(Versions.NOT_FOUND, 10)); assertFalse(VersionType.EXTERNAL.isVersionConflict(Versions.NOT_SET, 10)); // MATCH_ANY must throw an exception in the case of external version, as the version must be set! it used as the new value assertTrue(VersionType.EXTERNAL.isVersionConflict(10, Versions.MATCH_ANY)); // if we didn't find a version (but the index does support it), we always accept assertFalse(VersionType.EXTERNAL.isVersionConflict(Versions.NOT_FOUND, Versions.NOT_FOUND)); assertFalse(VersionType.EXTERNAL.isVersionConflict(Versions.NOT_FOUND, 10)); assertFalse(VersionType.EXTERNAL.isVersionConflict(Versions.NOT_FOUND, Versions.MATCH_ANY)); // and the standard behavior assertTrue(VersionType.EXTERNAL.isVersionConflict(10, 10)); assertFalse(VersionType.EXTERNAL.isVersionConflict(9, 10)); assertTrue(VersionType.EXTERNAL.isVersionConflict(10, 9)); // Old indexing code, dictating behavior // // an external version is provided, just check, if a local version exists, that its higher than it // // the actual version checking is one in an external system, and we just want to not index older versions // if (currentVersion >= 0) { // we can check!, its there // if (currentVersion >= index.version()) { // throw new VersionConflictEngineException(shardId, index.type(), index.id(), currentVersion, index.version()); // } // } // updatedVersion = index.version(); } @Test public void testUpdateVersion() { assertThat(VersionType.INTERNAL.updateVersion(Versions.NOT_SET, 10), equalTo(1l)); assertThat(VersionType.INTERNAL.updateVersion(Versions.NOT_FOUND, 10), equalTo(1l)); assertThat(VersionType.INTERNAL.updateVersion(1, 1), equalTo(2l)); assertThat(VersionType.INTERNAL.updateVersion(2, Versions.MATCH_ANY), equalTo(3l)); assertThat(VersionType.EXTERNAL.updateVersion(Versions.NOT_SET, 10), equalTo(10l)); assertThat(VersionType.EXTERNAL.updateVersion(Versions.NOT_FOUND, 10), equalTo(10l)); assertThat(VersionType.EXTERNAL.updateVersion(1, 10), equalTo(10l)); // Old indexing code // if (index.versionType() == VersionType.INTERNAL) { // internal version type // updatedVersion = (currentVersion == Versions.NOT_SET || currentVersion == Versions.NOT_FOUND) ? 1 : currentVersion + 1; // } else { // external version type // updatedVersion = expectedVersion; // } } }
0true
src_test_java_org_elasticsearch_index_VersionTypeTests.java
144
private static final class CharsetCorrection implements IMarkerResolution, IMarkerResolution2 { private final IProject project; private final String encoding; private CharsetCorrection(IProject project, String encoding) { this.project = project; this.encoding = encoding; } @Override public void run(IMarker marker) { CeylonEncodingSynchronizer.getInstance() .updateEncoding(project, encoding); } @Override public String getLabel() { return "change project character encoding to " + encoding; } @Override public String getDescription() { return null; } @Override public Image getImage() { return CeylonLabelProvider.MINOR_CHANGE; } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_MarkerResolutionGenerator.java
172
public abstract class DistributedStoreManagerTest<T extends DistributedStoreManager> { protected T manager; protected KeyColumnValueStore store; @Test @Category({ OrderedKeyStoreTests.class }) public void testGetDeployment() { assertEquals(Deployment.LOCAL, manager.getDeployment()); } @Test @Category({ OrderedKeyStoreTests.class }) public void testGetLocalKeyPartition() throws BackendException { List<KeyRange> local = manager.getLocalKeyPartition(); assertNotNull(local); assertEquals(1, local.size()); assertNotNull(local.get(0).getStart()); assertNotNull(local.get(0).getEnd()); } }
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_DistributedStoreManagerTest.java
4,444
public static class FieldDataWeigher implements Weigher<Key, AtomicFieldData> { @Override public int weigh(Key key, AtomicFieldData fieldData) { int weight = (int) Math.min(fieldData.getMemorySizeInBytes(), Integer.MAX_VALUE); return weight == 0 ? 1 : weight; } }
1no label
src_main_java_org_elasticsearch_indices_fielddata_cache_IndicesFieldDataCache.java
523
public class BLCRequestUtils { private static String OK_TO_USE_SESSION = "blOkToUseSession"; /** * Broadleaf "Resolver" and "Filter" classes may need to know if they are allowed to utilize the session. * BLC uses a pattern where we will store an attribute in the request indicating whether or not the * session can be used. For example, when using the REST APIs, we typically do not want to utilize the * session. * */ public static boolean isOKtoUseSession(WebRequest request) { Boolean useSessionForRequestProcessing = (Boolean) request.getAttribute(OK_TO_USE_SESSION, WebRequest.SCOPE_REQUEST); if (useSessionForRequestProcessing == null) { // by default we will use the session return true; } else { return useSessionForRequestProcessing.booleanValue(); } } /** * Sets whether or not Broadleaf can utilize the session in request processing. Used by the REST API * flow so that RESTful calls do not utilize the session. * */ public static void setOKtoUseSession(WebRequest request, Boolean value) { request.setAttribute(OK_TO_USE_SESSION, value, WebRequest.SCOPE_REQUEST); } /** * Get header or url parameter. Will obtain the parameter from a header variable or a URL parameter, preferring * header values if they are set. * */ public static String getURLorHeaderParameter(WebRequest request, String varName) { String returnValue = request.getHeader(varName); if (returnValue == null) { returnValue = request.getParameter(varName); } return returnValue; } }
0true
common_src_main_java_org_broadleafcommerce_common_util_BLCRequestUtils.java
3,427
public static interface RecoveryListener { void onRecoveryDone(); void onIgnoreRecovery(String reason); void onRecoveryFailed(IndexShardGatewayRecoveryException e); }
0true
src_main_java_org_elasticsearch_index_gateway_IndexShardGatewayService.java
21
public class InMemoryLogBuffer implements LogBuffer, ReadableByteChannel { private byte[] bytes = new byte[1000]; private int writeIndex; private int readIndex; private ByteBuffer bufferForConversions = ByteBuffer.wrap( new byte[100] ); public InMemoryLogBuffer() { } public void reset() { writeIndex = readIndex = 0; } private void ensureArrayCapacityPlus( int plus ) { while ( writeIndex+plus > bytes.length ) { byte[] tmp = bytes; bytes = new byte[bytes.length*2]; System.arraycopy( tmp, 0, bytes, 0, tmp.length ); } } private LogBuffer flipAndPut() { ensureArrayCapacityPlus( bufferForConversions.limit() ); System.arraycopy( bufferForConversions.flip().array(), 0, bytes, writeIndex, bufferForConversions.limit() ); writeIndex += bufferForConversions.limit(); return this; } public LogBuffer put( byte b ) throws IOException { ensureArrayCapacityPlus( 1 ); bytes[writeIndex++] = b; return this; } public LogBuffer putShort( short s ) throws IOException { ((ByteBuffer) bufferForConversions.clear()).putShort( s ); return flipAndPut(); } public LogBuffer putInt( int i ) throws IOException { ((ByteBuffer) bufferForConversions.clear()).putInt( i ); return flipAndPut(); } public LogBuffer putLong( long l ) throws IOException { ((ByteBuffer) bufferForConversions.clear()).putLong( l ); return flipAndPut(); } public LogBuffer putFloat( float f ) throws IOException { ((ByteBuffer) bufferForConversions.clear()).putFloat( f ); return flipAndPut(); } public LogBuffer putDouble( double d ) throws IOException { ((ByteBuffer) bufferForConversions.clear()).putDouble( d ); return flipAndPut(); } public LogBuffer put( byte[] bytes ) throws IOException { ensureArrayCapacityPlus( bytes.length ); System.arraycopy( bytes, 0, this.bytes, writeIndex, bytes.length ); writeIndex += bytes.length; return this; } public LogBuffer put( char[] chars ) throws IOException { ensureConversionBufferCapacity( chars.length*2 ); bufferForConversions.clear(); for ( char ch : chars ) { bufferForConversions.putChar( ch ); } return flipAndPut(); } private void ensureConversionBufferCapacity( int length ) { if ( bufferForConversions.capacity() < length ) { bufferForConversions = ByteBuffer.wrap( new byte[length*2] ); } } @Override public void writeOut() throws IOException { } public void force() throws IOException { } public long getFileChannelPosition() throws IOException { return this.readIndex; } public StoreChannel getFileChannel() { throw new UnsupportedOperationException(); } public boolean isOpen() { return true; } public void close() throws IOException { } public int read( ByteBuffer dst ) throws IOException { if ( readIndex >= writeIndex ) { return -1; } int actualLengthToRead = Math.min( dst.limit(), writeIndex-readIndex ); try { dst.put( bytes, readIndex, actualLengthToRead ); return actualLengthToRead; } finally { readIndex += actualLengthToRead; } } }
1no label
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_InMemoryLogBuffer.java
355
public class NodeStats extends NodeOperationResponse implements ToXContent { private long timestamp; @Nullable private NodeIndicesStats indices; @Nullable private OsStats os; @Nullable private ProcessStats process; @Nullable private JvmStats jvm; @Nullable private ThreadPoolStats threadPool; @Nullable private NetworkStats network; @Nullable private FsStats fs; @Nullable private TransportStats transport; @Nullable private HttpStats http; @Nullable private FieldDataBreakerStats breaker; NodeStats() { } public NodeStats(DiscoveryNode node, long timestamp, @Nullable NodeIndicesStats indices, @Nullable OsStats os, @Nullable ProcessStats process, @Nullable JvmStats jvm, @Nullable ThreadPoolStats threadPool, @Nullable NetworkStats network, @Nullable FsStats fs, @Nullable TransportStats transport, @Nullable HttpStats http, @Nullable FieldDataBreakerStats breaker) { super(node); this.timestamp = timestamp; this.indices = indices; this.os = os; this.process = process; this.jvm = jvm; this.threadPool = threadPool; this.network = network; this.fs = fs; this.transport = transport; this.http = http; this.breaker = breaker; } public long getTimestamp() { return this.timestamp; } @Nullable public String getHostname() { return getNode().getHostName(); } /** * Indices level stats. */ @Nullable public NodeIndicesStats getIndices() { return this.indices; } /** * Operating System level statistics. */ @Nullable public OsStats getOs() { return this.os; } /** * Process level statistics. */ @Nullable public ProcessStats getProcess() { return process; } /** * JVM level statistics. */ @Nullable public JvmStats getJvm() { return jvm; } /** * Thread Pool level statistics. */ @Nullable public ThreadPoolStats getThreadPool() { return this.threadPool; } /** * Network level statistics. */ @Nullable public NetworkStats getNetwork() { return network; } /** * File system level stats. */ @Nullable public FsStats getFs() { return fs; } @Nullable public TransportStats getTransport() { return this.transport; } @Nullable public HttpStats getHttp() { return this.http; } @Nullable public FieldDataBreakerStats getBreaker() { return this.breaker; } public static NodeStats readNodeStats(StreamInput in) throws IOException { NodeStats nodeInfo = new NodeStats(); nodeInfo.readFrom(in); return nodeInfo; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); timestamp = in.readVLong(); if (in.readBoolean()) { indices = NodeIndicesStats.readIndicesStats(in); } if (in.readBoolean()) { os = OsStats.readOsStats(in); } if (in.readBoolean()) { process = ProcessStats.readProcessStats(in); } if (in.readBoolean()) { jvm = JvmStats.readJvmStats(in); } if (in.readBoolean()) { threadPool = ThreadPoolStats.readThreadPoolStats(in); } if (in.readBoolean()) { network = NetworkStats.readNetworkStats(in); } if (in.readBoolean()) { fs = FsStats.readFsStats(in); } if (in.readBoolean()) { transport = TransportStats.readTransportStats(in); } if (in.readBoolean()) { http = HttpStats.readHttpStats(in); } breaker = FieldDataBreakerStats.readOptionalCircuitBreakerStats(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVLong(timestamp); if (indices == null) { out.writeBoolean(false); } else { out.writeBoolean(true); indices.writeTo(out); } if (os == null) { out.writeBoolean(false); } else { out.writeBoolean(true); os.writeTo(out); } if (process == null) { out.writeBoolean(false); } else { out.writeBoolean(true); process.writeTo(out); } if (jvm == null) { out.writeBoolean(false); } else { out.writeBoolean(true); jvm.writeTo(out); } if (threadPool == null) { out.writeBoolean(false); } else { out.writeBoolean(true); threadPool.writeTo(out); } if (network == null) { out.writeBoolean(false); } else { out.writeBoolean(true); network.writeTo(out); } if (fs == null) { out.writeBoolean(false); } else { out.writeBoolean(true); fs.writeTo(out); } if (transport == null) { out.writeBoolean(false); } else { out.writeBoolean(true); transport.writeTo(out); } if (http == null) { out.writeBoolean(false); } else { out.writeBoolean(true); http.writeTo(out); } out.writeOptionalStreamable(breaker); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { if (!params.param("node_info_format", "default").equals("none")) { builder.field("name", getNode().name(), XContentBuilder.FieldCaseConversion.NONE); builder.field("transport_address", getNode().address().toString(), XContentBuilder.FieldCaseConversion.NONE); builder.field("host", getNode().getHostName(), XContentBuilder.FieldCaseConversion.NONE); builder.field("ip", getNode().getAddress(), XContentBuilder.FieldCaseConversion.NONE); if (!getNode().attributes().isEmpty()) { builder.startObject("attributes"); for (Map.Entry<String, String> attr : getNode().attributes().entrySet()) { builder.field(attr.getKey(), attr.getValue(), XContentBuilder.FieldCaseConversion.NONE); } builder.endObject(); } } if (getIndices() != null) { getIndices().toXContent(builder, params); } if (getOs() != null) { getOs().toXContent(builder, params); } if (getProcess() != null) { getProcess().toXContent(builder, params); } if (getJvm() != null) { getJvm().toXContent(builder, params); } if (getThreadPool() != null) { getThreadPool().toXContent(builder, params); } if (getNetwork() != null) { getNetwork().toXContent(builder, params); } if (getFs() != null) { getFs().toXContent(builder, params); } if (getTransport() != null) { getTransport().toXContent(builder, params); } if (getHttp() != null) { getHttp().toXContent(builder, params); } if (getBreaker() != null) { getBreaker().toXContent(builder, params); } return builder; } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_stats_NodeStats.java
362
public static class GroupingTestMapper implements Mapper<Integer, Integer, String, Integer> { @Override public void map(Integer key, Integer value, Context<String, Integer> collector) { collector.emit(String.valueOf(key % 4), value); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_ClientMapReduceTest.java
1,798
public interface Binder { /** * Binds a scope to an annotation. */ void bindScope(Class<? extends Annotation> annotationType, Scope scope); /** * See the EDSL examples at {@link Binder}. */ <T> LinkedBindingBuilder<T> bind(Key<T> key); /** * See the EDSL examples at {@link Binder}. */ <T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral); /** * See the EDSL examples at {@link Binder}. */ <T> AnnotatedBindingBuilder<T> bind(Class<T> type); /** * See the EDSL examples at {@link Binder}. */ AnnotatedConstantBindingBuilder bindConstant(); /** * Upon successful creation, the {@link Injector} will inject instance fields * and methods of the given object. * * @param type of instance * @param instance for which members will be injected * @since 2.0 */ <T> void requestInjection(TypeLiteral<T> type, T instance); /** * Upon successful creation, the {@link Injector} will inject instance fields * and methods of the given object. * * @param instance for which members will be injected * @since 2.0 */ void requestInjection(Object instance); /** * Upon successful creation, the {@link Injector} will inject static fields * and methods in the given classes. * * @param types for which static members will be injected */ void requestStaticInjection(Class<?>... types); /** * Uses the given module to configure more bindings. */ void install(Module module); /** * Gets the current stage. */ Stage currentStage(); /** * Records an error message which will be presented to the user at a later * time. Unlike throwing an exception, this enable us to continue * configuring the Injector and discover more errors. Uses {@link * String#format(String, Object[])} to insert the arguments into the * message. */ void addError(String message, Object... arguments); /** * Records an exception, the full details of which will be logged, and the * message of which will be presented to the user at a later * time. If your Module calls something that you worry may fail, you should * catch the exception and pass it into this. */ void addError(Throwable t); /** * Records an error message to be presented to the user at a later time. * * @since 2.0 */ void addError(Message message); /** * Returns the provider used to obtain instances for the given injection key. * The returned will not be valid until the {@link Injector} has been * created. The provider will throw an {@code IllegalStateException} if you * try to use it beforehand. * * @since 2.0 */ <T> Provider<T> getProvider(Key<T> key); /** * Returns the provider used to obtain instances for the given injection type. * The returned provider will not be valid until the {@link Injector} has been * created. The provider will throw an {@code IllegalStateException} if you * try to use it beforehand. * * @since 2.0 */ <T> Provider<T> getProvider(Class<T> type); /** * Returns the members injector used to inject dependencies into methods and fields on instances * of the given type {@code T}. The returned members injector will not be valid until the main * {@link Injector} has been created. The members injector will throw an {@code * IllegalStateException} if you try to use it beforehand. * * @param typeLiteral type to get members injector for * @since 2.0 */ <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> typeLiteral); /** * Returns the members injector used to inject dependencies into methods and fields on instances * of the given type {@code T}. The returned members injector will not be valid until the main * {@link Injector} has been created. The members injector will throw an {@code * IllegalStateException} if you try to use it beforehand. * * @param type type to get members injector for * @since 2.0 */ <T> MembersInjector<T> getMembersInjector(Class<T> type); /** * Binds a type converter. The injector will use the given converter to * convert string constants to matching types as needed. * * @param typeMatcher matches types the converter can handle * @param converter converts values * @since 2.0 */ void convertToTypes(Matcher<? super TypeLiteral<?>> typeMatcher, TypeConverter converter); /** * Registers a listener for injectable types. Guice will notify the listener when it encounters * injectable types matched by the given type matcher. * * @param typeMatcher that matches injectable types the listener should be notified of * @param listener for injectable types matched by typeMatcher * @since 2.0 */ void bindListener(Matcher<? super TypeLiteral<?>> typeMatcher, TypeListener listener); /** * Returns a binder that uses {@code source} as the reference location for * configuration errors. This is typically a {@link StackTraceElement} * for {@code .java} source but it could any binding source, such as the * path to a {@code .properties} file. * * @param source any object representing the source location and has a * concise {@link Object#toString() toString()} value * @return a binder that shares its configuration with this binder * @since 2.0 */ Binder withSource(Object source); /** * Returns a binder that skips {@code classesToSkip} when identify the * calling code. The caller's {@link StackTraceElement} is used to locate * the source of configuration errors. * * @param classesToSkip library classes that create bindings on behalf of * their clients. * @return a binder that shares its configuration with this binder. * @since 2.0 */ Binder skipSources(Class... classesToSkip); /** * Creates a new private child environment for bindings and other configuration. The returned * binder can be used to add and configuration information in this environment. See {@link * PrivateModule} for details. * * @return a binder that inherits configuration from this binder. Only exposed configuration on * the returned binder will be visible to this binder. * @since 2.0 */ PrivateBinder newPrivateBinder(); }
0true
src_main_java_org_elasticsearch_common_inject_Binder.java
145
{ @Override public void bytesWritten( long numberOfBytes ) { bytesWritten.addAndGet( numberOfBytes ); } @Override public void bytesRead( long numberOfBytes ) { } } );
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestDirectMappedLogBuffer.java
1,210
public class ODefaultClusterFactory implements OClusterFactory { protected static final String[] TYPES = { OClusterLocal.TYPE, OClusterMemory.TYPE }; public OCluster createCluster(final String iType) { if (iType.equalsIgnoreCase(OClusterLocal.TYPE)) return new OClusterLocal(); else if (iType.equalsIgnoreCase(OClusterMemory.TYPE)) return new OClusterMemoryArrayList(); else OLogManager.instance().exception( "Cluster type '" + iType + "' is not supported. Supported types are: " + Arrays.toString(TYPES), null, OStorageException.class); return null; } public OCluster createCluster(final OStorageClusterConfiguration iConfig) { if (iConfig instanceof OStoragePhysicalClusterConfigurationLocal) return new OClusterLocal(); else if (iConfig instanceof OStorageMemoryClusterConfiguration) return new OClusterMemoryArrayList(); else if (iConfig instanceof OStorageMemoryLinearHashingClusterConfiguration) return new OClusterMemoryHashing(); else OLogManager.instance().exception( "Cluster type '" + iConfig + "' is not supported. Supported types are: " + Arrays.toString(TYPES), null, OStorageException.class); return null; } public String[] getSupported() { return TYPES; } @Override public boolean isSupported(final String iClusterType) { for (String type : TYPES) if (type.equalsIgnoreCase(iClusterType)) return true; return false; } }
0true
core_src_main_java_com_orientechnologies_orient_core_storage_ODefaultClusterFactory.java
296
public class TimestampParsingException extends ElasticsearchException { private final String timestamp; public TimestampParsingException(String timestamp) { super("failed to parse timestamp [" + timestamp + "]"); this.timestamp = timestamp; } public String timestamp() { return timestamp; } }
1no label
src_main_java_org_elasticsearch_action_TimestampParsingException.java
1,315
checkpointExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); return thread; } });
0true
core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_OLocalPaginatedStorage.java
1,066
public class ODefaultCommandExecutorSQLFactory implements OCommandExecutorSQLFactory { private static final Map<String, Class<? extends OCommandExecutorSQLAbstract>> COMMANDS; static { // COMMANDS final Map<String, Class<? extends OCommandExecutorSQLAbstract>> commands = new HashMap<String, Class<? extends OCommandExecutorSQLAbstract>>(); commands.put(OCommandExecutorSQLAlterDatabase.KEYWORD_ALTER + " " + OCommandExecutorSQLAlterDatabase.KEYWORD_DATABASE, OCommandExecutorSQLAlterDatabase.class); commands.put(OCommandExecutorSQLSelect.KEYWORD_SELECT, OCommandExecutorSQLSelect.class); commands.put(OCommandExecutorSQLTraverse.KEYWORD_TRAVERSE, OCommandExecutorSQLTraverse.class); commands.put(OCommandExecutorSQLInsert.KEYWORD_INSERT, OCommandExecutorSQLInsert.class); commands.put(OCommandExecutorSQLUpdate.KEYWORD_UPDATE, OCommandExecutorSQLUpdate.class); commands.put(OCommandExecutorSQLDelete.NAME, OCommandExecutorSQLDelete.class); commands.put(OCommandExecutorSQLCreateFunction.NAME, OCommandExecutorSQLCreateFunction.class); commands.put(OCommandExecutorSQLGrant.KEYWORD_GRANT, OCommandExecutorSQLGrant.class); commands.put(OCommandExecutorSQLRevoke.KEYWORD_REVOKE, OCommandExecutorSQLRevoke.class); commands.put(OCommandExecutorSQLCreateLink.KEYWORD_CREATE + " " + OCommandExecutorSQLCreateLink.KEYWORD_LINK, OCommandExecutorSQLCreateLink.class); commands.put(OCommandExecutorSQLCreateIndex.KEYWORD_CREATE + " " + OCommandExecutorSQLCreateIndex.KEYWORD_INDEX, OCommandExecutorSQLCreateIndex.class); commands.put(OCommandExecutorSQLDropIndex.KEYWORD_DROP + " " + OCommandExecutorSQLDropIndex.KEYWORD_INDEX, OCommandExecutorSQLDropIndex.class); commands.put(OCommandExecutorSQLRebuildIndex.KEYWORD_REBUILD + " " + OCommandExecutorSQLRebuildIndex.KEYWORD_INDEX, OCommandExecutorSQLRebuildIndex.class); commands.put(OCommandExecutorSQLCreateClass.KEYWORD_CREATE + " " + OCommandExecutorSQLCreateClass.KEYWORD_CLASS, OCommandExecutorSQLCreateClass.class); commands.put(OCommandExecutorSQLCreateCluster.KEYWORD_CREATE + " " + OCommandExecutorSQLCreateCluster.KEYWORD_CLUSTER, OCommandExecutorSQLCreateCluster.class); commands.put(OCommandExecutorSQLAlterClass.KEYWORD_ALTER + " " + OCommandExecutorSQLAlterClass.KEYWORD_CLASS, OCommandExecutorSQLAlterClass.class); commands.put(OCommandExecutorSQLCreateProperty.KEYWORD_CREATE + " " + OCommandExecutorSQLCreateProperty.KEYWORD_PROPERTY, OCommandExecutorSQLCreateProperty.class); commands.put(OCommandExecutorSQLAlterProperty.KEYWORD_ALTER + " " + OCommandExecutorSQLAlterProperty.KEYWORD_PROPERTY, OCommandExecutorSQLAlterProperty.class); commands.put(OCommandExecutorSQLDropCluster.KEYWORD_DROP + " " + OCommandExecutorSQLDropCluster.KEYWORD_CLUSTER, OCommandExecutorSQLDropCluster.class); commands.put(OCommandExecutorSQLDropClass.KEYWORD_DROP + " " + OCommandExecutorSQLDropClass.KEYWORD_CLASS, OCommandExecutorSQLDropClass.class); commands.put(OCommandExecutorSQLDropProperty.KEYWORD_DROP + " " + OCommandExecutorSQLDropProperty.KEYWORD_PROPERTY, OCommandExecutorSQLDropProperty.class); commands.put(OCommandExecutorSQLFindReferences.KEYWORD_FIND + " " + OCommandExecutorSQLFindReferences.KEYWORD_REFERENCES, OCommandExecutorSQLFindReferences.class); commands.put(OCommandExecutorSQLTruncateClass.KEYWORD_TRUNCATE + " " + OCommandExecutorSQLTruncateClass.KEYWORD_CLASS, OCommandExecutorSQLTruncateClass.class); commands.put(OCommandExecutorSQLTruncateCluster.KEYWORD_TRUNCATE + " " + OCommandExecutorSQLTruncateCluster.KEYWORD_CLUSTER, OCommandExecutorSQLTruncateCluster.class); commands.put(OCommandExecutorSQLTruncateRecord.KEYWORD_TRUNCATE + " " + OCommandExecutorSQLTruncateRecord.KEYWORD_RECORD, OCommandExecutorSQLTruncateRecord.class); commands.put(OCommandExecutorSQLAlterCluster.KEYWORD_ALTER + " " + OCommandExecutorSQLAlterCluster.KEYWORD_CLUSTER, OCommandExecutorSQLAlterCluster.class); commands.put(OCommandExecutorSQLExplain.KEYWORD_EXPLAIN, OCommandExecutorSQLExplain.class); commands.put(OCommandExecutorSQLTransactional.KEYWORD_TRANSACTIONAL, OCommandExecutorSQLTransactional.class); COMMANDS = Collections.unmodifiableMap(commands); } /** * {@inheritDoc} */ public Set<String> getCommandNames() { return COMMANDS.keySet(); } /** * {@inheritDoc} */ public OCommandExecutorSQLAbstract createCommand(final String name) throws OCommandExecutionException { final Class<? extends OCommandExecutorSQLAbstract> clazz = COMMANDS.get(name); if (clazz == null) { throw new OCommandExecutionException("Unknowned command name :" + name); } try { return clazz.newInstance(); } catch (Exception e) { throw new OCommandExecutionException("Error in creation of command " + name + "(). Probably there is not an empty constructor or the constructor generates errors", e); } } }
0true
core_src_main_java_com_orientechnologies_orient_core_sql_ODefaultCommandExecutorSQLFactory.java
272
public class ServerInfo implements Serializable { private static final long serialVersionUID = 1L; private String serverName; private Integer serverPort; private Integer securePort; private String appName; public String getSecureHost() { StringBuffer sb = new StringBuffer(); sb.append(serverName); if (!securePort.equals("443")) { sb.append(":"); sb.append(securePort); } return sb.toString(); } public String getHost() { StringBuffer sb = new StringBuffer(); sb.append(serverName); if (!serverPort.equals("80")) { sb.append(":"); sb.append(serverPort); } return sb.toString(); } /** * @return the serverName */ public String getServerName() { return serverName; } /** * @param serverName the serverName to set */ public void setServerName(String serverName) { this.serverName = serverName; } /** * @return the serverPort */ public Integer getServerPort() { return serverPort; } /** * @param serverPort the serverPort to set */ public void setServerPort(Integer serverPort) { this.serverPort = serverPort; } /** * @return the securePort */ public Integer getSecurePort() { return securePort; } /** * @param securePort the securePort to set */ public void setSecurePort(Integer securePort) { this.securePort = securePort; } /** * @return the appName */ public String getAppName() { return appName; } /** * @param appName the appName to set */ public void setAppName(String appName) { this.appName = appName; } }
1no label
common_src_main_java_org_broadleafcommerce_common_email_service_info_ServerInfo.java
170
class ValueFunctionDefinitionGenerator extends DefinitionGenerator { private final String brokenName; private final MemberOrTypeExpression node; private final CompilationUnit rootNode; private final String desc; private final Image image; private final ProducedType returnType; private final LinkedHashMap<String, ProducedType> parameters; private final Boolean isVariable; @Override String getBrokenName() { return brokenName; } @Override ProducedType getReturnType() { return returnType; } @Override LinkedHashMap<String, ProducedType> getParameters() { return parameters; } @Override String getDescription() { return desc; } @Override Image getImage() { return image; } @Override Tree.CompilationUnit getRootNode() { return rootNode; } @Override Node getNode() { return node; } private ValueFunctionDefinitionGenerator(String brokenName, Tree.MemberOrTypeExpression node, Tree.CompilationUnit rootNode, String desc, Image image, ProducedType returnType, LinkedHashMap<String, ProducedType> paramTypes, Boolean isVariable) { this.brokenName = brokenName; this.node = node; this.rootNode = rootNode; this.desc = desc; this.image = image; this.returnType = returnType; this.parameters = paramTypes; this.isVariable = isVariable; } String generateShared(String indent, String delim) { return "shared " + generate(indent, delim); } String generate(String indent, String delim) { StringBuffer def = new StringBuffer(); boolean isVoid = returnType==null; Unit unit = node.getUnit(); if (parameters!=null) { List<TypeParameter> typeParams = new ArrayList<TypeParameter>(); StringBuilder typeParamDef = new StringBuilder(); StringBuilder typeParamConstDef = new StringBuilder(); appendTypeParams(typeParams, typeParamDef, typeParamConstDef, returnType); appendTypeParams(typeParams, typeParamDef, typeParamConstDef, parameters.values()); if (typeParamDef.length() > 0) { typeParamDef.insert(0, "<"); typeParamDef.setLength(typeParamDef.length() - 1); typeParamDef.append(">"); } if (isVoid) { def.append("void"); } else { if (isTypeUnknown(returnType)) { def.append("function"); } else { def.append(returnType.getProducedTypeName(unit)); } } def.append(" ") .append(brokenName).append(typeParamDef); appendParameters(parameters, def); def.append(typeParamConstDef); if (isVoid) { def.append(" {}"); } else { //removed because it's ugly for parameters: //delim + indent + defIndent + defIndent + def.append(" => ") .append(defaultValue(unit, returnType)) .append(";"); } } else { if(isVariable){ def.append("variable "); } if (isVoid) { def.append("Anything"); } else { if (isTypeUnknown(returnType)) { def.append("value"); } else { def.append(returnType.getProducedTypeName(unit)); } } def.append(" ") .append(brokenName) .append(" = ") .append(defaultValue(unit, returnType)) .append(";"); } return def.toString(); } Set<Declaration> getImports() { Set<Declaration> imports = new HashSet<Declaration>(); importType(imports, returnType, rootNode); if (parameters!=null) { importTypes(imports, parameters.values(), rootNode); } return imports; } static ValueFunctionDefinitionGenerator create(String brokenName, Tree.MemberOrTypeExpression node, Tree.CompilationUnit rootNode) { boolean isUpperCase = Character.isUpperCase(brokenName.charAt(0)); if (isUpperCase) return null; FindValueFunctionVisitor fav = new FindValueFunctionVisitor(node); rootNode.visit(fav); ProducedType et = fav.expectedType; final boolean isVoid = et==null; ProducedType returnType = isVoid ? null : node.getUnit().denotableType(et); StringBuilder params = new StringBuilder(); LinkedHashMap<String, ProducedType> paramTypes = getParameters(fav); if (paramTypes!=null) { String desc = "function '" + brokenName + params + "'"; return new ValueFunctionDefinitionGenerator(brokenName, node, rootNode, desc, LOCAL_METHOD, returnType, paramTypes, null); } else { String desc = "value '" + brokenName + "'"; return new ValueFunctionDefinitionGenerator(brokenName, node, rootNode, desc, LOCAL_ATTRIBUTE, returnType, null, fav.isVariable); } } private static class FindValueFunctionVisitor extends FindArgumentsVisitor{ boolean isVariable = false; FindValueFunctionVisitor(MemberOrTypeExpression smte) { super(smte); } @Override public void visit(AssignmentOp that) { isVariable = ((Tree.AssignmentOp) that).getLeftTerm() == smte; super.visit(that); } @Override public void visit(UnaryOperatorExpression that) { isVariable = ((Tree.UnaryOperatorExpression) that).getTerm() == smte; super.visit(that); } @Override public void visit(SpecifierStatement that) { isVariable = ((Tree.SpecifierStatement) that).getBaseMemberExpression() == smte; super.visit(that); } } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ValueFunctionDefinitionGenerator.java
2,722
public class LocalGatewayMetaState extends AbstractComponent implements ClusterStateListener { static enum AutoImportDangledState { NO() { @Override public boolean shouldImport() { return false; } }, YES() { @Override public boolean shouldImport() { return true; } }, CLOSED() { @Override public boolean shouldImport() { return true; } }; public abstract boolean shouldImport(); public static AutoImportDangledState fromString(String value) { if ("no".equalsIgnoreCase(value)) { return NO; } else if ("yes".equalsIgnoreCase(value)) { return YES; } else if ("closed".equalsIgnoreCase(value)) { return CLOSED; } else { throw new ElasticsearchIllegalArgumentException("failed to parse [" + value + "], not a valid auto dangling import type"); } } } private final NodeEnvironment nodeEnv; private final ThreadPool threadPool; private final LocalAllocateDangledIndices allocateDangledIndices; private final NodeIndexDeletedAction nodeIndexDeletedAction; @Nullable private volatile MetaData currentMetaData; private final XContentType format; private final ToXContent.Params formatParams; private final ToXContent.Params globalOnlyFormatParams; private final AutoImportDangledState autoImportDangled; private final TimeValue danglingTimeout; private final Map<String, DanglingIndex> danglingIndices = ConcurrentCollections.newConcurrentMap(); private final Object danglingMutex = new Object(); @Inject public LocalGatewayMetaState(Settings settings, ThreadPool threadPool, NodeEnvironment nodeEnv, TransportNodesListGatewayMetaState nodesListGatewayMetaState, LocalAllocateDangledIndices allocateDangledIndices, NodeIndexDeletedAction nodeIndexDeletedAction) throws Exception { super(settings); this.nodeEnv = nodeEnv; this.threadPool = threadPool; this.format = XContentType.fromRestContentType(settings.get("format", "smile")); this.allocateDangledIndices = allocateDangledIndices; this.nodeIndexDeletedAction = nodeIndexDeletedAction; nodesListGatewayMetaState.init(this); if (this.format == XContentType.SMILE) { Map<String, String> params = Maps.newHashMap(); params.put("binary", "true"); formatParams = new ToXContent.MapParams(params); Map<String, String> globalOnlyParams = Maps.newHashMap(); globalOnlyParams.put("binary", "true"); globalOnlyParams.put(MetaData.GLOBAL_PERSISTENT_ONLY_PARAM, "true"); globalOnlyFormatParams = new ToXContent.MapParams(globalOnlyParams); } else { formatParams = ToXContent.EMPTY_PARAMS; Map<String, String> globalOnlyParams = Maps.newHashMap(); globalOnlyParams.put(MetaData.GLOBAL_PERSISTENT_ONLY_PARAM, "true"); globalOnlyFormatParams = new ToXContent.MapParams(globalOnlyParams); } this.autoImportDangled = AutoImportDangledState.fromString(settings.get("gateway.local.auto_import_dangled", AutoImportDangledState.YES.toString())); this.danglingTimeout = settings.getAsTime("gateway.local.dangling_timeout", TimeValue.timeValueHours(2)); logger.debug("using gateway.local.auto_import_dangled [{}], with gateway.local.dangling_timeout [{}]", this.autoImportDangled, this.danglingTimeout); if (DiscoveryNode.masterNode(settings)) { try { pre019Upgrade(); long start = System.currentTimeMillis(); loadState(); logger.debug("took {} to load state", TimeValue.timeValueMillis(System.currentTimeMillis() - start)); } catch (Exception e) { logger.error("failed to read local state, exiting...", e); throw e; } } } public MetaData loadMetaState() throws Exception { return loadState(); } public boolean isDangling(String index) { return danglingIndices.containsKey(index); } @Override public void clusterChanged(ClusterChangedEvent event) { if (event.state().blocks().disableStatePersistence()) { // reset the current metadata, we need to start fresh... this.currentMetaData = null; return; } MetaData newMetaData = event.state().metaData(); // we don't check if metaData changed, since we might be called several times and we need to check dangling... boolean success = true; // only applied to master node, writing the global and index level states if (event.state().nodes().localNode().masterNode()) { // check if the global state changed? if (currentMetaData == null || !MetaData.isGlobalStateEquals(currentMetaData, newMetaData)) { try { writeGlobalState("changed", newMetaData, currentMetaData); } catch (Throwable e) { success = false; } } // check and write changes in indices for (IndexMetaData indexMetaData : newMetaData) { String writeReason = null; IndexMetaData currentIndexMetaData; if (currentMetaData == null) { // a new event..., check from the state stored currentIndexMetaData = loadIndex(indexMetaData.index()); } else { currentIndexMetaData = currentMetaData.index(indexMetaData.index()); } if (currentIndexMetaData == null) { writeReason = "freshly created"; } else if (currentIndexMetaData.version() != indexMetaData.version()) { writeReason = "version changed from [" + currentIndexMetaData.version() + "] to [" + indexMetaData.version() + "]"; } // we update the writeReason only if we really need to write it if (writeReason == null) { continue; } try { writeIndex(writeReason, indexMetaData, currentIndexMetaData); } catch (Throwable e) { success = false; } } } // delete indices that were there before, but are deleted now // we need to do it so they won't be detected as dangling if (currentMetaData != null) { // only delete indices when we already received a state (currentMetaData != null) // and we had a go at processing dangling indices at least once // this will also delete the _state of the index itself for (IndexMetaData current : currentMetaData) { if (danglingIndices.containsKey(current.index())) { continue; } if (!newMetaData.hasIndex(current.index())) { logger.debug("[{}] deleting index that is no longer part of the metadata (indices: [{}])", current.index(), newMetaData.indices().keys()); if (nodeEnv.hasNodeFile()) { FileSystemUtils.deleteRecursively(nodeEnv.indexLocations(new Index(current.index()))); } try { nodeIndexDeletedAction.nodeIndexStoreDeleted(event.state(), current.index(), event.state().nodes().localNodeId()); } catch (Throwable e) { logger.debug("[{}] failed to notify master on local index store deletion", e, current.index()); } } } } // handle dangling indices, we handle those for all nodes that have a node file (data or master) if (nodeEnv.hasNodeFile()) { if (danglingTimeout.millis() >= 0) { synchronized (danglingMutex) { for (String danglingIndex : danglingIndices.keySet()) { if (newMetaData.hasIndex(danglingIndex)) { logger.debug("[{}] no longer dangling (created), removing", danglingIndex); DanglingIndex removed = danglingIndices.remove(danglingIndex); removed.future.cancel(false); } } // delete indices that are no longer part of the metadata try { for (String indexName : nodeEnv.findAllIndices()) { // if we have the index on the metadata, don't delete it if (newMetaData.hasIndex(indexName)) { continue; } if (danglingIndices.containsKey(indexName)) { // already dangling, continue continue; } IndexMetaData indexMetaData = loadIndex(indexName); if (indexMetaData != null) { if (danglingTimeout.millis() == 0) { logger.info("[{}] dangling index, exists on local file system, but not in cluster metadata, timeout set to 0, deleting now", indexName); FileSystemUtils.deleteRecursively(nodeEnv.indexLocations(new Index(indexName))); } else { logger.info("[{}] dangling index, exists on local file system, but not in cluster metadata, scheduling to delete in [{}], auto import to cluster state [{}]", indexName, danglingTimeout, autoImportDangled); danglingIndices.put(indexName, new DanglingIndex(indexName, threadPool.schedule(danglingTimeout, ThreadPool.Names.SAME, new RemoveDanglingIndex(indexName)))); } } } } catch (Throwable e) { logger.warn("failed to find dangling indices", e); } } } if (autoImportDangled.shouldImport() && !danglingIndices.isEmpty()) { final List<IndexMetaData> dangled = Lists.newArrayList(); for (String indexName : danglingIndices.keySet()) { IndexMetaData indexMetaData = loadIndex(indexName); if (indexMetaData == null) { logger.debug("failed to find state for dangling index [{}]", indexName); continue; } // we might have someone copying over an index, renaming the directory, handle that if (!indexMetaData.index().equals(indexName)) { logger.info("dangled index directory name is [{}], state name is [{}], renaming to directory name", indexName, indexMetaData.index()); indexMetaData = IndexMetaData.builder(indexMetaData).index(indexName).build(); } if (autoImportDangled == AutoImportDangledState.CLOSED) { indexMetaData = IndexMetaData.builder(indexMetaData).state(IndexMetaData.State.CLOSE).build(); } if (indexMetaData != null) { dangled.add(indexMetaData); } } IndexMetaData[] dangledIndices = dangled.toArray(new IndexMetaData[dangled.size()]); try { allocateDangledIndices.allocateDangled(dangledIndices, new LocalAllocateDangledIndices.Listener() { @Override public void onResponse(LocalAllocateDangledIndices.AllocateDangledResponse response) { logger.trace("allocated dangled"); } @Override public void onFailure(Throwable e) { logger.info("failed to send allocated dangled", e); } }); } catch (Throwable e) { logger.warn("failed to send allocate dangled", e); } } } if (success) { currentMetaData = newMetaData; } } private void deleteIndex(String index) { logger.trace("[{}] delete index state", index); File[] indexLocations = nodeEnv.indexLocations(new Index(index)); for (File indexLocation : indexLocations) { if (!indexLocation.exists()) { continue; } FileSystemUtils.deleteRecursively(new File(indexLocation, "_state")); } } private void writeIndex(String reason, IndexMetaData indexMetaData, @Nullable IndexMetaData previousIndexMetaData) throws Exception { logger.trace("[{}] writing state, reason [{}]", indexMetaData.index(), reason); XContentBuilder builder = XContentFactory.contentBuilder(format, new BytesStreamOutput()); builder.startObject(); IndexMetaData.Builder.toXContent(indexMetaData, builder, formatParams); builder.endObject(); builder.flush(); String stateFileName = "state-" + indexMetaData.version(); Throwable lastFailure = null; boolean wroteAtLeastOnce = false; for (File indexLocation : nodeEnv.indexLocations(new Index(indexMetaData.index()))) { File stateLocation = new File(indexLocation, "_state"); FileSystemUtils.mkdirs(stateLocation); File stateFile = new File(stateLocation, stateFileName); FileOutputStream fos = null; try { fos = new FileOutputStream(stateFile); BytesReference bytes = builder.bytes(); fos.write(bytes.array(), bytes.arrayOffset(), bytes.length()); fos.getChannel().force(true); fos.close(); wroteAtLeastOnce = true; } catch (Throwable e) { lastFailure = e; } finally { IOUtils.closeWhileHandlingException(fos); } } if (!wroteAtLeastOnce) { logger.warn("[{}]: failed to state", lastFailure, indexMetaData.index()); throw new IOException("failed to write state for [" + indexMetaData.index() + "]", lastFailure); } // delete the old files if (previousIndexMetaData != null && previousIndexMetaData.version() != indexMetaData.version()) { for (File indexLocation : nodeEnv.indexLocations(new Index(indexMetaData.index()))) { File[] files = new File(indexLocation, "_state").listFiles(); if (files == null) { continue; } for (File file : files) { if (!file.getName().startsWith("state-")) { continue; } if (file.getName().equals(stateFileName)) { continue; } file.delete(); } } } } private void writeGlobalState(String reason, MetaData metaData, @Nullable MetaData previousMetaData) throws Exception { logger.trace("[_global] writing state, reason [{}]", reason); XContentBuilder builder = XContentFactory.contentBuilder(format); builder.startObject(); MetaData.Builder.toXContent(metaData, builder, globalOnlyFormatParams); builder.endObject(); builder.flush(); String globalFileName = "global-" + metaData.version(); Throwable lastFailure = null; boolean wroteAtLeastOnce = false; for (File dataLocation : nodeEnv.nodeDataLocations()) { File stateLocation = new File(dataLocation, "_state"); FileSystemUtils.mkdirs(stateLocation); File stateFile = new File(stateLocation, globalFileName); FileOutputStream fos = null; try { fos = new FileOutputStream(stateFile); BytesReference bytes = builder.bytes(); fos.write(bytes.array(), bytes.arrayOffset(), bytes.length()); fos.getChannel().force(true); fos.close(); wroteAtLeastOnce = true; } catch (Throwable e) { lastFailure = e; } finally { IOUtils.closeWhileHandlingException(fos); } } if (!wroteAtLeastOnce) { logger.warn("[_global]: failed to write global state", lastFailure); throw new IOException("failed to write global state", lastFailure); } // delete the old files for (File dataLocation : nodeEnv.nodeDataLocations()) { File[] files = new File(dataLocation, "_state").listFiles(); if (files == null) { continue; } for (File file : files) { if (!file.getName().startsWith("global-")) { continue; } if (file.getName().equals(globalFileName)) { continue; } file.delete(); } } } private MetaData loadState() throws Exception { MetaData globalMetaData = loadGlobalState(); MetaData.Builder metaDataBuilder; if (globalMetaData != null) { metaDataBuilder = MetaData.builder(globalMetaData); } else { metaDataBuilder = MetaData.builder(); } Set<String> indices = nodeEnv.findAllIndices(); for (String index : indices) { IndexMetaData indexMetaData = loadIndex(index); if (indexMetaData == null) { logger.debug("[{}] failed to find metadata for existing index location", index); } else { metaDataBuilder.put(indexMetaData, false); } } return metaDataBuilder.build(); } @Nullable private IndexMetaData loadIndex(String index) { long highestVersion = -1; IndexMetaData indexMetaData = null; for (File indexLocation : nodeEnv.indexLocations(new Index(index))) { File stateDir = new File(indexLocation, "_state"); if (!stateDir.exists() || !stateDir.isDirectory()) { continue; } // now, iterate over the current versions, and find latest one File[] stateFiles = stateDir.listFiles(); if (stateFiles == null) { continue; } for (File stateFile : stateFiles) { if (!stateFile.getName().startsWith("state-")) { continue; } try { long version = Long.parseLong(stateFile.getName().substring("state-".length())); if (version > highestVersion) { byte[] data = Streams.copyToByteArray(new FileInputStream(stateFile)); if (data.length == 0) { logger.debug("[{}]: no data for [" + stateFile.getAbsolutePath() + "], ignoring...", index); continue; } XContentParser parser = null; try { parser = XContentHelper.createParser(data, 0, data.length); parser.nextToken(); // move to START_OBJECT indexMetaData = IndexMetaData.Builder.fromXContent(parser); highestVersion = version; } finally { if (parser != null) { parser.close(); } } } } catch (Throwable e) { logger.debug("[{}]: failed to read [" + stateFile.getAbsolutePath() + "], ignoring...", e, index); } } } return indexMetaData; } private MetaData loadGlobalState() { long highestVersion = -1; MetaData metaData = null; for (File dataLocation : nodeEnv.nodeDataLocations()) { File stateLocation = new File(dataLocation, "_state"); if (!stateLocation.exists()) { continue; } File[] stateFiles = stateLocation.listFiles(); if (stateFiles == null) { continue; } for (File stateFile : stateFiles) { String name = stateFile.getName(); if (!name.startsWith("global-")) { continue; } try { long version = Long.parseLong(stateFile.getName().substring("global-".length())); if (version > highestVersion) { byte[] data = Streams.copyToByteArray(new FileInputStream(stateFile)); if (data.length == 0) { logger.debug("[_global] no data for [" + stateFile.getAbsolutePath() + "], ignoring..."); continue; } XContentParser parser = null; try { parser = XContentHelper.createParser(data, 0, data.length); metaData = MetaData.Builder.fromXContent(parser); highestVersion = version; } finally { if (parser != null) { parser.close(); } } } } catch (Throwable e) { logger.debug("failed to load global state from [{}]", e, stateFile.getAbsolutePath()); } } } return metaData; } private void pre019Upgrade() throws Exception { long index = -1; File metaDataFile = null; MetaData metaData = null; long version = -1; for (File dataLocation : nodeEnv.nodeDataLocations()) { File stateLocation = new File(dataLocation, "_state"); if (!stateLocation.exists()) { continue; } File[] stateFiles = stateLocation.listFiles(); if (stateFiles == null) { continue; } for (File stateFile : stateFiles) { if (logger.isTraceEnabled()) { logger.trace("[upgrade]: processing [" + stateFile.getName() + "]"); } String name = stateFile.getName(); if (!name.startsWith("metadata-")) { continue; } long fileIndex = Long.parseLong(name.substring(name.indexOf('-') + 1)); if (fileIndex >= index) { // try and read the meta data try { byte[] data = Streams.copyToByteArray(new FileInputStream(stateFile)); if (data.length == 0) { continue; } XContentParser parser = XContentHelper.createParser(data, 0, data.length); try { String currentFieldName = null; XContentParser.Token token = parser.nextToken(); if (token != null) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { if ("meta-data".equals(currentFieldName)) { metaData = MetaData.Builder.fromXContent(parser); } } else if (token.isValue()) { if ("version".equals(currentFieldName)) { version = parser.longValue(); } } } } } finally { parser.close(); } index = fileIndex; metaDataFile = stateFile; } catch (IOException e) { logger.warn("failed to read pre 0.19 state from [" + name + "], ignoring...", e); } } } } if (metaData == null) { return; } logger.info("found old metadata state, loading metadata from [{}] and converting to new metadata location and strucutre...", metaDataFile.getAbsolutePath()); writeGlobalState("upgrade", MetaData.builder(metaData).version(version).build(), null); for (IndexMetaData indexMetaData : metaData) { IndexMetaData.Builder indexMetaDataBuilder = IndexMetaData.builder(indexMetaData).version(version); // set the created version to 0.18 indexMetaDataBuilder.settings(ImmutableSettings.settingsBuilder().put(indexMetaData.settings()).put(IndexMetaData.SETTING_VERSION_CREATED, Version.V_0_18_0)); writeIndex("upgrade", indexMetaDataBuilder.build(), null); } // rename shards state to backup state File backupFile = new File(metaDataFile.getParentFile(), "backup-" + metaDataFile.getName()); if (!metaDataFile.renameTo(backupFile)) { throw new IOException("failed to rename old state to backup state [" + metaDataFile.getAbsolutePath() + "]"); } // delete all other shards state files for (File dataLocation : nodeEnv.nodeDataLocations()) { File stateLocation = new File(dataLocation, "_state"); if (!stateLocation.exists()) { continue; } File[] stateFiles = stateLocation.listFiles(); if (stateFiles == null) { continue; } for (File stateFile : stateFiles) { String name = stateFile.getName(); if (!name.startsWith("metadata-")) { continue; } stateFile.delete(); } } logger.info("conversion to new metadata location and format done, backup create at [{}]", backupFile.getAbsolutePath()); } class RemoveDanglingIndex implements Runnable { private final String index; RemoveDanglingIndex(String index) { this.index = index; } @Override public void run() { synchronized (danglingMutex) { DanglingIndex remove = danglingIndices.remove(index); // no longer there... if (remove == null) { return; } logger.info("[{}] deleting dangling index", index); FileSystemUtils.deleteRecursively(nodeEnv.indexLocations(new Index(index))); } } } static class DanglingIndex { public final String index; public final ScheduledFuture future; DanglingIndex(String index, ScheduledFuture future) { this.index = index; this.future = future; } } }
0true
src_main_java_org_elasticsearch_gateway_local_state_meta_LocalGatewayMetaState.java
3,603
public abstract static class CustomNumericField extends Field { protected final NumberFieldMapper mapper; public CustomNumericField(NumberFieldMapper mapper, Number value, FieldType fieldType) { super(mapper.names().indexName(), fieldType); this.mapper = mapper; if (value != null) { this.fieldsData = value; } } @Override public String stringValue() { return null; } @Override public Reader readerValue() { return null; } public abstract String numericAsString(); }
0true
src_main_java_org_elasticsearch_index_mapper_core_NumberFieldMapper.java
597
@RunWith(HazelcastSerialClassRunner.class) @Category(NightlyTest.class) public class JoinStressTest extends HazelcastTestSupport { @Test public void testTCPIPJoinWithManyNodes() throws UnknownHostException, InterruptedException { final int count = 20; final CountDownLatch latch = new CountDownLatch(count); final ConcurrentHashMap<Integer, HazelcastInstance> mapOfInstances = new ConcurrentHashMap<Integer, HazelcastInstance>(); final Random random = new Random(); final ExecutorService ex = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2); for (int i = 0; i < count; i++) { final int seed = i; ex.execute(new Runnable() { public void run() { try { Thread.sleep(random.nextInt(10) * 1000); final Config config = new Config(); config.setProperty("hazelcast.wait.seconds.before.join", "5"); final NetworkConfig networkConfig = config.getNetworkConfig(); networkConfig.getJoin().getMulticastConfig().setEnabled(false); TcpIpConfig tcpIpConfig = networkConfig.getJoin().getTcpIpConfig(); tcpIpConfig.setEnabled(true); int port = 12301; networkConfig.setPortAutoIncrement(false); networkConfig.setPort(port + seed); for (int i = 0; i < count; i++) { tcpIpConfig.addMember("127.0.0.1:" + (port + i)); } HazelcastInstance h = Hazelcast.newHazelcastInstance(config); mapOfInstances.put(seed, h); latch.countDown(); } catch (Exception e) { e.printStackTrace(); } } }); } try { latch.await(200, TimeUnit.SECONDS); } finally { ex.shutdown(); } for (HazelcastInstance h : mapOfInstances.values()) { assertEquals(count, h.getCluster().getMembers().size()); } } @Test @Category(ProblematicTest.class) public void testTCPIPJoinWithManyNodesMultipleGroups() throws UnknownHostException, InterruptedException { final int count = 20; final int groupCount = 3; final CountDownLatch latch = new CountDownLatch(count); final ConcurrentHashMap<Integer, HazelcastInstance> mapOfInstances = new ConcurrentHashMap<Integer, HazelcastInstance>(); final Random random = new Random(); final Map<String, AtomicInteger> groups = new ConcurrentHashMap<String, AtomicInteger>(); for (int i = 0; i < groupCount; i++) { groups.put("group" + i, new AtomicInteger(0)); } final ExecutorService ex = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2); for (int i = 0; i < count; i++) { final int seed = i; ex.execute(new Runnable() { public void run() { try { Thread.sleep(random.nextInt(10) * 1000); final Config config = new Config(); config.setProperty("hazelcast.wait.seconds.before.join", "5"); String name = "group" + random.nextInt(groupCount); groups.get(name).incrementAndGet(); config.getGroupConfig().setName(name); final NetworkConfig networkConfig = config.getNetworkConfig(); networkConfig.getJoin().getMulticastConfig().setEnabled(false); TcpIpConfig tcpIpConfig = networkConfig.getJoin().getTcpIpConfig(); tcpIpConfig.setEnabled(true); int port = 12301; networkConfig.setPortAutoIncrement(false); networkConfig.setPort(port + seed); for (int i = 0; i < count; i++) { tcpIpConfig.addMember("127.0.0.1:" + (port + i)); } HazelcastInstance h = Hazelcast.newHazelcastInstance(config); mapOfInstances.put(seed, h); latch.countDown(); } catch (Exception e) { e.printStackTrace(); } } }); } try { latch.await(200, TimeUnit.SECONDS); } finally { ex.shutdown(); } for (HazelcastInstance h : mapOfInstances.values()) { int clusterSize = h.getCluster().getMembers().size(); int shouldBeClusterSize = groups.get(h.getConfig().getGroupConfig().getName()).get(); assertEquals(h.getConfig().getGroupConfig().getName() + ": ", shouldBeClusterSize, clusterSize); } } @Test @Category(ProblematicTest.class) public void testMulticastJoinAtTheSameTime() throws InterruptedException { multicastJoin(10, false); } @Test @Category(ProblematicTest.class) public void testMulticastJoinWithRandomStartTime() throws InterruptedException { multicastJoin(10, true); } private void multicastJoin(int count, final boolean sleep) throws InterruptedException { final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(count); final Config config = new Config(); config.setProperty("hazelcast.wait.seconds.before.join", "5"); config.getNetworkConfig().getJoin().getMulticastConfig().setMulticastTimeoutSeconds(25); final ConcurrentMap<Integer, HazelcastInstance> map = new ConcurrentHashMap<Integer, HazelcastInstance>(); final CountDownLatch latch = new CountDownLatch(count); final ExecutorService ex = Executors.newCachedThreadPool(); for (int i = 0; i < count; i++) { final int index = i; ex.execute(new Runnable() { public void run() { if (sleep) { try { Thread.sleep((int) (1000 * Math.random())); } catch (InterruptedException ignored) { } } HazelcastInstance h = nodeFactory.newHazelcastInstance(config); map.put(index, h); latch.countDown(); } }); } assertOpenEventually(latch); for (HazelcastInstance h : map.values()) { assertEquals(count, h.getCluster().getMembers().size()); } ex.shutdown(); } }
0true
hazelcast_src_test_java_com_hazelcast_cluster_JoinStressTest.java
59
@SuppressWarnings("serial") protected static class CountableLock extends ReentrantReadWriteLock { protected int countLocks = 0; public CountableLock() { super(false); } }
0true
commons_src_main_java_com_orientechnologies_common_concur_lock_OLockManager.java
1,715
return new UnmodifiableIterator<Long>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Long next() { return iterator.next().value; } };
0true
src_main_java_org_elasticsearch_common_collect_ImmutableOpenLongMap.java