Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
221
private static class TransactionBegin extends Exception { private static final long serialVersionUID = 1L; private TransactionBegin(String msg) { super(msg); } }
0true
titan-berkeleyje_src_main_java_com_thinkaurelius_titan_diskstorage_berkeleyje_BerkeleyJEStoreManager.java
580
executionService.scheduleWithFixedDelay(executorName, new Runnable() { public void run() { heartBeater(); } }, heartbeatInterval, heartbeatInterval, TimeUnit.SECONDS);
1no label
hazelcast_src_main_java_com_hazelcast_cluster_ClusterServiceImpl.java
304
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class ClientMapIssueTest { @After public void reset(){ HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } @Test public void testOperationNotBlockingAfterClusterShutdown() throws InterruptedException { final HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(); final HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(); final ClientConfig clientConfig = new ClientConfig(); clientConfig.getNetworkConfig().setConnectionAttemptLimit(Integer.MAX_VALUE); final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); final IMap<String, String> m = client.getMap("m"); m.put("elif", "Elif"); m.put("ali", "Ali"); m.put("alev", "Alev"); instance1.getLifecycleService().terminate(); instance2.getLifecycleService().terminate(); final CountDownLatch latch = new CountDownLatch(1); new Thread(){ public void run() { try { m.get("ali"); } catch (Exception ignored) { latch.countDown(); } } }.start(); assertTrue(latch.await(15, TimeUnit.SECONDS)); } @Test public void testMapPagingEntries() { final HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(); final HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(); final ClientConfig clientConfig = new ClientConfig(); final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); final IMap<Integer, Integer> map = client.getMap("map"); final int size = 50; final int pageSize = 5; for (int i = 0; i < size; i++) { map.put(i, i); } final PagingPredicate predicate = new PagingPredicate(pageSize); predicate.nextPage(); final Set<Map.Entry<Integer,Integer>> entries = map.entrySet(predicate); assertEquals(pageSize, entries.size()); } @Test public void testMapPagingValues() { final HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(); final HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(); final ClientConfig clientConfig = new ClientConfig(); final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); final IMap<Integer, Integer> map = client.getMap("map"); final int size = 50; final int pageSize = 5; for (int i = 0; i < size; i++) { map.put(i, i); } final PagingPredicate predicate = new PagingPredicate(pageSize); predicate.nextPage(); final Collection<Integer> values = map.values(predicate); assertEquals(pageSize, values.size()); } @Test public void testMapPagingKeySet() { final HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(); final HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(); final ClientConfig clientConfig = new ClientConfig(); final HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig); final IMap<Integer, Integer> map = client.getMap("map"); final int size = 50; final int pageSize = 5; for (int i = 0; i < size; i++) { map.put(size - i, i); } final PagingPredicate predicate = new PagingPredicate(pageSize); predicate.nextPage(); final Set<Integer> values = map.keySet(predicate); assertEquals(pageSize, values.size()); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapIssueTest.java
328
public class TransactionalConfiguration implements WriteConfiguration { private final WriteConfiguration config; private final Map<String,Object> readValues; private final Map<String,Object> writtenValues; public TransactionalConfiguration(WriteConfiguration config) { Preconditions.checkNotNull(config); this.config = config; this.readValues = new HashMap<String, Object>(); this.writtenValues = new HashMap<String, Object>(); } @Override public <O> void set(String key, O value) { writtenValues.put(key,value); } @Override public void remove(String key) { writtenValues.put(key,null); } @Override public WriteConfiguration copy() { return config.copy(); } @Override public <O> O get(String key, Class<O> datatype) { Object value = writtenValues.get(key); if (value!=null) return (O)value; value = readValues.get(key); if (value!=null) return (O)value; value = config.get(key,datatype); readValues.put(key,value); return (O)value; } @Override public Iterable<String> getKeys(final String prefix) { return Iterables.concat( Iterables.filter(writtenValues.keySet(),new Predicate<String>() { @Override public boolean apply(@Nullable String s) { return s.startsWith(prefix); } }), Iterables.filter(config.getKeys(prefix),new Predicate<String>() { @Override public boolean apply(@Nullable String s) { return !writtenValues.containsKey(s); } })); } public void commit() { for (Map.Entry<String,Object> entry : writtenValues.entrySet()) { if (config instanceof ConcurrentWriteConfiguration && readValues.containsKey(entry.getKey())) { ((ConcurrentWriteConfiguration)config) .set(entry.getKey(), entry.getValue(), readValues.get(entry.getKey())); } else { config.set(entry.getKey(),entry.getValue()); } } rollback(); } public void rollback() { writtenValues.clear(); readValues.clear(); } public boolean hasMutations() { return !writtenValues.isEmpty(); } public void logMutations(DataOutput out) { Preconditions.checkArgument(hasMutations()); VariableLong.writePositive(out,writtenValues.size()); for (Map.Entry<String,Object> entry : writtenValues.entrySet()) { out.writeObjectNotNull(entry.getKey()); out.writeClassAndObject(entry.getValue()); } } @Override public void close() { throw new UnsupportedOperationException(); } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_TransactionalConfiguration.java
1,202
public class OperationTimeoutException extends HazelcastException { public OperationTimeoutException() { } public OperationTimeoutException(String message) { super(message); } public OperationTimeoutException(String op, String message) { super("[" + op + "] " + message); } }
0true
hazelcast_src_main_java_com_hazelcast_core_OperationTimeoutException.java
151
public class ODateSerializer implements OBinarySerializer<Date> { public static ODateSerializer INSTANCE = new ODateSerializer(); public static final byte ID = 4; public int getObjectSize(Date object, Object... hints) { return OLongSerializer.LONG_SIZE; } public void serialize(Date object, byte[] stream, int startPosition, Object... hints) { Calendar calendar = Calendar.getInstance(); calendar.setTime(object); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer.INSTANCE; dateTimeSerializer.serialize(calendar.getTime(), stream, startPosition); } public Date deserialize(byte[] stream, int startPosition) { ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer.INSTANCE; return dateTimeSerializer.deserialize(stream, startPosition); } public int getObjectSize(byte[] stream, int startPosition) { return OLongSerializer.LONG_SIZE; } public byte getId() { return ID; } public int getObjectSizeNative(byte[] stream, int startPosition) { return OLongSerializer.LONG_SIZE; } public void serializeNative(Date object, byte[] stream, int startPosition, Object... hints) { Calendar calendar = Calendar.getInstance(); calendar.setTime(object); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer.INSTANCE; dateTimeSerializer.serializeNative(calendar.getTime(), stream, startPosition); } public Date deserializeNative(byte[] stream, int startPosition) { ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer.INSTANCE; return dateTimeSerializer.deserializeNative(stream, startPosition); } @Override public void serializeInDirectMemory(Date object, ODirectMemoryPointer pointer, long offset, Object... hints) { Calendar calendar = Calendar.getInstance(); calendar.setTime(object); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer.INSTANCE; dateTimeSerializer.serializeInDirectMemory(calendar.getTime(), pointer, offset); } @Override public Date deserializeFromDirectMemory(ODirectMemoryPointer pointer, long offset) { ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer.INSTANCE; return dateTimeSerializer.deserializeFromDirectMemory(pointer, offset); } @Override public int getObjectSizeInDirectMemory(ODirectMemoryPointer pointer, long offset) { return OLongSerializer.LONG_SIZE; } public boolean isFixedLength() { return true; } public int getFixedLength() { return OLongSerializer.LONG_SIZE; } @Override public Date preprocess(Date value, Object... hints) { final Calendar calendar = Calendar.getInstance(); calendar.setTime(value); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } }
0true
commons_src_main_java_com_orientechnologies_common_serialization_types_ODateSerializer.java
562
public class OCompositeIndexDefinition extends OAbstractIndexDefinition { private final List<OIndexDefinition> indexDefinitions; private String className; private int multiValueDefinitionIndex = -1; public OCompositeIndexDefinition() { indexDefinitions = new ArrayList<OIndexDefinition>(5); } /** * Constructor for new index creation. * * @param iClassName * - name of class which is owner of this index */ public OCompositeIndexDefinition(final String iClassName) { indexDefinitions = new ArrayList<OIndexDefinition>(5); className = iClassName; } /** * Constructor for new index creation. * * @param iClassName * - name of class which is owner of this index * @param iIndexes * List of indexDefinitions to add in given index. */ public OCompositeIndexDefinition(final String iClassName, final List<? extends OIndexDefinition> iIndexes) { indexDefinitions = new ArrayList<OIndexDefinition>(5); for (OIndexDefinition indexDefinition : iIndexes) { indexDefinitions.add(indexDefinition); if (indexDefinition instanceof OIndexDefinitionMultiValue) if (multiValueDefinitionIndex == -1) multiValueDefinitionIndex = indexDefinitions.size() - 1; else throw new OIndexException("Composite key can not contain more than one collection item"); } className = iClassName; } /** * {@inheritDoc} */ public String getClassName() { return className; } /** * Add new indexDefinition in current composite. * * @param indexDefinition * Index to add. */ public void addIndex(final OIndexDefinition indexDefinition) { indexDefinitions.add(indexDefinition); if (indexDefinition instanceof OIndexDefinitionMultiValue) { if (multiValueDefinitionIndex == -1) multiValueDefinitionIndex = indexDefinitions.size() - 1; else throw new OIndexException("Composite key can not contain more than one collection item"); } } /** * {@inheritDoc} */ public List<String> getFields() { final List<String> fields = new LinkedList<String>(); for (final OIndexDefinition indexDefinition : indexDefinitions) { fields.addAll(indexDefinition.getFields()); } return Collections.unmodifiableList(fields); } /** * {@inheritDoc} */ public List<String> getFieldsToIndex() { final List<String> fields = new LinkedList<String>(); for (final OIndexDefinition indexDefinition : indexDefinitions) { fields.addAll(indexDefinition.getFieldsToIndex()); } return Collections.unmodifiableList(fields); } /** * {@inheritDoc} */ public Object getDocumentValueToIndex(final ODocument iDocument) { final List<OCompositeKey> compositeKeys = new ArrayList<OCompositeKey>(10); final OCompositeKey firstKey = new OCompositeKey(); boolean containsCollection = false; compositeKeys.add(firstKey); for (final OIndexDefinition indexDefinition : indexDefinitions) { final Object result = indexDefinition.getDocumentValueToIndex(iDocument); if (result == null) return null; containsCollection = addKey(firstKey, compositeKeys, containsCollection, result); } if (!containsCollection) return firstKey; return compositeKeys; } public int getMultiValueDefinitionIndex() { return multiValueDefinitionIndex; } public String getMultiValueField() { if (multiValueDefinitionIndex >= 0) return indexDefinitions.get(multiValueDefinitionIndex).getFields().get(0); return null; } /** * {@inheritDoc} */ public Object createValue(final List<?> params) { int currentParamIndex = 0; final OCompositeKey firstKey = new OCompositeKey(); final List<OCompositeKey> compositeKeys = new ArrayList<OCompositeKey>(10); compositeKeys.add(firstKey); boolean containsCollection = false; for (final OIndexDefinition indexDefinition : indexDefinitions) { if (currentParamIndex + 1 > params.size()) break; final int endIndex; if (currentParamIndex + indexDefinition.getParamCount() > params.size()) endIndex = params.size(); else endIndex = currentParamIndex + indexDefinition.getParamCount(); final List<?> indexParams = params.subList(currentParamIndex, endIndex); currentParamIndex += indexDefinition.getParamCount(); final Object keyValue = indexDefinition.createValue(indexParams); if (keyValue == null) return null; containsCollection = addKey(firstKey, compositeKeys, containsCollection, keyValue); } if (!containsCollection) return firstKey; return compositeKeys; } public OIndexDefinitionMultiValue getMultiValueDefinition() { if (multiValueDefinitionIndex > -1) return (OIndexDefinitionMultiValue) indexDefinitions.get(multiValueDefinitionIndex); return null; } public OCompositeKey createSingleValue(final List<?> params) { final OCompositeKey compositeKey = new OCompositeKey(); int currentParamIndex = 0; for (final OIndexDefinition indexDefinition : indexDefinitions) { if (currentParamIndex + 1 > params.size()) break; final int endIndex; if (currentParamIndex + indexDefinition.getParamCount() > params.size()) endIndex = params.size(); else endIndex = currentParamIndex + indexDefinition.getParamCount(); final List<?> indexParams = params.subList(currentParamIndex, endIndex); currentParamIndex += indexDefinition.getParamCount(); final Object keyValue; if (indexDefinition instanceof OIndexDefinitionMultiValue) keyValue = ((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(indexParams.toArray()); else keyValue = indexDefinition.createValue(indexParams); if (keyValue == null) return null; compositeKey.addKey(keyValue); } return compositeKey; } private static boolean addKey(OCompositeKey firstKey, List<OCompositeKey> compositeKeys, boolean containsCollection, Object keyValue) { if (keyValue instanceof Collection) { final Collection<?> collectionKey = (Collection<?>) keyValue; if (!containsCollection) for (int i = 1; i < collectionKey.size(); i++) { final OCompositeKey compositeKey = new OCompositeKey(firstKey.getKeys()); compositeKeys.add(compositeKey); } else throw new OIndexException("Composite key can not contain more than one collection item"); int compositeIndex = 0; for (final Object keyItem : collectionKey) { final OCompositeKey compositeKey = compositeKeys.get(compositeIndex); compositeKey.addKey(keyItem); compositeIndex++; } containsCollection = true; } else if (containsCollection) for (final OCompositeKey compositeKey : compositeKeys) compositeKey.addKey(keyValue); else firstKey.addKey(keyValue); return containsCollection; } /** * {@inheritDoc} */ public Object createValue(final Object... params) { return createValue(Arrays.asList(params)); } public void processChangeEvent(OMultiValueChangeEvent<?, ?> changeEvent, Map<OCompositeKey, Integer> keysToAdd, Map<OCompositeKey, Integer> keysToRemove, Object... params) { final OIndexDefinitionMultiValue indexDefinitionMultiValue = (OIndexDefinitionMultiValue) indexDefinitions .get(multiValueDefinitionIndex); final CompositeWrapperMap compositeWrapperKeysToAdd = new CompositeWrapperMap(keysToAdd, indexDefinitions, params, multiValueDefinitionIndex); final CompositeWrapperMap compositeWrapperKeysToRemove = new CompositeWrapperMap(keysToRemove, indexDefinitions, params, multiValueDefinitionIndex); indexDefinitionMultiValue.processChangeEvent(changeEvent, compositeWrapperKeysToAdd, compositeWrapperKeysToRemove); } /** * {@inheritDoc} */ public int getParamCount() { int total = 0; for (final OIndexDefinition indexDefinition : indexDefinitions) total += indexDefinition.getParamCount(); return total; } /** * {@inheritDoc} */ public OType[] getTypes() { final List<OType> types = new LinkedList<OType>(); for (final OIndexDefinition indexDefinition : indexDefinitions) Collections.addAll(types, indexDefinition.getTypes()); return types.toArray(new OType[types.size()]); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final OCompositeIndexDefinition that = (OCompositeIndexDefinition) o; if (!className.equals(that.className)) return false; if (!indexDefinitions.equals(that.indexDefinitions)) return false; return true; } @Override public int hashCode() { int result = indexDefinitions.hashCode(); result = 31 * result + className.hashCode(); return result; } @Override public String toString() { return "OCompositeIndexDefinition{" + "indexDefinitions=" + indexDefinitions + ", className='" + className + '\'' + '}'; } /** * {@inheritDoc} */ @Override public ODocument toStream() { document.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); final List<ODocument> inds = new ArrayList<ODocument>(indexDefinitions.size()); final List<String> indClasses = new ArrayList<String>(indexDefinitions.size()); try { document.field("className", className); for (final OIndexDefinition indexDefinition : indexDefinitions) { final ODocument indexDocument = indexDefinition.toStream(); inds.add(indexDocument); indClasses.add(indexDefinition.getClass().getName()); } document.field("indexDefinitions", inds, OType.EMBEDDEDLIST); document.field("indClasses", indClasses, OType.EMBEDDEDLIST); } finally { document.setInternalStatus(ORecordElement.STATUS.LOADED); } document.field("collate", collate.getName()); return document; } /** * {@inheritDoc} */ public String toCreateIndexDDL(final String indexName, final String indexType) { final StringBuilder ddl = new StringBuilder("create index "); ddl.append(indexName).append(" on ").append(className).append(" ( "); final Iterator<String> fieldIterator = getFieldsToIndex().iterator(); if (fieldIterator.hasNext()) { ddl.append(fieldIterator.next()); while (fieldIterator.hasNext()) { ddl.append(", ").append(fieldIterator.next()); } } ddl.append(" ) ").append(indexType).append(' '); if (multiValueDefinitionIndex == -1) { boolean first = true; for (OType oType : getTypes()) { if (first) first = false; else ddl.append(", "); ddl.append(oType.name()); } } return ddl.toString(); } /** * {@inheritDoc} */ @Override protected void fromStream() { try { className = document.field("className"); final List<ODocument> inds = document.field("indexDefinitions"); final List<String> indClasses = document.field("indClasses"); indexDefinitions.clear(); for (int i = 0; i < indClasses.size(); i++) { final Class<?> clazz = Class.forName(indClasses.get(i)); final ODocument indDoc = inds.get(i); final OIndexDefinition indexDefinition = (OIndexDefinition) clazz.getDeclaredConstructor().newInstance(); indexDefinition.fromStream(indDoc); indexDefinitions.add(indexDefinition); if (indexDefinition instanceof OIndexDefinitionMultiValue) multiValueDefinitionIndex = indexDefinitions.size() - 1; } setCollate((String) document.field("collate")); } catch (final ClassNotFoundException e) { throw new OIndexException("Error during composite index deserialization", e); } catch (final NoSuchMethodException e) { throw new OIndexException("Error during composite index deserialization", e); } catch (final InvocationTargetException e) { throw new OIndexException("Error during composite index deserialization", e); } catch (final InstantiationException e) { throw new OIndexException("Error during composite index deserialization", e); } catch (final IllegalAccessException e) { throw new OIndexException("Error during composite index deserialization", e); } } private static final class CompositeWrapperMap implements Map<Object, Integer> { private final Map<OCompositeKey, Integer> underlying; private final Object[] params; private final List<OIndexDefinition> indexDefinitions; private final int multiValueIndex; private CompositeWrapperMap(Map<OCompositeKey, Integer> underlying, List<OIndexDefinition> indexDefinitions, Object[] params, int multiValueIndex) { this.underlying = underlying; this.params = params; this.multiValueIndex = multiValueIndex; this.indexDefinitions = indexDefinitions; } public int size() { return underlying.size(); } public boolean isEmpty() { return underlying.isEmpty(); } public boolean containsKey(Object key) { final OCompositeKey compositeKey = convertToCompositeKey(key); return underlying.containsKey(compositeKey); } public boolean containsValue(Object value) { return underlying.containsValue(value); } public Integer get(Object key) { return underlying.get(convertToCompositeKey(key)); } public Integer put(Object key, Integer value) { final OCompositeKey compositeKey = convertToCompositeKey(key); return underlying.put(compositeKey, value); } public Integer remove(Object key) { return underlying.remove(convertToCompositeKey(key)); } public void putAll(Map<? extends Object, ? extends Integer> m) { throw new UnsupportedOperationException("Unsupported because of performance reasons"); } public void clear() { underlying.clear(); } public Set<Object> keySet() { throw new UnsupportedOperationException("Unsupported because of performance reasons"); } public Collection<Integer> values() { return underlying.values(); } public Set<Entry<Object, Integer>> entrySet() { throw new UnsupportedOperationException(); } private OCompositeKey convertToCompositeKey(Object key) { final OCompositeKey compositeKey = new OCompositeKey(); int paramsIndex = 0; for (int i = 0; i < indexDefinitions.size(); i++) { final OIndexDefinition indexDefinition = indexDefinitions.get(i); if (i != multiValueIndex) { compositeKey.addKey(indexDefinition.createValue(params[paramsIndex])); paramsIndex++; } else compositeKey.addKey(((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(key)); } return compositeKey; } } @Override public boolean isAutomatic() { return indexDefinitions.get(0).isAutomatic(); } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_OCompositeIndexDefinition.java
1,400
@XmlRootElement(name = "orderAttribute") @XmlAccessorType(value = XmlAccessType.FIELD) public class OrderAttributeWrapper extends BaseWrapper implements APIWrapper<OrderAttribute> { @XmlElement protected Long id; @XmlElement protected String name; @XmlElement protected String value; @XmlElement protected Long orderId; @Override public void wrapDetails(OrderAttribute model, HttpServletRequest request) { this.id = model.getId(); this.name = model.getName(); this.value = model.getValue(); this.orderId = model.getOrder().getId(); } @Override public void wrapSummary(OrderAttribute model, HttpServletRequest request) { wrapDetails(model, request); } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_wrapper_OrderAttributeWrapper.java
300
public abstract class AbstractConfiguration implements Configuration { private final ConfigNamespace root; protected AbstractConfiguration(ConfigNamespace root) { Preconditions.checkNotNull(root); Preconditions.checkArgument(!root.isUmbrella(),"Root cannot be an umbrella namespace"); this.root = root; } public ConfigNamespace getRootNamespace() { return root; } protected void verifyElement(ConfigElement element) { Preconditions.checkNotNull(element); Preconditions.checkArgument(element.getRoot().equals(root),"Configuration element is not associated with this configuration: %s",element); } protected String getPath(ConfigElement option, String... umbrellaElements) { verifyElement(option); return ConfigElement.getPath(option,umbrellaElements); } protected Set<String> getContainedNamespaces(ReadConfiguration config, ConfigNamespace umbrella, String... umbrellaElements) { verifyElement(umbrella); Preconditions.checkArgument(umbrella.isUmbrella()); String prefix = ConfigElement.getPath(umbrella,umbrellaElements); Set<String> result = Sets.newHashSet(); for (String key : config.getKeys(prefix)) { Preconditions.checkArgument(key.startsWith(prefix)); String sub = key.substring(prefix.length()+1).trim(); if (!sub.isEmpty()) { String ns = ConfigElement.getComponents(sub)[0]; Preconditions.checkArgument(StringUtils.isNotBlank(ns),"Invalid sub-namespace for key: %s",key); result.add(ns); } } return result; } protected Map<String,Object> getSubset(ReadConfiguration config, ConfigNamespace umbrella, String... umbrellaElements) { verifyElement(umbrella); String prefix = ConfigElement.getPath(umbrella,umbrellaElements); Map<String,Object> result = Maps.newHashMap(); for (String key : config.getKeys(prefix)) { Preconditions.checkArgument(key.startsWith(prefix)); String sub = key.substring(prefix.length()+1).trim(); if (!sub.isEmpty()) { result.put(sub,config.get(key,Object.class)); } } return result; } protected static Configuration restrictTo(final Configuration config, final String... fixedUmbrella) { Preconditions.checkArgument(fixedUmbrella!=null && fixedUmbrella.length>0); return new Configuration() { private String[] concat(String... others) { if (others==null || others.length==0) return fixedUmbrella; String[] join = new String[fixedUmbrella.length+others.length]; System.arraycopy(fixedUmbrella,0,join,0,fixedUmbrella.length); System.arraycopy(others,0,join,fixedUmbrella.length,others.length); return join; } @Override public boolean has(ConfigOption option, String... umbrellaElements) { if (option.getNamespace().hasUmbrella()) return config.has(option,concat(umbrellaElements)); else return config.has(option); } @Override public <O> O get(ConfigOption<O> option, String... umbrellaElements) { if (option.getNamespace().hasUmbrella()) return config.get(option,concat(umbrellaElements)); else return config.get(option); } @Override public Set<String> getContainedNamespaces(ConfigNamespace umbrella, String... umbrellaElements) { return config.getContainedNamespaces(umbrella,concat(umbrellaElements)); } @Override public Map<String, Object> getSubset(ConfigNamespace umbrella, String... umbrellaElements) { return config.getSubset(umbrella,concat(umbrellaElements)); } @Override public Configuration restrictTo(String... umbrellaElements) { return config.restrictTo(concat(umbrellaElements)); } }; } public abstract void close(); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_AbstractConfiguration.java
3,030
public class DocValuesFormats { private static final ImmutableMap<String, PreBuiltDocValuesFormatProvider.Factory> builtInDocValuesFormats; static { MapBuilder<String, PreBuiltDocValuesFormatProvider.Factory> builtInDocValuesFormatsX = MapBuilder.newMapBuilder(); for (String name : DocValuesFormat.availableDocValuesFormats()) { builtInDocValuesFormatsX.put(name, new PreBuiltDocValuesFormatProvider.Factory(DocValuesFormat.forName(name))); } // LUCENE UPGRADE: update those DVF if necessary builtInDocValuesFormatsX.put(DocValuesFormatService.DEFAULT_FORMAT, new PreBuiltDocValuesFormatProvider.Factory(DocValuesFormatService.DEFAULT_FORMAT, DocValuesFormat.forName("Lucene45"))); builtInDocValuesFormatsX.put("memory", new PreBuiltDocValuesFormatProvider.Factory("memory", DocValuesFormat.forName("Memory"))); builtInDocValuesFormatsX.put("disk", new PreBuiltDocValuesFormatProvider.Factory("disk", DocValuesFormat.forName("Disk"))); builtInDocValuesFormats = builtInDocValuesFormatsX.immutableMap(); } public static DocValuesFormatProvider.Factory getAsFactory(String name) { return builtInDocValuesFormats.get(name); } public static DocValuesFormatProvider getAsProvider(String name) { final PreBuiltDocValuesFormatProvider.Factory factory = builtInDocValuesFormats.get(name); return factory == null ? null : factory.get(); } public static ImmutableCollection<PreBuiltDocValuesFormatProvider.Factory> listFactories() { return builtInDocValuesFormats.values(); } }
0true
src_main_java_org_elasticsearch_index_codec_docvaluesformat_DocValuesFormats.java
546
refreshAction.execute(Requests.refreshRequest(request.indices()), new ActionListener<RefreshResponse>() { @Override public void onResponse(RefreshResponse refreshResponse) { removeMapping(); } @Override public void onFailure(Throwable e) { removeMapping(); } protected void removeMapping() { DeleteMappingClusterStateUpdateRequest clusterStateUpdateRequest = new DeleteMappingClusterStateUpdateRequest() .indices(request.indices()).types(request.types()) .ackTimeout(request.timeout()) .masterNodeTimeout(request.masterNodeTimeout()); metaDataMappingService.removeMapping(clusterStateUpdateRequest, new ClusterStateUpdateListener() { @Override public void onResponse(ClusterStateUpdateResponse response) { listener.onResponse(new DeleteMappingResponse(response.isAcknowledged())); } @Override public void onFailure(Throwable t) { listener.onFailure(t); } }); } });
1no label
src_main_java_org_elasticsearch_action_admin_indices_mapping_delete_TransportDeleteMappingAction.java
708
constructors[COLLECTION_REMOVE_LISTENER] = new ConstructorFunction<Integer, Portable>() { public Portable createNew(Integer arg) { return new CollectionRemoveListenerRequest(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java
1,438
public class Invalidation implements DataSerializable { private Object key; private Object version; public Invalidation() { } public Invalidation(final Object key, final Object version) { this.key = key; this.version = version; } public Object getKey() { return key; } public Object getVersion() { return version; } public void writeData(final ObjectDataOutput out) throws IOException { out.writeObject(key); out.writeObject(version); } public void readData(final ObjectDataInput in) throws IOException { key = in.readObject(); version = in.readObject(); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Invalidation"); sb.append("{key=").append(key); sb.append(", version=").append(version); sb.append('}'); return sb.toString(); } }
0true
hazelcast-hibernate_hazelcast-hibernate4_src_main_java_com_hazelcast_hibernate_local_Invalidation.java
191
public class ClientProperties { public static final String PROP_CONNECTION_TIMEOUT = "hazelcast.client.connection.timeout"; public static final String PROP_CONNECTION_TIMEOUT_DEFAULT = "5000"; public static final String PROP_HEARTBEAT_INTERVAL = "hazelcast.client.heartbeat.interval"; public static final String PROP_HEARTBEAT_INTERVAL_DEFAULT = "10000"; public static final String PROP_MAX_FAILED_HEARTBEAT_COUNT = "hazelcast.client.max.failed.heartbeat.count"; public static final String PROP_MAX_FAILED_HEARTBEAT_COUNT_DEFAULT = "3"; public static final String PROP_RETRY_COUNT = "hazelcast.client.retry.count"; public static final String PROP_RETRY_COUNT_DEFAULT = "20"; public static final String PROP_RETRY_WAIT_TIME = "hazelcast.client.retry.wait.time"; public static final String PROP_RETRY_WAIT_TIME_DEFAULT = "250"; public final ClientProperty CONNECTION_TIMEOUT; public final ClientProperty HEARTBEAT_INTERVAL; public final ClientProperty MAX_FAILED_HEARTBEAT_COUNT; public final ClientProperty RETRY_COUNT; public final ClientProperty RETRY_WAIT_TIME; public ClientProperties(ClientConfig clientConfig) { CONNECTION_TIMEOUT = new ClientProperty(clientConfig, PROP_CONNECTION_TIMEOUT, PROP_CONNECTION_TIMEOUT_DEFAULT); HEARTBEAT_INTERVAL = new ClientProperty(clientConfig, PROP_HEARTBEAT_INTERVAL, PROP_HEARTBEAT_INTERVAL_DEFAULT); MAX_FAILED_HEARTBEAT_COUNT = new ClientProperty(clientConfig, PROP_MAX_FAILED_HEARTBEAT_COUNT, PROP_MAX_FAILED_HEARTBEAT_COUNT_DEFAULT); RETRY_COUNT = new ClientProperty(clientConfig, PROP_RETRY_COUNT, PROP_RETRY_COUNT_DEFAULT); RETRY_WAIT_TIME = new ClientProperty(clientConfig, PROP_RETRY_WAIT_TIME, PROP_RETRY_WAIT_TIME_DEFAULT); } public static class ClientProperty { private final String name; private final String value; ClientProperty(ClientConfig config, String name) { this(config, name, (String) null); } ClientProperty(ClientConfig config, String name, ClientProperty defaultValue) { this(config, name, defaultValue != null ? defaultValue.getString() : null); } ClientProperty(ClientConfig config, String name, String defaultValue) { this.name = name; String configValue = (config != null) ? config.getProperty(name) : null; if (configValue != null) { value = configValue; } else if (System.getProperty(name) != null) { value = System.getProperty(name); } else { value = defaultValue; } } public String getName() { return this.name; } public String getValue() { return value; } public int getInteger() { return Integer.parseInt(this.value); } public byte getByte() { return Byte.parseByte(this.value); } public boolean getBoolean() { return Boolean.valueOf(this.value); } public String getString() { return value; } public long getLong() { return Long.parseLong(this.value); } @Override public String toString() { return "ClientProperty [name=" + this.name + ", value=" + this.value + "]"; } } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_config_ClientProperties.java
371
future.andThen(new ExecutionCallback<Integer>() { @Override public void onResponse(Integer response) { try { result[0] = response.intValue(); } finally { semaphore.release(); } } @Override public void onFailure(Throwable t) { semaphore.release(); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_DistributedMapperClientMapReduceTest.java
351
@SuppressWarnings("unchecked") public abstract class ODatabaseWrapperAbstract<DB extends ODatabase> implements ODatabase { protected DB underlying; protected ODatabaseComplex<?> databaseOwner; public ODatabaseWrapperAbstract(final DB iDatabase) { underlying = iDatabase; databaseOwner = (ODatabaseComplex<?>) this; } @Override public void finalize() { // close(); } public <THISDB extends ODatabase> THISDB open(final String iUserName, final String iUserPassword) { underlying.open(iUserName, iUserPassword); Orient.instance().getDatabaseFactory().register(databaseOwner); return (THISDB) this; } public <THISDB extends ODatabase> THISDB create() { underlying.create(); Orient.instance().getDatabaseFactory().register(databaseOwner); return (THISDB) this; } public boolean exists() { return underlying.exists(); } public void reload() { underlying.reload(); } @Override public void backup(OutputStream out, Map<String, Object> options, Callable<Object> callable) throws IOException { underlying.backup(out, options, callable); } @Override public void restore(InputStream in, Map<String, Object> options, Callable<Object> callable) throws IOException { underlying.restore(in, options, callable); } public void close() { underlying.close(); Orient.instance().getDatabaseFactory().unregister(databaseOwner); } public void replaceStorage(OStorage iNewStorage) { underlying.replaceStorage(iNewStorage); } public void drop() { underlying.drop(); Orient.instance().getDatabaseFactory().unregister(databaseOwner); } public STATUS getStatus() { return underlying.getStatus(); } public <THISDB extends ODatabase> THISDB setStatus(final STATUS iStatus) { underlying.setStatus(iStatus); return (THISDB) this; } public String getName() { return underlying.getName(); } public String getURL() { return underlying.getURL(); } public OStorage getStorage() { return underlying.getStorage(); } public OLevel1RecordCache getLevel1Cache() { return underlying.getLevel1Cache(); } public OLevel2RecordCache getLevel2Cache() { return getStorage().getLevel2Cache(); } public boolean isClosed() { return underlying.isClosed(); } public long countClusterElements(final int iClusterId) { checkOpeness(); return underlying.countClusterElements(iClusterId); } public long countClusterElements(final int[] iClusterIds) { checkOpeness(); return underlying.countClusterElements(iClusterIds); } public long countClusterElements(final String iClusterName) { checkOpeness(); return underlying.countClusterElements(iClusterName); } @Override public long countClusterElements(int iClusterId, boolean countTombstones) { checkOpeness(); return underlying.countClusterElements(iClusterId, countTombstones); } @Override public long countClusterElements(int[] iClusterIds, boolean countTombstones) { checkOpeness(); return underlying.countClusterElements(iClusterIds, countTombstones); } public int getClusters() { checkOpeness(); return underlying.getClusters(); } public boolean existsCluster(String iClusterName) { checkOpeness(); return underlying.existsCluster(iClusterName); } public Collection<String> getClusterNames() { checkOpeness(); return underlying.getClusterNames(); } public String getClusterType(final String iClusterName) { checkOpeness(); return underlying.getClusterType(iClusterName); } public int getDataSegmentIdByName(final String iDataSegmentName) { checkOpeness(); return underlying.getDataSegmentIdByName(iDataSegmentName); } public String getDataSegmentNameById(final int iDataSegmentId) { checkOpeness(); return underlying.getDataSegmentNameById(iDataSegmentId); } public int getClusterIdByName(final String iClusterName) { checkOpeness(); return underlying.getClusterIdByName(iClusterName); } public String getClusterNameById(final int iClusterId) { checkOpeness(); return underlying.getClusterNameById(iClusterId); } public long getClusterRecordSizeById(int iClusterId) { return underlying.getClusterRecordSizeById(iClusterId); } public long getClusterRecordSizeByName(String iClusterName) { return underlying.getClusterRecordSizeByName(iClusterName); } public int addCluster(final String iType, final String iClusterName, final String iLocation, final String iDataSegmentName, final Object... iParameters) { checkOpeness(); return underlying.addCluster(iType, iClusterName, iLocation, iDataSegmentName, iParameters); } public int addCluster(String iType, String iClusterName, int iRequestedId, String iLocation, String iDataSegmentName, Object... iParameters) { return underlying.addCluster(iType, iClusterName, iRequestedId, iLocation, iDataSegmentName, iParameters); } public int addCluster(final String iClusterName, final CLUSTER_TYPE iType, final Object... iParameters) { checkOpeness(); return underlying.addCluster(iType.toString(), iClusterName, null, null, iParameters); } public int addCluster(String iClusterName, CLUSTER_TYPE iType) { checkOpeness(); return underlying.addCluster(iType.toString(), iClusterName, null, null); } public boolean dropDataSegment(final String name) { return underlying.dropDataSegment(name); } public boolean dropCluster(final String iClusterName, final boolean iTruncate) { getLevel1Cache().freeCluster(getClusterIdByName(iClusterName)); return underlying.dropCluster(iClusterName, true); } public boolean dropCluster(final int iClusterId, final boolean iTruncate) { getLevel1Cache().freeCluster(iClusterId); return underlying.dropCluster(iClusterId, true); } public int addDataSegment(final String iSegmentName, final String iLocation) { checkOpeness(); return underlying.addDataSegment(iSegmentName, iLocation); } public int getDefaultClusterId() { checkOpeness(); return underlying.getDefaultClusterId(); } public boolean declareIntent(final OIntent iIntent) { checkOpeness(); return underlying.declareIntent(iIntent); } public <DBTYPE extends ODatabase> DBTYPE getUnderlying() { return (DBTYPE) underlying; } public ODatabaseComplex<?> getDatabaseOwner() { return databaseOwner; } public ODatabaseComplex<?> setDatabaseOwner(final ODatabaseComplex<?> iOwner) { databaseOwner = iOwner; return (ODatabaseComplex<?>) this; } @Override public boolean equals(final Object iOther) { if (!(iOther instanceof ODatabase)) return false; final ODatabase other = (ODatabase) iOther; return other.getName().equals(getName()); } @Override public String toString() { return underlying.toString(); } public Object setProperty(final String iName, final Object iValue) { return underlying.setProperty(iName, iValue); } public Object getProperty(final String iName) { return underlying.getProperty(iName); } public Iterator<Entry<String, Object>> getProperties() { return underlying.getProperties(); } public Object get(final ATTRIBUTES iAttribute) { return underlying.get(iAttribute); } public <THISDB extends ODatabase> THISDB set(final ATTRIBUTES attribute, final Object iValue) { return (THISDB) underlying.set(attribute, iValue); } public void registerListener(final ODatabaseListener iListener) { underlying.registerListener(iListener); } public void unregisterListener(final ODatabaseListener iListener) { underlying.unregisterListener(iListener); } public <V> V callInLock(final Callable<V> iCallable, final boolean iExclusiveLock) { return getStorage().callInLock(iCallable, iExclusiveLock); } @Override public <V> V callInRecordLock(Callable<V> iCallable, ORID rid, boolean iExclusiveLock) { return underlying.callInRecordLock(iCallable, rid, iExclusiveLock); } @Override public ORecordMetadata getRecordMetadata(ORID rid) { return underlying.getRecordMetadata(rid); } public long getSize() { return underlying.getSize(); } protected void checkOpeness() { if (isClosed()) throw new ODatabaseException("Database '" + getURL() + "' is closed"); } public void freeze(boolean throwException) { underlying.freeze(throwException); } public void freeze() { underlying.freeze(); } public void release() { underlying.release(); } @Override public void freezeCluster(int iClusterId, boolean throwException) { underlying.freezeCluster(iClusterId, throwException); } @Override public void freezeCluster(int iClusterId) { underlying.freezeCluster(iClusterId); } @Override public void releaseCluster(int iClusterId) { underlying.releaseCluster(iClusterId); } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_ODatabaseWrapperAbstract.java
854
execute(request, new ActionListener<SearchResponse>() { @Override public void onResponse(SearchResponse result) { try { channel.sendResponse(result); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(e); } catch (Exception e1) { logger.warn("Failed to send response for search", e1); } } });
0true
src_main_java_org_elasticsearch_action_search_TransportSearchScrollAction.java
66
public class AwsURLEncoder { private AwsURLEncoder() { } public static String urlEncode(String string) { String encoded; try { encoded = URLEncoder.encode(string, "UTF-8").replace("+", "%20"); } catch (UnsupportedEncodingException e) { throw new HazelcastException(e); } return encoded; } }
0true
hazelcast-cloud_src_main_java_com_hazelcast_aws_utility_AwsURLEncoder.java
319
public static class Provider extends TransactionManagerProvider { public Provider() { super( NAME ); } @Override public AbstractTransactionManager loadTransactionManager( String txLogDir, XaDataSourceManager xaDataSourceManager, KernelPanicEventGenerator kpe, RemoteTxHook rollbackHook, StringLogger msgLog, FileSystemAbstraction fileSystem, TransactionStateFactory stateFactory ) { return new JOTMTransactionManager( xaDataSourceManager, stateFactory ); } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_JOTMTransactionManager.java
1,114
static class IntEntry { int key; int counter; IntEntry(int key, int counter) { this.key = key; this.counter = counter; } }
0true
src_test_java_org_elasticsearch_benchmark_hppc_StringMapAdjustOrPutBenchmark.java
2,495
public class AddEntryListenerRequest extends CallableClientRequest implements RetryableRequest { String name; Data key; boolean includeValue; public AddEntryListenerRequest() { } public AddEntryListenerRequest(String name, Data key, boolean includeValue) { this.name = name; this.key = key; this.includeValue = includeValue; } public Object call() throws Exception { final ClientEndpoint endpoint = getEndpoint(); final ClientEngine clientEngine = getClientEngine(); final MultiMapService service = getService(); EntryListener listener = new EntryAdapter() { @Override public void onEntryEvent(EntryEvent event) { send(event); } private void send(EntryEvent event) { if (endpoint.live()) { Data key = clientEngine.toData(event.getKey()); Data value = clientEngine.toData(event.getValue()); Data oldValue = clientEngine.toData(event.getOldValue()); final EntryEventType type = event.getEventType(); final String uuid = event.getMember().getUuid(); PortableEntryEvent portableEntryEvent = new PortableEntryEvent(key, value, oldValue, type, uuid); endpoint.sendEvent(portableEntryEvent, getCallId()); } } }; String registrationId = service.addListener(name, listener, key, includeValue, false); endpoint.setListenerRegistration(MultiMapService.SERVICE_NAME, name, registrationId); return registrationId; } public String getServiceName() { return MultiMapService.SERVICE_NAME; } public int getFactoryId() { return MultiMapPortableHook.F_ID; } public int getClassId() { return MultiMapPortableHook.ADD_ENTRY_LISTENER; } public void write(PortableWriter writer) throws IOException { writer.writeBoolean("i", includeValue); writer.writeUTF("n", name); final ObjectDataOutput out = writer.getRawDataOutput(); IOUtil.writeNullableData(out, key); } public void read(PortableReader reader) throws IOException { includeValue = reader.readBoolean("i"); name = reader.readUTF("n"); final ObjectDataInput in = reader.getRawDataInput(); key = IOUtil.readNullableData(in); } public Permission getRequiredPermission() { return new MultiMapPermission(name, ActionConstants.ACTION_LISTEN); } }
1no label
hazelcast_src_main_java_com_hazelcast_multimap_operations_client_AddEntryListenerRequest.java
146
public class TitanId { /** * Converts a user provided long id into a Titan vertex id. The id must be positive and can be at most 61 bits long. * This method is useful when providing ids during vertex creation via {@link com.tinkerpop.blueprints.Graph#addVertex(Object)}. * * @param id long id * @return a corresponding Titan vertex id */ public static final long toVertexId(long id) { Preconditions.checkArgument(id > 0, "Vertex id must be positive: %s", id); Preconditions.checkArgument(IDManager.VertexIDType.NormalVertex.removePadding(Long.MAX_VALUE) >= id, "Vertex id is too large: %s", id); return IDManager.VertexIDType.NormalVertex.addPadding(id); } /** * Converts a Titan vertex id to the user provided id as the inverse mapping of {@link #toVertexId(long)}. * * @param id Titan vertex id (must be positive) * @return original user provided id */ public static final long fromVertexId(long id) { Preconditions.checkArgument(id > 0, "Invalid vertex id provided: %s", id); return IDManager.VertexIDType.NormalVertex.removePadding(id); } /** * Converts a Titan vertex id of a given vertex to the user provided id as the inverse mapping of {@link #toVertexId(long)}. * * @param v Vertex * @return original user provided id */ public static final long fromVertexID(TitanVertex v) { Preconditions.checkArgument(v.hasId(), "Invalid vertex provided: %s", v); return fromVertexId(v.getLongId()); } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_util_TitanId.java
263
assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(executions, counter.get()); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_executor_ExecutionDelayTest.java
511
public class OEntityManagerInternal extends OEntityManager { public static final OEntityManagerInternal INSTANCE = new OEntityManagerInternal(); }
0true
core_src_main_java_com_orientechnologies_orient_core_entity_OEntityManagerInternal.java
1,113
public class RemoveFromCartException extends Exception { private static final long serialVersionUID = 1L; public RemoveFromCartException() { super(); } public RemoveFromCartException(String message, Throwable cause) { super(message, cause); } public RemoveFromCartException(String message) { super(message); } public RemoveFromCartException(Throwable cause) { super(cause); } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_exception_RemoveFromCartException.java
1,155
public class HazelcastInstanceNotActiveException extends IllegalStateException { public HazelcastInstanceNotActiveException() { super("Hazelcast instance is not active!"); } }
1no label
hazelcast_src_main_java_com_hazelcast_core_HazelcastInstanceNotActiveException.java
1,356
public static final class TestRecord implements OWALRecord { private OLogSequenceNumber lsn; private byte[] data; private boolean updateMasterRecord; public TestRecord() { } public TestRecord(int size, boolean updateMasterRecord) { Random random = new Random(); data = new byte[size - OIntegerSerializer.INT_SIZE - (OIntegerSerializer.INT_SIZE + 3) - 1]; random.nextBytes(data); this.updateMasterRecord = updateMasterRecord; } @Override public int toStream(byte[] content, int offset) { content[offset] = updateMasterRecord ? (byte) 1 : 0; offset++; OIntegerSerializer.INSTANCE.serializeNative(data.length, content, offset); offset += OIntegerSerializer.INT_SIZE; System.arraycopy(data, 0, content, offset, data.length); offset += data.length; return offset; } @Override public int fromStream(byte[] content, int offset) { updateMasterRecord = content[offset] > 0; offset++; int size = OIntegerSerializer.INSTANCE.deserializeNative(content, offset); offset += OIntegerSerializer.INT_SIZE; data = new byte[size]; System.arraycopy(content, offset, data, 0, data.length); offset += size; return offset; } @Override public int serializedSize() { return OIntegerSerializer.INT_SIZE + data.length + 1; } @Override public boolean isUpdateMasterRecord() { return updateMasterRecord; } @Override public OLogSequenceNumber getLsn() { return lsn; } @Override public void setLsn(OLogSequenceNumber lsn) { this.lsn = lsn; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TestRecord that = (TestRecord) o; if (updateMasterRecord != that.updateMasterRecord) return false; if (!Arrays.equals(data, that.data)) return false; return true; } @Override public int hashCode() { int result = Arrays.hashCode(data); result = 31 * result + (updateMasterRecord ? 1 : 0); return result; } @Override public String toString() { return "TestRecord {size: " + (data.length + OIntegerSerializer.INT_SIZE + 1 + (OIntegerSerializer.INT_SIZE + 3) + ", updateMasterRecord : " + updateMasterRecord + "}"); } }
0true
core_src_test_java_com_orientechnologies_orient_core_storage_impl_local_paginated_wal_WriteAheadLogTest.java
1,486
public class BroadleafRatingsController { @Resource(name = "blRatingService") protected RatingService ratingService; @Resource(name = "blCatalogService") protected CatalogService catalogService; protected String formView = "catalog/partials/review"; protected String successView = "catalog/partials/reviewSuccessful"; public String viewReviewForm(HttpServletRequest request, Model model, ReviewForm form, String itemId) { Product product = catalogService.findProductById(Long.valueOf(itemId)); form.setProduct(product); ReviewDetail reviewDetail = ratingService.readReviewByCustomerAndItem(CustomerState.getCustomer(), itemId); if (reviewDetail != null) { form.setReviewText(reviewDetail.getReviewText()); form.setRating(reviewDetail.getRatingDetail().getRating()); } model.addAttribute("reviewForm", form); return getFormView(); } public String reviewItem(HttpServletRequest request, Model model, ReviewForm form, String itemId) { ratingService.reviewItem(itemId, RatingType.PRODUCT, CustomerState.getCustomer(), form.getRating(), form.getReviewText()); model.addAttribute("reviewForm", form); return getSuccessView(); } public String getFormView() { return formView; } public String getSuccessView() { return successView; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_catalog_BroadleafRatingsController.java
1,855
@RunWith(HazelcastParallelClassRunner.class) @Category(NightlyTest.class) public class MapTransactionStressTest extends HazelcastTestSupport { @Test public void testTxnGetForUpdateAndIncrementStressTest() throws TransactionException, InterruptedException { Config config = new Config(); final TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2); final HazelcastInstance h1 = factory.newHazelcastInstance(config); final HazelcastInstance h2 = factory.newHazelcastInstance(config); final IMap<String, Integer> map = h2.getMap("default"); final String key = "count"; int count1 = 13000; int count2 = 15000; final CountDownLatch latch = new CountDownLatch(count1 + count2); map.put(key, 0); new Thread(new TxnIncrementor(count1, h1, latch)).start(); new Thread(new TxnIncrementor(count2, h2, latch)).start(); latch.await(600, TimeUnit.SECONDS); assertEquals(new Integer(count1 + count2), map.get(key)); } static class TxnIncrementor implements Runnable { int count = 0; HazelcastInstance instance; final String key = "count"; final CountDownLatch latch; TxnIncrementor(int count, HazelcastInstance instance, CountDownLatch latch) { this.count = count; this.instance = instance; this.latch = latch; } @Override public void run() { for (int i = 0; i < count; i++) { instance.executeTransaction(new TransactionalTask<Boolean>() { public Boolean execute(TransactionalTaskContext context) throws TransactionException { final TransactionalMap<String, Integer> txMap = context.getMap("default"); Integer value = txMap.getForUpdate(key); txMap.put(key, value + 1); return true; } }); latch.countDown(); } } } }
0true
hazelcast_src_test_java_com_hazelcast_map_MapTransactionStressTest.java
1,199
public interface MigrationListener extends EventListener { /** * Invoked when a partition migration is started. * * @param migrationEvent event */ void migrationStarted(MigrationEvent migrationEvent); /** * Invoked when a partition migration is completed. * * @param migrationEvent event */ void migrationCompleted(MigrationEvent migrationEvent); /** * Invoked when a partition migration is failed. * * @param migrationEvent event */ void migrationFailed(MigrationEvent migrationEvent); }
0true
hazelcast_src_main_java_com_hazelcast_core_MigrationListener.java
1,285
es.submit(new Runnable() { public void run() { IMap map = hazelcast.getMap("default"); while (true) { int keyInt = (int) (RANDOM.nextFloat() * ENTRY_COUNT); int operation = ((int) (RANDOM.nextFloat() * 1000)) % 20; Object key = String.valueOf(keyInt); if (operation < 1) { map.size(); stats.increment("size"); } else if (operation < 2) { map.get(key); stats.increment("get"); } else if (operation < 3) { map.remove(key); stats.increment("remove"); } else if (operation < 4) { map.containsKey(key); stats.increment("containsKey"); } else if (operation < 5) { Object value = String.valueOf(key); map.containsValue(value); stats.increment("containsValue"); } else if (operation < 6) { map.putIfAbsent(key, createValue()); stats.increment("putIfAbsent"); } else if (operation < 7) { Collection col = map.values(); for (Object o : col) { int i = 0; } stats.increment("values"); } else if (operation < 8) { Collection col = map.keySet(); for (Object o : col) { int i = 0; } stats.increment("keySet"); } else if (operation < 9) { Collection col = map.entrySet(); for (Object o : col) { int i = 0; } stats.increment("entrySet"); } else { map.put(key, createValue()); stats.increment("put"); } } } });
0true
hazelcast_src_main_java_com_hazelcast_examples_SimpleFunctionalMapTest.java
1,196
public class PaymentInfoServiceTest extends BaseTest { String userName = new String(); private PaymentInfo paymentInfo; @Resource private PaymentInfoService paymentInfoService; @Resource(name = "blOrderService") private OrderService orderService; @Resource private CustomerAddressDao customerAddressDao; @Resource private CustomerService customerService; @Test(groups={"createPaymentInfo"}, dataProvider="basicPaymentInfo", dataProviderClass=PaymentInfoDataProvider.class, dependsOnGroups={"readCustomer", "createOrder"}) @Rollback(false) @Transactional public void createPaymentInfo(PaymentInfo paymentInfo){ userName = "customer1"; Customer customer = customerService.readCustomerByUsername(userName); List<CustomerAddress> addresses = customerAddressDao.readActiveCustomerAddressesByCustomerId(customer.getId()); Address address = null; if (!addresses.isEmpty()) address = addresses.get(0).getAddress(); Order salesOrder = orderService.createNewCartForCustomer(customer); paymentInfo.setAddress(address); paymentInfo.setOrder(salesOrder); paymentInfo.setType(PaymentInfoType.CREDIT_CARD); assert paymentInfo.getId() == null; paymentInfo = paymentInfoService.save(paymentInfo); assert paymentInfo.getId() != null; this.paymentInfo = paymentInfo; } @Test(groups={"readPaymentInfoById"}, dependsOnGroups={"createPaymentInfo"}) public void readPaymentInfoById(){ PaymentInfo sop = paymentInfoService.readPaymentInfoById(paymentInfo.getId()); assert sop !=null; assert sop.getId().equals(paymentInfo.getId()); } @Test(groups={"readPaymentInfosByOrder"}, dependsOnGroups={"createPaymentInfo"}) @Transactional public void readPaymentInfoByOrder(){ List<PaymentInfo> payments = paymentInfoService.readPaymentInfosForOrder(paymentInfo.getOrder()); assert payments != null; assert payments.size() > 0; } @Test(groups={"testCreatePaymentInfo"}, dependsOnGroups={"createPaymentInfo"}) @Transactional public void createTestPaymentInfo(){ userName = "customer1"; PaymentInfo paymentInfo = paymentInfoService.create(); Customer customer = customerService.readCustomerByUsername(userName); List<CustomerAddress> addresses = customerAddressDao.readActiveCustomerAddressesByCustomerId(customer.getId()); Address address = null; if (!addresses.isEmpty()) address = addresses.get(0).getAddress(); Order salesOrder = orderService.findCartForCustomer(customer); paymentInfo.setAddress(address); paymentInfo.setOrder(salesOrder); paymentInfo.setType(PaymentInfoType.CREDIT_CARD); assert paymentInfo != null; paymentInfo = paymentInfoService.save(paymentInfo); assert paymentInfo.getId() != null; Long paymentInfoId = paymentInfo.getId(); paymentInfoService.delete(paymentInfo); paymentInfo = paymentInfoService.readPaymentInfoById(paymentInfoId); assert paymentInfo == null; } }
0true
integration_src_test_java_org_broadleafcommerce_core_payment_service_PaymentInfoServiceTest.java
2,062
public final class Modules { private Modules() { } public static final Module EMPTY_MODULE = new Module() { public void configure(Binder binder) { } }; /** * Returns a builder that creates a module that overlays override modules over the given * modules. If a key is bound in both sets of modules, only the binding from the override modules * is kept. This can be used to replace the bindings of a production module with test bindings: * <pre> * Module functionalTestModule * = Modules.override(new ProductionModule()).with(new TestModule()); * </pre> * <p/> * <p>Prefer to write smaller modules that can be reused and tested without overrides. * * @param modules the modules whose bindings are open to be overridden */ public static OverriddenModuleBuilder override(Module... modules) { return new RealOverriddenModuleBuilder(Arrays.asList(modules)); } /** * Returns a builder that creates a module that overlays override modules over the given * modules. If a key is bound in both sets of modules, only the binding from the override modules * is kept. This can be used to replace the bindings of a production module with test bindings: * <pre> * Module functionalTestModule * = Modules.override(getProductionModules()).with(getTestModules()); * </pre> * <p/> * <p>Prefer to write smaller modules that can be reused and tested without overrides. * * @param modules the modules whose bindings are open to be overridden */ public static OverriddenModuleBuilder override(Iterable<? extends Module> modules) { return new RealOverriddenModuleBuilder(modules); } /** * Returns a new module that installs all of {@code modules}. */ public static Module combine(Module... modules) { return combine(ImmutableSet.copyOf(modules)); } /** * Returns a new module that installs all of {@code modules}. */ public static Module combine(Iterable<? extends Module> modules) { final Set<Module> modulesSet = ImmutableSet.copyOf(modules); return new Module() { public void configure(Binder binder) { binder = binder.skipSources(getClass()); for (Module module : modulesSet) { binder.install(module); } } }; } /** * See the EDSL example at {@link Modules#override(Module[]) override()}. */ public interface OverriddenModuleBuilder { /** * See the EDSL example at {@link Modules#override(Module[]) override()}. */ Module with(Module... overrides); /** * See the EDSL example at {@link Modules#override(Module[]) override()}. */ Module with(Iterable<? extends Module> overrides); } private static final class RealOverriddenModuleBuilder implements OverriddenModuleBuilder { private final ImmutableSet<Module> baseModules; private RealOverriddenModuleBuilder(Iterable<? extends Module> baseModules) { this.baseModules = ImmutableSet.copyOf(baseModules); } public Module with(Module... overrides) { return with(Arrays.asList(overrides)); } public Module with(final Iterable<? extends Module> overrides) { return new AbstractModule() { @Override public void configure() { final List<Element> elements = Elements.getElements(baseModules); final List<Element> overrideElements = Elements.getElements(overrides); final Set<Key> overriddenKeys = Sets.newHashSet(); final Set<Class<? extends Annotation>> overridesScopeAnnotations = Sets.newHashSet(); // execute the overrides module, keeping track of which keys and scopes are bound new ModuleWriter(binder()) { @Override public <T> Void visit(Binding<T> binding) { overriddenKeys.add(binding.getKey()); return super.visit(binding); } @Override public Void visit(ScopeBinding scopeBinding) { overridesScopeAnnotations.add(scopeBinding.getAnnotationType()); return super.visit(scopeBinding); } @Override public Void visit(PrivateElements privateElements) { overriddenKeys.addAll(privateElements.getExposedKeys()); return super.visit(privateElements); } }.writeAll(overrideElements); // execute the original module, skipping all scopes and overridden keys. We only skip each // overridden binding once so things still blow up if the module binds the same thing // multiple times. final Map<Scope, Object> scopeInstancesInUse = Maps.newHashMap(); final List<ScopeBinding> scopeBindings = Lists.newArrayList(); new ModuleWriter(binder()) { @Override public <T> Void visit(Binding<T> binding) { if (!overriddenKeys.remove(binding.getKey())) { super.visit(binding); // Record when a scope instance is used in a binding Scope scope = getScopeInstanceOrNull(binding); if (scope != null) { scopeInstancesInUse.put(scope, binding.getSource()); } } return null; } @Override public Void visit(PrivateElements privateElements) { PrivateBinder privateBinder = binder.withSource(privateElements.getSource()) .newPrivateBinder(); Set<Key<?>> skippedExposes = Sets.newHashSet(); for (Key<?> key : privateElements.getExposedKeys()) { if (overriddenKeys.remove(key)) { skippedExposes.add(key); } else { privateBinder.withSource(privateElements.getExposedSource(key)).expose(key); } } // we're not skipping deep exposes, but that should be okay. If we ever need to, we // have to search through this set of elements for PrivateElements, recursively for (Element element : privateElements.getElements()) { if (element instanceof Binding && skippedExposes.contains(((Binding) element).getKey())) { continue; } element.applyTo(privateBinder); } return null; } @Override public Void visit(ScopeBinding scopeBinding) { scopeBindings.add(scopeBinding); return null; } }.writeAll(elements); // execute the scope bindings, skipping scopes that have been overridden. Any scope that // is overridden and in active use will prompt an error new ModuleWriter(binder()) { @Override public Void visit(ScopeBinding scopeBinding) { if (!overridesScopeAnnotations.remove(scopeBinding.getAnnotationType())) { super.visit(scopeBinding); } else { Object source = scopeInstancesInUse.get(scopeBinding.getScope()); if (source != null) { binder().withSource(source).addError( "The scope for @%s is bound directly and cannot be overridden.", scopeBinding.getAnnotationType().getSimpleName()); } } return null; } }.writeAll(scopeBindings); // TODO: bind the overridden keys using multibinder } private Scope getScopeInstanceOrNull(Binding<?> binding) { return binding.acceptScopingVisitor(new DefaultBindingScopingVisitor<Scope>() { public Scope visitScope(Scope scope) { return scope; } }); } }; } } private static class ModuleWriter extends DefaultElementVisitor<Void> { protected final Binder binder; ModuleWriter(Binder binder) { this.binder = binder; } @Override protected Void visitOther(Element element) { element.applyTo(binder); return null; } void writeAll(Iterable<? extends Element> elements) { for (Element element : elements) { element.acceptVisitor(this); } } } }
0true
src_main_java_org_elasticsearch_common_inject_util_Modules.java
26
final class ImportVisitor extends Visitor { private final String prefix; private final CommonToken token; private final int offset; private final Node node; private final CeylonParseController cpc; private final List<ICompletionProposal> result; ImportVisitor(String prefix, CommonToken token, int offset, Node node, CeylonParseController cpc, List<ICompletionProposal> result) { this.prefix = prefix; this.token = token; this.offset = offset; this.node = node; this.cpc = cpc; this.result = result; } @Override public void visit(Tree.ModuleDescriptor that) { super.visit(that); if (that.getImportPath()==node) { addCurrentPackageNameCompletion(cpc, offset, fullPath(offset, prefix, that.getImportPath()) + prefix, result); } } public void visit(Tree.PackageDescriptor that) { super.visit(that); if (that.getImportPath()==node) { addCurrentPackageNameCompletion(cpc, offset, fullPath(offset, prefix, that.getImportPath()) + prefix, result); } } @Override public void visit(Tree.Import that) { super.visit(that); if (that.getImportPath()==node) { addPackageCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node, result, nextTokenType(cpc, token)!=CeylonLexer.LBRACE); } } @Override public void visit(Tree.PackageLiteral that) { super.visit(that); if (that.getImportPath()==node) { addPackageCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node, result, false); } } @Override public void visit(Tree.ImportModule that) { super.visit(that); if (that.getImportPath()==node) { addModuleCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node, result, nextTokenType(cpc, token)!=CeylonLexer.STRING_LITERAL); } } @Override public void visit(Tree.ModuleLiteral that) { super.visit(that); if (that.getImportPath()==node) { addModuleCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node, result, false); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ImportVisitor.java
513
public class OCommandExecutionException extends OException { private static final long serialVersionUID = -7430575036316163711L; public OCommandExecutionException(String message, Throwable cause) { super(message, cause); } public OCommandExecutionException(String message) { super(message); } }
0true
core_src_main_java_com_orientechnologies_orient_core_exception_OCommandExecutionException.java
67
public class TransactionAlreadyActiveException extends IllegalStateException { public TransactionAlreadyActiveException( Thread thread, Transaction tx ) { super( "Thread '" + thread.getName() + "' tried to resume " + tx + ", but that transaction is already active" ); } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TransactionAlreadyActiveException.java
3,461
private class SpringXmlBuilder extends SpringXmlBuilderHelper { private final ParserContext parserContext; private BeanDefinitionBuilder builder; private ManagedMap nearCacheConfigMap;//= new HashMap<String, NearCacheConfig>(); public SpringXmlBuilder(ParserContext parserContext) { this.parserContext = parserContext; this.builder = BeanDefinitionBuilder.rootBeanDefinition(HazelcastClient.class); this.builder.setFactoryMethod("newHazelcastClient"); this.builder.setDestroyMethodName("shutdown"); this.nearCacheConfigMap = new ManagedMap(); this.configBuilder = BeanDefinitionBuilder.rootBeanDefinition(ClientConfig.class); configBuilder.addPropertyValue("nearCacheConfigMap", nearCacheConfigMap); BeanDefinitionBuilder managedContextBeanBuilder = createBeanBuilder(SpringManagedContext.class); this.configBuilder.addPropertyValue("managedContext", managedContextBeanBuilder.getBeanDefinition()); } public AbstractBeanDefinition getBeanDefinition() { return builder.getBeanDefinition(); } public void handleClient(Element element) { handleCommonBeanAttributes(element, builder, parserContext); final NamedNodeMap attrs = element.getAttributes(); if (attrs != null) { for (int a = 0; a < attrs.getLength(); a++) { final org.w3c.dom.Node att = attrs.item(a); final String name = att.getNodeName(); final String value = att.getNodeValue(); if ("executor-pool-size".equals(name)) { configBuilder.addPropertyValue("executorPoolSize", value); } else if ("credentials-ref".equals(name)) { configBuilder.addPropertyReference("credentials", value); } } } for (org.w3c.dom.Node node : new IterableNodeList(element, Node.ELEMENT_NODE)) { final String nodeName = cleanNodeName(node.getNodeName()); if ("group".equals(nodeName)) { createAndFillBeanBuilder(node, GroupConfig.class, "groupConfig", configBuilder); } else if ("properties".equals(nodeName)) { handleProperties(node, configBuilder); } else if ("network".equals(nodeName)) { handleNetwork(node); } else if ("listeners".equals(nodeName)) { final List listeners = parseListeners(node, ListenerConfig.class); configBuilder.addPropertyValue("listenerConfigs", listeners); } else if ("serialization".equals(nodeName)) { handleSerialization(node); } else if ("proxy-factories".equals(nodeName)) { final List list = parseProxyFactories(node, ProxyFactoryConfig.class); configBuilder.addPropertyValue("proxyFactoryConfigs", list); } else if ("load-balancer".equals(nodeName)) { handleLoadBalancer(node); } else if ("near-cache".equals(nodeName)) { handleNearCache(node); } } builder.addConstructorArgValue(configBuilder.getBeanDefinition()); } private void handleNetwork(Node node) { List<String> members = new ArrayList<String>(10); fillAttributeValues(node, configBuilder); for (org.w3c.dom.Node child : new IterableNodeList(node, Node.ELEMENT_NODE)) { final String nodeName = cleanNodeName(child); if ("member".equals(nodeName)) { members.add(getTextContent(child)); } else if ("socket-options".equals(nodeName)) { createAndFillBeanBuilder(child, SocketOptions.class, "socketOptions", configBuilder); } else if ("socket-interceptor".equals(nodeName)) { handleSocketInterceptorConfig(node, configBuilder); } else if ("ssl".equals(nodeName)) { handleSSLConfig(node, configBuilder); } } configBuilder.addPropertyValue("addresses", members); } private void handleSSLConfig(final Node node, final BeanDefinitionBuilder networkConfigBuilder) { BeanDefinitionBuilder sslConfigBuilder = createBeanBuilder(SSLConfig.class); final String implAttribute = "factory-implementation"; fillAttributeValues(node, sslConfigBuilder, implAttribute); Node implNode = node.getAttributes().getNamedItem(implAttribute); String implementation = implNode != null ? getTextContent(implNode) : null; if (implementation != null) { sslConfigBuilder.addPropertyReference(xmlToJavaName(implAttribute), implementation); } for (org.w3c.dom.Node child : new IterableNodeList(node, Node.ELEMENT_NODE)) { final String name = cleanNodeName(child); if ("properties".equals(name)) { handleProperties(child, sslConfigBuilder); } } networkConfigBuilder.addPropertyValue("SSLConfig", sslConfigBuilder.getBeanDefinition()); } private void handleLoadBalancer(Node node) { final String type = getAttribute(node, "type"); if ("random".equals(type)) { configBuilder.addPropertyValue("loadBalancer", new RandomLB()); } else if ("round-robin".equals(type)) { configBuilder.addPropertyValue("loadBalancer", new RoundRobinLB()); } } private void handleNearCache(Node node) { createAndFillListedBean(node, NearCacheConfig.class, "name", nearCacheConfigMap, "name"); } }
1no label
hazelcast-spring_src_main_java_com_hazelcast_spring_HazelcastClientBeanDefinitionParser.java
5,209
public class DateHistogramBuilder extends ValuesSourceAggregationBuilder<DateHistogramBuilder> { private Object interval; private Histogram.Order order; private Long minDocCount; private String preZone; private String postZone; private boolean preZoneAdjustLargeInterval; long preOffset = 0; long postOffset = 0; float factor = 1.0f; public DateHistogramBuilder(String name) { super(name, InternalDateHistogram.TYPE.name()); } public DateHistogramBuilder interval(long interval) { this.interval = interval; return this; } public DateHistogramBuilder interval(DateHistogram.Interval interval) { this.interval = interval; return this; } public DateHistogramBuilder order(DateHistogram.Order order) { this.order = order; return this; } public DateHistogramBuilder minDocCount(long minDocCount) { this.minDocCount = minDocCount; return this; } public DateHistogramBuilder preZone(String preZone) { this.preZone = preZone; return this; } public DateHistogramBuilder postZone(String postZone) { this.postZone = postZone; return this; } public DateHistogramBuilder preZoneAdjustLargeInterval(boolean preZoneAdjustLargeInterval) { this.preZoneAdjustLargeInterval = preZoneAdjustLargeInterval; return this; } public DateHistogramBuilder preOffset(long preOffset) { this.preOffset = preOffset; return this; } public DateHistogramBuilder postOffset(long postOffset) { this.postOffset = postOffset; return this; } public DateHistogramBuilder factor(float factor) { this.factor = factor; return this; } @Override protected XContentBuilder doInternalXContent(XContentBuilder builder, Params params) throws IOException { if (interval == null) { throw new SearchSourceBuilderException("[interval] must be defined for histogram aggregation [" + name + "]"); } if (interval instanceof Number) { interval = TimeValue.timeValueMillis(((Number) interval).longValue()).toString(); } builder.field("interval", interval); if (minDocCount != null) { builder.field("min_doc_count", minDocCount); } if (order != null) { builder.field("order"); order.toXContent(builder, params); } if (preZone != null) { builder.field("pre_zone", preZone); } if (postZone != null) { builder.field("post_zone", postZone); } if (preZoneAdjustLargeInterval) { builder.field("pre_zone_adjust_large_interval", true); } if (preOffset != 0) { builder.field("pre_offset", preOffset); } if (postOffset != 0) { builder.field("post_offset", postOffset); } if (factor != 1.0f) { builder.field("factor", factor); } return builder; } }
1no label
src_main_java_org_elasticsearch_search_aggregations_bucket_histogram_DateHistogramBuilder.java
9
public class OLazyIteratorListWrapper<T> implements OLazyIterator<T> { private ListIterator<T> underlying; public OLazyIteratorListWrapper(ListIterator<T> iUnderlying) { underlying = iUnderlying; } public boolean hasNext() { return underlying.hasNext(); } public T next() { return underlying.next(); } public void remove() { underlying.remove(); } public T update(T e) { underlying.set(e); return null; } }
0true
commons_src_main_java_com_orientechnologies_common_collection_OLazyIteratorListWrapper.java
961
@Test public class GZIPCompressionTest extends AbstractCompressionTest { public void testGZIPCompression() { testCompression(OGZIPCompression.NAME); } }
0true
core_src_test_java_com_orientechnologies_orient_core_serialization_compression_impl_GZIPCompressionTest.java
484
public class ClientCallFuture<V> implements ICompletableFuture<V>, Callback { private Object response; private final ClientRequest request; private final ClientExecutionServiceImpl executionService; private final ClientInvocationServiceImpl invocationService; private final SerializationService serializationService; private final EventHandler handler; public final int heartBeatInterval; public final int retryCount; public final int retryWaitTime; private AtomicInteger reSendCount = new AtomicInteger(); private volatile ClientConnection connection; private List<ExecutionCallbackNode> callbackNodeList = new LinkedList<ExecutionCallbackNode>(); public ClientCallFuture(HazelcastClient client, ClientRequest request, EventHandler handler) { int interval = client.clientProperties.HEARTBEAT_INTERVAL.getInteger(); this.heartBeatInterval = interval > 0 ? interval : Integer.parseInt(PROP_HEARTBEAT_INTERVAL_DEFAULT); int retry = client.clientProperties.RETRY_COUNT.getInteger(); this.retryCount = retry > 0 ? retry : Integer.parseInt(PROP_RETRY_COUNT_DEFAULT); int waitTime = client.clientProperties.RETRY_WAIT_TIME.getInteger(); this.retryWaitTime = waitTime > 0 ? waitTime : Integer.parseInt(PROP_RETRY_WAIT_TIME_DEFAULT); this.invocationService = (ClientInvocationServiceImpl) client.getInvocationService(); this.executionService = (ClientExecutionServiceImpl) client.getClientExecutionService(); this.serializationService = client.getSerializationService(); this.request = request; this.handler = handler; } public boolean cancel(boolean mayInterruptIfRunning) { return false; } public boolean isCancelled() { return false; } public boolean isDone() { return response != null; } public V get() throws InterruptedException, ExecutionException { try { return get(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } catch (TimeoutException ignored) { return null; } } public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (response == null) { long waitMillis = unit.toMillis(timeout); if (waitMillis > 0) { synchronized (this) { while (waitMillis > 0 && response == null) { long start = Clock.currentTimeMillis(); this.wait(Math.min(heartBeatInterval, waitMillis)); long elapsed = Clock.currentTimeMillis() - start; waitMillis -= elapsed; if (!isConnectionHealthy(elapsed)) { break; } } } } } return resolveResponse(); } private boolean isConnectionHealthy(long elapsed) { if (elapsed >= heartBeatInterval) { return connection.isHeartBeating(); } return true; } public void notify(Object response) { if (response == null) { throw new IllegalArgumentException("response can't be null"); } if (response instanceof TargetNotMemberException) { if (resend()) { return; } } if (response instanceof TargetDisconnectedException || response instanceof HazelcastInstanceNotActiveException) { if (request instanceof RetryableRequest || invocationService.isRedoOperation()) { if (resend()) { return; } } } setResponse(response); } private void setResponse(Object response) { synchronized (this) { if (this.response != null && handler == null) { throw new IllegalArgumentException("The Future.set method can only be called once"); } if (handler != null && !(response instanceof Throwable)) { handler.onListenerRegister(); } if (this.response != null && !(response instanceof Throwable)) { String uuid = serializationService.toObject(this.response); String alias = serializationService.toObject(response); invocationService.reRegisterListener(uuid, alias, request.getCallId()); return; } this.response = response; this.notifyAll(); } for (ExecutionCallbackNode node : callbackNodeList) { runAsynchronous(node.callback, node.executor); } callbackNodeList.clear(); } private V resolveResponse() throws ExecutionException, TimeoutException, InterruptedException { if (response instanceof Throwable) { ExceptionUtil.fixRemoteStackTrace((Throwable) response, Thread.currentThread().getStackTrace()); if (response instanceof ExecutionException) { throw (ExecutionException) response; } if (response instanceof TimeoutException) { throw (TimeoutException) response; } if (response instanceof Error) { throw (Error) response; } if (response instanceof InterruptedException) { throw (InterruptedException) response; } throw new ExecutionException((Throwable) response); } if (response == null) { throw new TimeoutException(); } return (V) response; } public void andThen(ExecutionCallback<V> callback) { andThen(callback, executionService.getAsyncExecutor()); } public void andThen(ExecutionCallback<V> callback, Executor executor) { synchronized (this) { if (response != null) { runAsynchronous(callback, executor); return; } callbackNodeList.add(new ExecutionCallbackNode(callback, executor)); } } public ClientRequest getRequest() { return request; } public EventHandler getHandler() { return handler; } public ClientConnection getConnection() { return connection; } public boolean resend() { if (request.isSingleConnection()) { return false; } if (handler == null && reSendCount.incrementAndGet() > retryCount) { return false; } executionService.execute(new ReSendTask()); return true; } private void runAsynchronous(final ExecutionCallback callback, Executor executor) { executor.execute(new Runnable() { public void run() { try { callback.onResponse(serializationService.toObject(resolveResponse())); } catch (Throwable t) { callback.onFailure(t); } } }); } public void setConnection(ClientConnection connection) { this.connection = connection; } class ReSendTask implements Runnable { public void run() { try { sleep(); invocationService.reSend(ClientCallFuture.this); } catch (Exception e) { if (handler != null) { invocationService.registerFailedListener(ClientCallFuture.this); } else { setResponse(e); } } } private void sleep(){ try { Thread.sleep(250); } catch (InterruptedException ignored) { } } } class ExecutionCallbackNode { final ExecutionCallback callback; final Executor executor; ExecutionCallbackNode(ExecutionCallback callback, Executor executor) { this.callback = callback; this.executor = executor; } } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_spi_impl_ClientCallFuture.java
421
}, new TxJob() { @Override public void run(IndexTransaction tx) { //do nothing } });
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexProviderTest.java
442
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) { Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.ADD); Assert.assertNull(event.getOldValue()); Assert.assertEquals(event.getKey(), "value1"); Assert.assertEquals(event.getValue(), "value1"); changed.value = true; } });
0true
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedSetTest.java
1,890
boolean b = h1.executeTransaction(options, new TransactionalTask<Boolean>() { public Boolean execute(TransactionalTaskContext context) throws TransactionException { final TransactionalMap<Object, Object> txMap = context.getMap("putWithTTL"); txMap.put("1", "value", 5, TimeUnit.SECONDS); assertEquals("value", txMap.get("1")); assertEquals(1, txMap.size()); return true; } });
0true
hazelcast_src_test_java_com_hazelcast_map_MapTransactionTest.java
453
public class OIndexRIDContainerSBTree implements Set<OIdentifiable> { public static final String INDEX_FILE_EXTENSION = ".irs"; private OSBTreeBonsai<OIdentifiable, Boolean> tree; protected static final OProfilerMBean PROFILER = Orient.instance().getProfiler(); public OIndexRIDContainerSBTree(long fileId) { tree = new OSBTreeBonsai<OIdentifiable, Boolean>(INDEX_FILE_EXTENSION, 1, false); tree.create(fileId, OLinkSerializer.INSTANCE, OBooleanSerializer.INSTANCE, (OStorageLocalAbstract) ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getUnderlying()); } public OIndexRIDContainerSBTree(long fileId, OBonsaiBucketPointer rootPointer) { tree = new OSBTreeBonsai<OIdentifiable, Boolean>(INDEX_FILE_EXTENSION, 1, false); tree.load(fileId, rootPointer, (OStorageLocalAbstract) ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getUnderlying()); } public OIndexRIDContainerSBTree(String file, OBonsaiBucketPointer rootPointer) { tree = new OSBTreeBonsai<OIdentifiable, Boolean>(INDEX_FILE_EXTENSION, 1, false); final OStorageLocalAbstract storage = (OStorageLocalAbstract) ODatabaseRecordThreadLocal.INSTANCE.get().getStorage() .getUnderlying(); final long fileId; try { fileId = storage.getDiskCache().openFile(file + INDEX_FILE_EXTENSION); } catch (IOException e) { throw new OSBTreeException("Exception during loading of sbtree " + file, e); } tree.load(fileId, rootPointer, storage); } public OBonsaiBucketPointer getRootPointer() { return tree.getRootBucketPointer(); } @Override public int size() { return (int) tree.size(); } @Override public boolean isEmpty() { return tree.size() == 0L; } @Override public boolean contains(Object o) { return o instanceof OIdentifiable && contains((OIdentifiable) o); } public boolean contains(OIdentifiable o) { return tree.get(o) != null; } @Override public Iterator<OIdentifiable> iterator() { return new TreeKeyIterator(tree, false); } @Override public Object[] toArray() { // TODO replace with more efficient implementation final ArrayList<OIdentifiable> list = new ArrayList<OIdentifiable>(size()); for (OIdentifiable identifiable : this) { list.add(identifiable); } return list.toArray(); } @Override public <T> T[] toArray(T[] a) { // TODO replace with more efficient implementation. final ArrayList<OIdentifiable> list = new ArrayList<OIdentifiable>(size()); for (OIdentifiable identifiable : this) { list.add(identifiable); } return list.toArray(a); } @Override public boolean add(OIdentifiable oIdentifiable) { return this.tree.put(oIdentifiable, Boolean.TRUE); } @Override public boolean remove(Object o) { return o instanceof OIdentifiable && remove((OIdentifiable) o); } public boolean remove(OIdentifiable o) { return tree.remove(o) != null; } @Override public boolean containsAll(Collection<?> c) { for (Object e : c) if (!contains(e)) return false; return true; } @Override public boolean addAll(Collection<? extends OIdentifiable> c) { boolean modified = false; for (OIdentifiable e : c) if (add(e)) modified = true; return modified; } @Override public boolean retainAll(Collection<?> c) { boolean modified = false; Iterator<OIdentifiable> it = iterator(); while (it.hasNext()) { if (!c.contains(it.next())) { it.remove(); modified = true; } } return modified; } @Override public boolean removeAll(Collection<?> c) { boolean modified = false; for (Object o : c) { modified |= remove(o); } return modified; } @Override public void clear() { tree.clear(); } public void delete() { tree.delete(); } public String getFileName() { return tree.getFileName(); } private static class TreeKeyIterator implements Iterator<OIdentifiable> { private final boolean autoConvertToRecord; private OSBTreeMapEntryIterator<OIdentifiable, Boolean> entryIterator; public TreeKeyIterator(OTreeInternal<OIdentifiable, Boolean> tree, boolean autoConvertToRecord) { entryIterator = new OSBTreeMapEntryIterator<OIdentifiable, Boolean>(tree); this.autoConvertToRecord = autoConvertToRecord; } @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public OIdentifiable next() { final OIdentifiable identifiable = entryIterator.next().getKey(); if (autoConvertToRecord) return identifiable.getRecord(); else return identifiable; } @Override public void remove() { entryIterator.remove(); } } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_record_ridset_sbtree_OIndexRIDContainerSBTree.java
3,322
static class BytesValues extends org.elasticsearch.index.fielddata.BytesValues.WithOrdinals { protected final FST<Long> fst; protected final Ordinals.Docs ordinals; // per-thread resources protected final BytesReader in; protected final Arc<Long> firstArc = new Arc<Long>(); protected final Arc<Long> scratchArc = new Arc<Long>(); protected final IntsRef scratchInts = new IntsRef(); BytesValues(FST<Long> fst, Ordinals.Docs ordinals) { super(ordinals); this.fst = fst; this.ordinals = ordinals; in = fst.getBytesReader(); } @Override public BytesRef getValueByOrd(long ord) { assert ord != Ordinals.MISSING_ORDINAL; in.setPosition(0); fst.getFirstArc(firstArc); try { IntsRef output = Util.getByOutput(fst, ord, in, firstArc, scratchArc, scratchInts); scratch.length = scratch.offset = 0; scratch.grow(output.length); Util.toBytesRef(output, scratch); } catch (IOException ex) { //bogus } return scratch; } }
0true
src_main_java_org_elasticsearch_index_fielddata_plain_FSTBytesAtomicFieldData.java
265
public class AppendCallable implements Callable<String>, DataSerializable{ public static final String APPENDAGE = ":CallableResult"; private String msg; public AppendCallable() { } public AppendCallable(String msg) { this.msg = msg; } public String call() throws Exception { return msg + APPENDAGE; } public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(msg); } public void readData(ObjectDataInput in) throws IOException { msg = in.readUTF(); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_executor_tasks_AppendCallable.java
327
public class NavigateActionGroup extends ActionGroup { private OpenEditorActionGroup fOpenEditorActionGroup; private OpenViewActionGroup fOpenViewActionGroup; /** * Creates a new <code>NavigateActionGroup</code>. The group requires * that the selection provided by the part's selection provider is of type <code> * org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param part the view part that owns this action group */ public NavigateActionGroup(IViewPart part) { fOpenEditorActionGroup= new OpenEditorActionGroup(part); fOpenViewActionGroup= new OpenViewActionGroup(part); } /** * Returns the open action managed by this action group. * * @return the open action. Returns <code>null</code> if the group * doesn't provide any open action */ public IAction getOpenAction() { return fOpenEditorActionGroup.getOpenAction(); } /* (non-Javadoc) * Method declared in ActionGroup */ @Override public void dispose() { super.dispose(); fOpenEditorActionGroup.dispose(); fOpenViewActionGroup.dispose(); } /* (non-Javadoc) * Method declared in ActionGroup */ @Override public void fillActionBars(IActionBars actionBars) { super.fillActionBars(actionBars); fOpenEditorActionGroup.fillActionBars(actionBars); fOpenViewActionGroup.fillActionBars(actionBars); } /* (non-Javadoc) * Method declared in ActionGroup */ @Override public void fillContextMenu(IMenuManager menu) { super.fillContextMenu(menu); fOpenEditorActionGroup.fillContextMenu(menu); fOpenViewActionGroup.fillContextMenu(menu); } /* (non-Javadoc) * Method declared in ActionGroup */ @Override public void setContext(ActionContext context) { super.setContext(context); fOpenEditorActionGroup.setContext(context); fOpenViewActionGroup.setContext(context); } /* (non-Javadoc) * Method declared in ActionGroup */ @Override public void updateActionBars() { super.updateActionBars(); fOpenEditorActionGroup.updateActionBars(); fOpenViewActionGroup.updateActionBars(); } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_explorer_NavigateActionGroup.java
3,128
private static final class RecoveryCounter { private volatile int ongoingRecoveries = 0; synchronized void increment() { ongoingRecoveries++; } synchronized void decrement() { ongoingRecoveries--; if (ongoingRecoveries == 0) { notifyAll(); // notify waiting threads - we only wait on ongoingRecoveries == 0 } assert ongoingRecoveries >= 0 : "ongoingRecoveries must be >= 0 but was: " + ongoingRecoveries; } int get() { // volatile read - no sync needed return ongoingRecoveries; } synchronized int awaitNoRecoveries(long timeout) throws InterruptedException { if (ongoingRecoveries > 0) { // no loop here - we either time out or we are done! wait(timeout); } return ongoingRecoveries; } }
0true
src_main_java_org_elasticsearch_index_engine_internal_InternalEngine.java
35
@SuppressWarnings("unchecked") public class OMVRBTreeEntryMemory<K, V> extends OMVRBTreeEntry<K, V> { protected int size = 1; protected int pageSize; protected K[] keys; protected V[] values; protected OMVRBTreeEntryMemory<K, V> left = null; protected OMVRBTreeEntryMemory<K, V> right = null; protected OMVRBTreeEntryMemory<K, V> parent; protected boolean color = OMVRBTree.RED; /** * Constructor called on unmarshalling. * */ protected OMVRBTreeEntryMemory(final OMVRBTree<K, V> iTree) { super(iTree); } /** * Make a new cell with given key, value, and parent, and with <tt>null</tt> child links, and BLACK color. */ protected OMVRBTreeEntryMemory(final OMVRBTree<K, V> iTree, final K iKey, final V iValue, final OMVRBTreeEntryMemory<K, V> iParent) { super(iTree); setParent(iParent); pageSize = tree.getDefaultPageSize(); keys = (K[]) new Object[pageSize]; keys[0] = iKey; values = (V[]) new Object[pageSize]; values[0] = iValue; init(); } /** * Copy values from the parent node. * * @param iParent * @param iPosition */ protected OMVRBTreeEntryMemory(final OMVRBTreeEntryMemory<K, V> iParent, final int iPosition) { super(iParent.getTree()); pageSize = tree.getDefaultPageSize(); keys = (K[]) new Object[pageSize]; values = (V[]) new Object[pageSize]; size = iParent.size - iPosition; System.arraycopy(iParent.keys, iPosition, keys, 0, size); System.arraycopy(iParent.values, iPosition, values, 0, size); Arrays.fill(iParent.keys, iPosition, iParent.size, null); Arrays.fill(iParent.values, iPosition, iParent.size, null); iParent.size = iPosition; setParent(iParent); init(); } @Override protected void setColor(final boolean iColor) { this.color = iColor; } @Override public boolean getColor() { return color; } @Override public void setLeft(final OMVRBTreeEntry<K, V> iLeft) { left = (OMVRBTreeEntryMemory<K, V>) iLeft; if (iLeft != null && iLeft.getParent() != this) iLeft.setParent(this); } @Override public OMVRBTreeEntry<K, V> getLeft() { return left; } @Override public void setRight(final OMVRBTreeEntry<K, V> iRight) { right = (OMVRBTreeEntryMemory<K, V>) iRight; if (iRight != null && iRight.getParent() != this) iRight.setParent(this); } @Override public OMVRBTreeEntry<K, V> getRight() { return right; } @Override public OMVRBTreeEntry<K, V> setParent(final OMVRBTreeEntry<K, V> iParent) { parent = (OMVRBTreeEntryMemory<K, V>) iParent; return iParent; } @Override public OMVRBTreeEntry<K, V> getParent() { return parent; } /** * Returns the successor of the current Entry only by traversing the memory, or null if no such. */ @Override public OMVRBTreeEntryMemory<K, V> getNextInMemory() { OMVRBTreeEntryMemory<K, V> t = this; OMVRBTreeEntryMemory<K, V> p = null; if (t.right != null) { p = t.right; while (p.left != null) p = p.left; } else { p = t.parent; while (p != null && t == p.right) { t = p; p = p.parent; } } return p; } public int getSize() { return size; } public int getPageSize() { return pageSize; } @Override protected OMVRBTreeEntry<K, V> getLeftInMemory() { return left; } @Override protected OMVRBTreeEntry<K, V> getParentInMemory() { return parent; } @Override protected OMVRBTreeEntry<K, V> getRightInMemory() { return right; } protected K getKeyAt(final int iIndex) { return keys[iIndex]; } protected V getValueAt(int iIndex) { return values[iIndex]; } /** * Replaces the value currently associated with the key with the given value. * * @return the value associated with the key before this method was called */ public V setValue(final V value) { V oldValue = this.getValue(); this.values[tree.pageIndex] = value; return oldValue; } protected void insert(final int iPosition, final K key, final V value) { if (iPosition < size) { // MOVE RIGHT TO MAKE ROOM FOR THE ITEM System.arraycopy(keys, iPosition, keys, iPosition + 1, size - iPosition); System.arraycopy(values, iPosition, values, iPosition + 1, size - iPosition); } keys[iPosition] = key; values[iPosition] = value; size++; } protected void remove() { if (tree.pageIndex == size - 1) { // LAST ONE: JUST REMOVE IT } else if (tree.pageIndex > -1) { // SHIFT LEFT THE VALUES System.arraycopy(keys, tree.pageIndex + 1, keys, tree.pageIndex, size - tree.pageIndex - 1); System.arraycopy(values, tree.pageIndex + 1, values, tree.pageIndex, size - tree.pageIndex - 1); } // FREE RESOURCES keys[size - 1] = null; values[size - 1] = null; size--; tree.pageIndex = 0; } protected void copyFrom(final OMVRBTreeEntry<K, V> iSource) { OMVRBTreeEntryMemory<K, V> source = (OMVRBTreeEntryMemory<K, V>) iSource; keys = (K[]) new Object[source.keys.length]; for (int i = 0; i < source.keys.length; ++i) keys[i] = source.keys[i]; values = (V[]) new Object[source.values.length]; for (int i = 0; i < source.values.length; ++i) values[i] = source.values[i]; size = source.size; } @Override public String toString() { if (keys == null) return "?"; final StringBuilder buffer = new StringBuilder(); final Object k = tree.pageIndex >= size ? '?' : getKey(); buffer.append(k); buffer.append(" (size="); buffer.append(size); if (size > 0) { buffer.append(" ["); buffer.append(keys[0] != null ? keys[0] : "{lazy}"); buffer.append('-'); buffer.append(keys[size - 1] != null ? keys[size - 1] : "{lazy}"); buffer.append(']'); } buffer.append(')'); return buffer.toString(); } }
0true
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTreeEntryMemory.java
1,297
@Test public class LocalPaginatedStorageRestoreTx { private ODatabaseDocumentTx testDocumentTx; private ODatabaseDocumentTx baseDocumentTx; private File buildDir; private ExecutorService executorService = Executors.newCachedThreadPool(); @BeforeClass public void beforeClass() { String buildDirectory = System.getProperty("buildDirectory", "."); buildDirectory += "/localPaginatedStorageRestoreFromTx"; buildDir = new File(buildDirectory); if (buildDir.exists()) buildDir.delete(); buildDir.mkdir(); } @AfterClass public void afterClass() { buildDir.delete(); } @BeforeMethod public void beforeMethod() { baseDocumentTx = new ODatabaseDocumentTx("plocal:" + buildDir.getAbsolutePath() + "/baseLocalPaginatedStorageRestoreFromTx"); if (baseDocumentTx.exists()) { baseDocumentTx.open("admin", "admin"); baseDocumentTx.drop(); } baseDocumentTx.create(); createSchema(baseDocumentTx); } @AfterMethod public void afterMethod() { testDocumentTx.open("admin", "admin"); testDocumentTx.drop(); baseDocumentTx.open("admin", "admin"); baseDocumentTx.drop(); } public void testSimpleRestore() throws Exception { List<Future<Void>> futures = new ArrayList<Future<Void>>(); baseDocumentTx.declareIntent(new OIntentMassiveInsert()); for (int i = 0; i < 5; i++) futures.add(executorService.submit(new DataPropagationTask())); for (Future<Void> future : futures) future.get(); Thread.sleep(1500); copyDataFromTestWithoutClose(); OStorage storage = baseDocumentTx.getStorage(); baseDocumentTx.close(); storage.close(); testDocumentTx = new ODatabaseDocumentTx("plocal:" + buildDir.getAbsolutePath() + "/testLocalPaginatedStorageRestoreFromTx"); testDocumentTx.open("admin", "admin"); testDocumentTx.close(); ODatabaseCompare databaseCompare = new ODatabaseCompare(testDocumentTx.getURL(), baseDocumentTx.getURL(), "admin", "admin", new OCommandOutputListener() { @Override public void onMessage(String text) { System.out.println(text); } }); Assert.assertTrue(databaseCompare.compare()); } private void copyDataFromTestWithoutClose() throws Exception { final String testStoragePath = baseDocumentTx.getURL().substring("plocal:".length()); final String copyTo = buildDir.getAbsolutePath() + File.separator + "testLocalPaginatedStorageRestoreFromTx"; final File testStorageDir = new File(testStoragePath); final File copyToDir = new File(copyTo); Assert.assertTrue(!copyToDir.exists()); Assert.assertTrue(copyToDir.mkdir()); File[] storageFiles = testStorageDir.listFiles(); Assert.assertNotNull(storageFiles); for (File storageFile : storageFiles) { String copyToPath; if (storageFile.getAbsolutePath().endsWith("baseLocalPaginatedStorageRestoreFromTx.wmr")) copyToPath = copyToDir.getAbsolutePath() + File.separator + "testLocalPaginatedStorageRestoreFromTx.wmr"; else if (storageFile.getAbsolutePath().endsWith("baseLocalPaginatedStorageRestoreFromTx.0.wal")) copyToPath = copyToDir.getAbsolutePath() + File.separator + "testLocalPaginatedStorageRestoreFromTx.0.wal"; else copyToPath = copyToDir.getAbsolutePath() + File.separator + storageFile.getName(); copyFile(storageFile.getAbsolutePath(), copyToPath); } } private static void copyFile(String from, String to) throws IOException { final File fromFile = new File(from); FileInputStream fromInputStream = new FileInputStream(fromFile); BufferedInputStream fromBufferedStream = new BufferedInputStream(fromInputStream); FileOutputStream toOutputStream = new FileOutputStream(to); byte[] data = new byte[1024]; int bytesRead = fromBufferedStream.read(data); while (bytesRead > 0) { toOutputStream.write(data, 0, bytesRead); bytesRead = fromBufferedStream.read(data); } fromBufferedStream.close(); toOutputStream.close(); } private void createSchema(ODatabaseDocumentTx databaseDocumentTx) { ODatabaseRecordThreadLocal.INSTANCE.set(databaseDocumentTx); OSchema schema = databaseDocumentTx.getMetadata().getSchema(); OClass testOneClass = schema.createClass("TestOne"); testOneClass.createProperty("intProp", OType.INTEGER); testOneClass.createProperty("stringProp", OType.STRING); testOneClass.createProperty("stringSet", OType.EMBEDDEDSET, OType.STRING); testOneClass.createProperty("linkMap", OType.LINKMAP, OType.STRING); OClass testTwoClass = schema.createClass("TestTwo"); testTwoClass.createProperty("stringList", OType.EMBEDDEDLIST, OType.STRING); } public class DataPropagationTask implements Callable<Void> { @Override public Void call() throws Exception { Random random = new Random(); final ODatabaseDocumentTx db = new ODatabaseDocumentTx(baseDocumentTx.getURL()); db.open("admin", "admin"); int rollbacksCount = 0; try { List<ORID> secondDocs = new ArrayList<ORID>(); List<ORID> firstDocs = new ArrayList<ORID>(); OClass classOne = db.getMetadata().getSchema().getClass("TestOne"); OClass classTwo = db.getMetadata().getSchema().getClass("TestTwo"); for (int i = 0; i < 2000; i++) { try { db.begin(OTransaction.TXTYPE.OPTIMISTIC); ODocument docOne = new ODocument(classOne); docOne.field("intProp", random.nextInt()); byte[] stringData = new byte[256]; random.nextBytes(stringData); String stringProp = new String(stringData); docOne.field("stringProp", stringProp); Set<String> stringSet = new HashSet<String>(); for (int n = 0; n < 5; n++) { stringSet.add("str" + random.nextInt()); } docOne.field("stringSet", stringSet); docOne.save(); ODocument docTwo = null; if (random.nextBoolean()) { docTwo = new ODocument(classTwo); List<String> stringList = new ArrayList<String>(); for (int n = 0; n < 5; n++) { stringList.add("strnd" + random.nextInt()); } docTwo.field("stringList", stringList); docTwo.save(); } if (!secondDocs.isEmpty()) { int startIndex = random.nextInt(secondDocs.size()); int endIndex = random.nextInt(secondDocs.size() - startIndex) + startIndex; Map<String, ORID> linkMap = new HashMap<String, ORID>(); for (int n = startIndex; n < endIndex; n++) { ORID docTwoRid = secondDocs.get(n); linkMap.put(docTwoRid.toString(), docTwoRid); } docOne.field("linkMap", linkMap); docOne.save(); } int deleteIndex = -1; if (!firstDocs.isEmpty()) { boolean deleteDoc = random.nextDouble() <= 0.2; if (deleteDoc) { deleteIndex = random.nextInt(firstDocs.size()); if (deleteIndex >= 0) { ORID rid = firstDocs.get(deleteIndex); db.delete(rid); } } } if (!secondDocs.isEmpty() && (random.nextDouble() <= 0.2)) { ODocument conflictDocTwo = new ODocument(); conflictDocTwo.setIdentity(new ORecordId(secondDocs.get(0))); conflictDocTwo.setDirty(); conflictDocTwo.save(); } db.commit(); if (deleteIndex >= 0) firstDocs.remove(deleteIndex); firstDocs.add(docOne.getIdentity()); if (docTwo != null) secondDocs.add(docTwo.getIdentity()); } catch (Exception e) { db.rollback(); rollbacksCount++; } } } finally { db.close(); } System.out.println("Rollbacks count " + rollbacksCount); return null; } } }
0true
core_src_test_java_com_orientechnologies_orient_core_storage_impl_local_paginated_LocalPaginatedStorageRestoreTx.java
1,407
@XmlRootElement(name = "paymentReferenceMap") @XmlAccessorType(value = XmlAccessType.FIELD) public class PaymentReferenceMapWrapper extends BaseWrapper { @XmlElement protected PaymentInfoWrapper paymentInfo; @XmlElement protected ReferencedWrapper referenced; public PaymentInfoWrapper getPaymentInfoWrapper() { return paymentInfo; } public void setPaymentInfoWrapper(PaymentInfoWrapper paymentInfo) { this.paymentInfo = paymentInfo; } public ReferencedWrapper getReferencedWrapper() { return referenced; } public void setReferencedWrapper(ReferencedWrapper referenced) { this.referenced = referenced; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_wrapper_PaymentReferenceMapWrapper.java
1,684
map.addEntryListener(new EntryAdapter<String, String>() { public void entryAdded(final EntryEvent<String, String> e) { testEvent(e); } public void entryRemoved(final EntryEvent<String, String> e) { testEvent(e); } private void testEvent(final EntryEvent<String, String> e) { if (key.equals(e.getKey())) { latch.countDown(); } else { fail("Invalid event: " + e); } } }, key, true);
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
1,841
localContext = new ThreadLocal<Object[]>() { protected Object[] initialValue() { return new Object[1]; } };
0true
src_main_java_org_elasticsearch_common_inject_InjectorImpl.java
519
@Component("blApplicationContextHolder") public class ApplicationContextHolder implements ApplicationContextAware { protected static ApplicationContext context; public static ApplicationContext getApplicationContext() { return context; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } }
0true
common_src_main_java_org_broadleafcommerce_common_util_ApplicationContextHolder.java
2,798
public abstract class AbstractTokenizerFactory extends AbstractIndexComponent implements TokenizerFactory { private final String name; protected final Version version; public AbstractTokenizerFactory(Index index, @IndexSettings Settings indexSettings, String name, Settings settings) { super(index, indexSettings); this.name = name; this.version = Analysis.parseAnalysisVersion(indexSettings, settings, logger); } @Override public String name() { return this.name; } public final Version version() { return version; } }
0true
src_main_java_org_elasticsearch_index_analysis_AbstractTokenizerFactory.java
847
DECIMAL("Decimal", 21, new Class<?>[] { BigDecimal.class }, new Class<?>[] { BigDecimal.class, Number.class }) { };
0true
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OType.java
1,060
public interface BandedWeightFulfillmentOption extends FulfillmentOption { public List<FulfillmentWeightBand> getBands(); public void setBands(List<FulfillmentWeightBand> bands); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_fulfillment_domain_BandedWeightFulfillmentOption.java
1,004
public class OStreamSerializerLong implements OStreamSerializer { public static final String NAME = "lo"; public static final OStreamSerializerLong INSTANCE = new OStreamSerializerLong(); public String getName() { return NAME; } public Object fromStream(final byte[] iStream) throws IOException { return OBinaryProtocol.bytes2long(iStream); } public byte[] toStream(final Object iObject) throws IOException { return OBinaryProtocol.long2bytes((Long) iObject); } }
0true
core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_stream_OStreamSerializerLong.java
415
private static final class MultiExecutionCallbackWrapper implements MultiExecutionCallback { private final AtomicInteger members; private final MultiExecutionCallback multiExecutionCallback; private final Map<Member, Object> values; private MultiExecutionCallbackWrapper(int memberSize, MultiExecutionCallback multiExecutionCallback) { this.multiExecutionCallback = multiExecutionCallback; this.members = new AtomicInteger(memberSize); values = new HashMap<Member, Object>(memberSize); } public void onResponse(Member member, Object value) { multiExecutionCallback.onResponse(member, value); values.put(member, value); int waitingResponse = members.decrementAndGet(); if (waitingResponse == 0) { onComplete(values); } } public void onComplete(Map<Member, Object> values) { multiExecutionCallback.onComplete(values); } }
0true
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientExecutorServiceProxy.java
684
@Entity @Polymorphism(type = PolymorphismType.EXPLICIT) @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_CATEGORY_PRODUCT_XREF") @AdminPresentationClass(excludeFromPolymorphism = false) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") public class CategoryProductXrefImpl implements CategoryProductXref { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; @EmbeddedId CategoryProductXrefPK categoryProductXref = new CategoryProductXrefPK(); public CategoryProductXrefPK getCategoryProductXref() { return categoryProductXref; } public void setCategoryProductXref(CategoryProductXrefPK categoryProductXref) { this.categoryProductXref = categoryProductXref; } /** The display order. */ @Column(name = "DISPLAY_ORDER") @AdminPresentation(visibility = VisibilityEnum.HIDDEN_ALL) protected Long displayOrder; /* (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.CategoryProductXref#getDisplayOrder() */ public Long getDisplayOrder() { return displayOrder; } /* (non-Javadoc) * @see org.broadleafcommerce.core.catalog.domain.CategoryProductXref#setDisplayOrder(java.lang.Integer) */ public void setDisplayOrder(Long displayOrder) { this.displayOrder = displayOrder; } /** * @return * @see org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl.CategoryProductXrefPK#getCategory() */ public Category getCategory() { return categoryProductXref.getCategory(); } /** * @param category * @see org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl.CategoryProductXrefPK#setCategory(org.broadleafcommerce.core.catalog.domain.Category) */ public void setCategory(Category category) { categoryProductXref.setCategory(category); } /** * @return * @see org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl.CategoryProductXrefPK#getProduct() */ public Product getProduct() { return categoryProductXref.getProduct(); } /** * @param product * @see org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl.CategoryProductXrefPK#setProduct(org.broadleafcommerce.core.catalog.domain.Product) */ public void setProduct(Product product) { categoryProductXref.setProduct(product); } @Override public boolean equals(Object o) { if (o instanceof CategoryProductXrefImpl) { CategoryProductXrefImpl that = (CategoryProductXrefImpl) o; return new EqualsBuilder() .append(categoryProductXref, that.categoryProductXref) .build(); } return false; } @Override public int hashCode() { int result = categoryProductXref != null ? categoryProductXref.hashCode() : 0; return result; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_CategoryProductXrefImpl.java
1,193
public interface PaymentInfoFactory { public PaymentInfo constructPaymentInfo(Order order); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_service_PaymentInfoFactory.java
1,695
Thread thread = new Thread(new Runnable() { public void run() { try { firstBool.set(map.tryRemove("key1", 1, TimeUnit.SECONDS)); latch2.countDown(); latch1.await(); secondBool.set(map.tryRemove("key1", 1, TimeUnit.SECONDS)); latch3.countDown(); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } });
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
1,591
public class ODistributedStorage implements OStorage, OFreezableStorage { protected final OServer serverInstance; protected final ODistributedServerManager dManager; protected final OStorageEmbedded wrapped; public ODistributedStorage(final OServer iServer, final OStorageEmbedded wrapped) { this.serverInstance = iServer; this.dManager = iServer.getDistributedManager(); this.wrapped = wrapped; } @Override public boolean isDistributed() { return true; } public Object command(final OCommandRequestText iCommand) { if (OScenarioThreadLocal.INSTANCE.get() == RUN_MODE.RUNNING_DISTRIBUTED) // ALREADY DISTRIBUTED return wrapped.command(iCommand); final ODistributedConfiguration dConfig = dManager.getDatabaseConfiguration(getName()); if (!dConfig.isReplicationActive(null)) // DON'T REPLICATE return wrapped.command(iCommand); final OCommandExecutor executor = OCommandManager.instance().getExecutor(iCommand); executor.setProgressListener(iCommand.getProgressListener()); executor.parse(iCommand); final OCommandExecutor exec = executor instanceof OCommandExecutorSQLDelegate ? ((OCommandExecutorSQLDelegate) executor) .getDelegate() : executor; boolean distribute = false; if (OScenarioThreadLocal.INSTANCE.get() != RUN_MODE.RUNNING_DISTRIBUTED) if (exec instanceof OCommandDistributedReplicateRequest) distribute = ((OCommandDistributedReplicateRequest) exec).isReplicated(); if (!distribute) // DON'T REPLICATE return wrapped.executeCommand(iCommand, executor); try { // REPLICATE IT // final OAbstractRemoteTask task = exec instanceof OCommandExecutorSQLResultsetAbstract ? new OMapReduceCommandTask( // iCommand.getText()) : new OSQLCommandTask(iCommand.getText()); final OAbstractRemoteTask task = new OSQLCommandTask(iCommand.getText()); final Object result = dManager.sendRequest(getName(), null, task, EXECUTION_MODE.RESPONSE); if (result instanceof ONeedRetryException) throw (ONeedRetryException) result; else if (result instanceof Throwable) throw new ODistributedException("Error on execution distributed COMMAND", (Throwable) result); return result; } catch (ONeedRetryException e) { // PASS THROUGH throw e; } catch (Exception e) { handleDistributedException("Cannot route COMMAND operation to the distributed node", e); // UNREACHABLE return null; } } public OStorageOperationResult<OPhysicalPosition> createRecord(final int iDataSegmentId, final ORecordId iRecordId, final byte[] iContent, final ORecordVersion iRecordVersion, final byte iRecordType, final int iMode, final ORecordCallback<OClusterPosition> iCallback) { if (OScenarioThreadLocal.INSTANCE.get() == RUN_MODE.RUNNING_DISTRIBUTED) // ALREADY DISTRIBUTED return wrapped.createRecord(iDataSegmentId, iRecordId, iContent, iRecordVersion, iRecordType, iMode, iCallback); Object result = null; try { // ASSIGN DESTINATION NODE final String clusterName = getClusterNameByRID(iRecordId); final ODistributedConfiguration dConfig = dManager.getDatabaseConfiguration(getName()); if (!dConfig.isReplicationActive(clusterName)) // DON'T REPLICATE return wrapped.createRecord(iDataSegmentId, iRecordId, iContent, iRecordVersion, iRecordType, iMode, iCallback); // REPLICATE IT result = dManager.sendRequest(getName(), clusterName, new OCreateRecordTask(iRecordId, iContent, iRecordVersion, iRecordType), EXECUTION_MODE.RESPONSE); if (result instanceof ONeedRetryException) throw (ONeedRetryException) result; else if (result instanceof Throwable) throw new ODistributedException("Error on execution distributed CREATE_RECORD", (Throwable) result); iRecordId.clusterPosition = ((OPhysicalPosition) result).clusterPosition; return new OStorageOperationResult<OPhysicalPosition>((OPhysicalPosition) result); } catch (ONeedRetryException e) { // PASS THROUGH throw e; } catch (Exception e) { handleDistributedException("Cannot route CREATE_RECORD operation against %s to the distributed node", e, iRecordId); // UNREACHABLE return null; } } public OStorageOperationResult<ORawBuffer> readRecord(final ORecordId iRecordId, final String iFetchPlan, final boolean iIgnoreCache, final ORecordCallback<ORawBuffer> iCallback, boolean loadTombstones) { if (OScenarioThreadLocal.INSTANCE.get() == RUN_MODE.RUNNING_DISTRIBUTED) // ALREADY DISTRIBUTED return wrapped.readRecord(iRecordId, iFetchPlan, iIgnoreCache, iCallback, loadTombstones); try { final String clusterName = getClusterNameByRID(iRecordId); final ODistributedConfiguration dConfig = dManager.getDatabaseConfiguration(getName()); if (!dConfig.isReplicationActive(clusterName)) // DON'T REPLICATE return wrapped.readRecord(iRecordId, iFetchPlan, iIgnoreCache, iCallback, loadTombstones); final ODistributedPartitioningStrategy strategy = dManager.getPartitioningStrategy(dConfig.getPartitionStrategy(clusterName)); final ODistributedPartition partition = strategy.getPartition(dManager, getName(), clusterName); if (partition.getNodes().contains(dManager.getLocalNodeName())) // LOCAL NODE OWNS THE DATA: GET IT LOCALLY BECAUSE IT'S FASTER return wrapped.readRecord(iRecordId, iFetchPlan, iIgnoreCache, iCallback, loadTombstones); // DISTRIBUTE IT final Object result = dManager.sendRequest(getName(), clusterName, new OReadRecordTask(iRecordId), EXECUTION_MODE.RESPONSE); if (result instanceof ONeedRetryException) throw (ONeedRetryException) result; else if (result instanceof Throwable) throw new ODistributedException("Error on execution distributed READ_RECORD", (Throwable) result); return new OStorageOperationResult<ORawBuffer>((ORawBuffer) result); } catch (ONeedRetryException e) { // PASS THROUGH throw e; } catch (Exception e) { handleDistributedException("Cannot route READ_RECORD operation against %s to the distributed node", e, iRecordId); // UNREACHABLE return null; } } public OStorageOperationResult<ORecordVersion> updateRecord(final ORecordId iRecordId, final byte[] iContent, final ORecordVersion iVersion, final byte iRecordType, final int iMode, final ORecordCallback<ORecordVersion> iCallback) { if (OScenarioThreadLocal.INSTANCE.get() == RUN_MODE.RUNNING_DISTRIBUTED) // ALREADY DISTRIBUTED return wrapped.updateRecord(iRecordId, iContent, iVersion, iRecordType, iMode, iCallback); try { final String clusterName = getClusterNameByRID(iRecordId); final ODistributedConfiguration dConfig = dManager.getDatabaseConfiguration(getName()); if (!dConfig.isReplicationActive(clusterName)) // DON'T REPLICATE return wrapped.updateRecord(iRecordId, iContent, iVersion, iRecordType, iMode, iCallback); // REPLICATE IT final Object result = dManager.sendRequest(getName(), clusterName, new OUpdateRecordTask(iRecordId, iContent, iVersion, iRecordType), EXECUTION_MODE.RESPONSE); if (result instanceof ONeedRetryException) throw (ONeedRetryException) result; else if (result instanceof Throwable) throw new ODistributedException("Error on execution distributed UPDATE_RECORD", (Throwable) result); // UPDATE LOCALLY return new OStorageOperationResult<ORecordVersion>((ORecordVersion) result); } catch (ONeedRetryException e) { // PASS THROUGH throw e; } catch (Exception e) { handleDistributedException("Cannot route UPDATE_RECORD operation against %s to the distributed node", e, iRecordId); // UNREACHABLE return null; } } public String getClusterNameByRID(final ORecordId iRid) { final OCluster cluster = getClusterById(iRid.clusterId); return cluster != null ? cluster.getName() : "*"; } public OStorageOperationResult<Boolean> deleteRecord(final ORecordId iRecordId, final ORecordVersion iVersion, final int iMode, final ORecordCallback<Boolean> iCallback) { if (OScenarioThreadLocal.INSTANCE.get() == RUN_MODE.RUNNING_DISTRIBUTED) // ALREADY DISTRIBUTED return wrapped.deleteRecord(iRecordId, iVersion, iMode, iCallback); try { final String clusterName = getClusterNameByRID(iRecordId); final ODistributedConfiguration dConfig = dManager.getDatabaseConfiguration(getName()); if (!dConfig.isReplicationActive(clusterName)) // DON'T REPLICATE return wrapped.deleteRecord(iRecordId, iVersion, iMode, iCallback); // REPLICATE IT final Object result = dManager.sendRequest(getName(), clusterName, new ODeleteRecordTask(iRecordId, iVersion), EXECUTION_MODE.RESPONSE); if (result instanceof ONeedRetryException) throw (ONeedRetryException) result; else if (result instanceof Throwable) throw new ODistributedException("Error on execution distributed DELETE_RECORD", (Throwable) result); return new OStorageOperationResult<Boolean>(true); } catch (ONeedRetryException e) { // PASS THROUGH throw e; } catch (Exception e) { handleDistributedException("Cannot route DELETE_RECORD operation against %s to the distributed node", e, iRecordId); // UNREACHABLE return null; } } @Override public boolean updateReplica(int dataSegmentId, ORecordId rid, byte[] content, ORecordVersion recordVersion, byte recordType) throws IOException { return wrapped.updateReplica(dataSegmentId, rid, content, recordVersion, recordType); } @Override public ORecordMetadata getRecordMetadata(ORID rid) { return wrapped.getRecordMetadata(rid); } @Override public boolean cleanOutRecord(ORecordId recordId, ORecordVersion recordVersion, int iMode, ORecordCallback<Boolean> callback) { return wrapped.cleanOutRecord(recordId, recordVersion, iMode, callback); } public boolean existsResource(final String iName) { return wrapped.existsResource(iName); } @SuppressWarnings("unchecked") public <T> T removeResource(final String iName) { return (T) wrapped.removeResource(iName); } public <T> T getResource(final String iName, final Callable<T> iCallback) { return (T) wrapped.getResource(iName, iCallback); } public void open(final String iUserName, final String iUserPassword, final Map<String, Object> iProperties) { wrapped.open(iUserName, iUserPassword, iProperties); } public void create(final Map<String, Object> iProperties) { wrapped.create(iProperties); } public boolean exists() { return wrapped.exists(); } public void reload() { wrapped.reload(); } public void delete() { wrapped.delete(); } public void close() { wrapped.close(); } public void close(final boolean iForce) { wrapped.close(iForce); } public boolean isClosed() { return wrapped.isClosed(); } public OLevel2RecordCache getLevel2Cache() { return wrapped.getLevel2Cache(); } public void commit(final OTransaction iTx, final Runnable callback) { if (OScenarioThreadLocal.INSTANCE.get() == RUN_MODE.RUNNING_DISTRIBUTED) // ALREADY DISTRIBUTED wrapped.commit(iTx, callback); else { try { final ODistributedConfiguration dConfig = dManager.getDatabaseConfiguration(getName()); if (!dConfig.isReplicationActive(null)) // DON'T REPLICATE wrapped.commit(iTx, callback); else { final OTxTask txTask = new OTxTask(); for (ORecordOperation op : iTx.getCurrentRecordEntries()) { final OAbstractRecordReplicatedTask task; final ORecordInternal<?> record = op.getRecord(); switch (op.type) { case ORecordOperation.CREATED: task = new OCreateRecordTask((ORecordId) op.record.getIdentity(), record.toStream(), record.getRecordVersion(), record.getRecordType()); break; case ORecordOperation.UPDATED: task = new OUpdateRecordTask((ORecordId) op.record.getIdentity(), record.toStream(), record.getRecordVersion(), record.getRecordType()); break; case ORecordOperation.DELETED: task = new ODeleteRecordTask((ORecordId) op.record.getIdentity(), record.getRecordVersion()); break; default: continue; } txTask.add(task); } // REPLICATE IT dManager.sendRequest(getName(), null, txTask, EXECUTION_MODE.RESPONSE); } } catch (Exception e) { handleDistributedException("Cannot route TX operation against distributed node", e); } } } public void rollback(final OTransaction iTx) { wrapped.rollback(iTx); } public OStorageConfiguration getConfiguration() { return wrapped.getConfiguration(); } public int getClusters() { return wrapped.getClusters(); } public Set<String> getClusterNames() { return wrapped.getClusterNames(); } public OCluster getClusterById(int iId) { return wrapped.getClusterById(iId); } public Collection<? extends OCluster> getClusterInstances() { return wrapped.getClusterInstances(); } public int addCluster(final String iClusterType, final String iClusterName, final String iLocation, final String iDataSegmentName, boolean forceListBased, final Object... iParameters) { return wrapped.addCluster(iClusterType, iClusterName, iLocation, iDataSegmentName, false, iParameters); } public int addCluster(String iClusterType, String iClusterName, int iRequestedId, String iLocation, String iDataSegmentName, boolean forceListBased, Object... iParameters) { return wrapped.addCluster(iClusterType, iClusterName, iRequestedId, iLocation, iDataSegmentName, forceListBased, iParameters); } public boolean dropCluster(final String iClusterName, final boolean iTruncate) { return wrapped.dropCluster(iClusterName, iTruncate); } public boolean dropCluster(final int iId, final boolean iTruncate) { return wrapped.dropCluster(iId, iTruncate); } public int addDataSegment(final String iDataSegmentName) { return wrapped.addDataSegment(iDataSegmentName); } public int addDataSegment(final String iSegmentName, final String iDirectory) { return wrapped.addDataSegment(iSegmentName, iDirectory); } public long count(final int iClusterId) { return wrapped.count(iClusterId); } @Override public long count(int iClusterId, boolean countTombstones) { return wrapped.count(iClusterId, countTombstones); } public long count(final int[] iClusterIds) { return wrapped.count(iClusterIds); } @Override public long count(int[] iClusterIds, boolean countTombstones) { return wrapped.count(iClusterIds, countTombstones); } public long getSize() { return wrapped.getSize(); } public long countRecords() { return wrapped.countRecords(); } public int getDefaultClusterId() { return wrapped.getDefaultClusterId(); } public void setDefaultClusterId(final int defaultClusterId) { wrapped.setDefaultClusterId(defaultClusterId); } public int getClusterIdByName(String iClusterName) { return wrapped.getClusterIdByName(iClusterName); } public String getClusterTypeByName(final String iClusterName) { return wrapped.getClusterTypeByName(iClusterName); } public String getPhysicalClusterNameById(final int iClusterId) { return wrapped.getPhysicalClusterNameById(iClusterId); } public boolean checkForRecordValidity(final OPhysicalPosition ppos) { return wrapped.checkForRecordValidity(ppos); } public String getName() { return wrapped.getName(); } public String getURL() { return wrapped.getURL(); } public long getVersion() { return wrapped.getVersion(); } public void synch() { wrapped.synch(); } public int getUsers() { return wrapped.getUsers(); } public int addUser() { return wrapped.addUser(); } public int removeUser() { return wrapped.removeUser(); } public OClusterPosition[] getClusterDataRange(final int currentClusterId) { return wrapped.getClusterDataRange(currentClusterId); } public <V> V callInLock(final Callable<V> iCallable, final boolean iExclusiveLock) { return wrapped.callInLock(iCallable, iExclusiveLock); } @Override public <V> V callInRecordLock(Callable<V> iCallable, ORID rid, boolean iExclusiveLock) { return wrapped.callInRecordLock(iCallable, rid, iExclusiveLock); } public ODataSegment getDataSegmentById(final int iDataSegmentId) { return wrapped.getDataSegmentById(iDataSegmentId); } public int getDataSegmentIdByName(final String iDataSegmentName) { return wrapped.getDataSegmentIdByName(iDataSegmentName); } public boolean dropDataSegment(final String iName) { return wrapped.dropDataSegment(iName); } public STATUS getStatus() { return wrapped.getStatus(); } @Override public void checkForClusterPermissions(final String iClusterName) { wrapped.checkForClusterPermissions(iClusterName); } @Override public OPhysicalPosition[] higherPhysicalPositions(int currentClusterId, OPhysicalPosition entry) { return wrapped.higherPhysicalPositions(currentClusterId, entry); } @Override public OPhysicalPosition[] ceilingPhysicalPositions(int clusterId, OPhysicalPosition physicalPosition) { return wrapped.ceilingPhysicalPositions(clusterId, physicalPosition); } @Override public OPhysicalPosition[] floorPhysicalPositions(int clusterId, OPhysicalPosition physicalPosition) { return wrapped.floorPhysicalPositions(clusterId, physicalPosition); } @Override public OPhysicalPosition[] lowerPhysicalPositions(int currentClusterId, OPhysicalPosition entry) { return wrapped.lowerPhysicalPositions(currentClusterId, entry); } @Override public OSharedResourceAdaptiveExternal getLock() { return wrapped.getLock(); } public OStorage getUnderlying() { return wrapped; } @Override public String getType() { return "distributed"; } protected void handleDistributedException(final String iMessage, Exception e, Object... iParams) { OLogManager.instance().error(this, iMessage, e, iParams); final Throwable t = e.getCause(); if (t != null) { if (t instanceof OException) throw (OException) t; else if (t.getCause() instanceof OException) throw (OException) t.getCause(); } throw new OStorageException(String.format(iMessage, iParams), e); } @Override public void freeze(boolean throwException) { getFreezableStorage().freeze(throwException); } @Override public void release() { getFreezableStorage().release(); } @Override public void backup(OutputStream out, Map<String, Object> options, Callable<Object> callable) throws IOException { wrapped.backup(out, options, callable); } @Override public void restore(InputStream in, Map<String, Object> options, Callable<Object> callable) throws IOException { wrapped.restore(in, options, callable); } private OFreezableStorage getFreezableStorage() { if (wrapped instanceof OFreezableStorage) return ((OFreezableStorage) wrapped); else throw new UnsupportedOperationException("Storage engine " + wrapped.getType() + " does not support freeze operation"); } }
1no label
server_src_main_java_com_orientechnologies_orient_server_distributed_ODistributedStorage.java
3,751
public class ParseMappingTypeLevelTests extends ElasticsearchTestCase { @Test public void testTypeLevel() throws Exception { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("_source").field("enabled", false).endObject() .endObject().endObject().string(); DocumentMapper mapper = MapperTestUtils.newParser().parse("type", mapping); assertThat(mapper.type(), equalTo("type")); assertThat(mapper.sourceMapper().enabled(), equalTo(false)); mapper = MapperTestUtils.newParser().parse(mapping); assertThat(mapper.type(), equalTo("type")); assertThat(mapper.sourceMapper().enabled(), equalTo(false)); } }
0true
src_test_java_org_elasticsearch_index_mapper_typelevels_ParseMappingTypeLevelTests.java
325
public class NodesInfoRequest extends NodesOperationRequest<NodesInfoRequest> { private boolean settings = true; private boolean os = true; private boolean process = true; private boolean jvm = true; private boolean threadPool = true; private boolean network = true; private boolean transport = true; private boolean http = true; private boolean plugin = true; public NodesInfoRequest() { } /** * Get information from nodes based on the nodes ids specified. If none are passed, information * for all nodes will be returned. */ public NodesInfoRequest(String... nodesIds) { super(nodesIds); } /** * Clears all info flags. */ public NodesInfoRequest clear() { settings = false; os = false; process = false; jvm = false; threadPool = false; network = false; transport = false; http = false; plugin = false; return this; } /** * Sets to return all the data. */ public NodesInfoRequest all() { settings = true; os = true; process = true; jvm = true; threadPool = true; network = true; transport = true; http = true; plugin = true; return this; } /** * Should the node settings be returned. */ public boolean settings() { return this.settings; } /** * Should the node settings be returned. */ public NodesInfoRequest settings(boolean settings) { this.settings = settings; return this; } /** * Should the node OS be returned. */ public boolean os() { return this.os; } /** * Should the node OS be returned. */ public NodesInfoRequest os(boolean os) { this.os = os; return this; } /** * Should the node Process be returned. */ public boolean process() { return this.process; } /** * Should the node Process be returned. */ public NodesInfoRequest process(boolean process) { this.process = process; return this; } /** * Should the node JVM be returned. */ public boolean jvm() { return this.jvm; } /** * Should the node JVM be returned. */ public NodesInfoRequest jvm(boolean jvm) { this.jvm = jvm; return this; } /** * Should the node Thread Pool info be returned. */ public boolean threadPool() { return this.threadPool; } /** * Should the node Thread Pool info be returned. */ public NodesInfoRequest threadPool(boolean threadPool) { this.threadPool = threadPool; return this; } /** * Should the node Network be returned. */ public boolean network() { return this.network; } /** * Should the node Network be returned. */ public NodesInfoRequest network(boolean network) { this.network = network; return this; } /** * Should the node Transport be returned. */ public boolean transport() { return this.transport; } /** * Should the node Transport be returned. */ public NodesInfoRequest transport(boolean transport) { this.transport = transport; return this; } /** * Should the node HTTP be returned. */ public boolean http() { return this.http; } /** * Should the node HTTP be returned. */ public NodesInfoRequest http(boolean http) { this.http = http; return this; } /** * Should information about plugins be returned * @param plugin true if you want info * @return The request */ public NodesInfoRequest plugin(boolean plugin) { this.plugin = plugin; return this; } /** * @return true if information about plugins is requested */ public boolean plugin() { return plugin; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); settings = in.readBoolean(); os = in.readBoolean(); process = in.readBoolean(); jvm = in.readBoolean(); threadPool = in.readBoolean(); network = in.readBoolean(); transport = in.readBoolean(); http = in.readBoolean(); plugin = in.readBoolean(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeBoolean(settings); out.writeBoolean(os); out.writeBoolean(process); out.writeBoolean(jvm); out.writeBoolean(threadPool); out.writeBoolean(network); out.writeBoolean(transport); out.writeBoolean(http); out.writeBoolean(plugin); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_info_NodesInfoRequest.java
1,049
public class MultiTermVectorsTests extends AbstractTermVectorTests { @Test public void testDuelESLucene() throws Exception { AbstractTermVectorTests.TestFieldSetting[] testFieldSettings = getFieldSettings(); createIndexBasedOnFieldSettings(testFieldSettings, -1); AbstractTermVectorTests.TestDoc[] testDocs = generateTestDocs(5, testFieldSettings); DirectoryReader directoryReader = indexDocsWithLucene(testDocs); AbstractTermVectorTests.TestConfig[] testConfigs = generateTestConfigs(20, testDocs, testFieldSettings); MultiTermVectorsRequestBuilder requestBuilder = client().prepareMultiTermVectors(); for (AbstractTermVectorTests.TestConfig test : testConfigs) { requestBuilder.add(getRequestForConfig(test).request()); } MultiTermVectorsItemResponse[] responseItems = requestBuilder.get().getResponses(); for (int i = 0; i < testConfigs.length; i++) { TestConfig test = testConfigs[i]; try { MultiTermVectorsItemResponse item = responseItems[i]; if (test.expectedException != null) { assertTrue(item.isFailed()); continue; } else if (item.isFailed()) { fail(item.getFailure().getMessage()); } Fields luceneTermVectors = getTermVectorsFromLucene(directoryReader, test.doc); validateResponse(item.getResponse(), luceneTermVectors, test); } catch (Throwable t) { throw new Exception("Test exception while running " + test.toString(), t); } } } public void testMissingIndexThrowsMissingIndex() throws Exception { TermVectorRequestBuilder requestBuilder = client().prepareTermVector("testX", "typeX", Integer.toString(1)); MultiTermVectorsRequestBuilder mtvBuilder = new MultiTermVectorsRequestBuilder(client()); mtvBuilder.add(requestBuilder.request()); MultiTermVectorsResponse response = mtvBuilder.execute().actionGet(); assertThat(response.getResponses().length, equalTo(1)); assertThat(response.getResponses()[0].getFailure().getMessage(), equalTo("[" + response.getResponses()[0].getIndex() + "] missing")); } }
0true
src_test_java_org_elasticsearch_action_termvector_MultiTermVectorsTests.java
2,000
private static class IdenticalTo extends AbstractMatcher<Object> implements Serializable { private final Object value; public IdenticalTo(Object value) { this.value = checkNotNull(value, "value"); } public boolean matches(Object other) { return value == other; } @Override public boolean equals(Object other) { return other instanceof IdenticalTo && ((IdenticalTo) other).value == value; } @Override public int hashCode() { return 37 * System.identityHashCode(value); } @Override public String toString() { return "identicalTo(" + value + ")"; } private static final long serialVersionUID = 0; }
0true
src_main_java_org_elasticsearch_common_inject_matcher_Matchers.java
742
public class ExplainAction extends Action<ExplainRequest, ExplainResponse, ExplainRequestBuilder> { public static final ExplainAction INSTANCE = new ExplainAction(); public static final String NAME = "explain"; private ExplainAction() { super(NAME); } public ExplainRequestBuilder newRequestBuilder(Client client) { return new ExplainRequestBuilder(client); } public ExplainResponse newResponse() { return new ExplainResponse(); } }
0true
src_main_java_org_elasticsearch_action_explain_ExplainAction.java
2,449
executor.execute(new Runnable() { @Override public void run() { try { wait.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } executed1.set(true); exec1Wait.countDown(); } });
0true
src_test_java_org_elasticsearch_common_util_concurrent_EsExecutorsTests.java
478
public class GetAliasesResponse extends ActionResponse { private ImmutableOpenMap<String, List<AliasMetaData>> aliases = ImmutableOpenMap.of(); public GetAliasesResponse(ImmutableOpenMap<String, List<AliasMetaData>> aliases) { this.aliases = aliases; } GetAliasesResponse() { } public ImmutableOpenMap<String, List<AliasMetaData>> getAliases() { return aliases; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); int size = in.readVInt(); ImmutableOpenMap.Builder<String, List<AliasMetaData>> aliasesBuilder = ImmutableOpenMap.builder(); for (int i = 0; i < size; i++) { String key = in.readString(); int valueSize = in.readVInt(); List<AliasMetaData> value = new ArrayList<AliasMetaData>(valueSize); for (int j = 0; j < valueSize; j++) { value.add(AliasMetaData.Builder.readFrom(in)); } aliasesBuilder.put(key, ImmutableList.copyOf(value)); } aliases = aliasesBuilder.build(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(aliases.size()); for (ObjectObjectCursor<String, List<AliasMetaData>> entry : aliases) { out.writeString(entry.key); out.writeVInt(entry.value.size()); for (AliasMetaData aliasMetaData : entry.value) { AliasMetaData.Builder.writeTo(aliasMetaData, out); } } } }
0true
src_main_java_org_elasticsearch_action_admin_indices_alias_get_GetAliasesResponse.java
2
public class Prover { private final Queue<ClusterState> unexploredKnownStates = new LinkedList<>( ); private final ProofDatabase db = new ProofDatabase("./clusterproof"); public static void main(String ... args) throws Exception { new Prover().prove(); } public void prove() throws Exception { try { System.out.println("Bootstrap genesis state.."); bootstrapCluster(); System.out.println("Begin exploring delivery orders."); exploreUnexploredStates(); System.out.println("Exporting graphviz.."); db.export(new GraphVizExporter(new File("./proof.gs"))); } finally { db.shutdown(); } // Generate .svg : // dot -Tsvg proof.gs -o proof.svg } private void bootstrapCluster() throws Exception { Logging logging = new TestLogging(); String instance1 = "cluster://localhost:5001"; String instance2 = "cluster://localhost:5002"; String instance3 = "cluster://localhost:5003"; ClusterConfiguration config = new ClusterConfiguration( "default", logging.getMessagesLog( ClusterConfiguration.class ), instance1, instance2, instance3 ); ClusterState state = new ClusterState( asList( newClusterInstance( new InstanceId( 1 ), new URI( instance1 ), config, logging ), newClusterInstance( new InstanceId( 2 ), new URI( instance2 ), config, logging ), newClusterInstance( new InstanceId( 3 ), new URI( instance3 ), config, logging )), emptySetOf( ClusterAction.class )); state = state.performAction( new MessageDeliveryAction( Message.to( ClusterMessage.create, new URI( instance3 ), "defaultcluster" ).setHeader( Message.CONVERSATION_ID, "-1" ).setHeader( Message.FROM, instance3 ) ) ); state = state.performAction( new MessageDeliveryAction( Message.to( ClusterMessage.join, new URI( instance2 ), new Object[]{"defaultcluster", new URI[]{new URI( instance3 )}} ).setHeader( Message.CONVERSATION_ID, "-1" ).setHeader( Message.FROM, instance2 ) ) ); state = state.performAction( new MessageDeliveryAction( Message.to( ClusterMessage.join, new URI( instance1 ), new Object[]{"defaultcluster", new URI[]{new URI( instance3 )}} ).setHeader( Message.CONVERSATION_ID, "-1" ).setHeader( Message.FROM, instance1 ) ) ); state.addPendingActions( new InstanceCrashedAction( instance3 ) ); unexploredKnownStates.add( state ); db.newState( state ); } private void exploreUnexploredStates() { while(!unexploredKnownStates.isEmpty()) { ClusterState state = unexploredKnownStates.poll(); Iterator<Pair<ClusterAction, ClusterState>> newStates = state.transitions(); while(newStates.hasNext()) { Pair<ClusterAction, ClusterState> next = newStates.next(); System.out.println( db.numberOfKnownStates() + " ("+unexploredKnownStates.size()+")" ); ClusterState nextState = next.other(); if(!db.isKnownState( nextState )) { db.newStateTransition( state, next ); unexploredKnownStates.offer( nextState ); if(nextState.isDeadEnd()) { System.out.println("DEAD END: " + nextState.toString() + " (" + db.id(nextState) + ")"); } } } } } }
1no label
enterprise_ha_src_test_java_org_neo4j_ha_correctness_Prover.java
596
public interface OIndexEngine<V> { void init(); void flush(); void create(String indexName, OIndexDefinition indexDefinition, String clusterIndexName, OStreamSerializer valueSerializer, boolean isAutomatic); void delete(); void deleteWithoutLoad(String indexName); void load(ORID indexRid, String indexName, OIndexDefinition indexDefinition, boolean isAutomatic); boolean contains(Object key); boolean remove(Object key); ORID getIdentity(); void clear(); Iterator<Map.Entry<Object, V>> iterator(); Iterator<Map.Entry<Object, V>> inverseIterator(); Iterator<V> valuesIterator(); Iterator<V> inverseValuesIterator(); Iterable<Object> keys(); void unload(); void startTransaction(); void stopTransaction(); void afterTxRollback(); void afterTxCommit(); void closeDb(); void close(); void beforeTxBegin(); V get(Object key); void put(Object key, V value); void getValuesBetween(Object rangeFrom, boolean fromInclusive, Object rangeTo, boolean toInclusive, ValuesTransformer<V> transformer, ValuesResultListener valuesResultListener); void getValuesMajor(Object fromKey, boolean isInclusive, ValuesTransformer<V> transformer, ValuesResultListener valuesResultListener); void getValuesMinor(final Object toKey, final boolean isInclusive, ValuesTransformer<V> transformer, ValuesResultListener valuesResultListener); void getEntriesMajor(final Object fromKey, final boolean isInclusive, ValuesTransformer<V> transformer, EntriesResultListener entriesResultListener); void getEntriesMinor(Object toKey, boolean isInclusive, ValuesTransformer<V> transformer, EntriesResultListener entriesResultListener); void getEntriesBetween(Object iRangeFrom, Object iRangeTo, boolean iInclusive, ValuesTransformer<V> transformer, EntriesResultListener entriesResultListener); long size(ValuesTransformer<V> transformer); long count(Object rangeFrom, final boolean fromInclusive, Object rangeTo, final boolean toInclusive, final int maxValuesToFetch, ValuesTransformer<V> transformer); boolean hasRangeQuerySupport(); interface ValuesTransformer<V> { Collection<OIdentifiable> transformFromValue(V value); V transformToValue(Collection<OIdentifiable> collection); } interface ValuesResultListener { boolean addResult(OIdentifiable identifiable); } interface EntriesResultListener { boolean addResult(ODocument entry); } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_OIndexEngine.java
1,721
EntryListener<Object, Object> listener = new EntryListener<Object, Object>() { public void entryAdded(EntryEvent<Object, Object> event) { addedKey[0] = event.getKey(); addedValue[0] = event.getValue(); } public void entryRemoved(EntryEvent<Object, Object> event) { removedKey[0] = event.getKey(); removedValue[0] = event.getOldValue(); } public void entryUpdated(EntryEvent<Object, Object> event) { updatedKey[0] = event.getKey(); oldValue[0] = event.getOldValue(); newValue[0] = event.getValue(); } public void entryEvicted(EntryEvent<Object, Object> event) { } };
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
830
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_ORDER_ITEM_ADJUSTMENT") @Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements") @AdminPresentationMergeOverrides( { @AdminPresentationMergeOverride(name = "", mergeEntries = @AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.READONLY, booleanOverrideValue = true)) } ) @AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "OrderItemAdjustmentImpl_baseOrderItemAdjustment") public class OrderItemAdjustmentImpl implements OrderItemAdjustment, CurrencyCodeIdentifiable { public static final long serialVersionUID = 1L; @Id @GeneratedValue(generator= "OrderItemAdjustmentId") @GenericGenerator( name="OrderItemAdjustmentId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="OrderItemAdjustmentImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.offer.domain.OrderItemAdjustmentImpl") } ) @Column(name = "ORDER_ITEM_ADJUSTMENT_ID") protected Long id; @ManyToOne(targetEntity = OrderItemImpl.class) @JoinColumn(name = "ORDER_ITEM_ID") @Index(name="OIADJUST_ITEM_INDEX", columnNames={"ORDER_ITEM_ID"}) @AdminPresentation(excluded = true) protected OrderItem orderItem; @ManyToOne(targetEntity = OfferImpl.class, optional=false) @JoinColumn(name = "OFFER_ID") @Index(name="OIADJUST_OFFER_INDEX", columnNames={"OFFER_ID"}) @AdminPresentation(friendlyName = "OrderItemAdjustmentImpl_Offer", order=1000, group = "OrderItemAdjustmentImpl_Description", prominent = true, gridOrder = 1000) @AdminPresentationToOneLookup() protected Offer offer; @Column(name = "ADJUSTMENT_REASON", nullable=false) @AdminPresentation(friendlyName = "OrderItemAdjustmentImpl_Item_Adjustment_Reason", order=2000) protected String reason; @Column(name = "ADJUSTMENT_VALUE", nullable=false, precision=19, scale=5) @AdminPresentation(friendlyName = "OrderItemAdjustmentImpl_Item_Adjustment_Value", order=3000, fieldType = SupportedFieldType.MONEY, prominent = true, gridOrder = 2000) protected BigDecimal value = Money.ZERO.getAmount(); @Column(name = "APPLIED_TO_SALE_PRICE") @AdminPresentation(friendlyName = "OrderItemAdjustmentImpl_Apply_To_Sale_Price", order=4000) protected boolean appliedToSalePrice; @Transient protected Money retailValue; @Transient protected Money salesValue; @Override public void init(OrderItem orderItem, Offer offer, String reason){ this.orderItem = orderItem; this.offer = offer; this.reason = reason; } @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public OrderItem getOrderItem() { return orderItem; } @Override public Offer getOffer() { return offer; } @Override public String getReason() { return reason; } @Override public void setReason(String reason) { this.reason = reason; } @Override public void setOrderItem(OrderItem orderItem) { this.orderItem = orderItem; } public void setOffer(Offer offer) { this.offer = offer; } @Override public Money getValue() { return value == null ? null : BroadleafCurrencyUtils.getMoney(value, getOrderItem().getOrder().getCurrency()); } @Override public void setValue(Money value) { this.value = value.getAmount(); } @Override public boolean isAppliedToSalePrice() { return appliedToSalePrice; } @Override public void setAppliedToSalePrice(boolean appliedToSalePrice) { this.appliedToSalePrice = appliedToSalePrice; } @Override public Money getRetailPriceValue() { if (retailValue == null) { return BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, getOrderItem().getOrder().getCurrency()); } return this.retailValue; } @Override public void setRetailPriceValue(Money retailPriceValue) { this.retailValue = retailPriceValue; } @Override public Money getSalesPriceValue() { if (salesValue == null) { return BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, getOrderItem().getOrder().getCurrency()); } return salesValue; } @Override public void setSalesPriceValue(Money salesPriceValue) { this.salesValue = salesPriceValue; } @Override public String getCurrencyCode() { return ((CurrencyCodeIdentifiable) orderItem).getCurrencyCode(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((offer == null) ? 0 : offer.hashCode()); result = prime * result + ((orderItem == null) ? 0 : orderItem.hashCode()); result = prime * result + ((reason == null) ? 0 : reason.hashCode()); result = prime * result + ((value == null) ? 0 : value.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; } OrderItemAdjustmentImpl other = (OrderItemAdjustmentImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (offer == null) { if (other.offer != null) { return false; } } else if (!offer.equals(other.offer)) { return false; } if (orderItem == null) { if (other.orderItem != null) { return false; } } else if (!orderItem.equals(other.orderItem)) { return false; } if (reason == null) { if (other.reason != null) { return false; } } else if (!reason.equals(other.reason)) { return false; } if (value == null) { if (other.value != null) { return false; } } else if (!value.equals(other.value)) { return false; } return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_OrderItemAdjustmentImpl.java
423
public class TransportRestoreSnapshotAction extends TransportMasterNodeOperationAction<RestoreSnapshotRequest, RestoreSnapshotResponse> { private final RestoreService restoreService; @Inject public TransportRestoreSnapshotAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool, RestoreService restoreService) { super(settings, transportService, clusterService, threadPool); this.restoreService = restoreService; } @Override protected String executor() { return ThreadPool.Names.SNAPSHOT; } @Override protected String transportAction() { return RestoreSnapshotAction.NAME; } @Override protected RestoreSnapshotRequest newRequest() { return new RestoreSnapshotRequest(); } @Override protected RestoreSnapshotResponse newResponse() { return new RestoreSnapshotResponse(); } @Override protected ClusterBlockException checkBlock(RestoreSnapshotRequest request, ClusterState state) { return state.blocks().indexBlockedException(ClusterBlockLevel.METADATA, ""); } @Override protected void masterOperation(final RestoreSnapshotRequest request, ClusterState state, final ActionListener<RestoreSnapshotResponse> listener) throws ElasticsearchException { RestoreService.RestoreRequest restoreRequest = new RestoreService.RestoreRequest("restore_snapshot[" + request.snapshot() + "]", request.repository(), request.snapshot()) .indices(request.indices()) .indicesOptions(request.indicesOptions()) .renamePattern(request.renamePattern()) .renameReplacement(request.renameReplacement()) .includeGlobalState(request.includeGlobalState()) .settings(request.settings()) .masterNodeTimeout(request.masterNodeTimeout()); restoreService.restoreSnapshot(restoreRequest, new RestoreSnapshotListener() { @Override public void onResponse(RestoreInfo restoreInfo) { if (restoreInfo == null) { if (request.waitForCompletion()) { restoreService.addListener(new RestoreService.RestoreCompletionListener() { SnapshotId snapshotId = new SnapshotId(request.repository(), request.snapshot()); @Override public void onRestoreCompletion(SnapshotId snapshotId, RestoreInfo snapshot) { if (this.snapshotId.equals(snapshotId)) { listener.onResponse(new RestoreSnapshotResponse(snapshot)); restoreService.removeListener(this); } } }); } else { listener.onResponse(new RestoreSnapshotResponse(null)); } } else { listener.onResponse(new RestoreSnapshotResponse(restoreInfo)); } } @Override public void onFailure(Throwable t) { listener.onFailure(t); } }); } }
1no label
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_restore_TransportRestoreSnapshotAction.java
3,248
public final class FloatValuesComparator extends DoubleValuesComparatorBase<Float> { private final float[] values; public FloatValuesComparator(IndexNumericFieldData<?> indexFieldData, float missingValue, int numHits, SortMode sortMode) { super(indexFieldData, missingValue, sortMode); assert indexFieldData.getNumericType().requiredBits() <= 32; this.values = new float[numHits]; } @Override public int compare(int slot1, int slot2) { final float v1 = values[slot1]; final float v2 = values[slot2]; return Float.compare(v1, v2); } @Override public void setBottom(int slot) { this.bottom = values[slot]; } @Override public void copy(int slot, int doc) throws IOException { values[slot] = (float) sortMode.getRelevantValue(readerValues, doc, missingValue); } @Override public Float value(int slot) { return Float.valueOf(values[slot]); } @Override public void add(int slot, int doc) { values[slot] += (float) sortMode.getRelevantValue(readerValues, doc, missingValue); } @Override public void divide(int slot, int divisor) { values[slot] /= divisor; } @Override public void missing(int slot) { values[slot] = (float) missingValue; } }
0true
src_main_java_org_elasticsearch_index_fielddata_fieldcomparator_FloatValuesComparator.java
2,417
public interface IntArray extends BigArray { /** * Get an element given its index. */ public abstract int get(long index); /** * Set a value at the given index and return the previous value. */ public abstract int set(long index, int value); /** * Increment value at the given index by <code>inc</code> and return the value. */ public abstract int increment(long index, int inc); }
0true
src_main_java_org_elasticsearch_common_util_IntArray.java
2,413
new IntroSorter() { long pivot; @Override protected void swap(int i, int j) { final long tmp = array[i]; array[i] = array[j]; array[j] = tmp; } @Override protected int compare(int i, int j) { return Longs.compare(array[i], array[j]); } @Override protected void setPivot(int i) { pivot = array[i]; } @Override protected int comparePivot(int j) { return Longs.compare(pivot, array[j]); } }.sort(0, len);
0true
src_main_java_org_elasticsearch_common_util_CollectionUtils.java
387
public class IndexEntry implements MetaAnnotated, MetaAnnotatable { public final String field; public final Object value; public IndexEntry(final String field, final Object value) { this(field, value, null); } public IndexEntry(final String field, final Object value, Map<EntryMetaData, Object> metadata) { Preconditions.checkNotNull(field); Preconditions.checkNotNull(value); Preconditions.checkArgument(StringUtils.isNotBlank(field)); this.field = field; this.value = value; if (metadata == null || metadata == EntryMetaData.EMPTY_METADATA) return; for (Map.Entry<EntryMetaData, Object> e : metadata.entrySet()) setMetaData(e.getKey(), e.getValue()); } //########## META DATA ############ //copied from StaticArrayEntry private Map<EntryMetaData,Object> metadata = EntryMetaData.EMPTY_METADATA; @Override public synchronized Object setMetaData(EntryMetaData key, Object value) { if (metadata == EntryMetaData.EMPTY_METADATA) metadata = new EntryMetaData.Map(); return metadata.put(key,value); } @Override public boolean hasMetaData() { return !metadata.isEmpty(); } @Override public Map<EntryMetaData,Object> getMetaData() { return metadata; } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexEntry.java
1,043
public class MultiTermVectorsRequestBuilder extends ActionRequestBuilder<MultiTermVectorsRequest, MultiTermVectorsResponse, MultiTermVectorsRequestBuilder> { public MultiTermVectorsRequestBuilder(Client client) { super((InternalClient) client, new MultiTermVectorsRequest()); } public MultiTermVectorsRequestBuilder add(String index, @Nullable String type, Iterable<String> ids) { for (String id : ids) { request.add(index, type, id); } return this; } public MultiTermVectorsRequestBuilder add(String index, @Nullable String type, String... ids) { for (String id : ids) { request.add(index, type, id); } return this; } public MultiTermVectorsRequestBuilder add(TermVectorRequest termVectorRequest) { request.add(termVectorRequest); return this; } @Override protected void doExecute(ActionListener<MultiTermVectorsResponse> listener) { ((Client) client).multiTermVectors(request, listener); } }
0true
src_main_java_org_elasticsearch_action_termvector_MultiTermVectorsRequestBuilder.java
1,842
public class ContextType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, ContextType> TYPES = new LinkedHashMap<String, ContextType>(); public static final ContextType GLOBAL = new ContextType("GLOBAL", "Global"); public static final ContextType SITE = new ContextType("SITE", "Site"); public static final ContextType CATALOG = new ContextType("CATALOG", "Catalog"); public static final ContextType TEMPLATE = new ContextType("TEMPLATE", "Template"); public static ContextType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public ContextType() { //do nothing } public ContextType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } @Override public String getType() { return type; } @Override public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ContextType other = (ContextType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_type_ContextType.java
942
public abstract class AcknowledgedRequestBuilder<Request extends AcknowledgedRequest<Request>, Response extends AcknowledgedResponse, RequestBuilder extends AcknowledgedRequestBuilder<Request, Response, RequestBuilder>> extends MasterNodeOperationRequestBuilder<Request, Response, RequestBuilder> { protected AcknowledgedRequestBuilder(InternalGenericClient client, Request request) { super(client, request); } /** * Sets the maximum wait for acknowledgement from other nodes */ @SuppressWarnings("unchecked") public RequestBuilder setTimeout(TimeValue timeout) { request.timeout(timeout); return (RequestBuilder)this; } /** * Timeout to wait for the operation to be acknowledged by current cluster nodes. Defaults * to <tt>10s</tt>. */ @SuppressWarnings("unchecked") public RequestBuilder setTimeout(String timeout) { request.timeout(timeout); return (RequestBuilder)this; } }
0true
src_main_java_org_elasticsearch_action_support_master_AcknowledgedRequestBuilder.java
155
public static final Map<String, String> REGISTERED_INDEX_PROVIDERS = new HashMap<String, String>() {{ put("lucene", "com.thinkaurelius.titan.diskstorage.lucene.LuceneIndex"); put("elasticsearch", "com.thinkaurelius.titan.diskstorage.es.ElasticSearchIndex"); put("es", "com.thinkaurelius.titan.diskstorage.es.ElasticSearchIndex"); put("solr", "com.thinkaurelius.titan.diskstorage.solr.SolrIndex"); }};
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_Backend.java
28
@Service("blCustomerFieldService") public class CustomerFieldServiceImpl extends AbstractRuleBuilderFieldService { @Override public void init() { fields.add(new FieldData.Builder() .label("rule_customerDeactivated") .name("deactivated") .operators("blcOperators_Boolean") .options("[]") .type(SupportedFieldType.BOOLEAN) .build()); fields.add(new FieldData.Builder() .label("rule_customerId") .name("id") .operators("blcOperators_Numeric") .options("[]") .type(SupportedFieldType.ID) .build()); fields.add(new FieldData.Builder() .label("rule_customerReceiveEmail") .name("receiveEmail") .operators("blcOperators_Boolean") .options("[]") .type(SupportedFieldType.BOOLEAN) .build()); fields.add(new FieldData.Builder() .label("rule_customerRegistered") .name("registered") .operators("blcOperators_Boolean") .options("[]") .type(SupportedFieldType.BOOLEAN) .build()); fields.add(new FieldData.Builder() .label("rule_customerUserName") .name("username") .operators("blcOperators_Text") .options("[]") .type(SupportedFieldType.STRING) .build()); fields.add(new FieldData.Builder() .label("rule_customerEmailAddress") .name("emailAddress") .operators("blcOperators_Text") .options("[]") .type(SupportedFieldType.STRING) .build()); fields.add(new FieldData.Builder() .label("rule_customerFirstName") .name("firstName") .operators("blcOperators_Text") .options("[]") .type(SupportedFieldType.STRING) .build()); fields.add(new FieldData.Builder() .label("rule_customerLastName") .name("lastName") .operators("blcOperators_Text") .options("[]") .type(SupportedFieldType.STRING) .build()); } @Override public String getName() { return RuleIdentifier.CUSTOMER; } @Override public String getDtoClassName() { return "org.broadleafcommerce.profile.core.domain.CustomerImpl"; } }
0true
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_web_rulebuilder_service_CustomerFieldServiceImpl.java
1,520
public class RebalanceAfterActiveTests extends ElasticsearchAllocationTestCase { private final ESLogger logger = Loggers.getLogger(RebalanceAfterActiveTests.class); @Test public void testRebalanceOnlyAfterAllShardsAreActive() { AllocationService strategy = createAllocationService(settingsBuilder() .put("cluster.routing.allocation.concurrent_recoveries", 10) .put("cluster.routing.allocation.allow_rebalance", "always") .put("cluster.routing.allocation.cluster_concurrent_rebalance", -1) .build()); logger.info("Building initial routing table"); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test").numberOfShards(5).numberOfReplicas(1)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); assertThat(routingTable.index("test").shards().size(), equalTo(5)); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).shards().get(0).state(), equalTo(UNASSIGNED)); assertThat(routingTable.index("test").shard(i).shards().get(1).state(), equalTo(UNASSIGNED)); assertThat(routingTable.index("test").shard(i).shards().get(0).currentNodeId(), nullValue()); assertThat(routingTable.index("test").shard(i).shards().get(1).currentNodeId(), nullValue()); } logger.info("start two nodes and fully start the shards"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2"))).build(); RoutingTable prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED)); } logger.info("start all the primary shards, replicas will start initializing"); RoutingNodes routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(INITIALIZING)); } logger.info("now, start 8 more nodes, and check that no rebalancing/relocation have happened"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()) .put(newNode("node3")).put(newNode("node4")).put(newNode("node5")).put(newNode("node6")).put(newNode("node7")).put(newNode("node8")).put(newNode("node9")).put(newNode("node10"))) .build(); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(INITIALIZING)); } logger.info("start the replica shards, rebalancing should start"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); // we only allow one relocation at a time assertThat(routingTable.shardsWithState(STARTED).size(), equalTo(5)); assertThat(routingTable.shardsWithState(RELOCATING).size(), equalTo(5)); logger.info("complete relocation, other half of relocation should happen"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); // we now only relocate 3, since 2 remain where they are! assertThat(routingTable.shardsWithState(STARTED).size(), equalTo(7)); assertThat(routingTable.shardsWithState(RELOCATING).size(), equalTo(3)); logger.info("complete relocation, thats it!"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(routingTable.shardsWithState(STARTED).size(), equalTo(10)); // make sure we have an even relocation for (RoutingNode routingNode : routingNodes) { assertThat(routingNode.size(), equalTo(1)); } } }
0true
src_test_java_org_elasticsearch_cluster_routing_allocation_RebalanceAfterActiveTests.java
269
public class EmailException extends RuntimeException { private static final long serialVersionUID = 1L; public EmailException() { super(); } public EmailException(String arg0, Throwable arg1) { super(arg0, arg1); } public EmailException(String arg0) { super(arg0); } public EmailException(Throwable arg0) { super(arg0); } }
0true
common_src_main_java_org_broadleafcommerce_common_email_service_exception_EmailException.java
1,545
public static class WeightFunction { private final float indexBalance; private final float shardBalance; private final float primaryBalance; private final EnumMap<Operation, float[]> thetaMap = new EnumMap<BalancedShardsAllocator.Operation, float[]>(Operation.class); public WeightFunction(float indexBalance, float shardBalance, float primaryBalance) { float sum = indexBalance + shardBalance + primaryBalance; if (sum <= 0.0f) { throw new ElasticsearchIllegalArgumentException("Balance factors must sum to a value > 0 but was: " + sum); } final float[] defaultTheta = new float[]{shardBalance / sum, indexBalance / sum, primaryBalance / sum}; for (Operation operation : Operation.values()) { switch (operation) { case THRESHOLD_CHECK: sum = indexBalance + shardBalance; if (sum <= 0.0f) { thetaMap.put(operation, defaultTheta); } else { thetaMap.put(operation, new float[]{shardBalance / sum, indexBalance / sum, 0}); } break; case BALANCE: case ALLOCATE: case MOVE: thetaMap.put(operation, defaultTheta); break; default: assert false; } } this.indexBalance = indexBalance; this.shardBalance = shardBalance; this.primaryBalance = primaryBalance; } public float weight(Operation operation, Balancer balancer, ModelNode node, String index) { final float weightShard = (node.numShards() - balancer.avgShardsPerNode()); final float weightIndex = (node.numShards(index) - balancer.avgShardsPerNode(index)); final float weightPrimary = (node.numPrimaries() - balancer.avgPrimariesPerNode()); final float[] theta = thetaMap.get(operation); assert theta != null; return theta[0] * weightShard + theta[1] * weightIndex + theta[2] * weightPrimary; } }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_allocator_BalancedShardsAllocator.java
362
public class PropertyFilter extends Filter { protected boolean isJoinTableFilter = false; protected String propertyName; public Boolean getJoinTableFilter() { return isJoinTableFilter; } public void setJoinTableFilter(Boolean joinTableFilter) { isJoinTableFilter = joinTableFilter; } public String getPropertyName() { return propertyName; } public void setPropertyName(String propertyName) { this.propertyName = propertyName; } }
0true
common_src_main_java_org_broadleafcommerce_common_filter_PropertyFilter.java
1,546
public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, WritableComparable> { private String key; private boolean isVertex; private WritableHandler handler; private SafeMapperOutputs outputs; @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class); this.key = context.getConfiguration().get(KEY); this.handler = new WritableHandler(context.getConfiguration().getClass(TYPE, Text.class, WritableComparable.class)); this.outputs = new SafeMapperOutputs(context); } @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, WritableComparable>.Context context) throws IOException, InterruptedException { this.outputs.write(Tokens.GRAPH, NullWritable.get(), value); if (this.isVertex) { if (value.hasPaths()) { WritableComparable writable = this.handler.set(ElementPicker.getProperty(value, this.key)); for (int i = 0; i < value.pathCount(); i++) { this.outputs.write(Tokens.SIDEEFFECT, NullWritable.get(), writable); } DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_PROCESSED, 1L); } } else { long edgesProcessed = 0; for (final Edge e : value.getEdges(Direction.OUT)) { final StandardFaunusEdge edge = (StandardFaunusEdge) e; if (edge.hasPaths()) { WritableComparable writable = this.handler.set(ElementPicker.getProperty(edge, this.key)); for (int i = 0; i < edge.pathCount(); i++) { this.outputs.write(Tokens.SIDEEFFECT, NullWritable.get(), writable); } edgesProcessed++; } } DEFAULT_COMPAT.incrementContextCounter(context, Counters.OUT_EDGES_PROCESSED, edgesProcessed); } } @Override public void cleanup(final Mapper<NullWritable, FaunusVertex, NullWritable, WritableComparable>.Context context) throws IOException, InterruptedException { this.outputs.close(); } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_transform_PropertyMap.java
274
public final class ExceptionsHelper { private static final ESLogger logger = Loggers.getLogger(ExceptionsHelper.class); public static RuntimeException convertToRuntime(Throwable t) { if (t instanceof RuntimeException) { return (RuntimeException) t; } return new ElasticsearchException(t.getMessage(), t); } public static ElasticsearchException convertToElastic(Throwable t) { if (t instanceof ElasticsearchException) { return (ElasticsearchException) t; } return new ElasticsearchException(t.getMessage(), t); } public static RestStatus status(Throwable t) { if (t instanceof ElasticsearchException) { return ((ElasticsearchException) t).status(); } return RestStatus.INTERNAL_SERVER_ERROR; } public static Throwable unwrapCause(Throwable t) { int counter = 0; Throwable result = t; while (result instanceof ElasticsearchWrapperException) { if (result.getCause() == null) { return result; } if (result.getCause() == result) { return result; } if (counter++ > 10) { // dear god, if we got more than 10 levels down, WTF? just bail logger.warn("Exception cause unwrapping ran for 10 levels...", t); return result; } result = result.getCause(); } return result; } public static String detailedMessage(Throwable t) { return detailedMessage(t, false, 0); } public static String detailedMessage(Throwable t, boolean newLines, int initialCounter) { if (t == null) { return "Unknown"; } int counter = initialCounter + 1; if (t.getCause() != null) { StringBuilder sb = new StringBuilder(); while (t != null) { sb.append(t.getClass().getSimpleName()); if (t.getMessage() != null) { sb.append("["); sb.append(t.getMessage()); sb.append("]"); } if (!newLines) { sb.append("; "); } t = t.getCause(); if (t != null) { if (newLines) { sb.append("\n"); for (int i = 0; i < counter; i++) { sb.append("\t"); } } else { sb.append("nested: "); } } counter++; } return sb.toString(); } else { return t.getClass().getSimpleName() + "[" + t.getMessage() + "]"; } } }
1no label
src_main_java_org_elasticsearch_ExceptionsHelper.java
2,610
class PingRequestHandler extends BaseTransportRequestHandler<PingRequest> { public static final String ACTION = "discovery/zen/fd/ping"; @Override public PingRequest newInstance() { return new PingRequest(); } @Override public void messageReceived(PingRequest request, TransportChannel channel) throws Exception { // if we are not the node we are supposed to be pinged, send an exception // this can happen when a kill -9 is sent, and another node is started using the same port if (!latestNodes.localNodeId().equals(request.nodeId)) { throw new ElasticsearchIllegalStateException("Got pinged as node [" + request.nodeId + "], but I am node [" + latestNodes.localNodeId() + "]"); } channel.sendResponse(new PingResponse()); } @Override public String executor() { return ThreadPool.Names.SAME; } }
1no label
src_main_java_org_elasticsearch_discovery_zen_fd_NodesFaultDetection.java
2,744
public class NoneGatewayModule extends AbstractModule implements PreProcessModule { @Override public void processModule(Module module) { if (module instanceof ShardsAllocatorModule) { ((ShardsAllocatorModule) module).setGatewayAllocator(NoneGatewayAllocator.class); } } @Override protected void configure() { bind(Gateway.class).to(NoneGateway.class).asEagerSingleton(); } }
0true
src_main_java_org_elasticsearch_gateway_none_NoneGatewayModule.java
1,639
public static final Validator DOUBLE_GTE_2 = new Validator() { @Override public String validate(String setting, String value) { try { if (Double.parseDouble(value) < 2.0) { return "the value of the setting " + setting + " must be >= 2.0"; } } catch (NumberFormatException ex) { return "cannot parse value [" + value + "] as a double"; } return null; } };
0true
src_main_java_org_elasticsearch_cluster_settings_Validator.java
987
class Counter { int count = 0; void inc() { count++; } int get() { return count; } }
0true
hazelcast_src_test_java_com_hazelcast_concurrent_semaphore_AdvancedSemaphoreTest.java
1,711
runnable = new Runnable() { public void run() { map.getEntryView(null); } };
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
2,384
public class SizeValue implements Serializable, Streamable { private long size; private SizeUnit sizeUnit; private SizeValue() { } public SizeValue(long singles) { this(singles, SizeUnit.SINGLE); } public SizeValue(long size, SizeUnit sizeUnit) { this.size = size; this.sizeUnit = sizeUnit; } public long singles() { return sizeUnit.toSingles(size); } public long getSingles() { return singles(); } public long kilo() { return sizeUnit.toKilo(size); } public long getKilo() { return kilo(); } public long mega() { return sizeUnit.toMega(size); } public long getMega() { return mega(); } public long giga() { return sizeUnit.toGiga(size); } public long getGiga() { return giga(); } public long tera() { return sizeUnit.toTera(size); } public long getTera() { return tera(); } public long peta() { return sizeUnit.toPeta(size); } public long getPeta() { return peta(); } public double kiloFrac() { return ((double) singles()) / SizeUnit.C1; } public double getKiloFrac() { return kiloFrac(); } public double megaFrac() { return ((double) singles()) / SizeUnit.C2; } public double getMegaFrac() { return megaFrac(); } public double gigaFrac() { return ((double) singles()) / SizeUnit.C3; } public double getGigaFrac() { return gigaFrac(); } public double teraFrac() { return ((double) singles()) / SizeUnit.C4; } public double getTeraFrac() { return teraFrac(); } public double petaFrac() { return ((double) singles()) / SizeUnit.C5; } public double getPetaFrac() { return petaFrac(); } @Override public String toString() { long singles = singles(); double value = singles; String suffix = ""; if (singles >= SizeUnit.C5) { value = petaFrac(); suffix = "p"; } else if (singles >= SizeUnit.C4) { value = teraFrac(); suffix = "t"; } else if (singles >= SizeUnit.C3) { value = gigaFrac(); suffix = "g"; } else if (singles >= SizeUnit.C2) { value = megaFrac(); suffix = "m"; } else if (singles >= SizeUnit.C1) { value = kiloFrac(); suffix = "k"; } return Strings.format1Decimals(value, suffix); } public static SizeValue parseSizeValue(String sValue) throws ElasticsearchParseException { return parseSizeValue(sValue, null); } public static SizeValue parseSizeValue(String sValue, SizeValue defaultValue) throws ElasticsearchParseException { if (sValue == null) { return defaultValue; } long singles; try { if (sValue.endsWith("b")) { singles = Long.parseLong(sValue.substring(0, sValue.length() - 1)); } else if (sValue.endsWith("k") || sValue.endsWith("K")) { singles = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * SizeUnit.C1); } else if (sValue.endsWith("m") || sValue.endsWith("M")) { singles = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * SizeUnit.C2); } else if (sValue.endsWith("g") || sValue.endsWith("G")) { singles = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * SizeUnit.C3); } else if (sValue.endsWith("t") || sValue.endsWith("T")) { singles = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * SizeUnit.C4); } else if (sValue.endsWith("p") || sValue.endsWith("P")) { singles = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * SizeUnit.C5); } else { singles = Long.parseLong(sValue); } } catch (NumberFormatException e) { throw new ElasticsearchParseException("Failed to parse [" + sValue + "]", e); } return new SizeValue(singles, SizeUnit.SINGLE); } public static SizeValue readSizeValue(StreamInput in) throws IOException { SizeValue sizeValue = new SizeValue(); sizeValue.readFrom(in); return sizeValue; } @Override public void readFrom(StreamInput in) throws IOException { size = in.readVLong(); sizeUnit = SizeUnit.SINGLE; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVLong(singles()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SizeValue sizeValue = (SizeValue) o; if (size != sizeValue.size) return false; if (sizeUnit != sizeValue.sizeUnit) return false; return true; } @Override public int hashCode() { int result = (int) (size ^ (size >>> 32)); result = 31 * result + (sizeUnit != null ? sizeUnit.hashCode() : 0); return result; } }
0true
src_main_java_org_elasticsearch_common_unit_SizeValue.java
322
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
1,291
clusterService1.submitStateUpdateTask("test2", new TimeoutClusterStateUpdateTask() { @Override public TimeValue timeout() { return TimeValue.timeValueMillis(2); } @Override public void onFailure(String source, Throwable t) { timedOut.countDown(); } @Override public ClusterState execute(ClusterState currentState) { executeCalled.set(true); return currentState; } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { } });
0true
src_test_java_org_elasticsearch_cluster_ClusterServiceTests.java
337
new Thread() { public void run() { try { if (tempMap.tryLock("key1", 20, TimeUnit.SECONDS)) { latch2.countDown(); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java