Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
287
public class CTConnectionPool extends GenericKeyedObjectPool<String, CTConnection> { private static final Logger log = LoggerFactory.getLogger(CTConnectionPool.class); public CTConnectionPool(KeyedPoolableObjectFactory<String, CTConnection> factory) { super(factory); } /** * If {@code conn} is non-null and is still open, then call * {@link GenericKeyedObjectPool#returnObject(String, CTConnection), * catching and logging and Exception that method might generate. * This method does not emit any exceptions. * * @param keyspace The key of the pooled object being returned * @param conn The pooled object being returned, or null to do nothing */ public void returnObjectUnsafe(String keyspace, CTConnection conn) { if (conn != null && conn.isOpen()) { try { returnObject(keyspace, conn); } catch (Exception e) { log.warn("Failed to return Cassandra connection to pool", e); log.warn( "Failure context: keyspace={}, pool={}, connection={}", new Object[] { keyspace, this, conn }); } } } }
0true
titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_thrift_thriftpool_CTConnectionPool.java
1,099
public class OSQLFunctionDocument extends OSQLFunctionMultiValueAbstract<ODocument> { public static final String NAME = "document"; public OSQLFunctionDocument() { super(NAME, 1, -1); } @SuppressWarnings("unchecked") public Object execute(final OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParameters, OCommandContext iContext) { if (iParameters.length > 2) // IN LINE MODE context = new ODocument(); if (iParameters.length == 1) { if (iParameters[0] instanceof ODocument) // INSERT EVERY DOCUMENT FIELD context.merge((ODocument) iParameters[0], true, false); else if (iParameters[0] instanceof Map<?, ?>) // INSERT EVERY SINGLE COLLECTION ITEM context.fields((Map<String, Object>) iParameters[0]); else throw new IllegalArgumentException("Map function: expected a map or pairs of parameters as key, value"); } else if (iParameters.length % 2 != 0) throw new IllegalArgumentException("Map function: expected a map or pairs of parameters as key, value"); else for (int i = 0; i < iParameters.length; i += 2) { final String key = iParameters[i].toString(); final Object value = iParameters[i + 1]; if (value != null) { if (iParameters.length <= 2 && context == null) // AGGREGATION MODE (STATEFULL) context = new ODocument(); context.field(key, value); } } return prepareResult(context); } public String getSyntax() { return "Syntax error: map(<map>|[<key>,<value>]*)"; } public boolean aggregateResults(final Object[] configuredParameters) { return configuredParameters.length <= 2; } @Override public ODocument getResult() { final ODocument res = context; context = null; return prepareResult(res); } protected ODocument prepareResult(ODocument res) { if (returnDistributedResult()) { final ODocument doc = new ODocument(); doc.field("node", getDistributedStorageId()); doc.field("context", res); return doc; } else { return res; } } @SuppressWarnings("unchecked") @Override public Object mergeDistributedResult(List<Object> resultsToMerge) { final Map<Long, Map<Object, Object>> chunks = new HashMap<Long, Map<Object, Object>>(); for (Object iParameter : resultsToMerge) { final Map<String, Object> container = (Map<String, Object>) ((Map<Object, Object>) iParameter).get("doc"); chunks.put((Long) container.get("node"), (Map<Object, Object>) container.get("context")); } final Map<Object, Object> result = new HashMap<Object, Object>(); for (Map<Object, Object> chunk : chunks.values()) { result.putAll(chunk); } return result; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_functions_coll_OSQLFunctionDocument.java
271
public class InMemoryLogBuffer implements LogBuffer, ReadableByteChannel { private byte[] bytes = new byte[1000]; private int writeIndex; private int readIndex; private ByteBuffer bufferForConversions = ByteBuffer.wrap( new byte[100] ); public InMemoryLogBuffer() { } public void reset() { writeIndex = readIndex = 0; } public void truncateTo( int bytes ) { writeIndex = bytes; } public int bytesWritten() { return writeIndex; } private void ensureArrayCapacityPlus( int plus ) { while ( writeIndex+plus > bytes.length ) { byte[] tmp = bytes; bytes = new byte[bytes.length*2]; System.arraycopy( tmp, 0, bytes, 0, tmp.length ); } } private LogBuffer flipAndPut() { ensureArrayCapacityPlus( bufferForConversions.limit() ); System.arraycopy( bufferForConversions.flip().array(), 0, bytes, writeIndex, bufferForConversions.limit() ); writeIndex += bufferForConversions.limit(); return this; } public LogBuffer put( byte b ) throws IOException { ensureArrayCapacityPlus( 1 ); bytes[writeIndex++] = b; return this; } public LogBuffer putShort( short s ) throws IOException { ((ByteBuffer) bufferForConversions.clear()).putShort( s ); return flipAndPut(); } public LogBuffer putInt( int i ) throws IOException { ((ByteBuffer) bufferForConversions.clear()).putInt( i ); return flipAndPut(); } public LogBuffer putLong( long l ) throws IOException { ((ByteBuffer) bufferForConversions.clear()).putLong( l ); return flipAndPut(); } public LogBuffer putFloat( float f ) throws IOException { ((ByteBuffer) bufferForConversions.clear()).putFloat( f ); return flipAndPut(); } public LogBuffer putDouble( double d ) throws IOException { ((ByteBuffer) bufferForConversions.clear()).putDouble( d ); return flipAndPut(); } public LogBuffer put( byte[] bytes ) throws IOException { ensureArrayCapacityPlus( bytes.length ); System.arraycopy( bytes, 0, this.bytes, writeIndex, bytes.length ); writeIndex += bytes.length; return this; } public LogBuffer put( char[] chars ) throws IOException { ensureConversionBufferCapacity( chars.length*2 ); bufferForConversions.clear(); for ( char ch : chars ) { bufferForConversions.putChar( ch ); } return flipAndPut(); } private void ensureConversionBufferCapacity( int length ) { if ( bufferForConversions.capacity() < length ) { bufferForConversions = ByteBuffer.wrap( new byte[length*2] ); } } @Override public void writeOut() throws IOException { } public void force() throws IOException { } public long getFileChannelPosition() throws IOException { return this.readIndex; } public StoreChannel getFileChannel() { throw new UnsupportedOperationException(); } public boolean isOpen() { return true; } public void close() throws IOException { } public int read( ByteBuffer dst ) throws IOException { if ( readIndex >= writeIndex ) { return -1; } int actualLengthToRead = Math.min( dst.limit(), writeIndex-readIndex ); try { dst.put( bytes, readIndex, actualLengthToRead ); return actualLengthToRead; } finally { readIndex += actualLengthToRead; } } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_nioneo_xa_LogTruncationTest.java
3,594
public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { LongFieldMapper.Builder builder = longField(name); parseNumberField(builder, name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String propName = Strings.toUnderscoreCase(entry.getKey()); Object propNode = entry.getValue(); if (propName.equals("null_value")) { builder.nullValue(nodeLongValue(propNode)); } } return builder; } }
0true
src_main_java_org_elasticsearch_index_mapper_core_LongFieldMapper.java
2,141
public class MultiCollector extends XCollector { private final Collector collector; private final Collector[] collectors; public MultiCollector(Collector collector, Collector[] collectors) { this.collector = collector; this.collectors = collectors; } @Override public void setScorer(Scorer scorer) throws IOException { // always wrap it in a scorer wrapper if (!(scorer instanceof ScoreCachingWrappingScorer)) { scorer = new ScoreCachingWrappingScorer(scorer); } collector.setScorer(scorer); for (Collector collector : collectors) { collector.setScorer(scorer); } } @Override public void collect(int doc) throws IOException { collector.collect(doc); for (Collector collector : collectors) { collector.collect(doc); } } @Override public void setNextReader(AtomicReaderContext context) throws IOException { collector.setNextReader(context); for (Collector collector : collectors) { collector.setNextReader(context); } } @Override public boolean acceptsDocsOutOfOrder() { if (!collector.acceptsDocsOutOfOrder()) { return false; } for (Collector collector : collectors) { if (!collector.acceptsDocsOutOfOrder()) { return false; } } return true; } @Override public void postCollection() { if (collector instanceof XCollector) { ((XCollector) collector).postCollection(); } for (Collector collector : collectors) { if (collector instanceof XCollector) { ((XCollector) collector).postCollection(); } } } }
0true
src_main_java_org_elasticsearch_common_lucene_MultiCollector.java
277
@Category(SerialTests.class) public class ThriftLogTest extends KCVSLogTest { @BeforeClass public static void startCassandra() { CassandraStorageSetup.startCleanEmbedded(); } @Override public KeyColumnValueStoreManager openStorageManager() throws BackendException { return new CassandraThriftStoreManager(CassandraStorageSetup.getCassandraThriftConfiguration(this.getClass().getSimpleName())); } }
0true
titan-cassandra_src_test_java_com_thinkaurelius_titan_diskstorage_cassandra_thrift_ThriftLogTest.java
2,664
public static interface NewClusterStateListener { static interface NewStateProcessed { void onNewClusterStateProcessed(); void onNewClusterStateFailed(Throwable t); } void onNewClusterState(ClusterState clusterState, NewStateProcessed newStateProcessed); }
0true
src_main_java_org_elasticsearch_discovery_zen_publish_PublishClusterStateAction.java
2,700
cluster().fullRestart(new RestartCallback() { @Override public Settings onNodeStopped(String nodeName) throws Exception { if (node_1.equals(nodeName)) { logger.info("--> deleting the data for the first node"); gateway1.reset(); } return null; } });
0true
src_test_java_org_elasticsearch_gateway_local_LocalGatewayIndexStateTests.java
691
private static final class NodeSplitResult { private final long[] newNode; private final boolean allLeftHashMapsEqual; private final boolean allRightHashMapsEqual; private NodeSplitResult(long[] newNode, boolean allLeftHashMapsEqual, boolean allRightHashMapsEqual) { this.newNode = newNode; this.allLeftHashMapsEqual = allLeftHashMapsEqual; this.allRightHashMapsEqual = allRightHashMapsEqual; } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_hashindex_local_OLocalHashTable.java
2,289
public interface Recycler<T> { public static interface Factory<T> { Recycler<T> build(); } public static interface C<T> { /** Create a new empty instance of the given size. */ T newInstance(int sizing); /** Clear the data. This operation is called when the data-structure is released. */ void clear(T value); } public static interface V<T> extends Releasable { /** Reference to the value. */ T v(); /** Whether this instance has been recycled (true) or newly allocated (false). */ boolean isRecycled(); } void close(); V<T> obtain(); V<T> obtain(int sizing); }
0true
src_main_java_org_elasticsearch_common_recycler_Recycler.java
375
public class MetadataMBeanInfoAssembler extends org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler { protected void checkManagedBean(Object managedBean) throws IllegalArgumentException { //do nothing } protected ModelMBeanNotificationInfo[] getNotificationInfo(Object managedBean, String beanKey) { managedBean = AspectUtil.exposeRootBean(managedBean); return super.getNotificationInfo(managedBean, beanKey); } protected void populateMBeanDescriptor(Descriptor desc, Object managedBean, String beanKey) { managedBean = AspectUtil.exposeRootBean(managedBean); super.populateMBeanDescriptor(desc, managedBean, beanKey); } protected ModelMBeanAttributeInfo[] getAttributeInfo(Object managedBean, String beanKey) throws JMException { managedBean = AspectUtil.exposeRootBean(managedBean); return super.getAttributeInfo(managedBean, beanKey); } protected ModelMBeanOperationInfo[] getOperationInfo(Object managedBean, String beanKey) { managedBean = AspectUtil.exposeRootBean(managedBean); return super.getOperationInfo(managedBean, beanKey); } }
0true
common_src_main_java_org_broadleafcommerce_common_jmx_MetadataMBeanInfoAssembler.java
4,267
public class FsChannelSnapshot implements Translog.Snapshot { private final long id; private final int totalOperations; private final RafReference raf; private final FileChannel channel; private final long length; private Translog.Operation lastOperationRead = null; private int position = 0; private ByteBuffer cacheBuffer; public FsChannelSnapshot(long id, RafReference raf, long length, int totalOperations) throws FileNotFoundException { this.id = id; this.raf = raf; this.channel = raf.raf().getChannel(); this.length = length; this.totalOperations = totalOperations; } @Override public long translogId() { return this.id; } @Override public long position() { return this.position; } @Override public long length() { return this.length; } @Override public int estimatedTotalOperations() { return this.totalOperations; } @Override public InputStream stream() throws IOException { return new FileChannelInputStream(channel, position, lengthInBytes()); } @Override public long lengthInBytes() { return length - position; } @Override public boolean hasNext() { try { if (position > length) { return false; } if (cacheBuffer == null) { cacheBuffer = ByteBuffer.allocate(1024); } cacheBuffer.limit(4); int bytesRead = channel.read(cacheBuffer, position); if (bytesRead < 4) { return false; } cacheBuffer.flip(); int opSize = cacheBuffer.getInt(); position += 4; if ((position + opSize) > length) { // restore the position to before we read the opSize position -= 4; return false; } if (cacheBuffer.capacity() < opSize) { cacheBuffer = ByteBuffer.allocate(opSize); } cacheBuffer.clear(); cacheBuffer.limit(opSize); channel.read(cacheBuffer, position); cacheBuffer.flip(); position += opSize; lastOperationRead = TranslogStreams.readTranslogOperation(new BytesStreamInput(cacheBuffer.array(), 0, opSize, true)); return true; } catch (Exception e) { return false; } } @Override public Translog.Operation next() { return this.lastOperationRead; } @Override public void seekForward(long length) { this.position += length; } @Override public boolean release() throws ElasticsearchException { raf.decreaseRefCount(true); return true; } }
1no label
src_main_java_org_elasticsearch_index_translog_fs_FsChannelSnapshot.java
1,257
abstract class NodeSampler { public void sample() { synchronized (mutex) { if (closed) { return; } doSample(); } } protected abstract void doSample(); /** * validates a set of potentially newly discovered nodes and returns an immutable * list of the nodes that has passed. */ protected ImmutableList<DiscoveryNode> validateNewNodes(Set<DiscoveryNode> nodes) { for (Iterator<DiscoveryNode> it = nodes.iterator(); it.hasNext(); ) { DiscoveryNode node = it.next(); if (!transportService.nodeConnected(node)) { try { logger.trace("connecting to node [{}]", node); transportService.connectToNode(node); } catch (Throwable e) { it.remove(); logger.debug("failed to connect to discovered node [" + node + "]", e); } } } return new ImmutableList.Builder<DiscoveryNode>().addAll(nodes).build(); } }
1no label
src_main_java_org_elasticsearch_client_transport_TransportClientNodesService.java
3,463
public class ShardGetService extends AbstractIndexShardComponent { private final ScriptService scriptService; private final MapperService mapperService; private final IndexFieldDataService fieldDataService; private IndexShard indexShard; private final MeanMetric existsMetric = new MeanMetric(); private final MeanMetric missingMetric = new MeanMetric(); private final CounterMetric currentMetric = new CounterMetric(); @Inject public ShardGetService(ShardId shardId, @IndexSettings Settings indexSettings, ScriptService scriptService, MapperService mapperService, IndexFieldDataService fieldDataService) { super(shardId, indexSettings); this.scriptService = scriptService; this.mapperService = mapperService; this.fieldDataService = fieldDataService; } public GetStats stats() { return new GetStats(existsMetric.count(), TimeUnit.NANOSECONDS.toMillis(existsMetric.sum()), missingMetric.count(), TimeUnit.NANOSECONDS.toMillis(missingMetric.sum()), currentMetric.count()); } // sadly, to overcome cyclic dep, we need to do this and inject it ourselves... public ShardGetService setIndexShard(IndexShard indexShard) { this.indexShard = indexShard; return this; } public GetResult get(String type, String id, String[] gFields, boolean realtime, long version, VersionType versionType, FetchSourceContext fetchSourceContext) throws ElasticsearchException { currentMetric.inc(); try { long now = System.nanoTime(); GetResult getResult = innerGet(type, id, gFields, realtime, version, versionType, fetchSourceContext); if (getResult.isExists()) { existsMetric.inc(System.nanoTime() - now); } else { missingMetric.inc(System.nanoTime() - now); } return getResult; } finally { currentMetric.dec(); } } /** * Returns {@link GetResult} based on the specified {@link Engine.GetResult} argument. * This method basically loads specified fields for the associated document in the engineGetResult. * This method load the fields from the Lucene index and not from transaction log and therefore isn't realtime. * <p/> * Note: Call <b>must</b> release engine searcher associated with engineGetResult! */ public GetResult get(Engine.GetResult engineGetResult, String id, String type, String[] fields, FetchSourceContext fetchSourceContext) { if (!engineGetResult.exists()) { return new GetResult(shardId.index().name(), type, id, -1, false, null, null); } currentMetric.inc(); try { long now = System.nanoTime(); DocumentMapper docMapper = mapperService.documentMapper(type); if (docMapper == null) { missingMetric.inc(System.nanoTime() - now); return new GetResult(shardId.index().name(), type, id, -1, false, null, null); } fetchSourceContext = normalizeFetchSourceContent(fetchSourceContext, fields); GetResult getResult = innerGetLoadFromStoredFields(type, id, fields, fetchSourceContext, engineGetResult, docMapper); if (getResult.isExists()) { existsMetric.inc(System.nanoTime() - now); } else { missingMetric.inc(System.nanoTime() - now); // This shouldn't happen... } return getResult; } finally { currentMetric.dec(); } } /** * decides what needs to be done based on the request input and always returns a valid non-null FetchSourceContext */ protected FetchSourceContext normalizeFetchSourceContent(@Nullable FetchSourceContext context, @Nullable String[] gFields) { if (context != null) { return context; } if (gFields == null) { return FetchSourceContext.FETCH_SOURCE; } for (String field : gFields) { if (SourceFieldMapper.NAME.equals(field)) { return FetchSourceContext.FETCH_SOURCE; } } return FetchSourceContext.DO_NOT_FETCH_SOURCE; } public GetResult innerGet(String type, String id, String[] gFields, boolean realtime, long version, VersionType versionType, FetchSourceContext fetchSourceContext) throws ElasticsearchException { fetchSourceContext = normalizeFetchSourceContent(fetchSourceContext, gFields); boolean loadSource = (gFields != null && gFields.length > 0) || fetchSourceContext.fetchSource(); Engine.GetResult get = null; if (type == null || type.equals("_all")) { for (String typeX : mapperService.types()) { get = indexShard.get(new Engine.Get(realtime, new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(typeX, id))) .loadSource(loadSource).version(version).versionType(versionType)); if (get.exists()) { type = typeX; break; } else { get.release(); } } if (get == null) { return new GetResult(shardId.index().name(), type, id, -1, false, null, null); } if (!get.exists()) { // no need to release here as well..., we release in the for loop for non exists return new GetResult(shardId.index().name(), type, id, -1, false, null, null); } } else { get = indexShard.get(new Engine.Get(realtime, new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(type, id))) .loadSource(loadSource).version(version).versionType(versionType)); if (!get.exists()) { get.release(); return new GetResult(shardId.index().name(), type, id, -1, false, null, null); } } DocumentMapper docMapper = mapperService.documentMapper(type); if (docMapper == null) { get.release(); return new GetResult(shardId.index().name(), type, id, -1, false, null, null); } try { // break between having loaded it from translog (so we only have _source), and having a document to load if (get.docIdAndVersion() != null) { return innerGetLoadFromStoredFields(type, id, gFields, fetchSourceContext, get, docMapper); } else { Translog.Source source = get.source(); Map<String, GetField> fields = null; SearchLookup searchLookup = null; // we can only load scripts that can run against the source if (gFields != null && gFields.length > 0) { Map<String, Object> sourceAsMap = null; for (String field : gFields) { if (SourceFieldMapper.NAME.equals(field)) { // dealt with when normalizing fetchSourceContext. continue; } Object value = null; if (field.equals(RoutingFieldMapper.NAME) && docMapper.routingFieldMapper().fieldType().stored()) { value = source.routing; } else if (field.equals(ParentFieldMapper.NAME) && docMapper.parentFieldMapper().active() && docMapper.parentFieldMapper().fieldType().stored()) { value = source.parent; } else if (field.equals(TimestampFieldMapper.NAME) && docMapper.timestampFieldMapper().fieldType().stored()) { value = source.timestamp; } else if (field.equals(TTLFieldMapper.NAME) && docMapper.TTLFieldMapper().fieldType().stored()) { // Call value for search with timestamp + ttl here to display the live remaining ttl value and be consistent with the search result display if (source.ttl > 0) { value = docMapper.TTLFieldMapper().valueForSearch(source.timestamp + source.ttl); } } else if (field.equals(SizeFieldMapper.NAME) && docMapper.rootMapper(SizeFieldMapper.class).fieldType().stored()) { value = source.source.length(); } else { if (searchLookup == null) { searchLookup = new SearchLookup(mapperService, fieldDataService, new String[]{type}); searchLookup.source().setNextSource(source.source); } FieldMapper<?> x = docMapper.mappers().smartNameFieldMapper(field); if (x == null) { if (docMapper.objectMappers().get(field) != null) { // Only fail if we know it is a object field, missing paths / fields shouldn't fail. throw new ElasticsearchIllegalArgumentException("field [" + field + "] isn't a leaf field"); } } else if (docMapper.sourceMapper().enabled() || x.fieldType().stored()) { List<Object> values = searchLookup.source().extractRawValues(field); if (!values.isEmpty()) { for (int i = 0; i < values.size(); i++) { values.set(i, x.valueForSearch(values.get(i))); } value = values; } } } if (value != null) { if (fields == null) { fields = newHashMapWithExpectedSize(2); } if (value instanceof List) { fields.put(field, new GetField(field, (List) value)); } else { fields.put(field, new GetField(field, ImmutableList.of(value))); } } } } // deal with source, but only if it's enabled (we always have it from the translog) BytesReference sourceToBeReturned = null; SourceFieldMapper sourceFieldMapper = docMapper.sourceMapper(); if (fetchSourceContext.fetchSource() && sourceFieldMapper.enabled()) { sourceToBeReturned = source.source; // Cater for source excludes/includes at the cost of performance // We must first apply the field mapper filtering to make sure we get correct results // in the case that the fetchSourceContext white lists something that's not included by the field mapper Map<String, Object> filteredSource = null; XContentType sourceContentType = null; if (sourceFieldMapper.includes().length > 0 || sourceFieldMapper.excludes().length > 0) { // TODO: The source might parsed and available in the sourceLookup but that one uses unordered maps so different. Do we care? Tuple<XContentType, Map<String, Object>> typeMapTuple = XContentHelper.convertToMap(source.source, true); sourceContentType = typeMapTuple.v1(); filteredSource = XContentMapValues.filter(typeMapTuple.v2(), sourceFieldMapper.includes(), sourceFieldMapper.excludes()); } if (fetchSourceContext.includes().length > 0 || fetchSourceContext.excludes().length > 0) { if (filteredSource == null) { Tuple<XContentType, Map<String, Object>> typeMapTuple = XContentHelper.convertToMap(source.source, true); sourceContentType = typeMapTuple.v1(); filteredSource = typeMapTuple.v2(); } filteredSource = XContentMapValues.filter(filteredSource, fetchSourceContext.includes(), fetchSourceContext.excludes()); } if (filteredSource != null) { try { sourceToBeReturned = XContentFactory.contentBuilder(sourceContentType).map(filteredSource).bytes(); } catch (IOException e) { throw new ElasticsearchException("Failed to get type [" + type + "] and id [" + id + "] with includes/excludes set", e); } } } return new GetResult(shardId.index().name(), type, id, get.version(), get.exists(), sourceToBeReturned, fields); } } finally { get.release(); } } private GetResult innerGetLoadFromStoredFields(String type, String id, String[] gFields, FetchSourceContext fetchSourceContext, Engine.GetResult get, DocumentMapper docMapper) { Map<String, GetField> fields = null; BytesReference source = null; Versions.DocIdAndVersion docIdAndVersion = get.docIdAndVersion(); FieldsVisitor fieldVisitor = buildFieldsVisitors(gFields, fetchSourceContext); if (fieldVisitor != null) { try { docIdAndVersion.context.reader().document(docIdAndVersion.docId, fieldVisitor); } catch (IOException e) { throw new ElasticsearchException("Failed to get type [" + type + "] and id [" + id + "]", e); } source = fieldVisitor.source(); if (!fieldVisitor.fields().isEmpty()) { fieldVisitor.postProcess(docMapper); fields = new HashMap<String, GetField>(fieldVisitor.fields().size()); for (Map.Entry<String, List<Object>> entry : fieldVisitor.fields().entrySet()) { fields.put(entry.getKey(), new GetField(entry.getKey(), entry.getValue())); } } } // now, go and do the script thingy if needed if (gFields != null && gFields.length > 0) { SearchLookup searchLookup = null; for (String field : gFields) { Object value = null; FieldMappers x = docMapper.mappers().smartName(field); if (x == null) { if (docMapper.objectMappers().get(field) != null) { // Only fail if we know it is a object field, missing paths / fields shouldn't fail. throw new ElasticsearchIllegalArgumentException("field [" + field + "] isn't a leaf field"); } } else if (!x.mapper().fieldType().stored()) { if (searchLookup == null) { searchLookup = new SearchLookup(mapperService, fieldDataService, new String[]{type}); searchLookup.setNextReader(docIdAndVersion.context); searchLookup.source().setNextSource(source); searchLookup.setNextDocId(docIdAndVersion.docId); } List<Object> values = searchLookup.source().extractRawValues(field); if (!values.isEmpty()) { for (int i = 0; i < values.size(); i++) { values.set(i, x.mapper().valueForSearch(values.get(i))); } value = values; } } if (value != null) { if (fields == null) { fields = newHashMapWithExpectedSize(2); } if (value instanceof List) { fields.put(field, new GetField(field, (List) value)); } else { fields.put(field, new GetField(field, ImmutableList.of(value))); } } } } if (!fetchSourceContext.fetchSource()) { source = null; } else if (fetchSourceContext.includes().length > 0 || fetchSourceContext.excludes().length > 0) { Map<String, Object> filteredSource; XContentType sourceContentType = null; // TODO: The source might parsed and available in the sourceLookup but that one uses unordered maps so different. Do we care? Tuple<XContentType, Map<String, Object>> typeMapTuple = XContentHelper.convertToMap(source, true); sourceContentType = typeMapTuple.v1(); filteredSource = XContentMapValues.filter(typeMapTuple.v2(), fetchSourceContext.includes(), fetchSourceContext.excludes()); try { source = XContentFactory.contentBuilder(sourceContentType).map(filteredSource).bytes(); } catch (IOException e) { throw new ElasticsearchException("Failed to get type [" + type + "] and id [" + id + "] with includes/excludes set", e); } } return new GetResult(shardId.index().name(), type, id, get.version(), get.exists(), source, fields); } private static FieldsVisitor buildFieldsVisitors(String[] fields, FetchSourceContext fetchSourceContext) { if (fields == null || fields.length == 0) { return fetchSourceContext.fetchSource() ? new JustSourceFieldsVisitor() : null; } return new CustomFieldsVisitor(Sets.newHashSet(fields), fetchSourceContext.fetchSource()); } }
1no label
src_main_java_org_elasticsearch_index_get_ShardGetService.java
331
public class UserModifiableConfiguration implements TitanConfiguration { private final ModifiableConfiguration config; private final ConfigVerifier verifier; public UserModifiableConfiguration(ModifiableConfiguration config) { this(config,ALLOW_ALL); } public UserModifiableConfiguration(ModifiableConfiguration config, ConfigVerifier verifier) { Preconditions.checkArgument(config!=null && verifier!=null); this.config = config; this.verifier = verifier; } /** * Returns the backing configuration as a {@link ReadConfiguration} that can be used * to create and configure a Titan graph. * * @return */ public ReadConfiguration getConfiguration() { return config.getConfiguration(); } @Override public String get(String path) { ConfigElement.PathIdentifier pp = ConfigElement.parse(config.getRootNamespace(),path); if (pp.element.isNamespace()) { ConfigNamespace ns = (ConfigNamespace)pp.element; StringBuilder s = new StringBuilder(); if (ns.isUmbrella() && !pp.lastIsUmbrella) { for (String sub : config.getContainedNamespaces(ns,pp.umbrellaElements)) { s.append("+ ").append(sub).append("\n"); } } /* else { for (ConfigElement element : ns.getChildren()) { s.append(ConfigElement.toStringSingle(element)).append("\n"); } } */ return s.toString(); } else { Object value; if (config.has((ConfigOption)pp.element,pp.umbrellaElements) || ((ConfigOption) pp.element).getDefaultValue()!=null) { value = config.get((ConfigOption)pp.element,pp.umbrellaElements); } else { return "null"; } Preconditions.checkNotNull(value); if (value.getClass().isArray()) { StringBuilder s = new StringBuilder(); s.append("["); for (int i=0;i<Array.getLength(value);i++) { if (i>0) s.append(","); s.append(Array.get(value,i)); } s.append("]"); return s.toString(); } else return String.valueOf(value); } } @Override public UserModifiableConfiguration set(String path, Object value) { ConfigElement.PathIdentifier pp = ConfigElement.parse(config.getRootNamespace(),path); Preconditions.checkArgument(pp.element.isOption(),"Need to provide configuration option - not namespace: %s",path); ConfigOption option = (ConfigOption)pp.element; verifier.verifyModification(option); if (option.getDatatype().isArray()) { Class arrayType = option.getDatatype().getComponentType(); Object arr; if (value.getClass().isArray()) { int size = Array.getLength(value); arr = Array.newInstance(arrayType,size); for (int i=0;i<size;i++) { Array.set(arr,i,convertBasic(Array.get(value,i),arrayType)); } } else { arr = Array.newInstance(arrayType,1); Array.set(arr,0,convertBasic(value,arrayType)); } value = arr; } else { value = convertBasic(value,option.getDatatype()); } config.set(option,value,pp.umbrellaElements); return this; } /** * Closes this configuration handler */ public void close() { config.close(); } private static final Object convertBasic(Object value, Class datatype) { if (Number.class.isAssignableFrom(datatype)) { Preconditions.checkArgument(value instanceof Number,"Expected a number but got: %s",value); Number n = (Number)value; if (datatype==Long.class) { return n.longValue(); } else if (datatype==Integer.class) { return n.intValue(); } else if (datatype==Short.class) { return n.shortValue(); } else if (datatype==Byte.class) { return n.byteValue(); } else if (datatype==Float.class) { return n.floatValue(); } else if (datatype==Double.class) { return n.doubleValue(); } else throw new IllegalArgumentException("Unexpected number data type: " + datatype); } else if (datatype==Boolean.class) { Preconditions.checkArgument(value instanceof Boolean,"Expected boolean value: %s",value); return value; } else if (datatype==String.class) { Preconditions.checkArgument(value instanceof String,"Expected string value: %s",value); return value; } else if (Duration.class.isAssignableFrom(datatype)) { Preconditions.checkArgument(value instanceof Duration,"Expected duration value: %s",value); return value; } else if (datatype.isEnum()) { // Check if value is an enum instance for (Object e : datatype.getEnumConstants()) if (e.equals(value)) return e; // Else toString() it and try to parse it as an enum value for (Object e : datatype.getEnumConstants()) if (e.toString().equals(value.toString())) return e; throw new IllegalArgumentException("No match for " + value + " in enum " + datatype); } else throw new IllegalArgumentException("Unexpected data type: " + datatype ); } public interface ConfigVerifier { /** * Throws an exception if the given configuration option is not allowed to be changed. * Otherwise just returns. * @param option */ public void verifyModification(ConfigOption option); } public static final ConfigVerifier ALLOW_ALL = new ConfigVerifier() { @Override public void verifyModification(ConfigOption option) { //Do nothing; } }; }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_UserModifiableConfiguration.java
365
private static class HBaseGetter implements StaticArrayEntry.GetColVal<Map.Entry<byte[], NavigableMap<Long, byte[]>>, byte[]> { private final EntryMetaData[] schema; private HBaseGetter(EntryMetaData[] schema) { this.schema = schema; } @Override public byte[] getColumn(Map.Entry<byte[], NavigableMap<Long, byte[]>> element) { return element.getKey(); } @Override public byte[] getValue(Map.Entry<byte[], NavigableMap<Long, byte[]>> element) { return element.getValue().lastEntry().getValue(); } @Override public EntryMetaData[] getMetaSchema(Map.Entry<byte[], NavigableMap<Long, byte[]>> element) { return schema; } @Override public Object getMetaData(Map.Entry<byte[], NavigableMap<Long, byte[]>> element, EntryMetaData meta) { switch(meta) { case TIMESTAMP: return element.getValue().lastEntry().getKey(); default: throw new UnsupportedOperationException("Unsupported meta data: " + meta); } } }
0true
titan-hbase-parent_titan-hbase-core_src_main_java_com_thinkaurelius_titan_diskstorage_hbase_HBaseKeyColumnValueStore.java
850
return new IAnswer<OrderItem>() { @Override public OrderItem answer() throws Throwable { OrderItem orderItem = (OrderItem) EasyMock.getCurrentArguments()[0]; if (orderItem.getId() == null) { orderItem.setId(getOrderItemId()); } return orderItem; } };
0true
core_broadleaf-framework_src_test_java_org_broadleafcommerce_core_offer_service_OfferDataItemProvider.java
1,392
OGlobalConfiguration.MVRBTREE_OPTIMIZE_THRESHOLD.getValueAsInteger()) { /** * Set the optimization rather than remove eldest element. */ @Override protected boolean removeEldestEntry(final Map.Entry<ORID, OMVRBTreeEntryPersistent<K, V>> eldest) { if (super.removeEldestEntry(eldest)) // TOO MANY ITEMS: SET THE OPTIMIZATION setOptimization(2); return false; } };
0true
core_src_main_java_com_orientechnologies_orient_core_type_tree_OMVRBTreePersistent.java
188
public interface OService { public String getName(); public void startup(); public void shutdown(); }
0true
commons_src_main_java_com_orientechnologies_common_util_OService.java
166
public interface RetryableRequest { }
0true
hazelcast_src_main_java_com_hazelcast_client_RetryableRequest.java
850
private class TransportHandler extends BaseTransportRequestHandler<SearchRequest> { @Override public SearchRequest newInstance() { return new SearchRequest(); } @Override public void messageReceived(SearchRequest request, final TransportChannel channel) throws Exception { // no need for a threaded listener request.listenerThreaded(false); // we don't spawn, so if we get a request with no threading, change it to single threaded if (request.operationThreading() == SearchOperationThreading.NO_THREADS) { request.operationThreading(SearchOperationThreading.SINGLE_THREAD); } 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); } } }); } @Override public String executor() { return ThreadPool.Names.SAME; } }
0true
src_main_java_org_elasticsearch_action_search_TransportSearchAction.java
849
public class TransportSearchAction extends TransportAction<SearchRequest, SearchResponse> { private final ClusterService clusterService; private final TransportSearchDfsQueryThenFetchAction dfsQueryThenFetchAction; private final TransportSearchQueryThenFetchAction queryThenFetchAction; private final TransportSearchDfsQueryAndFetchAction dfsQueryAndFetchAction; private final TransportSearchQueryAndFetchAction queryAndFetchAction; private final TransportSearchScanAction scanAction; private final TransportSearchCountAction countAction; private final boolean optimizeSingleShard; @Inject public TransportSearchAction(Settings settings, ThreadPool threadPool, TransportService transportService, ClusterService clusterService, TransportSearchDfsQueryThenFetchAction dfsQueryThenFetchAction, TransportSearchQueryThenFetchAction queryThenFetchAction, TransportSearchDfsQueryAndFetchAction dfsQueryAndFetchAction, TransportSearchQueryAndFetchAction queryAndFetchAction, TransportSearchScanAction scanAction, TransportSearchCountAction countAction) { super(settings, threadPool); this.clusterService = clusterService; this.dfsQueryThenFetchAction = dfsQueryThenFetchAction; this.queryThenFetchAction = queryThenFetchAction; this.dfsQueryAndFetchAction = dfsQueryAndFetchAction; this.queryAndFetchAction = queryAndFetchAction; this.scanAction = scanAction; this.countAction = countAction; this.optimizeSingleShard = componentSettings.getAsBoolean("optimize_single_shard", true); transportService.registerHandler(SearchAction.NAME, new TransportHandler()); } @Override protected void doExecute(SearchRequest searchRequest, ActionListener<SearchResponse> listener) { // optimize search type for cases where there is only one shard group to search on if (optimizeSingleShard && searchRequest.searchType() != SCAN && searchRequest.searchType() != COUNT) { try { ClusterState clusterState = clusterService.state(); String[] concreteIndices = clusterState.metaData().concreteIndices(searchRequest.indices(), searchRequest.indicesOptions()); Map<String, Set<String>> routingMap = clusterState.metaData().resolveSearchRouting(searchRequest.routing(), searchRequest.indices()); int shardCount = clusterService.operationRouting().searchShardsCount(clusterState, searchRequest.indices(), concreteIndices, routingMap, searchRequest.preference()); if (shardCount == 1) { // if we only have one group, then we always want Q_A_F, no need for DFS, and no need to do THEN since we hit one shard searchRequest.searchType(QUERY_AND_FETCH); } } catch (IndexMissingException e) { // ignore this, we will notify the search response if its really the case // from the actual action } catch (Exception e) { logger.debug("failed to optimize search type, continue as normal", e); } } if (searchRequest.searchType() == DFS_QUERY_THEN_FETCH) { dfsQueryThenFetchAction.execute(searchRequest, listener); } else if (searchRequest.searchType() == SearchType.QUERY_THEN_FETCH) { queryThenFetchAction.execute(searchRequest, listener); } else if (searchRequest.searchType() == SearchType.DFS_QUERY_AND_FETCH) { dfsQueryAndFetchAction.execute(searchRequest, listener); } else if (searchRequest.searchType() == SearchType.QUERY_AND_FETCH) { queryAndFetchAction.execute(searchRequest, listener); } else if (searchRequest.searchType() == SearchType.SCAN) { scanAction.execute(searchRequest, listener); } else if (searchRequest.searchType() == SearchType.COUNT) { countAction.execute(searchRequest, listener); } } private class TransportHandler extends BaseTransportRequestHandler<SearchRequest> { @Override public SearchRequest newInstance() { return new SearchRequest(); } @Override public void messageReceived(SearchRequest request, final TransportChannel channel) throws Exception { // no need for a threaded listener request.listenerThreaded(false); // we don't spawn, so if we get a request with no threading, change it to single threaded if (request.operationThreading() == SearchOperationThreading.NO_THREADS) { request.operationThreading(SearchOperationThreading.SINGLE_THREAD); } 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); } } }); } @Override public String executor() { return ThreadPool.Names.SAME; } } }
1no label
src_main_java_org_elasticsearch_action_search_TransportSearchAction.java
91
public class OScannerCommandStream implements OCommandStream { private Scanner scanner; public OScannerCommandStream(String commands) { scanner = new Scanner(commands); init(); } public OScannerCommandStream(File file) throws FileNotFoundException { scanner = new Scanner(file); init(); } private void init() { scanner.useDelimiter(";(?=([^\"]*\"[^\"]*\")*[^\"]*$)(?=([^']*'[^']*')*[^']*$)|\n"); } @Override public boolean hasNext() { return scanner.hasNext(); } @Override public String nextCommand() { return scanner.next().trim(); } @Override public void close() { scanner.close(); } }
0true
commons_src_main_java_com_orientechnologies_common_console_OScannerCommandStream.java
291
new Thread(new Runnable() { public void run() { lock.lock(); try { if (lock.isLockedByCurrentThread()) { count.incrementAndGet(); } awaitLatch.countDown(); condition.await(); if (lock.isLockedByCurrentThread()) { count.incrementAndGet(); } } catch (InterruptedException ignored) { } finally { lock.unlock(); finalLatch.countDown(); } } }).start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_lock_ClientConditionTest.java
187
public class DisplayContentTag extends BodyTagSupport { private static final long serialVersionUID = 1L; public static final String BLC_RULE_MAP_PARAM = "blRuleMap"; // The following attribute is set in BroadleafProcessURLFilter public static final String REQUEST_DTO = "blRequestDTO"; private String contentType; private String contentName; private Object product; private Integer count; private String contentListVar; private String contentItemVar; private String numResultsVar; private Locale locale; private StructuredContentService structuredContentService; private StaticAssetService staticAssetService; public DisplayContentTag() { initVariables(); } /** * MVEL is used to process the content targeting rules. * * * @param request * @return */ private Map<String,Object> buildMvelParameters(HttpServletRequest request) { TimeDTO timeDto = new TimeDTO(SystemTime.asCalendar()); RequestDTO requestDto = (RequestDTO) request.getAttribute(REQUEST_DTO); Map<String, Object> mvelParameters = new HashMap<String, Object>(); mvelParameters.put("time", timeDto); mvelParameters.put("request", requestDto); Map<String,Object> blcRuleMap = (Map<String,Object>) request.getAttribute(BLC_RULE_MAP_PARAM); if (blcRuleMap != null) { for (String mapKey : blcRuleMap.keySet()) { mvelParameters.put(mapKey, blcRuleMap.get(mapKey)); } } if (product != null) { mvelParameters.put("product", product); } return mvelParameters; } protected void initServices() { if (structuredContentService == null || staticAssetService == null) { WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext()); structuredContentService = (StructuredContentService) applicationContext.getBean("blStructuredContentService"); staticAssetService = (StaticAssetService) applicationContext.getBean("blStaticAssetService"); } } public boolean isSecure(HttpServletRequest request) { boolean secure = false; if (request != null) { secure = ("HTTPS".equalsIgnoreCase(request.getScheme()) || request.isSecure()); } return secure; } public int doStartTag() throws JspException { HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); Map<String, Object> mvelParameters = buildMvelParameters(request); SandBox currentSandbox = (SandBox) request.getAttribute(BroadleafProcessURLFilter.SANDBOX_VAR); initServices(); List<StructuredContentDTO> contentItems; StructuredContentType structuredContentType = structuredContentService.findStructuredContentTypeByName(contentType); assert(contentName != null && !"".equals(contentName) && structuredContentType != null); if (locale == null) { locale = (Locale) request.getAttribute(BroadleafProcessURLFilter.LOCALE_VAR); } int cnt = (count == null) ? Integer.MAX_VALUE : count; if (structuredContentType == null) { contentItems = structuredContentService.lookupStructuredContentItemsByName(currentSandbox, contentName, locale, cnt, mvelParameters, isSecure(request)); } else { if (contentName == null || "".equals(contentName)) { contentItems = structuredContentService.lookupStructuredContentItemsByType(currentSandbox, structuredContentType, locale, cnt, mvelParameters, isSecure(request)); } else { contentItems = structuredContentService.lookupStructuredContentItemsByName(currentSandbox, structuredContentType, contentName, locale, cnt, mvelParameters, isSecure(request)); } } pageContext.setAttribute(getNumResultsVar(), contentItems.size()); if (contentItems.size() > 0) { List<Map<String,String>> contentItemFields = new ArrayList<Map<String, String>>(); for(StructuredContentDTO item : contentItems) { contentItemFields.add(item.getValues()); } pageContext.setAttribute(contentItemVar, contentItemFields.get(0)); pageContext.setAttribute(contentListVar, contentItemFields); pageContext.setAttribute("structuredContentList", contentItems); pageContext.setAttribute(numResultsVar, contentItems.size()); } else { pageContext.setAttribute(contentItemVar, null); pageContext.setAttribute(contentListVar, null); pageContext.setAttribute("structuredContentList", null); pageContext.setAttribute(numResultsVar, 0); } return EVAL_BODY_INCLUDE; } @Override public int doEndTag() throws JspException { int returnVal = super.doEndTag(); initVariables(); return returnVal; } private void initVariables() { contentType=null; contentName=null; product=null; count=null; locale=null; contentListVar = "contentList"; contentItemVar = "contentItem"; numResultsVar = "numResults"; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public String getContentName() { return contentName; } public void setContentName(String contentName) { this.contentName = contentName; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public String getContentListVar() { return contentListVar; } public void setContentListVar(String contentVar) { this.contentListVar = contentVar; } public String getContentItemVar() { return contentItemVar; } public void setContentItemVar(String contentItemVar) { this.contentItemVar = contentItemVar; } public String getNumResultsVar() { return numResultsVar; } public void setNumResultsVar(String numResultsVar) { this.numResultsVar = numResultsVar; } public Locale getLocale() { return locale; } public void setLocale(Locale locale) { this.locale = locale; } public Object getProduct() { return product; } public void setProduct(Object product) { this.product = product; } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_web_structure_DisplayContentTag.java
234
assertTrueEventually(new AssertTask() { public void run() throws Exception { assertEquals(CLUSTER_SIZE, map.size()); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceExecuteTest.java
1,411
clusterService.submitStateUpdateTask("close-indices " + indicesAsString, Priority.URGENT, new AckedClusterStateUpdateTask() { @Override public boolean mustAck(DiscoveryNode discoveryNode) { return true; } @Override public void onAllNodesAcked(@Nullable Throwable t) { listener.onResponse(new ClusterStateUpdateResponse(true)); } @Override public void onAckTimeout() { listener.onResponse(new ClusterStateUpdateResponse(false)); } @Override public TimeValue ackTimeout() { return request.ackTimeout(); } @Override public TimeValue timeout() { return request.masterNodeTimeout(); } @Override public void onFailure(String source, Throwable t) { listener.onFailure(t); } @Override public ClusterState execute(ClusterState currentState) { List<String> indicesToClose = new ArrayList<String>(); for (String index : request.indices()) { IndexMetaData indexMetaData = currentState.metaData().index(index); if (indexMetaData == null) { throw new IndexMissingException(new Index(index)); } if (indexMetaData.state() != IndexMetaData.State.CLOSE) { IndexRoutingTable indexRoutingTable = currentState.routingTable().index(index); for (IndexShardRoutingTable shard : indexRoutingTable) { if (!shard.primaryAllocatedPostApi()) { throw new IndexPrimaryShardNotAllocatedException(new Index(index)); } } indicesToClose.add(index); } } if (indicesToClose.isEmpty()) { return currentState; } logger.info("closing indices [{}]", indicesAsString); MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData()); ClusterBlocks.Builder blocksBuilder = ClusterBlocks.builder() .blocks(currentState.blocks()); for (String index : indicesToClose) { mdBuilder.put(IndexMetaData.builder(currentState.metaData().index(index)).state(IndexMetaData.State.CLOSE)); blocksBuilder.addIndexBlock(index, INDEX_CLOSED_BLOCK); } ClusterState updatedState = ClusterState.builder(currentState).metaData(mdBuilder).blocks(blocksBuilder).build(); RoutingTable.Builder rtBuilder = RoutingTable.builder(currentState.routingTable()); for (String index : indicesToClose) { rtBuilder.remove(index); } RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder(updatedState).routingTable(rtBuilder).build()); //no explicit wait for other nodes needed as we use AckedClusterStateUpdateTask return ClusterState.builder(updatedState).routingResult(routingResult).build(); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { } });
0true
src_main_java_org_elasticsearch_cluster_metadata_MetaDataIndexStateService.java
455
public class OSBTreeCollectionManager { private final Map<OBonsaiBucketPointer, OSBTreeBonsai<OIdentifiable, Boolean>> treeCache = new HashMap<OBonsaiBucketPointer, OSBTreeBonsai<OIdentifiable, Boolean>>(); public static final String FILE_ID = "ridset"; public OSBTreeBonsai<OIdentifiable, Boolean> createSBTree() { OSBTreeBonsai<OIdentifiable, Boolean> tree = new OSBTreeBonsai<OIdentifiable, Boolean>(".sbt", 1, true); tree.create(FILE_ID, OLinkSerializer.INSTANCE, OBooleanSerializer.INSTANCE, (OStorageLocalAbstract) ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getUnderlying()); treeCache.put(tree.getRootBucketPointer(), tree); return tree; } public OSBTreeBonsai<OIdentifiable, Boolean> loadSBTree(long fileId, OBonsaiBucketPointer rootIndex) { OSBTreeBonsai<OIdentifiable, Boolean> tree = treeCache.get(rootIndex); if (tree != null) return tree; tree = new OSBTreeBonsai<OIdentifiable, Boolean>(".sbt", 1, true); tree.load(fileId, rootIndex, (OStorageLocalAbstract) ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getUnderlying()); treeCache.put(tree.getRootBucketPointer(), tree); return tree; } public void startup() { } public void shutdown() { treeCache.clear(); } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_record_ridset_sbtree_OSBTreeCollectionManager.java
930
public interface OrderOfferProcessor extends BaseProcessor { public void filterOrderLevelOffer(PromotableOrder promotableOrder, List<PromotableCandidateOrderOffer> qualifiedOrderOffers, Offer offer); public Boolean executeExpression(String expression, Map<String, Object> vars); /** * Executes the appliesToOrderRules in the Offer to determine if this offer * can be applied to the Order, OrderItem, or FulfillmentGroup. * * @param offer * @param order * @return true if offer can be applied, otherwise false */ public boolean couldOfferApplyToOrder(Offer offer, PromotableOrder promotableOrder); public List<PromotableCandidateOrderOffer> removeTrailingNotCombinableOrderOffers(List<PromotableCandidateOrderOffer> candidateOffers); /** * Takes a list of sorted CandidateOrderOffers and determines if each offer can be * applied based on the restrictions (stackable and/or combinable) on that offer. OrderAdjustments * are create on the Order for each applied CandidateOrderOffer. An offer with stackable equals false * cannot be applied to an Order that already contains an OrderAdjustment. An offer with combinable * equals false cannot be applied to the Order if the Order already contains an OrderAdjustment. * * @param orderOffers a sorted list of CandidateOrderOffer * @param order the Order to apply the CandidateOrderOffers */ public void applyAllOrderOffers(List<PromotableCandidateOrderOffer> orderOffers, PromotableOrder promotableOrder); public PromotableItemFactory getPromotableItemFactory(); public void setPromotableItemFactory(PromotableItemFactory promotableItemFactory); /** * Takes the adjustments and PriceDetails from the passed in PromotableOrder and transfers them to the * actual order first checking to see if they already exist. * * @param promotableOrder */ public void synchronizeAdjustmentsAndPrices(PromotableOrder promotableOrder); /** * Set the offerDao (primarily for unit testing) */ public void setOfferDao(OfferDao offerDao); /** * Set the orderItemDao (primarily for unit testing) */ public void setOrderItemDao(OrderItemDao orderItemDao); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_processor_OrderOfferProcessor.java
882
public final class AwaitRequest extends KeyBasedClientRequest implements Portable, SecureRequest { private String name; private long timeout; public AwaitRequest() { } public AwaitRequest(String name, long timeout) { this.name = name; this.timeout = timeout; } @Override protected Object getKey() { return name; } @Override protected Operation prepareOperation() { return new AwaitOperation(name, timeout); } @Override public String getServiceName() { return CountDownLatchService.SERVICE_NAME; } @Override public int getFactoryId() { return CountDownLatchPortableHook.F_ID; } @Override public int getClassId() { return CountDownLatchPortableHook.AWAIT; } @Override public void write(PortableWriter writer) throws IOException { writer.writeUTF("name", name); writer.writeLong("timeout", timeout); } @Override public void read(PortableReader reader) throws IOException { name = reader.readUTF("name"); timeout = reader.readLong("timeout"); } @Override public Permission getRequiredPermission() { return new CountDownLatchPermission(name, ActionConstants.ACTION_READ); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_countdownlatch_client_AwaitRequest.java
7
private static class HBasePidfileParseException extends Exception { private static final long serialVersionUID = 1L; public HBasePidfileParseException(String message) { super(message); } }
0true
titan-hbase-parent_titan-hbase-core_src_test_java_com_thinkaurelius_titan_HBaseStatus.java
1,144
static class SearchThread implements Runnable { private final Client client; private final int numValues; private volatile boolean run = true; SearchThread(Client client) { this.client = client; this.numValues = NUM_CHILDREN_PER_PARENT / NUM_CHILDREN_PER_PARENT; } @Override public void run() { while (run) { try { long totalQueryTime = 0; for (int j = 0; j < QUERY_COUNT; j++) { SearchResponse searchResponse = client.prepareSearch(indexName) .setQuery( filteredQuery( matchAllQuery(), hasChildFilter("child", termQuery("field2", "value" + random.nextInt(numValues))) ) ) .execute().actionGet(); if (searchResponse.getFailedShards() > 0) { System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures())); } totalQueryTime += searchResponse.getTookInMillis(); } System.out.println("--> has_child filter with term filter Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms"); totalQueryTime = 0; for (int j = 1; j <= QUERY_COUNT; j++) { SearchResponse searchResponse = client.prepareSearch(indexName) .setQuery( filteredQuery( matchAllQuery(), hasChildFilter("child", matchAllQuery()) ) ) .execute().actionGet(); if (searchResponse.getFailedShards() > 0) { System.err.println("Search Failures " + Arrays.toString(searchResponse.getShardFailures())); } totalQueryTime += searchResponse.getTookInMillis(); } System.out.println("--> has_child filter with match_all child query, Query Avg: " + (totalQueryTime / QUERY_COUNT) + "ms"); NodesStatsResponse statsResponse = client.admin().cluster().prepareNodesStats() .setJvm(true).execute().actionGet(); System.out.println("--> Committed heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapCommitted()); System.out.println("--> Used heap size: " + statsResponse.getNodes()[0].getJvm().getMem().getHeapUsed()); Thread.sleep(1000); } catch (Throwable e) { e.printStackTrace(); } } } public void stop() { run = false; } }
0true
src_test_java_org_elasticsearch_benchmark_search_child_ChildSearchAndIndexingBenchmark.java
1,395
@RunWith(HazelcastSerialClassRunner.class) @Category(SlowTest.class) public class RegionFactoryDefaultTest extends HibernateStatisticsTestSupport { protected Properties getCacheProperties() { Properties props = new Properties(); props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName()); return props; } @Test public void testInsertGetUpdateGet() { Session session = sf.openSession(); DummyEntity e = new DummyEntity(1L, "test", 0d, null); Transaction tx = session.beginTransaction(); try { session.save(e); tx.commit(); } catch (Exception ex) { ex.printStackTrace(); tx.rollback(); fail(ex.getMessage()); } finally { session.close(); } session = sf.openSession(); try { e = (DummyEntity) session.get(DummyEntity.class, 1L); assertEquals("test", e.getName()); assertNull(e.getDate()); } catch (Exception ex) { ex.printStackTrace(); fail(ex.getMessage()); } finally { session.close(); } session = sf.openSession(); tx = session.beginTransaction(); try { e = (DummyEntity) session.get(DummyEntity.class, 1L); assertEquals("test", e.getName()); assertNull(e.getDate()); e.setName("dummy"); e.setDate(new Date()); session.update(e); tx.commit(); } catch (Exception ex) { ex.printStackTrace(); tx.rollback(); fail(ex.getMessage()); } finally { session.close(); } session = sf.openSession(); try { e = (DummyEntity) session.get(DummyEntity.class, 1L); assertEquals("dummy", e.getName()); Assert.assertNotNull(e.getDate()); } catch (Exception ex) { ex.printStackTrace(); fail(ex.getMessage()); } finally { session.close(); } // stats.logSummary(); } }
0true
hazelcast-hibernate_hazelcast-hibernate3_src_test_java_com_hazelcast_hibernate_RegionFactoryDefaultTest.java
723
sbTree.loadEntriesMajor(firstKey, firstTime, new OTreeInternal.RangeResultListener<K, V>() { @Override public boolean addResult(final Map.Entry<K, V> entry) { final V value = entry.getValue(); final V resultValue; if (value instanceof OIndexRIDContainer) resultValue = (V) new HashSet<OIdentifiable>((Collection<? extends OIdentifiable>) value); else resultValue = value; preFetchedValues.add(new Map.Entry<K, V>() { @Override public K getKey() { return entry.getKey(); } @Override public V getValue() { return resultValue; } @Override public V setValue(V v) { throw new UnsupportedOperationException("setValue"); } }); return preFetchedValues.size() <= 8000; } });
0true
core_src_main_java_com_orientechnologies_orient_core_index_sbtree_OSBTreeMapEntryIterator.java
1,433
private static class CleanupThread extends Thread { private CleanupThread(final Runnable target, final String name) { super(target, name); } public void run() { try { super.run(); } catch (OutOfMemoryError e) { OutOfMemoryErrorDispatcher.onOutOfMemory(e); } } }
0true
hazelcast-hibernate_hazelcast-hibernate3_src_main_java_com_hazelcast_hibernate_local_CleanupService.java
328
public class MergeManagerSetupException extends Exception { private static final long serialVersionUID = 1L; public MergeManagerSetupException() { super(); } public MergeManagerSetupException(String arg0, Throwable arg1) { super(arg0, arg1); } public MergeManagerSetupException(String arg0) { super(arg0); } public MergeManagerSetupException(Throwable arg0) { super(arg0); } }
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_exceptions_MergeManagerSetupException.java
1,691
runnable = new Runnable() { public void run() { map.putIfAbsent(null, "value", 1, TimeUnit.SECONDS); } };
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
1,501
@Component("blCartState") public class CartState { /** * Gets the current cart based on the current request * * @return the current customer's cart */ public static Order getCart() { WebRequest request = BroadleafRequestContext.getBroadleafRequestContext().getWebRequest(); return (Order) request.getAttribute(CartStateRequestProcessor.getCartRequestAttributeName(), WebRequest.SCOPE_REQUEST); } /** * Sets the current cart on the current request * * @param cart the new cart to set */ public static void setCart(Order cart) { WebRequest request = BroadleafRequestContext.getBroadleafRequestContext().getWebRequest(); request.setAttribute(CartStateRequestProcessor.getCartRequestAttributeName(), cart, WebRequest.SCOPE_REQUEST); } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_order_CartState.java
197
public static class OnePhaseCommit extends Commit { OnePhaseCommit( int identifier, long txId, long timeWritten ) { super( identifier, txId, timeWritten, "1PC" ); } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogEntry.java
1,363
@ClusterScope(scope = Scope.TEST, numNodes = 0) public class ClusterRerouteTests extends ElasticsearchIntegrationTest { private final ESLogger logger = Loggers.getLogger(ClusterRerouteTests.class); @Test public void rerouteWithCommands_disableAllocationSettings() throws Exception { Settings commonSettings = settingsBuilder() .put(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_NEW_ALLOCATION, true) .put(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_ALLOCATION, true) .build(); rerouteWithCommands(commonSettings); } @Test public void rerouteWithCommands_enableAllocationSettings() throws Exception { Settings commonSettings = settingsBuilder() .put(EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE, EnableAllocationDecider.Allocation.NONE.name()) .put("gateway.type", "local") .build(); rerouteWithCommands(commonSettings); } private void rerouteWithCommands(Settings commonSettings) throws Exception { String node_1 = cluster().startNode(commonSettings); String node_2 = cluster().startNode(commonSettings); logger.info("--> create an index with 1 shard, 1 replica, nothing should allocate"); client().admin().indices().prepareCreate("test") .setSettings(settingsBuilder().put("index.number_of_shards", 1)) .execute().actionGet(); ClusterState state = client().admin().cluster().prepareState().execute().actionGet().getState(); assertThat(state.routingNodes().unassigned().size(), equalTo(2)); logger.info("--> explicitly allocate shard 1, *under dry_run*"); state = client().admin().cluster().prepareReroute() .add(new AllocateAllocationCommand(new ShardId("test", 0), node_1, true)) .setDryRun(true) .execute().actionGet().getState(); assertThat(state.routingNodes().unassigned().size(), equalTo(1)); assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.INITIALIZING)); logger.info("--> get the state, verify nothing changed because of the dry run"); state = client().admin().cluster().prepareState().execute().actionGet().getState(); assertThat(state.routingNodes().unassigned().size(), equalTo(2)); logger.info("--> explicitly allocate shard 1, actually allocating, no dry run"); state = client().admin().cluster().prepareReroute() .add(new AllocateAllocationCommand(new ShardId("test", 0), node_1, true)) .execute().actionGet().getState(); assertThat(state.routingNodes().unassigned().size(), equalTo(1)); assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.INITIALIZING)); ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet(); assertThat(healthResponse.isTimedOut(), equalTo(false)); logger.info("--> get the state, verify shard 1 primary allocated"); state = client().admin().cluster().prepareState().execute().actionGet().getState(); assertThat(state.routingNodes().unassigned().size(), equalTo(1)); assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.STARTED)); logger.info("--> move shard 1 primary from node1 to node2"); state = client().admin().cluster().prepareReroute() .add(new MoveAllocationCommand(new ShardId("test", 0), node_1, node_2)) .execute().actionGet().getState(); assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.RELOCATING)); assertThat(state.routingNodes().node(state.nodes().resolveNode(node_2).id()).get(0).state(), equalTo(ShardRoutingState.INITIALIZING)); healthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().setWaitForRelocatingShards(0).execute().actionGet(); assertThat(healthResponse.isTimedOut(), equalTo(false)); logger.info("--> get the state, verify shard 1 primary moved from node1 to node2"); state = client().admin().cluster().prepareState().execute().actionGet().getState(); assertThat(state.routingNodes().unassigned().size(), equalTo(1)); assertThat(state.routingNodes().node(state.nodes().resolveNode(node_2).id()).get(0).state(), equalTo(ShardRoutingState.STARTED)); } @Test public void rerouteWithAllocateLocalGateway_disableAllocationSettings() throws Exception { Settings commonSettings = settingsBuilder() .put(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_NEW_ALLOCATION, true) .put(DisableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_DISABLE_ALLOCATION, true) .put("gateway.type", "local") .build(); rerouteWithAllocateLocalGateway(commonSettings); } @Test public void rerouteWithAllocateLocalGateway_enableAllocationSettings() throws Exception { Settings commonSettings = settingsBuilder() .put(EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE, EnableAllocationDecider.Allocation.NONE.name()) .put("gateway.type", "local") .build(); rerouteWithAllocateLocalGateway(commonSettings); } private void rerouteWithAllocateLocalGateway(Settings commonSettings) throws Exception { logger.info("--> starting 2 nodes"); String node_1 = cluster().startNode(commonSettings); cluster().startNode(commonSettings); assertThat(cluster().size(), equalTo(2)); ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth().setWaitForNodes("2").execute().actionGet(); assertThat(healthResponse.isTimedOut(), equalTo(false)); logger.info("--> create an index with 1 shard, 1 replica, nothing should allocate"); client().admin().indices().prepareCreate("test") .setSettings(settingsBuilder().put("index.number_of_shards", 1)) .execute().actionGet(); ClusterState state = client().admin().cluster().prepareState().execute().actionGet().getState(); assertThat(state.routingNodes().unassigned().size(), equalTo(2)); logger.info("--> explicitly allocate shard 1, actually allocating, no dry run"); state = client().admin().cluster().prepareReroute() .add(new AllocateAllocationCommand(new ShardId("test", 0), node_1, true)) .execute().actionGet().getState(); assertThat(state.routingNodes().unassigned().size(), equalTo(1)); assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.INITIALIZING)); healthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet(); assertThat(healthResponse.isTimedOut(), equalTo(false)); logger.info("--> get the state, verify shard 1 primary allocated"); state = client().admin().cluster().prepareState().execute().actionGet().getState(); assertThat(state.routingNodes().unassigned().size(), equalTo(1)); assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.STARTED)); client().prepareIndex("test", "type", "1").setSource("field", "value").setRefresh(true).execute().actionGet(); logger.info("--> closing all nodes"); File[] shardLocation = cluster().getInstance(NodeEnvironment.class, node_1).shardLocations(new ShardId("test", 0)); assertThat(FileSystemUtils.exists(shardLocation), equalTo(true)); // make sure the data is there! cluster().closeNonSharedNodes(false); // don't wipe data directories the index needs to be there! logger.info("--> deleting the shard data [{}] ", Arrays.toString(shardLocation)); assertThat(FileSystemUtils.exists(shardLocation), equalTo(true)); // verify again after cluster was shut down assertThat(FileSystemUtils.deleteRecursively(shardLocation), equalTo(true)); logger.info("--> starting nodes back, will not allocate the shard since it has no data, but the index will be there"); node_1 = cluster().startNode(commonSettings); cluster().startNode(commonSettings); // wait a bit for the cluster to realize that the shard is not there... // TODO can we get around this? the cluster is RED, so what do we wait for? client().admin().cluster().prepareReroute().get(); assertThat(client().admin().cluster().prepareHealth().setWaitForNodes("2").execute().actionGet().getStatus(), equalTo(ClusterHealthStatus.RED)); logger.info("--> explicitly allocate primary"); state = client().admin().cluster().prepareReroute() .add(new AllocateAllocationCommand(new ShardId("test", 0), node_1, true)) .execute().actionGet().getState(); assertThat(state.routingNodes().unassigned().size(), equalTo(1)); assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.INITIALIZING)); healthResponse = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet(); assertThat(healthResponse.isTimedOut(), equalTo(false)); logger.info("--> get the state, verify shard 1 primary allocated"); state = client().admin().cluster().prepareState().execute().actionGet().getState(); assertThat(state.routingNodes().unassigned().size(), equalTo(1)); assertThat(state.routingNodes().node(state.nodes().resolveNode(node_1).id()).get(0).state(), equalTo(ShardRoutingState.STARTED)); } }
0true
src_test_java_org_elasticsearch_cluster_allocation_ClusterRerouteTests.java
2,468
public class PrioritizedExecutorsTests extends ElasticsearchTestCase { @Test public void testPriorityQueue() throws Exception { PriorityBlockingQueue<Priority> queue = new PriorityBlockingQueue<Priority>(); queue.add(Priority.LANGUID); queue.add(Priority.NORMAL); queue.add(Priority.HIGH); queue.add(Priority.LOW); queue.add(Priority.URGENT); assertThat(queue.poll(), equalTo(Priority.URGENT)); assertThat(queue.poll(), equalTo(Priority.HIGH)); assertThat(queue.poll(), equalTo(Priority.NORMAL)); assertThat(queue.poll(), equalTo(Priority.LOW)); assertThat(queue.poll(), equalTo(Priority.LANGUID)); } @Test public void testSubmitPrioritizedExecutorWithRunnables() throws Exception { ExecutorService executor = EsExecutors.newSinglePrioritizing(Executors.defaultThreadFactory()); List<Integer> results = new ArrayList<Integer>(7); CountDownLatch awaitingLatch = new CountDownLatch(1); CountDownLatch finishedLatch = new CountDownLatch(7); executor.submit(new AwaitingJob(awaitingLatch)); executor.submit(new Job(6, Priority.LANGUID, results, finishedLatch)); executor.submit(new Job(4, Priority.LOW, results, finishedLatch)); executor.submit(new Job(1, Priority.HIGH, results, finishedLatch)); executor.submit(new Job(5, Priority.LOW, results, finishedLatch)); // will execute after the first LOW (fifo) executor.submit(new Job(0, Priority.URGENT, results, finishedLatch)); executor.submit(new Job(3, Priority.NORMAL, results, finishedLatch)); executor.submit(new Job(2, Priority.HIGH, results, finishedLatch)); // will execute after the first HIGH (fifo) awaitingLatch.countDown(); finishedLatch.await(); assertThat(results.size(), equalTo(7)); assertThat(results.get(0), equalTo(0)); assertThat(results.get(1), equalTo(1)); assertThat(results.get(2), equalTo(2)); assertThat(results.get(3), equalTo(3)); assertThat(results.get(4), equalTo(4)); assertThat(results.get(5), equalTo(5)); assertThat(results.get(6), equalTo(6)); } @Test public void testExecutePrioritizedExecutorWithRunnables() throws Exception { ExecutorService executor = EsExecutors.newSinglePrioritizing(Executors.defaultThreadFactory()); List<Integer> results = new ArrayList<Integer>(7); CountDownLatch awaitingLatch = new CountDownLatch(1); CountDownLatch finishedLatch = new CountDownLatch(7); executor.execute(new AwaitingJob(awaitingLatch)); executor.execute(new Job(6, Priority.LANGUID, results, finishedLatch)); executor.execute(new Job(4, Priority.LOW, results, finishedLatch)); executor.execute(new Job(1, Priority.HIGH, results, finishedLatch)); executor.execute(new Job(5, Priority.LOW, results, finishedLatch)); // will execute after the first LOW (fifo) executor.execute(new Job(0, Priority.URGENT, results, finishedLatch)); executor.execute(new Job(3, Priority.NORMAL, results, finishedLatch)); executor.execute(new Job(2, Priority.HIGH, results, finishedLatch)); // will execute after the first HIGH (fifo) awaitingLatch.countDown(); finishedLatch.await(); assertThat(results.size(), equalTo(7)); assertThat(results.get(0), equalTo(0)); assertThat(results.get(1), equalTo(1)); assertThat(results.get(2), equalTo(2)); assertThat(results.get(3), equalTo(3)); assertThat(results.get(4), equalTo(4)); assertThat(results.get(5), equalTo(5)); assertThat(results.get(6), equalTo(6)); } @Test public void testSubmitPrioritizedExecutorWithCallables() throws Exception { ExecutorService executor = EsExecutors.newSinglePrioritizing(Executors.defaultThreadFactory()); List<Integer> results = new ArrayList<Integer>(7); CountDownLatch awaitingLatch = new CountDownLatch(1); CountDownLatch finishedLatch = new CountDownLatch(7); executor.submit(new AwaitingJob(awaitingLatch)); executor.submit(new CallableJob(6, Priority.LANGUID, results, finishedLatch)); executor.submit(new CallableJob(4, Priority.LOW, results, finishedLatch)); executor.submit(new CallableJob(1, Priority.HIGH, results, finishedLatch)); executor.submit(new CallableJob(5, Priority.LOW, results, finishedLatch)); // will execute after the first LOW (fifo) executor.submit(new CallableJob(0, Priority.URGENT, results, finishedLatch)); executor.submit(new CallableJob(3, Priority.NORMAL, results, finishedLatch)); executor.submit(new CallableJob(2, Priority.HIGH, results, finishedLatch)); // will execute after the first HIGH (fifo) awaitingLatch.countDown(); finishedLatch.await(); assertThat(results.size(), equalTo(7)); assertThat(results.get(0), equalTo(0)); assertThat(results.get(1), equalTo(1)); assertThat(results.get(2), equalTo(2)); assertThat(results.get(3), equalTo(3)); assertThat(results.get(4), equalTo(4)); assertThat(results.get(5), equalTo(5)); assertThat(results.get(6), equalTo(6)); } @Test public void testSubmitPrioritizedExecutorWithMixed() throws Exception { ExecutorService executor = EsExecutors.newSinglePrioritizing(Executors.defaultThreadFactory()); List<Integer> results = new ArrayList<Integer>(7); CountDownLatch awaitingLatch = new CountDownLatch(1); CountDownLatch finishedLatch = new CountDownLatch(7); executor.submit(new AwaitingJob(awaitingLatch)); executor.submit(new CallableJob(6, Priority.LANGUID, results, finishedLatch)); executor.submit(new Job(4, Priority.LOW, results, finishedLatch)); executor.submit(new CallableJob(1, Priority.HIGH, results, finishedLatch)); executor.submit(new Job(5, Priority.LOW, results, finishedLatch)); // will execute after the first LOW (fifo) executor.submit(new CallableJob(0, Priority.URGENT, results, finishedLatch)); executor.submit(new Job(3, Priority.NORMAL, results, finishedLatch)); executor.submit(new CallableJob(2, Priority.HIGH, results, finishedLatch)); // will execute after the first HIGH (fifo) awaitingLatch.countDown(); finishedLatch.await(); assertThat(results.size(), equalTo(7)); assertThat(results.get(0), equalTo(0)); assertThat(results.get(1), equalTo(1)); assertThat(results.get(2), equalTo(2)); assertThat(results.get(3), equalTo(3)); assertThat(results.get(4), equalTo(4)); assertThat(results.get(5), equalTo(5)); assertThat(results.get(6), equalTo(6)); } @Test public void testTimeout() throws Exception { ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(); PrioritizedEsThreadPoolExecutor executor = EsExecutors.newSinglePrioritizing(Executors.defaultThreadFactory()); final CountDownLatch block = new CountDownLatch(1); executor.execute(new Runnable() { @Override public void run() { try { block.await(); } catch (InterruptedException e) { fail(); } } @Override public String toString() { return "the blocking"; } }); final AtomicBoolean executeCalled = new AtomicBoolean(); final CountDownLatch timedOut = new CountDownLatch(1); executor.execute(new Runnable() { @Override public void run() { executeCalled.set(true); } @Override public String toString() { return "the waiting"; } }, timer, TimeValue.timeValueMillis(100) /* enough timeout to catch them in the pending list... */, new Runnable() { @Override public void run() { timedOut.countDown(); } } ); PrioritizedEsThreadPoolExecutor.Pending[] pending = executor.getPending(); assertThat(pending.length, equalTo(1)); assertThat(pending[0].task.toString(), equalTo("the waiting")); assertThat(timedOut.await(2, TimeUnit.SECONDS), equalTo(true)); block.countDown(); Thread.sleep(100); // sleep a bit to double check that execute on the timed out update task is not called... assertThat(executeCalled.get(), equalTo(false)); timer.shutdownNow(); executor.shutdownNow(); } static class AwaitingJob extends PrioritizedRunnable { private final CountDownLatch latch; private AwaitingJob(CountDownLatch latch) { super(Priority.URGENT); this.latch = latch; } @Override public void run() { try { latch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } static class Job extends PrioritizedRunnable { private final int result; private final List<Integer> results; private final CountDownLatch latch; Job(int result, Priority priority, List<Integer> results, CountDownLatch latch) { super(priority); this.result = result; this.results = results; this.latch = latch; } @Override public void run() { results.add(result); latch.countDown(); } } static class CallableJob extends PrioritizedCallable<Integer> { private final int result; private final List<Integer> results; private final CountDownLatch latch; CallableJob(int result, Priority priority, List<Integer> results, CountDownLatch latch) { super(priority); this.result = result; this.results = results; this.latch = latch; } @Override public Integer call() throws Exception { results.add(result); latch.countDown(); return result; } } }
0true
src_test_java_org_elasticsearch_common_util_concurrent_PrioritizedExecutorsTests.java
51
public abstract class ONeedRetryException extends OException { private static final long serialVersionUID = 1L; public ONeedRetryException() { super(); } public ONeedRetryException(String message, Throwable cause) { super(message, cause); } public ONeedRetryException(String message) { super(message); } public ONeedRetryException(Throwable cause) { super(cause); } }
0true
commons_src_main_java_com_orientechnologies_common_concur_ONeedRetryException.java
3,551
public static class Defaults extends AbstractFieldMapper.Defaults { public static final long COMPRESS_THRESHOLD = -1; public static final FieldType FIELD_TYPE = new FieldType(AbstractFieldMapper.Defaults.FIELD_TYPE); static { FIELD_TYPE.setIndexed(false); FIELD_TYPE.freeze(); } }
0true
src_main_java_org_elasticsearch_index_mapper_core_BinaryFieldMapper.java
331
static class DummyCommandFactory extends XaCommandFactory { @Override public XaCommand readCommand( ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException { buffer.clear(); buffer.limit( 4 ); if ( byteChannel.read( buffer ) == 4 ) { buffer.flip(); return new DummyCommand( buffer.getInt() ); } return null; } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_DummyXaDataSource.java
308
public class MergeClassPathXMLApplicationContext extends AbstractMergeXMLApplicationContext { public MergeClassPathXMLApplicationContext(ApplicationContext parent) { super(parent); } /** * Create a new MergeClassPathXMLApplicationContext, loading the definitions from the given definitions. Note, * all sourceLocation files will be merged using standard Spring configuration override rules. However, the patch * files are fully merged into the result of the sourceLocations simple merge. Patch merges are first executed according * to beans with the same id. Subsequent merges within a bean are executed against tagnames - ignoring any * further id attributes. * * @param sourceLocations array of relative (or absolute) paths within the class path for the source application context files * @param patchLocations array of relative (or absolute) paths within the class path for the patch application context files * @throws BeansException */ public MergeClassPathXMLApplicationContext(String[] sourceLocations, String[] patchLocations) throws BeansException { this(sourceLocations, patchLocations, null); } /** * Create a new MergeClassPathXMLApplicationContext, loading the definitions from the given definitions. Note, * all sourceLocation files will be merged using standard Spring configuration override rules. However, the patch * files are fully merged into the result of the sourceLocations simple merge. Patch merges are first executed according * to beans with the same id. Subsequent merges within a bean are executed against tagnames - ignoring any * further id attributes. * * @param sourceLocations array of relative (or absolute) paths within the class path for the source application context files * @param patchLocations array of relative (or absolute) paths within the class path for the patch application context files * @param parent the parent context * @throws BeansException */ public MergeClassPathXMLApplicationContext(String[] sourceLocations, String[] patchLocations, ApplicationContext parent) throws BeansException { this(parent); ResourceInputStream[] sources = new ResourceInputStream[sourceLocations.length]; for (int j=0;j<sourceLocations.length;j++){ sources[j] = new ResourceInputStream(getClassLoader(parent).getResourceAsStream(sourceLocations[j]), sourceLocations[j]); } ResourceInputStream[] patches = new ResourceInputStream[patchLocations.length]; for (int j=0;j<patches.length;j++){ patches[j] = new ResourceInputStream(getClassLoader(parent).getResourceAsStream(patchLocations[j]), patchLocations[j]); } ImportProcessor importProcessor = new ImportProcessor(this); try { sources = importProcessor.extract(sources); patches = importProcessor.extract(patches); } catch (MergeException e) { throw new FatalBeanException("Unable to merge source and patch locations", e); } this.configResources = new MergeApplicationContextXmlConfigResource().getConfigResources(sources, patches); refresh(); } /** * This could be advantageous for subclasses to override in order to utilize the parent application context. By default, * this utilizes the class loader for the current class. */ protected ClassLoader getClassLoader(ApplicationContext parent) { return MergeClassPathXMLApplicationContext.class.getClassLoader(); } }
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_context_MergeClassPathXMLApplicationContext.java
1,075
threadPool.executor(executor()).execute(new Runnable() { @Override public void run() { shardOperation(request, listener, retryCount + 1); } });
1no label
src_main_java_org_elasticsearch_action_update_TransportUpdateAction.java
150
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_SC_TYPE") @Cache(usage= CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blCMSElements") @AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "StructuredContentTypeImpl_baseStructuredContentType") public class StructuredContentTypeImpl implements StructuredContentType, AdminMainEntity { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "StructuredContentTypeId") @GenericGenerator( name="StructuredContentTypeId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="StructuredContentTypeImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.cms.structure.domain.StructuredContentTypeImpl") } ) @Column(name = "SC_TYPE_ID") protected Long id; @Column (name = "NAME") @AdminPresentation(friendlyName = "StructuredContentTypeImpl_Name", order = 1, gridOrder = 1, group = "StructuredContentTypeImpl_Details", prominent = true) @Index(name="SC_TYPE_NAME_INDEX", columnNames={"NAME"}) protected String name; @Column (name = "DESCRIPTION") protected String description; @ManyToOne(targetEntity = StructuredContentFieldTemplateImpl.class) @JoinColumn(name="SC_FLD_TMPLT_ID") protected StructuredContentFieldTemplate structuredContentFieldTemplate; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getDescription() { return description; } @Override public void setDescription(String description) { this.description = description; } @Override public StructuredContentFieldTemplate getStructuredContentFieldTemplate() { return structuredContentFieldTemplate; } @Override public void setStructuredContentFieldTemplate(StructuredContentFieldTemplate scft) { this.structuredContentFieldTemplate = scft; } @Override public String getMainEntityName() { return getName(); } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContentTypeImpl.java
1,396
@XmlRootElement(name = "fulfillmentOption") @XmlAccessorType(value = XmlAccessType.FIELD) public class FulfillmentOptionWrapper extends BaseWrapper implements APIWrapper<FulfillmentOption> { @XmlElement protected Long id; @XmlElement protected String name; @XmlElement protected String description; @XmlElement protected BroadleafEnumerationTypeWrapper fulfillmentType; @Override public void wrapDetails(FulfillmentOption model, HttpServletRequest request) { this.id = model.getId(); if (model.getFulfillmentType() != null) { this.fulfillmentType = (BroadleafEnumerationTypeWrapper) context.getBean(BroadleafEnumerationTypeWrapper.class.getName()); this.fulfillmentType.wrapDetails(model.getFulfillmentType(), request); } this.name = model.getName(); this.description = model.getLongDescription(); } @Override public void wrapSummary(FulfillmentOption model, HttpServletRequest request) { wrapDetails(model, request); } public Long getId() { return this.id; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_wrapper_FulfillmentOptionWrapper.java
488
@Component("blCookieUtils") public class GenericCookieUtilsImpl implements CookieUtils { /* (non-Javadoc) * @see org.broadleafcommerce.profile.web.CookieUtils#getCookieValue(javax.servlet.http.HttpServletRequest, java.lang.String) */ public String getCookieValue(HttpServletRequest request, String cookieName) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) return (cookie.getValue()); } } return null; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.web.CookieUtils#setCookieValue(javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String, java.lang.Integer) */ public void setCookieValue(HttpServletResponse response, String cookieName, String cookieValue, String path, Integer maxAge, Boolean isSecure) { Cookie cookie = new Cookie(cookieName, cookieValue); cookie.setPath(path); if (maxAge != null) { cookie.setMaxAge(maxAge); } cookie.setSecure(isSecure); final StringBuffer sb = new StringBuffer(); ServerCookie.appendCookieValue (sb, cookie.getVersion(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getDomain(), cookie.getComment(), cookie.getMaxAge(), cookie.getSecure(), true); //if we reached here, no exception, cookie is valid // the header name is Set-Cookie for both "old" and v.1 ( RFC2109 ) // RFC2965 is not supported by browsers and the Servlet spec // asks for 2109. response.addHeader("Set-Cookie", sb.toString()); } /* (non-Javadoc) * @see org.broadleafcommerce.profile.web.CookieUtils#setCookieValue(javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String) */ public void setCookieValue(HttpServletResponse response, String cookieName, String cookieValue) { setCookieValue(response, cookieName, cookieValue, "/", null, false); } /* (non-Javadoc) * @see org.broadleafcommerce.profile.web.CookieUtils#invalidateCookie(javax.servlet.http.HttpServletResponse, java.lang.String) */ public void invalidateCookie(HttpServletResponse response, String cookieName) { setCookieValue(response, cookieName, "", "/", 0, false); } }
0true
common_src_main_java_org_broadleafcommerce_common_security_util_GenericCookieUtilsImpl.java
305
public class ClusterHealthAction extends ClusterAction<ClusterHealthRequest, ClusterHealthResponse, ClusterHealthRequestBuilder> { public static final ClusterHealthAction INSTANCE = new ClusterHealthAction(); public static final String NAME = "cluster/health"; private ClusterHealthAction() { super(NAME); } @Override public ClusterHealthResponse newResponse() { return new ClusterHealthResponse(); } @Override public ClusterHealthRequestBuilder newRequestBuilder(ClusterAdminClient client) { return new ClusterHealthRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_health_ClusterHealthAction.java
842
public abstract class AbstractAlterRequest extends PartitionClientRequest implements Portable, SecureRequest { protected String name; protected Data function; public AbstractAlterRequest() { } public AbstractAlterRequest(String name, Data function) { this.name = name; this.function = function; } @Override protected int getPartition() { Data key = getClientEngine().getSerializationService().toData(name); return getClientEngine().getPartitionService().getPartitionId(key); } @Override public String getServiceName() { return AtomicReferenceService.SERVICE_NAME; } @Override public int getFactoryId() { return AtomicReferencePortableHook.F_ID; } @Override public void write(PortableWriter writer) throws IOException { writer.writeUTF("n", name); final ObjectDataOutput out = writer.getRawDataOutput(); IOUtil.writeNullableData(out, function); } @Override public void read(PortableReader reader) throws IOException { name = reader.readUTF("n"); ObjectDataInput in = reader.getRawDataInput(); function = IOUtil.readNullableData(in); } @Override public Permission getRequiredPermission() { return new AtomicReferencePermission(name, ActionConstants.ACTION_MODIFY); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_AbstractAlterRequest.java
809
public class PlotViewFactory { private final static Logger logger = LoggerFactory.getLogger(PlotViewFactory.class); /** * Create the plot from persisted settings if available. Otherwise, create a default plot. */ static PlotView createPlot(PlotSettings settings, long currentTime, PlotViewManifestation parentManifestation, int numberOfSubPlots, PlotView oldPlot, AbbreviatingPlotLabelingAlgorithm plotLabelingAlgorithm) { PlotView thePlot; // Insure we always have at least one plot. numberOfSubPlots = Math.max(1,numberOfSubPlots); if (!settings.isNull()) { // The plot has persisted settings so apply them. if (!settings.pinTimeAxis) { adjustPlotStartAndEndTimeToMatchCurrentTime(settings, currentTime); } thePlot = createPlotFromSettings(settings, numberOfSubPlots, plotLabelingAlgorithm); } else { // Setup a default plot to view while the user is configuring it. thePlot = new PlotView.Builder(PlotterPlot.class). numberOfSubPlots(numberOfSubPlots). timeVariableAxisMaxValue(currentTime). timeVariableAxisMinValue(currentTime - PlotConstants.DEFAUlT_PLOT_SPAN). plotLabelingAlgorithm(plotLabelingAlgorithm).build(); } thePlot.setManifestation(parentManifestation); thePlot.setPlotLabelingAlgorithm(plotLabelingAlgorithm); assert thePlot!=null : "Plot labeling algorithm should NOT be NULL at this point."; logger.debug("plotLabelingAlgorithm.getPanelContextTitleList().size()=" + plotLabelingAlgorithm.getPanelContextTitleList().size() + ", plotLabelingAlgorithm.getCanvasContextTitleList().size()=" + plotLabelingAlgorithm.getCanvasContextTitleList().size()); // Copy across feed mapping from old plot, unless structure is different if (oldPlot!=null && oldPlot.subPlots.size() == numberOfSubPlots) { for (String dataSetName: oldPlot.dataSetNameToSubGroupMap.keySet()) { String nameLower = dataSetName.toLowerCase(); for(AbstractPlottingPackage plot : oldPlot.dataSetNameToSubGroupMap.get(dataSetName)) { int indexInOldPlot = oldPlot.subPlots.indexOf(plot); thePlot.addDataSet(indexInOldPlot, dataSetName, oldPlot.dataSetNameToDisplayMap.get(nameLower)); } } } return thePlot; } /** * Create the plot using the persisted settings. */ static PlotView createPlotFromSettings(PlotSettings settings, int numberOfSubPlots, AbbreviatingPlotLabelingAlgorithm plotLabelingAlgorithm) { PlotView newPlot = new PlotView.Builder(PlotterPlot.class) .axisOrientation(settings.timeAxisSetting) .xAxisMaximumLocation(settings.xAxisMaximumLocation) .yAxisMaximumLocation(settings.yAxisMaximumLocation) .nonTimeVaribleAxisMaxValue(settings.maxNonTime) .nonTimeVaribleAxisMinValue(settings.minNonTime) .timeAxisBoundsSubsequentSetting(settings.timeAxisSubsequent) .nonTimeAxisMinSubsequentSetting(settings.nonTimeAxisSubsequentMinSetting) .nonTimeAxisMaxSubsequentSetting(settings.nonTimeAxisSubsequentMaxSetting) .timeVariableAxisMaxValue(settings.maxTime) .timeVariableAxisMinValue(settings.minTime) .scrollRescaleMarginTimeAxis(settings.timePadding) .scrollRescaleMarginNonTimeMaxAxis(settings.nonTimeMaxPadding) .scrollRescaleMarginNonTimeMinAxis(settings.nonTimeMinPadding) .numberOfSubPlots(numberOfSubPlots) .useOrdinalPositionForSubplots(settings.ordinalPositionForStackedPlots) .pinTimeAxis(settings.pinTimeAxis) .plotLineDraw(settings.plotLineDraw) .plotLineConnectionType(settings.plotLineConnectionType) .plotLabelingAlgorithm(plotLabelingAlgorithm) .build(); newPlot.setPlotLabelingAlgorithm(plotLabelingAlgorithm); newPlot.setPlotLineDraw(settings.plotLineDraw); newPlot.setPlotLineConnectionType(settings.plotLineConnectionType); return newPlot; } private static void adjustPlotStartAndEndTimeToMatchCurrentTime(PlotSettings settings, long currentTime) { if (settings.timeAxisSubsequent == TimeAxisSubsequentBoundsSetting.SCRUNCH) { if (currentTime > settings.maxTime) { // Fast forward to now on the upper bound. settings.maxTime = currentTime; } } } }
1no label
fastPlotViews_src_main_java_gov_nasa_arc_mct_fastplot_view_PlotViewFactory.java
468
while (makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<Boolean>() { public Boolean call() { return indexIteratorOne.hasNext(); } })) {
1no label
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java
1,937
public final class ConstantBindingBuilderImpl<T> extends AbstractBindingBuilder<T> implements AnnotatedConstantBindingBuilder, ConstantBindingBuilder { @SuppressWarnings("unchecked") // constant bindings start out with T unknown public ConstantBindingBuilderImpl(Binder binder, List<Element> elements, Object source) { super(binder, elements, source, (Key<T>) NULL_KEY); } public ConstantBindingBuilder annotatedWith(Class<? extends Annotation> annotationType) { annotatedWithInternal(annotationType); return this; } public ConstantBindingBuilder annotatedWith(Annotation annotation) { annotatedWithInternal(annotation); return this; } public void to(final String value) { toConstant(String.class, value); } public void to(final int value) { toConstant(Integer.class, value); } public void to(final long value) { toConstant(Long.class, value); } public void to(final boolean value) { toConstant(Boolean.class, value); } public void to(final double value) { toConstant(Double.class, value); } public void to(final float value) { toConstant(Float.class, value); } public void to(final short value) { toConstant(Short.class, value); } public void to(final char value) { toConstant(Character.class, value); } public void to(final Class<?> value) { toConstant(Class.class, value); } public <E extends Enum<E>> void to(final E value) { toConstant(value.getDeclaringClass(), value); } private void toConstant(Class<?> type, Object instance) { // this type will define T, so these assignments are safe @SuppressWarnings("unchecked") Class<T> typeAsClassT = (Class<T>) type; @SuppressWarnings("unchecked") T instanceAsT = (T) instance; if (keyTypeIsSet()) { binder.addError(CONSTANT_VALUE_ALREADY_SET); return; } BindingImpl<T> base = getBinding(); Key<T> key; if (base.getKey().getAnnotation() != null) { key = Key.get(typeAsClassT, base.getKey().getAnnotation()); } else if (base.getKey().getAnnotationType() != null) { key = Key.get(typeAsClassT, base.getKey().getAnnotationType()); } else { key = Key.get(typeAsClassT); } if (instanceAsT == null) { binder.addError(BINDING_TO_NULL); } setBinding(new InstanceBindingImpl<T>( base.getSource(), key, base.getScoping(), ImmutableSet.<InjectionPoint>of(), instanceAsT)); } @Override public String toString() { return "ConstantBindingBuilder"; } }
0true
src_main_java_org_elasticsearch_common_inject_internal_ConstantBindingBuilderImpl.java
3,381
public class PackedArrayEstimator implements PerValueEstimator { private final MemoryCircuitBreaker breaker; private final NumericType type; public PackedArrayEstimator(MemoryCircuitBreaker breaker, NumericType type) { this.breaker = breaker; this.type = type; } /** * @return number of bytes per term, based on the NumericValue.requiredBits() */ @Override public long bytesPerValue(BytesRef term) { // Estimate about about 0.8 (8 / 10) compression ratio for // numbers, but at least 4 bytes return Math.max(type.requiredBits() / 10, 4); } /** * @return A TermsEnum wrapped in a RamAccountingTermsEnum * @throws IOException */ @Override public TermsEnum beforeLoad(Terms terms) throws IOException { return new RamAccountingTermsEnum(type.wrapTermsEnum(terms.iterator(null)), breaker, this); } /** * Adjusts the breaker based on the aggregated value from the RamAccountingTermsEnum * * @param termsEnum terms that were wrapped and loaded * @param actualUsed actual field data memory usage */ @Override public void afterLoad(TermsEnum termsEnum, long actualUsed) { assert termsEnum instanceof RamAccountingTermsEnum; long estimatedBytes = ((RamAccountingTermsEnum) termsEnum).getTotalBytes(); breaker.addWithoutBreaking(-(estimatedBytes - actualUsed)); } /** * Adjust the breaker when no terms were actually loaded, but the field * data takes up space regardless. For instance, when ordinals are * used. * @param actualUsed bytes actually used */ public void adjustForNoTerms(long actualUsed) { breaker.addWithoutBreaking(actualUsed); } }
0true
src_main_java_org_elasticsearch_index_fielddata_plain_PackedArrayIndexFieldData.java
5,920
public class GeoDistanceSortParser implements SortParser { @Override public String[] names() { return new String[]{"_geo_distance", "_geoDistance"}; } @Override public SortField parse(XContentParser parser, SearchContext context) throws Exception { String fieldName = null; GeoPoint point = new GeoPoint(); DistanceUnit unit = DistanceUnit.DEFAULT; GeoDistance geoDistance = GeoDistance.DEFAULT; boolean reverse = false; SortMode sortMode = null; String nestedPath = null; Filter nestedFilter = null; boolean normalizeLon = true; boolean normalizeLat = true; XContentParser.Token token; String currentName = parser.currentName(); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentName = parser.currentName(); } else if (token == XContentParser.Token.START_ARRAY) { GeoPoint.parse(parser, point); fieldName = currentName; } else if (token == XContentParser.Token.START_OBJECT) { // the json in the format of -> field : { lat : 30, lon : 12 } if ("nested_filter".equals(currentName) || "nestedFilter".equals(currentName)) { ParsedFilter parsedFilter = context.queryParserService().parseInnerFilter(parser); nestedFilter = parsedFilter == null ? null : parsedFilter.filter(); } else { fieldName = currentName; GeoPoint.parse(parser, point); } } else if (token.isValue()) { if ("reverse".equals(currentName)) { reverse = parser.booleanValue(); } else if ("order".equals(currentName)) { reverse = "desc".equals(parser.text()); } else if (currentName.equals("unit")) { unit = DistanceUnit.fromString(parser.text()); } else if (currentName.equals("distance_type") || currentName.equals("distanceType")) { geoDistance = GeoDistance.fromString(parser.text()); } else if ("normalize".equals(currentName)) { normalizeLat = parser.booleanValue(); normalizeLon = parser.booleanValue(); } else if ("sort_mode".equals(currentName) || "sortMode".equals(currentName) || "mode".equals(currentName)) { sortMode = SortMode.fromString(parser.text()); } else if ("nested_path".equals(currentName) || "nestedPath".equals(currentName)) { nestedPath = parser.text(); } else { point.resetFromString(parser.text()); fieldName = currentName; } } } if (normalizeLat || normalizeLon) { GeoUtils.normalizePoint(point, normalizeLat, normalizeLon); } if (sortMode == null) { sortMode = reverse ? SortMode.MAX : SortMode.MIN; } if (sortMode == SortMode.SUM) { throw new ElasticsearchIllegalArgumentException("sort_mode [sum] isn't supported for sorting by geo distance"); } FieldMapper mapper = context.smartNameFieldMapper(fieldName); if (mapper == null) { throw new ElasticsearchIllegalArgumentException("failed to find mapper for [" + fieldName + "] for geo distance based sort"); } IndexGeoPointFieldData indexFieldData = context.fieldData().getForField(mapper); IndexFieldData.XFieldComparatorSource geoDistanceComparatorSource = new GeoDistanceComparatorSource( indexFieldData, point.lat(), point.lon(), unit, geoDistance, sortMode ); ObjectMapper objectMapper; if (nestedPath != null) { ObjectMappers objectMappers = context.mapperService().objectMapper(nestedPath); if (objectMappers == null) { throw new ElasticsearchIllegalArgumentException("failed to find nested object mapping for explicit nested path [" + nestedPath + "]"); } objectMapper = objectMappers.mapper(); if (!objectMapper.nested().isNested()) { throw new ElasticsearchIllegalArgumentException("mapping for explicit nested path is not mapped as nested: [" + nestedPath + "]"); } } else { objectMapper = context.mapperService().resolveClosestNestedObjectMapper(fieldName); } if (objectMapper != null && objectMapper.nested().isNested()) { Filter rootDocumentsFilter = context.filterCache().cache(NonNestedDocsFilter.INSTANCE); Filter innerDocumentsFilter; if (nestedFilter != null) { innerDocumentsFilter = context.filterCache().cache(nestedFilter); } else { innerDocumentsFilter = context.filterCache().cache(objectMapper.nestedTypeFilter()); } geoDistanceComparatorSource = new NestedFieldComparatorSource( sortMode, geoDistanceComparatorSource, rootDocumentsFilter, innerDocumentsFilter ); } return new SortField(fieldName, geoDistanceComparatorSource, reverse); } }
1no label
src_main_java_org_elasticsearch_search_sort_GeoDistanceSortParser.java
3,277
public interface Ordinals { static final long MISSING_ORDINAL = 0; static final long MIN_ORDINAL = 1; /** * The memory size this ordinals take. */ long getMemorySizeInBytes(); /** * Is one of the docs maps to more than one ordinal? */ boolean isMultiValued(); /** * The number of docs in this ordinals. */ int getNumDocs(); /** * The number of ordinals, excluding the {@link #MISSING_ORDINAL} ordinal indicating a missing value. */ long getNumOrds(); /** * Returns total unique ord count; this includes +1 for * the {@link #MISSING_ORDINAL} ord (always {@value #MISSING_ORDINAL} ). */ long getMaxOrd(); /** * Returns a lightweight (non thread safe) view iterator of the ordinals. */ Docs ordinals(); /** * A non thread safe ordinals abstraction, yet very lightweight to create. The idea * is that this gets created for each "iteration" over ordinals. * <p/> * <p>A value of 0 ordinal when iterating indicated "no" value.</p> * To iterate of a set of ordinals for a given document use {@link #setDocument(int)} and {@link #nextOrd()} as * show in the example below: * <pre> * Ordinals.Docs docs = ...; * final int len = docs.setDocId(docId); * for (int i = 0; i < len; i++) { * final long ord = docs.nextOrd(); * // process ord * } * </pre> */ interface Docs { /** * Returns the original ordinals used to generate this Docs "itereator". */ Ordinals ordinals(); /** * The number of docs in this ordinals. */ int getNumDocs(); /** * The number of ordinals, excluding the "0" ordinal (indicating a missing value). */ long getNumOrds(); /** * Returns total unique ord count; this includes +1 for * the null ord (always 0). */ long getMaxOrd(); /** * Is one of the docs maps to more than one ordinal? */ boolean isMultiValued(); /** * The ordinal that maps to the relevant docId. If it has no value, returns * <tt>0</tt>. */ long getOrd(int docId); /** * Returns an array of ordinals matching the docIds, with 0 length one * for a doc with no ordinals. */ LongsRef getOrds(int docId); /** * Returns the next ordinal for the current docID set to {@link #setDocument(int)}. * This method should only be called <tt>N</tt> times where <tt>N</tt> is the number * returned from {@link #setDocument(int)}. If called more than <tt>N</tt> times the behavior * is undefined. * * Note: This method will never return <tt>0</tt>. * * @return the next ordinal for the current docID set to {@link #setDocument(int)}. */ long nextOrd(); /** * Sets iteration to the specified docID and returns the number of * ordinals for this document ID, * @param docId document ID * * @see #nextOrd() */ int setDocument(int docId); /** * Returns the current ordinal in the iteration * @return the current ordinal in the iteration */ long currentOrd(); } }
0true
src_main_java_org_elasticsearch_index_fielddata_ordinals_Ordinals.java
1,219
public enum CLUSTER_TYPE { PHYSICAL, MEMORY }
0true
core_src_main_java_com_orientechnologies_orient_core_storage_OStorage.java
246
public class FocusEditingSupport implements IEditingSupport { private final CeylonEditor editor; public FocusEditingSupport(CeylonEditor editor) { this.editor = editor; } public boolean ownsFocusShell() { Shell editorShell = editor.getSite().getShell(); Shell activeShell = editorShell.getDisplay().getActiveShell(); return editorShell == activeShell; } public boolean isOriginator(DocumentEvent event, IRegion subjectRegion) { return false; //leave on external modification outside positions } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_FocusEditingSupport.java
1,562
public class AllocationDeciders extends AllocationDecider { private final AllocationDecider[] allocations; public AllocationDeciders(Settings settings, AllocationDecider[] allocations) { super(settings); this.allocations = allocations; } @Inject public AllocationDeciders(Settings settings, Set<AllocationDecider> allocations) { this(settings, allocations.toArray(new AllocationDecider[allocations.size()])); } @Override public Decision canRebalance(ShardRouting shardRouting, RoutingAllocation allocation) { Decision.Multi ret = new Decision.Multi(); for (AllocationDecider allocationDecider : allocations) { Decision decision = allocationDecider.canRebalance(shardRouting, allocation); // short track if a NO is returned. if (decision == Decision.NO) { if (!allocation.debugDecision()) { return decision; } else { ret.add(decision); } } else if (decision != Decision.ALWAYS) { ret.add(decision); } } return ret; } @Override public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { if (allocation.shouldIgnoreShardForNode(shardRouting.shardId(), node.nodeId())) { return Decision.NO; } Decision.Multi ret = new Decision.Multi(); for (AllocationDecider allocationDecider : allocations) { Decision decision = allocationDecider.canAllocate(shardRouting, node, allocation); // short track if a NO is returned. if (decision == Decision.NO) { if (logger.isTraceEnabled()) { logger.trace("Can not allocate [{}] on node [{}] due to [{}]", shardRouting, node.nodeId(), allocationDecider.getClass().getSimpleName()); } // short circuit only if debugging is not enabled if (!allocation.debugDecision()) { return decision; } else { ret.add(decision); } } else if (decision != Decision.ALWAYS) { // the assumption is that a decider that returns the static instance Decision#ALWAYS // does not really implements canAllocate ret.add(decision); } } return ret; } @Override public Decision canRemain(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { if (allocation.shouldIgnoreShardForNode(shardRouting.shardId(), node.nodeId())) { if (logger.isTraceEnabled()) { logger.trace("Shard [{}] should be ignored for node [{}]", shardRouting, node.nodeId()); } return Decision.NO; } Decision.Multi ret = new Decision.Multi(); for (AllocationDecider allocationDecider : allocations) { Decision decision = allocationDecider.canRemain(shardRouting, node, allocation); // short track if a NO is returned. if (decision == Decision.NO) { if (logger.isTraceEnabled()) { logger.trace("Shard [{}] can not remain on node [{}] due to [{}]", shardRouting, node.nodeId(), allocationDecider.getClass().getSimpleName()); } if (!allocation.debugDecision()) { return decision; } else { ret.add(decision); } } else if (decision != Decision.ALWAYS) { ret.add(decision); } } return ret; } public Decision canAllocate(ShardRouting shardRouting, RoutingAllocation allocation) { Decision.Multi ret = new Decision.Multi(); for (AllocationDecider allocationDecider : allocations) { Decision decision = allocationDecider.canAllocate(shardRouting, allocation); // short track if a NO is returned. if (decision == Decision.NO) { if (!allocation.debugDecision()) { return decision; } else { ret.add(decision); } } else if (decision != Decision.ALWAYS) { ret.add(decision); } } return ret; } public Decision canAllocate(RoutingNode node, RoutingAllocation allocation) { Decision.Multi ret = new Decision.Multi(); for (AllocationDecider allocationDecider : allocations) { Decision decision = allocationDecider.canAllocate(node, allocation); // short track if a NO is returned. if (decision == Decision.NO) { if (!allocation.debugDecision()) { return decision; } else { ret.add(decision); } } else if (decision != Decision.ALWAYS) { ret.add(decision); } } return ret; } }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_decider_AllocationDeciders.java
1,931
public class MapContainsKeyRequest extends KeyBasedClientRequest implements Portable, RetryableRequest, SecureRequest { private String name; private Data key; public MapContainsKeyRequest() { } public MapContainsKeyRequest(String name, Data key) { this.name = name; this.key = key; } @Override protected Object getKey() { return key; } @Override protected Operation prepareOperation() { return new ContainsKeyOperation(name, key); } public String getServiceName() { return MapService.SERVICE_NAME; } @Override public int getFactoryId() { return MapPortableHook.F_ID; } public int getClassId() { return MapPortableHook.CONTAINS_KEY; } public void write(PortableWriter writer) throws IOException { writer.writeUTF("n", name); final ObjectDataOutput out = writer.getRawDataOutput(); key.writeData(out); } public void read(PortableReader reader) throws IOException { name = reader.readUTF("n"); final ObjectDataInput in = reader.getRawDataInput(); key = new Data(); key.readData(in); } public Permission getRequiredPermission() { return new MapPermission(name, ActionConstants.ACTION_READ); } }
0true
hazelcast_src_main_java_com_hazelcast_map_client_MapContainsKeyRequest.java
1,550
public class ShardsAllocatorModule extends AbstractModule { public static final String EVEN_SHARD_COUNT_ALLOCATOR_KEY = "even_shard"; public static final String BALANCED_ALLOCATOR_KEY = "balanced"; // default public static final String TYPE_KEY = "cluster.routing.allocation.type"; private Settings settings; private Class<? extends ShardsAllocator> shardsAllocator; private Class<? extends GatewayAllocator> gatewayAllocator = NoneGatewayAllocator.class; public ShardsAllocatorModule(Settings settings) { this.settings = settings; shardsAllocator = loadShardsAllocator(settings); } public void setGatewayAllocator(Class<? extends GatewayAllocator> gatewayAllocator) { this.gatewayAllocator = gatewayAllocator; } public void setShardsAllocator(Class<? extends ShardsAllocator> shardsAllocator) { this.shardsAllocator = shardsAllocator; } @Override protected void configure() { if (shardsAllocator == null) { shardsAllocator = loadShardsAllocator(settings); } bind(GatewayAllocator.class).to(gatewayAllocator).asEagerSingleton(); bind(ShardsAllocator.class).to(shardsAllocator).asEagerSingleton(); } private Class<? extends ShardsAllocator> loadShardsAllocator(Settings settings) { final Class<? extends ShardsAllocator> shardsAllocator; final String type = settings.get(TYPE_KEY, BALANCED_ALLOCATOR_KEY); if (BALANCED_ALLOCATOR_KEY.equals(type)) { shardsAllocator = BalancedShardsAllocator.class; } else if (EVEN_SHARD_COUNT_ALLOCATOR_KEY.equals(type)) { shardsAllocator = EvenShardsCountAllocator.class; } else { shardsAllocator = settings.getAsClass(TYPE_KEY, BalancedShardsAllocator.class, "org.elasticsearch.cluster.routing.allocation.allocator.", "Allocator"); } return shardsAllocator; } }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_allocator_ShardsAllocatorModule.java
1,364
@ClusterScope(scope=Scope.TEST, numNodes=0) public class FilteringAllocationTests extends ElasticsearchIntegrationTest { private final ESLogger logger = Loggers.getLogger(FilteringAllocationTests.class); @Test public void testDecommissionNodeNoReplicas() throws Exception { logger.info("--> starting 2 nodes"); final String node_0 = cluster().startNode(); final String node_1 = cluster().startNode(); assertThat(cluster().size(), equalTo(2)); logger.info("--> creating an index with no replicas"); client().admin().indices().prepareCreate("test") .setSettings(settingsBuilder().put("index.number_of_replicas", 0)) .execute().actionGet(); ensureGreen(); logger.info("--> index some data"); for (int i = 0; i < 100; i++) { client().prepareIndex("test", "type", Integer.toString(i)).setSource("field", "value" + i).execute().actionGet(); } client().admin().indices().prepareRefresh().execute().actionGet(); assertThat(client().prepareCount().setQuery(QueryBuilders.matchAllQuery()).execute().actionGet().getCount(), equalTo(100l)); logger.info("--> decommission the second node"); client().admin().cluster().prepareUpdateSettings() .setTransientSettings(settingsBuilder().put("cluster.routing.allocation.exclude._name", node_1)) .execute().actionGet(); waitForRelocation(); logger.info("--> verify all are allocated on node1 now"); ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState(); for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) { for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) { for (ShardRouting shardRouting : indexShardRoutingTable) { assertThat(clusterState.nodes().get(shardRouting.currentNodeId()).name(), equalTo(node_0)); } } } client().admin().indices().prepareRefresh().execute().actionGet(); assertThat(client().prepareCount().setQuery(QueryBuilders.matchAllQuery()).execute().actionGet().getCount(), equalTo(100l)); } @Test public void testDisablingAllocationFiltering() throws Exception { logger.info("--> starting 2 nodes"); final String node_0 = cluster().startNode(); final String node_1 = cluster().startNode(); assertThat(cluster().size(), equalTo(2)); logger.info("--> creating an index with no replicas"); client().admin().indices().prepareCreate("test") .setSettings(settingsBuilder().put("index.number_of_replicas", 0)) .execute().actionGet(); ensureGreen(); logger.info("--> index some data"); for (int i = 0; i < 100; i++) { client().prepareIndex("test", "type", Integer.toString(i)).setSource("field", "value" + i).execute().actionGet(); } client().admin().indices().prepareRefresh().execute().actionGet(); assertThat(client().prepareCount().setQuery(QueryBuilders.matchAllQuery()).execute().actionGet().getCount(), equalTo(100l)); ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState(); IndexRoutingTable indexRoutingTable = clusterState.routingTable().index("test"); int numShardsOnNode1 = 0; for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) { for (ShardRouting shardRouting : indexShardRoutingTable) { if ("node1".equals(clusterState.nodes().get(shardRouting.currentNodeId()).name())) { numShardsOnNode1++; } } } if (numShardsOnNode1 > ThrottlingAllocationDecider.DEFAULT_CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES) { client().admin().cluster().prepareUpdateSettings() .setTransientSettings(settingsBuilder().put("cluster.routing.allocation.node_concurrent_recoveries", numShardsOnNode1)).execute().actionGet(); // make sure we can recover all the nodes at once otherwise we might run into a state where one of the shards has not yet started relocating // but we already fired up the request to wait for 0 relocating shards. } logger.info("--> remove index from the first node"); client().admin().indices().prepareUpdateSettings("test") .setSettings(settingsBuilder().put("index.routing.allocation.exclude._name", node_0)) .execute().actionGet(); client().admin().cluster().prepareReroute().get(); ensureGreen(); logger.info("--> verify all shards are allocated on node_1 now"); clusterState = client().admin().cluster().prepareState().execute().actionGet().getState(); indexRoutingTable = clusterState.routingTable().index("test"); for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) { for (ShardRouting shardRouting : indexShardRoutingTable) { assertThat(clusterState.nodes().get(shardRouting.currentNodeId()).name(), equalTo(node_1)); } } logger.info("--> disable allocation filtering "); client().admin().indices().prepareUpdateSettings("test") .setSettings(settingsBuilder().put("index.routing.allocation.exclude._name", "")) .execute().actionGet(); client().admin().cluster().prepareReroute().get(); ensureGreen(); logger.info("--> verify that there are shards allocated on both nodes now"); clusterState = client().admin().cluster().prepareState().execute().actionGet().getState(); assertThat(clusterState.routingTable().index("test").numberOfNodesShardsAreAllocatedOn(), equalTo(2)); } }
0true
src_test_java_org_elasticsearch_cluster_allocation_FilteringAllocationTests.java
607
public class BroadleafRequestInterceptor implements WebRequestInterceptor { @Resource(name = "blRequestProcessor") protected BroadleafRequestProcessor requestProcessor; @Override public void preHandle(WebRequest request) throws Exception { requestProcessor.process(request); } @Override public void postHandle(WebRequest request, ModelMap model) throws Exception { //unimplemented } @Override public void afterCompletion(WebRequest request, Exception ex) throws Exception { requestProcessor.postProcess(request); } }
0true
common_src_main_java_org_broadleafcommerce_common_web_BroadleafRequestInterceptor.java
731
public interface RelatedProductsService { /** * Uses the data in the passed in DTO to return a list of relatedProducts. * * For example, upSale, crossSale, or featured products. * * @param relatedProductDTO * @return */ public List<? extends PromotableProduct> findRelatedProducts(RelatedProductDTO relatedProductDTO); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_service_RelatedProductsService.java
635
public class IndicesStatusRequestBuilder extends BroadcastOperationRequestBuilder<IndicesStatusRequest, IndicesStatusResponse, IndicesStatusRequestBuilder> { public IndicesStatusRequestBuilder(IndicesAdminClient indicesClient) { super((InternalIndicesAdminClient) indicesClient, new IndicesStatusRequest()); } /** * Should the status include recovery information. Defaults to <tt>false</tt>. */ public IndicesStatusRequestBuilder setRecovery(boolean recovery) { request.recovery(recovery); return this; } /** * Should the status include recovery information. Defaults to <tt>false</tt>. */ public IndicesStatusRequestBuilder setSnapshot(boolean snapshot) { request.snapshot(snapshot); return this; } @Override protected void doExecute(ActionListener<IndicesStatusResponse> listener) { ((IndicesAdminClient) client).status(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_status_IndicesStatusRequestBuilder.java
1,572
public class AdminAuditableListener { @PrePersist public void setAuditCreatedBy(Object entity) throws Exception { if (entity.getClass().isAnnotationPresent(Entity.class)) { Field field = getSingleField(entity.getClass(), "auditable"); field.setAccessible(true); if (field.isAnnotationPresent(Embedded.class)) { Object auditable = field.get(entity); if (auditable == null) { field.set(entity, new AdminAuditable()); auditable = field.get(entity); } Field temporalCreatedField = auditable.getClass().getDeclaredField("dateCreated"); Field temporalUpdatedField = auditable.getClass().getDeclaredField("dateUpdated"); Field agentField = auditable.getClass().getDeclaredField("createdBy"); setAuditValueTemporal(temporalCreatedField, auditable); setAuditValueTemporal(temporalUpdatedField, auditable); setAuditValueAgent(agentField, auditable); } } } @PreUpdate public void setAuditUpdatedBy(Object entity) throws Exception { if (entity.getClass().isAnnotationPresent(Entity.class)) { Field field = getSingleField(entity.getClass(), "auditable"); field.setAccessible(true); if (field.isAnnotationPresent(Embedded.class)) { Object auditable = field.get(entity); if (auditable == null) { field.set(entity, new AdminAuditable()); auditable = field.get(entity); } Field temporalField = auditable.getClass().getDeclaredField("dateUpdated"); Field agentField = auditable.getClass().getDeclaredField("updatedBy"); setAuditValueTemporal(temporalField, auditable); setAuditValueAgent(agentField, auditable); } } } protected void setAuditValueTemporal(Field field, Object entity) throws IllegalArgumentException, IllegalAccessException { Calendar cal = SystemTime.asCalendar(); field.setAccessible(true); field.set(entity, cal.getTime()); } protected void setAuditValueAgent(Field field, Object entity) throws IllegalArgumentException, IllegalAccessException { try { SandBoxContext context = SandBoxContext.getSandBoxContext(); if (context != null && context instanceof AdminSandBoxContext) { AdminSandBoxContext adminContext = (AdminSandBoxContext) context; field.setAccessible(true); field.set(entity, adminContext.getAdminUser().getId()); } } catch (IllegalStateException e) { //do nothing } catch (Exception e) { e.printStackTrace(); } } private Field getSingleField(Class<?> clazz, String fieldName) throws IllegalStateException { try { return clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException nsf) { // Try superclass if (clazz.getSuperclass() != null) { return getSingleField(clazz.getSuperclass(), fieldName); } return null; } } }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_audit_AdminAuditableListener.java
1,507
@Component("blAuthenticationSuccessHandler") public class BroadleafAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { String targetUrl = request.getParameter(getTargetUrlParameter()); if (StringUtils.isNotBlank(targetUrl) && targetUrl.contains(":")) { getRedirectStrategy().sendRedirect(request, response, getDefaultTargetUrl()); } else { super.onAuthenticationSuccess(request, response, authentication); } } }
1no label
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_order_security_BroadleafAuthenticationSuccessHandler.java
2,794
public class ASCIIFoldingTokenFilterFactory extends AbstractTokenFilterFactory { @Inject public ASCIIFoldingTokenFilterFactory(Index index, @IndexSettings Settings indexSettings, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); } @Override public TokenStream create(TokenStream tokenStream) { return new ASCIIFoldingFilter(tokenStream); } }
1no label
src_main_java_org_elasticsearch_index_analysis_ASCIIFoldingTokenFilterFactory.java
1,387
public abstract class HibernateStatisticsTestSupport extends HibernateTestSupport { protected SessionFactory sf; protected SessionFactory sf2; @Before public void postConstruct() { sf = createSessionFactory(getCacheProperties()); sf2 = createSessionFactory(getCacheProperties()); } @After public void preDestroy() { if (sf != null) { sf.close(); sf = null; } if (sf2 != null) { sf2.close(); sf2 = null; } Hazelcast.shutdownAll(); } protected HazelcastInstance getHazelcastInstance(SessionFactory sf) { return HazelcastAccessor.getHazelcastInstance(sf); } protected abstract Properties getCacheProperties(); protected void insertDummyEntities(int count) { insertDummyEntities(count, 0); } protected void insertDummyEntities(int count, int childCount) { Session session = sf.openSession(); Transaction tx = session.beginTransaction(); try { for (int i = 0; i < count; i++) { DummyEntity e = new DummyEntity((long) i, "dummy:" + i, i * 123456d, new Date()); session.save(e); for (int j = 0; j < childCount; j++) { DummyProperty p = new DummyProperty("key:" + j, e); session.save(p); } } tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } finally { session.close(); } } @Test public void testEntity() { final HazelcastInstance hz = getHazelcastInstance(sf); assertNotNull(hz); final int count = 100; final int childCount = 3; insertDummyEntities(count, childCount); sleep(1); List<DummyEntity> list = new ArrayList<DummyEntity>(count); Session session = sf.openSession(); try { for (int i = 0; i < count; i++) { DummyEntity e = (DummyEntity) session.get(DummyEntity.class, (long) i); session.evict(e); list.add(e); } } finally { session.close(); } session = sf.openSession(); Transaction tx = session.beginTransaction(); try { for (DummyEntity dummy : list) { dummy.setDate(new Date()); session.update(dummy); } tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } finally { session.close(); } Statistics stats = sf.getStatistics(); Map<?, ?> cache = hz.getMap(DummyEntity.class.getName()); Map<?, ?> propCache = hz.getMap(DummyProperty.class.getName()); Map<?, ?> propCollCache = hz.getMap(DummyEntity.class.getName() + ".properties"); assertEquals((childCount + 1) * count, stats.getEntityInsertCount()); // twice put of entity and properties (on load and update) and once put of collection // TODO: fix next assertion -> // assertEquals((childCount + 1) * count * 2, stats.getSecondLevelCachePutCount()); assertEquals(childCount * count, stats.getEntityLoadCount()); assertEquals(count, stats.getSecondLevelCacheHitCount()); // collection cache miss assertEquals(count, stats.getSecondLevelCacheMissCount()); assertEquals(count, cache.size()); assertEquals(count * childCount, propCache.size()); assertEquals(count, propCollCache.size()); sf.getCache().evictEntityRegion(DummyEntity.class); sf.getCache().evictEntityRegion(DummyProperty.class); assertEquals(0, cache.size()); assertEquals(0, propCache.size()); stats.logSummary(); } @Test @Category(ProblematicTest.class) public void testQuery() { final int entityCount = 10; final int queryCount = 3; insertDummyEntities(entityCount); sleep(1); List<DummyEntity> list = null; for (int i = 0; i < queryCount; i++) { list = executeQuery(sf); assertEquals(entityCount, list.size()); sleep(1); } assertNotNull(list); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); try { for (DummyEntity dummy : list) { session.delete(dummy); } tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } finally { session.close(); } Statistics stats = sf.getStatistics(); assertEquals(1, stats.getQueryCachePutCount()); assertEquals(1, stats.getQueryCacheMissCount()); assertEquals(queryCount - 1, stats.getQueryCacheHitCount()); assertEquals(1, stats.getQueryExecutionCount()); assertEquals(entityCount, stats.getEntityInsertCount()); // FIXME // HazelcastRegionFactory puts into L2 cache 2 times; 1 on insert, 1 on query execution // assertEquals(entityCount, stats.getSecondLevelCachePutCount()); assertEquals(entityCount, stats.getEntityLoadCount()); assertEquals(entityCount, stats.getEntityDeleteCount()); assertEquals(entityCount * (queryCount - 1) * 2, stats.getSecondLevelCacheHitCount()); // collection cache miss assertEquals(entityCount, stats.getSecondLevelCacheMissCount()); stats.logSummary(); } protected List<DummyEntity> executeQuery(SessionFactory factory) { Session session = factory.openSession(); try { Query query = session.createQuery("from " + DummyEntity.class.getName()); query.setCacheable(true); return query.list(); } finally { session.close(); } } @Test public void testQuery2() { final int entityCount = 10; final int queryCount = 2; insertDummyEntities(entityCount); sleep(1); List<DummyEntity> list = null; for (int i = 0; i < queryCount; i++) { list = executeQuery(sf); assertEquals(entityCount, list.size()); sleep(1); } for (int i = 0; i < queryCount; i++) { list = executeQuery(sf2); assertEquals(entityCount, list.size()); sleep(1); } assertNotNull(list); DummyEntity toDelete = list.get(0); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); try { session.delete(toDelete); tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } finally { session.close(); } assertEquals(entityCount - 1, executeQuery(sf).size()); assertEquals(entityCount - 1, executeQuery(sf2).size()); } }
0true
hazelcast-hibernate_hazelcast-hibernate3_src_test_java_com_hazelcast_hibernate_HibernateStatisticsTestSupport.java
220
public interface RuntimeEnvironmentKeyResolver { /** * Determine and return the runtime environment; if an implementation is * unable to determine the runtime environment, null can be returned to * indicate this. */ String resolveRuntimeEnvironmentKey(); }
0true
common_src_main_java_org_broadleafcommerce_common_config_RuntimeEnvironmentKeyResolver.java
480
final EventHandler<PortableDistributedObjectEvent> eventHandler = new EventHandler<PortableDistributedObjectEvent>() { public void handle(PortableDistributedObjectEvent e) { final ObjectNamespace ns = new DefaultObjectNamespace(e.getServiceName(), e.getName()); ClientProxyFuture future = proxies.get(ns); ClientProxy proxy = future == null ? null : future.get(); if (proxy == null) { proxy = getProxy(e.getServiceName(), e.getName()); } DistributedObjectEvent event = new DistributedObjectEvent(e.getEventType(), e.getServiceName(), proxy); if (DistributedObjectEvent.EventType.CREATED.equals(e.getEventType())) { listener.distributedObjectCreated(event); } else if (DistributedObjectEvent.EventType.DESTROYED.equals(e.getEventType())) { listener.distributedObjectDestroyed(event); } } @Override public void onListenerRegister() { } };
1no label
hazelcast-client_src_main_java_com_hazelcast_client_spi_ProxyManager.java
2,085
public class PostJoinMapOperation extends AbstractOperation { private List<MapIndexInfo> indexInfoList = new LinkedList<MapIndexInfo>(); private List<InterceptorInfo> interceptorInfoList = new LinkedList<InterceptorInfo>(); @Override public String getServiceName() { return MapService.SERVICE_NAME; } public void addMapIndex(MapContainer mapContainer) { final IndexService indexService = mapContainer.getIndexService(); if (indexService.hasIndex()) { MapIndexInfo mapIndexInfo = new MapIndexInfo(mapContainer.getName()); for (Index index : indexService.getIndexes()) { mapIndexInfo.addIndexInfo(index.getAttributeName(), index.isOrdered()); } indexInfoList.add(mapIndexInfo); } } public void addMapInterceptors(MapContainer mapContainer) { List<MapInterceptor> interceptorList = mapContainer.getInterceptors(); Map<String, MapInterceptor> interceptorMap = mapContainer.getInterceptorMap(); Map<MapInterceptor, String> revMap = new HashMap<MapInterceptor, String>(); for (Map.Entry<String, MapInterceptor> entry : interceptorMap.entrySet()) { revMap.put(entry.getValue(), entry.getKey()); } InterceptorInfo interceptorInfo = new InterceptorInfo(mapContainer.getName()); for (MapInterceptor interceptor : interceptorList) { interceptorInfo.addInterceptor(revMap.get(interceptor), interceptor); } interceptorInfoList.add(interceptorInfo); } static class InterceptorInfo implements DataSerializable { String mapName; final List<Map.Entry<String, MapInterceptor>> interceptors = new LinkedList<Map.Entry<String, MapInterceptor>>(); InterceptorInfo(String mapName) { this.mapName = mapName; } InterceptorInfo() { } void addInterceptor(String id, MapInterceptor interceptor) { interceptors.add(new AbstractMap.SimpleImmutableEntry<String, MapInterceptor>(id, interceptor)); } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(mapName); out.writeInt(interceptors.size()); for (Map.Entry<String, MapInterceptor> entry : interceptors) { out.writeUTF(entry.getKey()); out.writeObject(entry.getValue()); } } @Override public void readData(ObjectDataInput in) throws IOException { mapName = in.readUTF(); int size = in.readInt(); for (int i = 0; i < size; i++) { String id = in.readUTF(); MapInterceptor interceptor = in.readObject(); interceptors.add(new AbstractMap.SimpleImmutableEntry<String, MapInterceptor>(id, interceptor)); } } } static class MapIndexInfo implements DataSerializable { String mapName; private List<MapIndexInfo.IndexInfo> lsIndexes = new LinkedList<MapIndexInfo.IndexInfo>(); public MapIndexInfo(String mapName) { this.mapName = mapName; } public MapIndexInfo() { } static class IndexInfo implements DataSerializable { String attributeName; boolean ordered; IndexInfo() { } IndexInfo(String attributeName, boolean ordered) { this.attributeName = attributeName; this.ordered = ordered; } public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(attributeName); out.writeBoolean(ordered); } public void readData(ObjectDataInput in) throws IOException { attributeName = in.readUTF(); ordered = in.readBoolean(); } } public void addIndexInfo(String attributeName, boolean ordered) { lsIndexes.add(new MapIndexInfo.IndexInfo(attributeName, ordered)); } public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(mapName); out.writeInt(lsIndexes.size()); for (MapIndexInfo.IndexInfo indexInfo : lsIndexes) { indexInfo.writeData(out); } } public void readData(ObjectDataInput in) throws IOException { mapName = in.readUTF(); int size = in.readInt(); for (int i = 0; i < size; i++) { MapIndexInfo.IndexInfo indexInfo = new MapIndexInfo.IndexInfo(); indexInfo.readData(in); lsIndexes.add(indexInfo); } } } @Override public void run() throws Exception { MapService mapService = getService(); for (MapIndexInfo mapIndex : indexInfoList) { final MapContainer mapContainer = mapService.getMapContainer(mapIndex.mapName); final IndexService indexService = mapContainer.getIndexService(); for (MapIndexInfo.IndexInfo indexInfo : mapIndex.lsIndexes) { indexService.addOrGetIndex(indexInfo.attributeName, indexInfo.ordered); } } for (InterceptorInfo interceptorInfo : interceptorInfoList) { final MapContainer mapContainer = mapService.getMapContainer(interceptorInfo.mapName); Map<String, MapInterceptor> interceptorMap = mapContainer.getInterceptorMap(); List<Map.Entry<String, MapInterceptor>> entryList = interceptorInfo.interceptors; for (Map.Entry<String, MapInterceptor> entry : entryList) { if (!interceptorMap.containsKey(entry.getKey())) { mapContainer.addInterceptor(entry.getKey(), entry.getValue()); } } } } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeInt(indexInfoList.size()); for (MapIndexInfo mapIndex : indexInfoList) { mapIndex.writeData(out); } out.writeInt(interceptorInfoList.size()); for (InterceptorInfo interceptorInfo : interceptorInfoList) { interceptorInfo.writeData(out); } } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); int size = in.readInt(); for (int i = 0; i < size; i++) { MapIndexInfo mapIndexInfo = new MapIndexInfo(); mapIndexInfo.readData(in); indexInfoList.add(mapIndexInfo); } int size2 = in.readInt(); for (int i = 0; i < size2; i++) { InterceptorInfo info = new InterceptorInfo(); info.readData(in); interceptorInfoList.add(info); } } }
0true
hazelcast_src_main_java_com_hazelcast_map_operation_PostJoinMapOperation.java
385
public class ClusterUpdateSettingsAction extends ClusterAction<ClusterUpdateSettingsRequest, ClusterUpdateSettingsResponse, ClusterUpdateSettingsRequestBuilder> { public static final ClusterUpdateSettingsAction INSTANCE = new ClusterUpdateSettingsAction(); public static final String NAME = "cluster/settings/update"; private ClusterUpdateSettingsAction() { super(NAME); } @Override public ClusterUpdateSettingsResponse newResponse() { return new ClusterUpdateSettingsResponse(); } @Override public ClusterUpdateSettingsRequestBuilder newRequestBuilder(ClusterAdminClient client) { return new ClusterUpdateSettingsRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_settings_ClusterUpdateSettingsAction.java
1,390
public class OMVRBTreeEntryPersistent<K, V> extends OMVRBTreeEntry<K, V> implements OIdentityChangedListener { protected OMVRBTreeEntryDataProvider<K, V> dataProvider; protected OMVRBTreePersistent<K, V> pTree; protected OMVRBTreeEntryPersistent<K, V> parent; protected OMVRBTreeEntryPersistent<K, V> left; protected OMVRBTreeEntryPersistent<K, V> right; /** * Called upon unmarshalling. * * @param iTree * Tree which belong * @param iParent * Parent node if any * @param iRecordId * Record to unmarshall */ public OMVRBTreeEntryPersistent(final OMVRBTreePersistent<K, V> iTree, final OMVRBTreeEntryPersistent<K, V> iParent, final ORID iRecordId) { super(iTree); pTree = iTree; dataProvider = pTree.dataProvider.getEntry(iRecordId); dataProvider.setIdentityChangedListener(this); init(); parent = iParent; // setParent(iParent); pTree.addNodeInMemory(this); } /** * Make a new cell with given key, value, and parent, and with <tt>null</tt> child links, and BLACK color. */ public OMVRBTreeEntryPersistent(final OMVRBTreePersistent<K, V> iTree, final K iKey, final V iValue, final OMVRBTreeEntryPersistent<K, V> iParent) { super(iTree); pTree = iTree; dataProvider = pTree.dataProvider.createEntry(); dataProvider.setIdentityChangedListener(this); dataProvider.insertAt(0, iKey, iValue); init(); setParent(iParent); pTree.addNodeInMemory(this); // created entry : force dispatch dirty node. markDirty(); } /** * Called on event of splitting an entry. Copy values from the parent node. * * @param iParent * Parent node * @param iPosition * Current position */ public OMVRBTreeEntryPersistent(final OMVRBTreeEntry<K, V> iParent, final int iPosition) { super(((OMVRBTreeEntryPersistent<K, V>) iParent).getTree()); pTree = (OMVRBTreePersistent<K, V>) tree; OMVRBTreeEntryPersistent<K, V> pParent = (OMVRBTreeEntryPersistent<K, V>) iParent; dataProvider = pTree.dataProvider.createEntry(); dataProvider.setIdentityChangedListener(this); dataProvider.copyDataFrom(pParent.dataProvider, iPosition); if (pParent.dataProvider.truncate(iPosition)) pParent.markDirty(); init(); setParent(pParent); pTree.addNodeInMemory(this); // created entry : force dispatch dirty node. markDirty(); } public OMVRBTreeEntryDataProvider<K, V> getProvider() { return dataProvider; } /** * Assures that all the links versus parent, left and right are consistent. * */ public OMVRBTreeEntryPersistent<K, V> save() throws OSerializationException { if (!dataProvider.isEntryDirty()) return this; final boolean isNew = dataProvider.getIdentity().isNew(); // FOR EACH NEW LINK, SAVE BEFORE if (left != null && left.dataProvider.getIdentity().isNew()) { if (isNew) { // TEMPORARY INCORRECT SAVE FOR GETTING AN ID. WILL BE SET DIRTY AGAIN JUST AFTER left.dataProvider.save(); } else left.save(); } if (right != null && right.dataProvider.getIdentity().isNew()) { if (isNew) { // TEMPORARY INCORRECT SAVE FOR GETTING AN ID. WILL BE SET DIRTY AGAIN JUST AFTER right.dataProvider.save(); } else right.save(); } if (parent != null && parent.dataProvider.getIdentity().isNew()) { if (isNew) { // TEMPORARY INCORRECT SAVE FOR GETTING AN ID. WILL BE SET DIRTY AGAIN JUST AFTER parent.dataProvider.save(); } else parent.save(); } dataProvider.save(); // if (parent != null) // if (!parent.record.getIdentity().equals(parentRid)) // OLogManager.instance().error(this, // "[save]: Tree node %s has parentRid '%s' different by the rid of the assigned parent node: %s", record.getIdentity(), // parentRid, parent.record.getIdentity()); checkEntryStructure(); if (pTree.searchNodeInCache(dataProvider.getIdentity()) != this) { // UPDATE THE CACHE pTree.addNodeInMemory(this); } return this; } /** * Delete all the nodes recursively. IF they are not loaded in memory, load all the tree. * * @throws IOException */ public OMVRBTreeEntryPersistent<K, V> delete() throws IOException { if (dataProvider != null) { pTree.removeNodeFromMemory(this); pTree.removeEntry(dataProvider.getIdentity()); // EARLY LOAD LEFT AND DELETE IT RECURSIVELY if (getLeft() != null) ((OMVRBTreeEntryPersistent<K, V>) getLeft()).delete(); // EARLY LOAD RIGHT AND DELETE IT RECURSIVELY if (getRight() != null) ((OMVRBTreeEntryPersistent<K, V>) getRight()).delete(); // DELETE MYSELF dataProvider.removeIdentityChangedListener(this); dataProvider.delete(); clear(); } return this; } /** * Disconnect the current node from others. * * @param iForceDirty * Force disconnection also if the record it's dirty * @param iLevel * @return count of nodes that has been disconnected */ protected int disconnect(final boolean iForceDirty, final int iLevel) { if (dataProvider == null) // DIRTY NODE, JUST REMOVE IT return 1; int totalDisconnected = 0; final ORID rid = dataProvider.getIdentity(); boolean disconnectedFromParent = false; if (parent != null) { // DISCONNECT RECURSIVELY THE PARENT NODE if (canDisconnectFrom(parent) || iForceDirty) { if (parent.left == this) { parent.left = null; } else if (parent.right == this) { parent.right = null; } else OLogManager.instance().warn(this, "Node " + rid + " has the parent (" + parent + ") unlinked to itself. It links to " + parent); totalDisconnected += parent.disconnect(iForceDirty, iLevel + 1); parent = null; disconnectedFromParent = true; } } else { disconnectedFromParent = true; } boolean disconnectedFromLeft = false; if (left != null) { // DISCONNECT RECURSIVELY THE LEFT NODE if (canDisconnectFrom(left) || iForceDirty) { if (left.parent == this) left.parent = null; else OLogManager.instance().warn(this, "Node " + rid + " has the left (" + left + ") unlinked to itself. It links to " + left.parent); totalDisconnected += left.disconnect(iForceDirty, iLevel + 1); left = null; disconnectedFromLeft = true; } } else { disconnectedFromLeft = true; } boolean disconnectedFromRight = false; if (right != null) { // DISCONNECT RECURSIVELY THE RIGHT NODE if (canDisconnectFrom(right) || iForceDirty) { if (right.parent == this) right.parent = null; else OLogManager.instance().warn(this, "Node " + rid + " has the right (" + right + ") unlinked to itself. It links to " + right.parent); totalDisconnected += right.disconnect(iForceDirty, iLevel + 1); right = null; disconnectedFromRight = true; } } else { disconnectedFromLeft = true; } if (disconnectedFromParent && disconnectedFromLeft && disconnectedFromRight) if ((!dataProvider.isEntryDirty() && !dataProvider.getIdentity().isTemporary() || iForceDirty) && !pTree.isNodeEntryPoint(this)) { totalDisconnected++; pTree.removeNodeFromMemory(this); clear(); } return totalDisconnected; } private boolean canDisconnectFrom(OMVRBTreeEntryPersistent<K, V> entry) { return dataProvider == null || !dataProvider.getIdentity().isNew() && !entry.dataProvider.getIdentity().isNew(); } protected void clear() { // SPEED UP MEMORY CLAIM BY RESETTING INTERNAL FIELDS pTree = null; tree = null; dataProvider.removeIdentityChangedListener(this); dataProvider.clear(); dataProvider = null; } /** * Clear links and current node only if it's not an entry point. * * @param iForceDirty * * @param iSource */ protected int disconnectLinked(final boolean iForce) { return disconnect(iForce, 0); } public int getDepthInMemory() { int level = 0; OMVRBTreeEntryPersistent<K, V> entry = this; while (entry.parent != null) { level++; entry = entry.parent; } return level; } @Override public int getDepth() { int level = 0; OMVRBTreeEntryPersistent<K, V> entry = this; while (entry.getParent() != null) { level++; entry = (OMVRBTreeEntryPersistent<K, V>) entry.getParent(); } return level; } @Override public OMVRBTreeEntry<K, V> getParent() { if (dataProvider == null) return null; if (parent == null && dataProvider.getParent().isValid()) { // System.out.println("Node " + record.getIdentity() + " is loading PARENT node " + parentRid + "..."); // LAZY LOADING OF THE PARENT NODE parent = pTree.loadEntry(null, dataProvider.getParent()); checkEntryStructure(); if (parent != null) { // TRY TO ASSIGN IT FOLLOWING THE RID if (parent.dataProvider.getLeft().isValid() && parent.dataProvider.getLeft().equals(dataProvider.getIdentity())) parent.left = this; else if (parent.dataProvider.getRight().isValid() && parent.dataProvider.getRight().equals(dataProvider.getIdentity())) parent.right = this; else { OLogManager.instance().error(this, "getParent: Cannot assign node %s to parent. Nodes parent-left=%s, parent-right=%s", dataProvider.getParent(), parent.dataProvider.getLeft(), parent.dataProvider.getRight()); } } } return parent; } @Override public OMVRBTreeEntry<K, V> setParent(final OMVRBTreeEntry<K, V> iParent) { if (iParent != parent) { OMVRBTreeEntryPersistent<K, V> newParent = (OMVRBTreeEntryPersistent<K, V>) iParent; ORID newParentId = iParent == null ? ORecordId.EMPTY_RECORD_ID : newParent.dataProvider.getIdentity(); parent = newParent; if (dataProvider.setParent(newParentId)) markDirty(); if (parent != null) { ORID thisRid = dataProvider.getIdentity(); if (parent.left == this && !parent.dataProvider.getLeft().equals(thisRid)) if (parent.dataProvider.setLeft(thisRid)) parent.markDirty(); if (parent.left != this && parent.dataProvider.getLeft().isValid() && parent.dataProvider.getLeft().equals(thisRid)) parent.left = this; if (parent.right == this && !parent.dataProvider.getRight().equals(thisRid)) if (parent.dataProvider.setRight(thisRid)) parent.markDirty(); if (parent.right != this && parent.dataProvider.getRight().isValid() && parent.dataProvider.getRight().equals(thisRid)) parent.right = this; } } return iParent; } @Override public OMVRBTreeEntry<K, V> getLeft() { if (dataProvider == null) return null; if (left == null && dataProvider.getLeft().isValid()) { // LAZY LOADING OF THE LEFT LEAF left = pTree.loadEntry(this, dataProvider.getLeft()); checkEntryStructure(); } return left; } @Override public void setLeft(final OMVRBTreeEntry<K, V> iLeft) { if (iLeft != left) { OMVRBTreeEntryPersistent<K, V> newLeft = (OMVRBTreeEntryPersistent<K, V>) iLeft; ORID newLeftId = iLeft == null ? ORecordId.EMPTY_RECORD_ID : newLeft.dataProvider.getIdentity(); left = newLeft; if (dataProvider.setLeft(newLeftId)) markDirty(); if (left != null && left.parent != this) left.setParent(this); checkEntryStructure(); } } @Override public OMVRBTreeEntry<K, V> getRight() { if (dataProvider == null) return null; if (right == null && dataProvider.getRight().isValid()) { // LAZY LOADING OF THE RIGHT LEAF right = pTree.loadEntry(this, dataProvider.getRight()); checkEntryStructure(); } return right; } @Override public void setRight(final OMVRBTreeEntry<K, V> iRight) { if (iRight != right) { OMVRBTreeEntryPersistent<K, V> newRight = (OMVRBTreeEntryPersistent<K, V>) iRight; ORID newRightId = iRight == null ? ORecordId.EMPTY_RECORD_ID : newRight.dataProvider.getIdentity(); right = newRight; if (dataProvider.setRight(newRightId)) markDirty(); if (right != null && right.parent != this) right.setParent(this); checkEntryStructure(); } } public void checkEntryStructure() { if (!tree.isRuntimeCheckEnabled()) return; if (dataProvider.getParent() == null) OLogManager.instance().error(this, "checkEntryStructure: Node %s has parentRid null!\n", this); if (dataProvider.getLeft() == null) OLogManager.instance().error(this, "checkEntryStructure: Node %s has leftRid null!\n", this); if (dataProvider.getRight() == null) OLogManager.instance().error(this, "checkEntryStructure: Node %s has rightRid null!\n", this); if (this == left || dataProvider.getIdentity().isValid() && dataProvider.getIdentity().equals(dataProvider.getLeft())) OLogManager.instance().error(this, "checkEntryStructure: Node %s has left that points to itself!\n", this); if (this == right || dataProvider.getIdentity().isValid() && dataProvider.getIdentity().equals(dataProvider.getRight())) OLogManager.instance().error(this, "checkEntryStructure: Node %s has right that points to itself!\n", this); if (left != null && left == right) OLogManager.instance().error(this, "checkEntryStructure: Node %s has left and right equals!\n", this); if (left != null) { if (!left.dataProvider.getIdentity().equals(dataProvider.getLeft())) OLogManager.instance().error(this, "checkEntryStructure: Wrong left node loaded: " + dataProvider.getLeft()); if (left.parent != this) OLogManager.instance().error(this, "checkEntryStructure: Left node is not correctly connected to the parent" + dataProvider.getLeft()); } if (right != null) { if (!right.dataProvider.getIdentity().equals(dataProvider.getRight())) OLogManager.instance().error(this, "checkEntryStructure: Wrong right node loaded: " + dataProvider.getRight()); if (right.parent != this) OLogManager.instance().error(this, "checkEntryStructure: Right node is not correctly connected to the parent" + dataProvider.getRight()); } } @Override protected void copyFrom(final OMVRBTreeEntry<K, V> iSource) { if (dataProvider.copyFrom(((OMVRBTreeEntryPersistent<K, V>) iSource).dataProvider)) markDirty(); } @Override protected void insert(final int iIndex, final K iKey, final V iValue) { K oldKey = iIndex == 0 ? dataProvider.getKeyAt(0) : null; if (dataProvider.insertAt(iIndex, iKey, iValue)) markDirty(); if (iIndex == 0) pTree.updateEntryPoint(oldKey, this); } @Override protected void remove() { final int index = tree.getPageIndex(); final K oldKey = index == 0 ? getKeyAt(0) : null; if (dataProvider.removeAt(index)) markDirty(); tree.setPageIndex(index - 1); if (index == 0) pTree.updateEntryPoint(oldKey, this); } @Override public K getKeyAt(final int iIndex) { return dataProvider.getKeyAt(iIndex); } @Override protected V getValueAt(final int iIndex) { return dataProvider.getValueAt(iIndex); } /** * Invalidate serialized Value associated in order to be re-marshalled on the next node storing. */ public V setValue(final V iValue) { V oldValue = getValue(); int index = tree.getPageIndex(); if (dataProvider.setValueAt(index, iValue)) markDirty(); return oldValue; } public int getSize() { return dataProvider != null ? dataProvider.getSize() : 0; } public int getPageSize() { return dataProvider.getPageSize(); } public int getMaxDepthInMemory() { return getMaxDepthInMemory(0); } private int getMaxDepthInMemory(final int iCurrDepthLevel) { int depth; if (left != null) // GET THE LEFT'S DEPTH LEVEL AS GOOD depth = left.getMaxDepthInMemory(iCurrDepthLevel + 1); else // GET THE CURRENT DEPTH LEVEL AS GOOD depth = iCurrDepthLevel; if (right != null) { int rightDepth = right.getMaxDepthInMemory(iCurrDepthLevel + 1); if (rightDepth > depth) depth = rightDepth; } return depth; } /** * Returns the successor of the current Entry only by traversing the memory, or null if no such. */ @Override public OMVRBTreeEntryPersistent<K, V> getNextInMemory() { OMVRBTreeEntryPersistent<K, V> t = this; OMVRBTreeEntryPersistent<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; } @Override public boolean getColor() { return dataProvider.getColor(); } @Override protected void setColor(final boolean iColor) { if (dataProvider.setColor(iColor)) markDirty(); } public void markDirty() { pTree.signalNodeChanged(this); } @Override protected OMVRBTreeEntry<K, V> getLeftInMemory() { return left; } @Override protected OMVRBTreeEntry<K, V> getParentInMemory() { return parent; } @Override protected OMVRBTreeEntry<K, V> getRightInMemory() { return right; } public void onIdentityChanged(ORID rid) { if (left != null) { if (left.dataProvider.setParent(rid)) left.markDirty(); } if (right != null) { if (right.dataProvider.setParent(rid)) right.markDirty(); } if (parent != null) { if (parent.left == this) { if (parent.dataProvider.setLeft(rid)) parent.markDirty(); } else if (parent.right == this) { if (parent.dataProvider.setRight(rid)) parent.markDirty(); } else { OLogManager.instance().error(this, "[save]: Tree inconsistent entries."); } } else if (pTree.getRoot() == this) { if (pTree.dataProvider.setRoot(rid)) pTree.markDirty(); } } }
0true
core_src_main_java_com_orientechnologies_orient_core_type_tree_OMVRBTreeEntryPersistent.java
307
public class MergeApplicationContextXmlConfigResource extends MergeXmlConfigResource { private static final Log LOG = LogFactory.getLog(MergeApplicationContextXmlConfigResource.class); /** * Generate a merged configuration resource, loading the definitions from the given streams. Note, * all sourceLocation streams will be merged using standard Spring configuration override rules. However, the patch * streams are fully merged into the result of the sourceLocations simple merge. Patch merges are first executed according * to beans with the same id. Subsequent merges within a bean are executed against tagnames - ignoring any * further id attributes. * * @param sources array of input streams for the source application context files * @param patches array of input streams for the patch application context files * @throws BeansException */ public Resource[] getConfigResources(ResourceInputStream[] sources, ResourceInputStream[] patches) throws BeansException { Resource[] configResources = null; ResourceInputStream merged = null; try { merged = merge(sources); if (patches != null) { ResourceInputStream[] patches2 = new ResourceInputStream[patches.length+1]; patches2[0] = merged; System.arraycopy(patches, 0, patches2, 1, patches.length); merged = merge(patches2); } //read the final stream into a byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); boolean eof = false; while (!eof) { int temp = merged.read(); if (temp == -1) { eof = true; } else { baos.write(temp); } } configResources = new Resource[]{new ByteArrayResource(baos.toByteArray())}; if (LOG.isDebugEnabled()) { LOG.debug("Merged ApplicationContext Including Patches: \n" + serialize(configResources[0])); } } catch (MergeException e) { throw new FatalBeanException("Unable to merge source and patch locations", e); } catch (MergeManagerSetupException e) { throw new FatalBeanException("Unable to merge source and patch locations", e); } catch (IOException e) { throw new FatalBeanException("Unable to merge source and patch locations", e); } finally { if (merged != null) { try{ merged.close(); } catch (Throwable e) { LOG.error("Unable to merge source and patch locations", e); } } } return configResources; } }
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_context_MergeApplicationContextXmlConfigResource.java
1,686
runnable = new Runnable() { public void run() { map.tryPut("key", null, 1, TimeUnit.SECONDS); } };
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
1,787
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class IssuesTest extends HazelcastTestSupport { @Test public void testIssue321_1() throws Exception { int n = 1; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(n); final IMap<Integer, Integer> imap = factory.newHazelcastInstance(null).getMap("testIssue321_1"); final BlockingQueue<EntryEvent<Integer, Integer>> events1 = new LinkedBlockingQueue<EntryEvent<Integer, Integer>>(); final BlockingQueue<EntryEvent<Integer, Integer>> events2 = new LinkedBlockingQueue<EntryEvent<Integer, Integer>>(); imap.addEntryListener(new EntryAdapter<Integer, Integer>() { @Override public void entryAdded(EntryEvent<Integer, Integer> event) { events2.add(event); } }, false); imap.addEntryListener(new EntryAdapter<Integer, Integer>() { @Override public void entryAdded(EntryEvent<Integer, Integer> event) { events1.add(event); } }, true); imap.put(1, 1); final EntryEvent<Integer, Integer> event1 = events1.poll(10, TimeUnit.SECONDS); final EntryEvent<Integer, Integer> event2 = events2.poll(10, TimeUnit.SECONDS); assertNotNull(event1); assertNotNull(event2); assertNotNull(event1.getValue()); assertNull(event2.getValue()); } @Test public void testIssue321_2() throws Exception { int n = 1; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(n); final IMap<Integer, Integer> imap = factory.newHazelcastInstance(null).getMap("testIssue321_2"); final BlockingQueue<EntryEvent<Integer, Integer>> events1 = new LinkedBlockingQueue<EntryEvent<Integer, Integer>>(); final BlockingQueue<EntryEvent<Integer, Integer>> events2 = new LinkedBlockingQueue<EntryEvent<Integer, Integer>>(); imap.addEntryListener(new EntryAdapter<Integer, Integer>() { @Override public void entryAdded(EntryEvent<Integer, Integer> event) { events1.add(event); } }, true); Thread.sleep(50L); imap.addEntryListener(new EntryAdapter<Integer, Integer>() { @Override public void entryAdded(EntryEvent<Integer, Integer> event) { events2.add(event); } }, false); imap.put(1, 1); final EntryEvent<Integer, Integer> event1 = events1.poll(10, TimeUnit.SECONDS); final EntryEvent<Integer, Integer> event2 = events2.poll(10, TimeUnit.SECONDS); assertNotNull(event1); assertNotNull(event2); assertNotNull(event1.getValue()); assertNull(event2.getValue()); } @Test public void testIssue321_3() throws Exception { int n = 1; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(n); final IMap<Integer, Integer> imap = factory.newHazelcastInstance(null).getMap("testIssue321_3"); final BlockingQueue<EntryEvent<Integer, Integer>> events = new LinkedBlockingQueue<EntryEvent<Integer, Integer>>(); final EntryAdapter<Integer, Integer> listener = new EntryAdapter<Integer, Integer>() { @Override public void entryAdded(EntryEvent<Integer, Integer> event) { events.add(event); } }; imap.addEntryListener(listener, true); Thread.sleep(50L); imap.addEntryListener(listener, false); imap.put(1, 1); final EntryEvent<Integer, Integer> event1 = events.poll(10, TimeUnit.SECONDS); final EntryEvent<Integer, Integer> event2 = events.poll(10, TimeUnit.SECONDS); assertNotNull(event1); assertNotNull(event2); assertNotNull(event1.getValue()); assertNull(event2.getValue()); } @Test public void testIssue304() { int n = 1; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(n); IMap<String, String> map = factory.newHazelcastInstance(null).getMap("testIssue304"); map.lock("1"); assertEquals(0, map.size()); assertEquals(0, map.entrySet().size()); map.put("1", "value"); assertEquals(1, map.size()); assertEquals(1, map.entrySet().size()); map.unlock("1"); assertEquals(1, map.size()); assertEquals(1, map.entrySet().size()); map.remove("1"); assertEquals(0, map.size()); assertEquals(0, map.entrySet().size()); } /* github issue 174 */ @Test public void testIssue174NearCacheContainsKeySingleNode() { int n = 1; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(n); Config config = new Config(); config.getGroupConfig().setName("testIssue174NearCacheContainsKeySingleNode"); NearCacheConfig nearCacheConfig = new NearCacheConfig(); config.getMapConfig("default").setNearCacheConfig(nearCacheConfig); HazelcastInstance h = factory.newHazelcastInstance(config); IMap<String, String> map = h.getMap("testIssue174NearCacheContainsKeySingleNode"); map.put("key", "value"); assertTrue(map.containsKey("key")); h.shutdown(); } @Test public void testIssue1067GlobalSerializer() { TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2); final Config config = new Config(); config.getSerializationConfig().setGlobalSerializerConfig(new GlobalSerializerConfig() .setImplementation(new StreamSerializer() { public void write(ObjectDataOutput out, Object object) throws IOException { } public Object read(ObjectDataInput in) throws IOException { return new DummyValue(); } public int getTypeId() { return 123; } public void destroy() { } })); HazelcastInstance hz = factory.newHazelcastInstance(config); IMap<Object, Object> map = hz.getMap("test"); for (int i = 0; i < 10; i++) { map.put(i, new DummyValue()); } assertEquals(10, map.size()); HazelcastInstance hz2 = factory.newHazelcastInstance(config); IMap<Object, Object> map2 = hz2.getMap("test"); assertEquals(10, map2.size()); assertEquals(10, map.size()); for (int i = 0; i < 10; i++) { Object o = map2.get(i); assertNotNull(o); assertTrue(o instanceof DummyValue); } } private static class DummyValue { } @Test public void testMapInterceptorInstanceAware() { TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2); HazelcastInstance hz1 = factory.newHazelcastInstance(); HazelcastInstance hz2 = factory.newHazelcastInstance(); IMap<Object, Object> map = hz1.getMap("test"); InstanceAwareMapInterceptorImpl interceptor = new InstanceAwareMapInterceptorImpl(); map.addInterceptor(interceptor); assertNotNull(interceptor.hazelcastInstance); assertEquals(hz1, interceptor.hazelcastInstance); for (int i = 0; i < 100; i++) { map.put(i, i); } for (int i = 0; i < 100; i++) { assertEquals("notNull", map.get(i)); } } static class InstanceAwareMapInterceptorImpl implements MapInterceptor, HazelcastInstanceAware { transient HazelcastInstance hazelcastInstance; @Override public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { this.hazelcastInstance = hazelcastInstance; } @Override public Object interceptGet(Object value) { return null; } @Override public void afterGet(Object value) { } @Override public Object interceptPut(Object oldValue, Object newValue) { if (hazelcastInstance != null) { return "notNull"; } return ">null"; } @Override public void afterPut(Object value) { } @Override public Object interceptRemove(Object removedValue) { return null; } @Override public void afterRemove(Object value) { } } @Test // Issue #1795 public void testMapClearDoesNotTriggerEqualsOrHashCodeOnKeyObject() { int n = 1; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(n); final HazelcastInstance instance = factory.newHazelcastInstance(); final IMap map = instance.getMap(randomString()); final CompositeKey key = new CompositeKey(); map.put(key, "value"); map.clear(); assertFalse("hashCode method should not have been called on key during clear", CompositeKey.hashCodeCalled); assertFalse("equals method should not have been called on key during clear", CompositeKey.equalsCalled); } public static class CompositeKey implements Serializable { static boolean hashCodeCalled = false; static boolean equalsCalled = false; @Override public int hashCode() { hashCodeCalled = true; return super.hashCode(); } @Override public boolean equals(Object o) { equalsCalled = true; return super.equals(o); } } }
0true
hazelcast_src_test_java_com_hazelcast_map_IssuesTest.java
843
TRANSIENT("Transient", 18, new Class<?>[] {}, new Class<?>[] {}) { },
0true
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OType.java
1,253
@Deprecated public interface ShippingModule { public String getName(); public void setName(String name); public FulfillmentGroup calculateShippingForFulfillmentGroup(FulfillmentGroup fulfillmentGroup) throws FulfillmentPriceException; public String getServiceName(); public Boolean isValidModuleForService(String serviceName); public void setDefaultModule(Boolean isDefaultModule); public Boolean isDefaultModule(); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_service_module_ShippingModule.java
2,837
final class PartitionReplicaVersions { final int partitionId; // read and updated only by operation/partition threads final long[] versions = new long[InternalPartition.MAX_BACKUP_COUNT]; PartitionReplicaVersions(int partitionId) { this.partitionId = partitionId; } long[] incrementAndGet(int backupCount) { for (int i = 0; i < backupCount; i++) { versions[i]++; } return versions; } long[] get() { return versions; } boolean update(long[] newVersions, int currentReplica) { int index = currentReplica - 1; long current = versions[index]; long next = newVersions[index]; boolean updated = (current == next - 1); if (updated) { arraycopy(newVersions, 0, versions, 0, newVersions.length); } return updated; } void reset(long[] newVersions) { arraycopy(newVersions, 0, versions, 0, newVersions.length); } void clear() { for (int i = 0; i < versions.length; i++) { versions[i] = 0; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("PartitionReplicaVersions"); sb.append("{partitionId=").append(partitionId); sb.append(", versions=").append(Arrays.toString(versions)); sb.append('}'); return sb.toString(); } }
1no label
hazelcast_src_main_java_com_hazelcast_partition_impl_PartitionReplicaVersions.java
687
@Entity @Polymorphism(type = PolymorphismType.EXPLICIT) @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_CATEGORY_XREF") @AdminPresentationClass(excludeFromPolymorphism = false) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") public class CategoryXrefImpl implements CategoryXref { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** The category id. */ @EmbeddedId CategoryXrefPK categoryXrefPK = new CategoryXrefPK(); public CategoryXrefPK getCategoryXrefPK() { return categoryXrefPK; } public void setCategoryXrefPK(final CategoryXrefPK categoryXrefPK) { this.categoryXrefPK = categoryXrefPK; } @Column(name = "DISPLAY_ORDER") @AdminPresentation(visibility = VisibilityEnum.HIDDEN_ALL) protected Long displayOrder; public Long getDisplayOrder() { return displayOrder; } public void setDisplayOrder(final Long displayOrder) { this.displayOrder = displayOrder; } /** * @return * @see org.broadleafcommerce.core.catalog.domain.CategoryXrefImpl.CategoryXrefPK#getCategory() */ public Category getCategory() { return categoryXrefPK.getCategory(); } /** * @param category * @see org.broadleafcommerce.core.catalog.domain.CategoryXrefImpl.CategoryXrefPK#setCategory(org.broadleafcommerce.core.catalog.domain.Category) */ public void setCategory(Category category) { categoryXrefPK.setCategory(category); } /** * @return * @see org.broadleafcommerce.core.catalog.domain.CategoryXrefImpl.CategoryXrefPK#getSubCategory() */ public Category getSubCategory() { return categoryXrefPK.getSubCategory(); } /** * @param subCategory * @see org.broadleafcommerce.core.catalog.domain.CategoryXrefImpl.CategoryXrefPK#setSubCategory(org.broadleafcommerce.core.catalog.domain.Category) */ public void setSubCategory(Category subCategory) { categoryXrefPK.setSubCategory(subCategory); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CategoryXrefImpl)) return false; CategoryXrefImpl that = (CategoryXrefImpl) o; if (categoryXrefPK != null ? !categoryXrefPK.equals(that.categoryXrefPK) : that.categoryXrefPK != null) return false; if (displayOrder != null ? !displayOrder.equals(that.displayOrder) : that.displayOrder != null) return false; return true; } @Override public int hashCode() { int result = categoryXrefPK != null ? categoryXrefPK.hashCode() : 0; result = 31 * result + (displayOrder != null ? displayOrder.hashCode() : 0); return result; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_CategoryXrefImpl.java
1,534
public class OMetadataObject implements OMetadata { protected OMetadata underlying; protected OSchemaProxyObject schema; public OMetadataObject(OMetadata iUnderlying) { underlying = iUnderlying; } public OMetadataObject(OMetadata iUnderlying, OSchemaProxyObject iSchema) { underlying = iUnderlying; schema = iSchema; } @Override public void load() { underlying.load(); } @Override public void create() throws IOException { underlying.create(); } @Override public OSchemaProxyObject getSchema() { if (schema == null) schema = new OSchemaProxyObject(underlying.getSchema()); return schema; } @Override public OSecurity getSecurity() { return underlying.getSecurity(); } @Override public OIndexManagerProxy getIndexManager() { return underlying.getIndexManager(); } @Override public int getSchemaClusterId() { return underlying.getSchemaClusterId(); } @Override public void reload() { underlying.reload(); } @Override public void close() { underlying.close(); } @Override public OFunctionLibrary getFunctionLibrary() { return underlying.getFunctionLibrary(); } @Override public OSchedulerListener getSchedulerListener() { return underlying.getSchedulerListener(); } public OMetadata getUnderlying() { return underlying; } }
0true
object_src_main_java_com_orientechnologies_orient_object_metadata_OMetadataObject.java
1
public class CassandraStorageSetup { public static final String CONFDIR_SYSPROP = "test.cassandra.confdir"; public static final String DATADIR_SYSPROP = "test.cassandra.datadir"; private static volatile Paths paths; private static final Logger log = LoggerFactory.getLogger(CassandraStorageSetup.class); private static synchronized Paths getPaths() { if (null == paths) { String yamlPath = "file://" + loadAbsoluteDirectoryPath("conf", CONFDIR_SYSPROP, true) + File.separator + "cassandra.yaml"; String dataPath = loadAbsoluteDirectoryPath("data", DATADIR_SYSPROP, false); paths = new Paths(yamlPath, dataPath); } return paths; } private static ModifiableConfiguration getGenericConfiguration(String ks, String backend) { ModifiableConfiguration config = buildConfiguration(); config.set(CASSANDRA_KEYSPACE, cleanKeyspaceName(ks)); log.debug("Set keyspace name: {}", config.get(CASSANDRA_KEYSPACE)); config.set(PAGE_SIZE,500); config.set(CONNECTION_TIMEOUT, new StandardDuration(60L, TimeUnit.SECONDS)); config.set(STORAGE_BACKEND, backend); return config; } public static ModifiableConfiguration getEmbeddedConfiguration(String ks) { ModifiableConfiguration config = getGenericConfiguration(ks, "embeddedcassandra"); config.set(STORAGE_CONF_FILE, getPaths().yamlPath); return config; } public static ModifiableConfiguration getEmbeddedCassandraPartitionConfiguration(String ks) { ModifiableConfiguration config = getEmbeddedConfiguration(ks); config.set(CLUSTER_PARTITION, true); config.set(IDS_FLUSH,false); return config; } public static WriteConfiguration getEmbeddedGraphConfiguration(String ks) { return getEmbeddedConfiguration(ks).getConfiguration(); } public static WriteConfiguration getEmbeddedCassandraPartitionGraphConfiguration(String ks) { return getEmbeddedConfiguration(ks).getConfiguration(); } public static ModifiableConfiguration getAstyanaxConfiguration(String ks) { return getGenericConfiguration(ks, "astyanax"); } public static ModifiableConfiguration getAstyanaxSSLConfiguration(String ks) { return enableSSL(getGenericConfiguration(ks, "astyanax")); } public static WriteConfiguration getAstyanaxGraphConfiguration(String ks) { return getAstyanaxConfiguration(ks).getConfiguration(); } public static ModifiableConfiguration getCassandraConfiguration(String ks) { return getGenericConfiguration(ks, "cassandra"); } public static WriteConfiguration getCassandraGraphConfiguration(String ks) { return getCassandraConfiguration(ks).getConfiguration(); } public static ModifiableConfiguration getCassandraThriftConfiguration(String ks) { return getGenericConfiguration(ks, "cassandrathrift"); } public static ModifiableConfiguration getCassandraThriftSSLConfiguration(String ks) { return enableSSL(getGenericConfiguration(ks, "cassandrathrift")); } public static WriteConfiguration getCassandraThriftGraphConfiguration(String ks) { return getCassandraThriftConfiguration(ks).getConfiguration(); } /** * Load cassandra.yaml and data paths from the environment or from default * values if nothing is set in the environment, then delete all existing * data, and finally start Cassandra. * <p> * This method is idempotent. Calls after the first have no effect aside * from logging statements. */ public static void startCleanEmbedded() { startCleanEmbedded(getPaths()); } /* * Cassandra only accepts keyspace names 48 characters long or shorter made * up of alphanumeric characters and underscores. */ public static String cleanKeyspaceName(String raw) { Preconditions.checkNotNull(raw); Preconditions.checkArgument(0 < raw.length()); if (48 < raw.length() || raw.matches("[^a-zA-Z_]")) { return "strhash" + String.valueOf(Math.abs(raw.hashCode())); } else { return raw; } } private static ModifiableConfiguration enableSSL(ModifiableConfiguration mc) { mc.set(AbstractCassandraStoreManager.SSL_ENABLED, true); mc.set(STORAGE_HOSTS, new String[]{ "localhost" }); mc.set(AbstractCassandraStoreManager.SSL_TRUSTSTORE_LOCATION, Joiner.on(File.separator).join("target", "cassandra", "conf", "localhost-murmur-ssl", "test.truststore")); mc.set(AbstractCassandraStoreManager.SSL_TRUSTSTORE_PASSWORD, "cassandra"); return mc; } private static void startCleanEmbedded(Paths p) { if (!CassandraDaemonWrapper.isStarted()) { try { FileUtils.deleteDirectory(new File(p.dataPath)); } catch (IOException e) { throw new RuntimeException(e); } } CassandraDaemonWrapper.start(p.yamlPath); } private static String loadAbsoluteDirectoryPath(String name, String prop, boolean mustExistAndBeAbsolute) { String s = System.getProperty(prop); if (null == s) { s = Joiner.on(File.separator).join(System.getProperty("user.dir"), "target", "cassandra", name, "localhost-bop"); log.info("Set default Cassandra {} directory path {}", name, s); } else { log.info("Loaded Cassandra {} directory path {} from system property {}", new Object[] { name, s, prop }); } if (mustExistAndBeAbsolute) { File dir = new File(s); Preconditions.checkArgument(dir.isDirectory(), "Path %s must be a directory", s); Preconditions.checkArgument(dir.isAbsolute(), "Path %s must be absolute", s); } return s; } private static class Paths { private final String yamlPath; private final String dataPath; public Paths(String yamlPath, String dataPath) { this.yamlPath = yamlPath; this.dataPath = dataPath; } } }
0true
titan-cassandra_src_test_java_com_thinkaurelius_titan_CassandraStorageSetup.java
3,225
return new IndexFieldData<AtomicFieldData<ScriptDocValues>>() { @Override public Index index() { return in.index(); } @Override public Names getFieldNames() { return in.getFieldNames(); } @Override public boolean valuesOrdered() { return in.valuesOrdered(); } @Override public AtomicFieldData<ScriptDocValues> load(AtomicReaderContext context) { return in.load(context); } @Override public AtomicFieldData<ScriptDocValues> loadDirect(AtomicReaderContext context) throws Exception { return in.loadDirect(context); } @Override public XFieldComparatorSource comparatorSource(Object missingValue, SortMode sortMode) { return new BytesRefFieldComparatorSource(this, missingValue, sortMode); } @Override public void clear() { in.clear(); } @Override public void clear(IndexReader reader) { in.clear(reader); } };
0true
src_test_java_org_elasticsearch_index_fielddata_NoOrdinalsStringFieldDataTests.java
161
private class Itr extends AbstractItr { Node<E> startNode() { return first(); } Node<E> nextNode(Node<E> p) { return succ(p); } }
0true
src_main_java_jsr166y_ConcurrentLinkedDeque.java
682
public static class Order { public static final int Marketing = 2000; public static final int Media = 3000; public static final int Advanced = 4000; public static final int Products = 5000; public static final int SearchFacets = 3500; }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_CategoryImpl.java
3,734
public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { Map<String, Object> objectNode = node; ObjectMapper.Builder builder = createBuilder(name); boolean nested = false; boolean nestedIncludeInParent = false; boolean nestedIncludeInRoot = false; for (Map.Entry<String, Object> entry : objectNode.entrySet()) { String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("dynamic")) { String value = fieldNode.toString(); if (value.equalsIgnoreCase("strict")) { builder.dynamic(Dynamic.STRICT); } else { builder.dynamic(nodeBooleanValue(fieldNode) ? Dynamic.TRUE : Dynamic.FALSE); } } else if (fieldName.equals("type")) { String type = fieldNode.toString(); if (type.equals(CONTENT_TYPE)) { builder.nested = Nested.NO; } else if (type.equals(NESTED_CONTENT_TYPE)) { nested = true; } else { throw new MapperParsingException("Trying to parse an object but has a different type [" + type + "] for [" + name + "]"); } } else if (fieldName.equals("include_in_parent")) { nestedIncludeInParent = nodeBooleanValue(fieldNode); } else if (fieldName.equals("include_in_root")) { nestedIncludeInRoot = nodeBooleanValue(fieldNode); } else if (fieldName.equals("enabled")) { builder.enabled(nodeBooleanValue(fieldNode)); } else if (fieldName.equals("path")) { builder.pathType(parsePathType(name, fieldNode.toString())); } else if (fieldName.equals("properties")) { parseProperties(builder, (Map<String, Object>) fieldNode, parserContext); } else if (fieldName.equals("include_in_all")) { builder.includeInAll(nodeBooleanValue(fieldNode)); } else { processField(builder, fieldName, fieldNode); } } if (nested) { builder.nested = Nested.newNested(nestedIncludeInParent, nestedIncludeInRoot); } return builder; } private void parseProperties(ObjectMapper.Builder objBuilder, Map<String, Object> propsNode, ParserContext parserContext) { for (Map.Entry<String, Object> entry : propsNode.entrySet()) { String propName = entry.getKey(); Map<String, Object> propNode = (Map<String, Object>) entry.getValue(); String type; Object typeNode = propNode.get("type"); if (typeNode != null) { type = typeNode.toString(); } else { // lets see if we can derive this... if (propNode.get("properties") != null) { type = ObjectMapper.CONTENT_TYPE; } else if (propNode.size() == 1 && propNode.get("enabled") != null) { // if there is a single property with the enabled flag on it, make it an object // (usually, setting enabled to false to not index any type, including core values, which // non enabled object type supports). type = ObjectMapper.CONTENT_TYPE; } else { throw new MapperParsingException("No type specified for property [" + propName + "]"); } } Mapper.TypeParser typeParser = parserContext.typeParser(type); if (typeParser == null) { throw new MapperParsingException("No handler for type [" + type + "] declared on field [" + propName + "]"); } objBuilder.add(typeParser.parse(propName, propNode, parserContext)); } } protected Builder createBuilder(String name) { return object(name); } protected void processField(Builder builder, String fieldName, Object fieldNode) { } }
1no label
src_main_java_org_elasticsearch_index_mapper_object_ObjectMapper.java
1,427
clusterService.submitStateUpdateTask("put-mapping [" + request.type() + "]", Priority.HIGH, new AckedClusterStateUpdateTask() { @Override public boolean mustAck(DiscoveryNode discoveryNode) { return true; } @Override public void onAllNodesAcked(@Nullable Throwable t) { listener.onResponse(new ClusterStateUpdateResponse(true)); } @Override public void onAckTimeout() { listener.onResponse(new ClusterStateUpdateResponse(false)); } @Override public TimeValue ackTimeout() { return request.ackTimeout(); } @Override public TimeValue timeout() { return request.masterNodeTimeout(); } @Override public void onFailure(String source, Throwable t) { listener.onFailure(t); } @Override public ClusterState execute(final ClusterState currentState) throws Exception { List<String> indicesToClose = Lists.newArrayList(); try { for (String index : request.indices()) { if (!currentState.metaData().hasIndex(index)) { throw new IndexMissingException(new Index(index)); } } // pre create indices here and add mappings to them so we can merge the mappings here if needed for (String index : request.indices()) { if (indicesService.hasIndex(index)) { continue; } final IndexMetaData indexMetaData = currentState.metaData().index(index); IndexService indexService = indicesService.createIndex(indexMetaData.index(), indexMetaData.settings(), clusterService.localNode().id()); indicesToClose.add(indexMetaData.index()); // make sure to add custom default mapping if exists if (indexMetaData.mappings().containsKey(MapperService.DEFAULT_MAPPING)) { indexService.mapperService().merge(MapperService.DEFAULT_MAPPING, indexMetaData.mappings().get(MapperService.DEFAULT_MAPPING).source(), false); } // only add the current relevant mapping (if exists) if (indexMetaData.mappings().containsKey(request.type())) { indexService.mapperService().merge(request.type(), indexMetaData.mappings().get(request.type()).source(), false); } } Map<String, DocumentMapper> newMappers = newHashMap(); Map<String, DocumentMapper> existingMappers = newHashMap(); for (String index : request.indices()) { IndexService indexService = indicesService.indexService(index); if (indexService != null) { // try and parse it (no need to add it here) so we can bail early in case of parsing exception DocumentMapper newMapper; DocumentMapper existingMapper = indexService.mapperService().documentMapper(request.type()); if (MapperService.DEFAULT_MAPPING.equals(request.type())) { // _default_ types do not go through merging, but we do test the new settings. Also don't apply the old default newMapper = indexService.mapperService().parse(request.type(), new CompressedString(request.source()), false); } else { newMapper = indexService.mapperService().parse(request.type(), new CompressedString(request.source())); if (existingMapper != null) { // first, simulate DocumentMapper.MergeResult mergeResult = existingMapper.merge(newMapper, mergeFlags().simulate(true)); // if we have conflicts, and we are not supposed to ignore them, throw an exception if (!request.ignoreConflicts() && mergeResult.hasConflicts()) { throw new MergeMappingException(mergeResult.conflicts()); } } } newMappers.put(index, newMapper); if (existingMapper != null) { existingMappers.put(index, existingMapper); } } else { throw new IndexMissingException(new Index(index)); } } String mappingType = request.type(); if (mappingType == null) { mappingType = newMappers.values().iterator().next().type(); } else if (!mappingType.equals(newMappers.values().iterator().next().type())) { throw new InvalidTypeNameException("Type name provided does not match type name within mapping definition"); } if (!MapperService.DEFAULT_MAPPING.equals(mappingType) && !PercolatorService.TYPE_NAME.equals(mappingType) && mappingType.charAt(0) == '_') { throw new InvalidTypeNameException("Document mapping type name can't start with '_'"); } final Map<String, MappingMetaData> mappings = newHashMap(); for (Map.Entry<String, DocumentMapper> entry : newMappers.entrySet()) { String index = entry.getKey(); // do the actual merge here on the master, and update the mapping source DocumentMapper newMapper = entry.getValue(); IndexService indexService = indicesService.indexService(index); CompressedString existingSource = null; if (existingMappers.containsKey(entry.getKey())) { existingSource = existingMappers.get(entry.getKey()).mappingSource(); } DocumentMapper mergedMapper = indexService.mapperService().merge(newMapper.type(), newMapper.mappingSource(), false); CompressedString updatedSource = mergedMapper.mappingSource(); if (existingSource != null) { if (existingSource.equals(updatedSource)) { // same source, no changes, ignore it } else { // use the merged mapping source mappings.put(index, new MappingMetaData(mergedMapper)); if (logger.isDebugEnabled()) { logger.debug("[{}] update_mapping [{}] with source [{}]", index, mergedMapper.type(), updatedSource); } else if (logger.isInfoEnabled()) { logger.info("[{}] update_mapping [{}]", index, mergedMapper.type()); } } } else { mappings.put(index, new MappingMetaData(mergedMapper)); if (logger.isDebugEnabled()) { logger.debug("[{}] create_mapping [{}] with source [{}]", index, newMapper.type(), updatedSource); } else if (logger.isInfoEnabled()) { logger.info("[{}] create_mapping [{}]", index, newMapper.type()); } } } if (mappings.isEmpty()) { // no changes, return return currentState; } MetaData.Builder builder = MetaData.builder(currentState.metaData()); for (String indexName : request.indices()) { IndexMetaData indexMetaData = currentState.metaData().index(indexName); if (indexMetaData == null) { throw new IndexMissingException(new Index(indexName)); } MappingMetaData mappingMd = mappings.get(indexName); if (mappingMd != null) { builder.put(IndexMetaData.builder(indexMetaData).putMapping(mappingMd)); } } return ClusterState.builder(currentState).metaData(builder).build(); } finally { for (String index : indicesToClose) { indicesService.removeIndex(index, "created for mapping processing"); } } } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { } });
0true
src_main_java_org_elasticsearch_cluster_metadata_MetaDataMappingService.java
962
@Test public class NothingCompressionTest extends AbstractCompressionTest { public void testNothingCompression() { testCompression(ONothingCompression.NAME); } }
0true
core_src_test_java_com_orientechnologies_orient_core_serialization_compression_impl_NothingCompressionTest.java
113
HazelcastTestSupport.assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { final NearCacheStats stats = map.getLocalMapStats().getNearCacheStats(); assertEquals(remainingSize, stats.getOwnedEntryCount()); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_ClientNearCacheTest.java
1,801
class BindingProcessor extends AbstractProcessor { private final List<CreationListener> creationListeners = Lists.newArrayList(); private final Initializer initializer; private final List<Runnable> uninitializedBindings = Lists.newArrayList(); BindingProcessor(Errors errors, Initializer initializer) { super(errors); this.initializer = initializer; } @Override public <T> Boolean visit(Binding<T> command) { final Object source = command.getSource(); if (Void.class.equals(command.getKey().getRawType())) { if (command instanceof ProviderInstanceBinding && ((ProviderInstanceBinding) command).getProviderInstance() instanceof ProviderMethod) { errors.voidProviderMethod(); } else { errors.missingConstantValues(); } return true; } final Key<T> key = command.getKey(); Class<? super T> rawType = key.getTypeLiteral().getRawType(); if (rawType == Provider.class) { errors.bindingToProvider(); return true; } validateKey(command.getSource(), command.getKey()); final Scoping scoping = Scopes.makeInjectable( ((BindingImpl<?>) command).getScoping(), injector, errors); command.acceptTargetVisitor(new BindingTargetVisitor<T, Void>() { public Void visit(InstanceBinding<? extends T> binding) { Set<InjectionPoint> injectionPoints = binding.getInjectionPoints(); T instance = binding.getInstance(); Initializable<T> ref = initializer.requestInjection( injector, instance, source, injectionPoints); ConstantFactory<? extends T> factory = new ConstantFactory<T>(ref); InternalFactory<? extends T> scopedFactory = Scopes.scope(key, injector, factory, scoping); putBinding(new InstanceBindingImpl<T>(injector, key, source, scopedFactory, injectionPoints, instance)); return null; } public Void visit(ProviderInstanceBinding<? extends T> binding) { Provider<? extends T> provider = binding.getProviderInstance(); Set<InjectionPoint> injectionPoints = binding.getInjectionPoints(); Initializable<Provider<? extends T>> initializable = initializer .<Provider<? extends T>>requestInjection(injector, provider, source, injectionPoints); InternalFactory<T> factory = new InternalFactoryToProviderAdapter<T>(initializable, source); InternalFactory<? extends T> scopedFactory = Scopes.scope(key, injector, factory, scoping); putBinding(new ProviderInstanceBindingImpl<T>(injector, key, source, scopedFactory, scoping, provider, injectionPoints)); return null; } public Void visit(ProviderKeyBinding<? extends T> binding) { Key<? extends Provider<? extends T>> providerKey = binding.getProviderKey(); BoundProviderFactory<T> boundProviderFactory = new BoundProviderFactory<T>(injector, providerKey, source); creationListeners.add(boundProviderFactory); InternalFactory<? extends T> scopedFactory = Scopes.scope( key, injector, (InternalFactory<? extends T>) boundProviderFactory, scoping); putBinding(new LinkedProviderBindingImpl<T>( injector, key, source, scopedFactory, scoping, providerKey)); return null; } public Void visit(LinkedKeyBinding<? extends T> binding) { Key<? extends T> linkedKey = binding.getLinkedKey(); if (key.equals(linkedKey)) { errors.recursiveBinding(); } FactoryProxy<T> factory = new FactoryProxy<T>(injector, key, linkedKey, source); creationListeners.add(factory); InternalFactory<? extends T> scopedFactory = Scopes.scope(key, injector, factory, scoping); putBinding( new LinkedBindingImpl<T>(injector, key, source, scopedFactory, scoping, linkedKey)); return null; } public Void visit(UntargettedBinding<? extends T> untargetted) { // Error: Missing implementation. // Example: bind(Date.class).annotatedWith(Red.class); // We can't assume abstract types aren't injectable. They may have an // @ImplementedBy annotation or something. if (key.hasAnnotationType()) { errors.missingImplementation(key); putBinding(invalidBinding(injector, key, source)); return null; } // This cast is safe after the preceeding check. final BindingImpl<T> binding; try { binding = injector.createUnitializedBinding(key, scoping, source, errors); putBinding(binding); } catch (ErrorsException e) { errors.merge(e.getErrors()); putBinding(invalidBinding(injector, key, source)); return null; } uninitializedBindings.add(new Runnable() { public void run() { try { ((InjectorImpl) binding.getInjector()).initializeBinding( binding, errors.withSource(source)); } catch (ErrorsException e) { errors.merge(e.getErrors()); } } }); return null; } public Void visit(ExposedBinding<? extends T> binding) { throw new IllegalArgumentException("Cannot apply a non-module element"); } public Void visit(ConvertedConstantBinding<? extends T> binding) { throw new IllegalArgumentException("Cannot apply a non-module element"); } public Void visit(ConstructorBinding<? extends T> binding) { throw new IllegalArgumentException("Cannot apply a non-module element"); } public Void visit(ProviderBinding<? extends T> binding) { throw new IllegalArgumentException("Cannot apply a non-module element"); } }); return true; } @Override public Boolean visit(PrivateElements privateElements) { for (Key<?> key : privateElements.getExposedKeys()) { bindExposed(privateElements, key); } return false; // leave the private elements for the PrivateElementsProcessor to handle } private <T> void bindExposed(PrivateElements privateElements, Key<T> key) { ExposedKeyFactory<T> exposedKeyFactory = new ExposedKeyFactory<T>(key, privateElements); creationListeners.add(exposedKeyFactory); putBinding(new ExposedBindingImpl<T>( injector, privateElements.getExposedSource(key), key, exposedKeyFactory, privateElements)); } private <T> void validateKey(Object source, Key<T> key) { Annotations.checkForMisplacedScopeAnnotations(key.getRawType(), source, errors); } <T> UntargettedBindingImpl<T> invalidBinding(InjectorImpl injector, Key<T> key, Object source) { return new UntargettedBindingImpl<T>(injector, key, source); } public void initializeBindings() { for (Runnable initializer : uninitializedBindings) { initializer.run(); } } public void runCreationListeners() { for (CreationListener creationListener : creationListeners) { creationListener.notify(errors); } } private void putBinding(BindingImpl<?> binding) { Key<?> key = binding.getKey(); Class<?> rawType = key.getRawType(); if (FORBIDDEN_TYPES.contains(rawType)) { errors.cannotBindToGuiceType(rawType.getSimpleName()); return; } Binding<?> original = injector.state.getExplicitBinding(key); if (original != null && !isOkayDuplicate(original, binding)) { errors.bindingAlreadySet(key, original.getSource()); return; } // prevent the parent from creating a JIT binding for this key injector.state.parent().blacklist(key); injector.state.putBinding(key, binding); } /** * We tolerate duplicate bindings only if one exposes the other. * * @param original the binding in the parent injector (candidate for an exposing binding) * @param binding the binding to check (candidate for the exposed binding) */ private boolean isOkayDuplicate(Binding<?> original, BindingImpl<?> binding) { if (original instanceof ExposedBindingImpl) { ExposedBindingImpl exposed = (ExposedBindingImpl) original; InjectorImpl exposedFrom = (InjectorImpl) exposed.getPrivateElements().getInjector(); return (exposedFrom == binding.getInjector()); } return false; } // It's unfortunate that we have to maintain a blacklist of specific // classes, but we can't easily block the whole package because of // all our unit tests. private static final Set<Class<?>> FORBIDDEN_TYPES = ImmutableSet.of( AbstractModule.class, Binder.class, Binding.class, Injector.class, Key.class, MembersInjector.class, Module.class, Provider.class, Scope.class, TypeLiteral.class); // TODO(jessewilson): fix BuiltInModule, then add Stage interface CreationListener { void notify(Errors errors); } }
0true
src_main_java_org_elasticsearch_common_inject_BindingProcessor.java
843
public class AlterAndGetRequest extends AbstractAlterRequest { public AlterAndGetRequest() { } public AlterAndGetRequest(String name, Data function) { super(name, function); } @Override protected Operation prepareOperation() { return new AlterAndGetOperation(name, function); } @Override public int getClassId() { return AtomicReferencePortableHook.ALTER_AND_GET; } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_AlterAndGetRequest.java
960
@Repository("blOrderItemDao") public class OrderItemDaoImpl implements OrderItemDao { @PersistenceContext(unitName="blPU") protected EntityManager em; @Resource(name="blEntityConfiguration") protected EntityConfiguration entityConfiguration; public OrderItem save(final OrderItem orderItem) { return em.merge(orderItem); } public OrderItem readOrderItemById(final Long orderItemId) { return em.find(OrderItemImpl.class, orderItemId); } public void delete(OrderItem orderItem) { if (!em.contains(orderItem)) { orderItem = readOrderItemById(orderItem.getId()); } if (GiftWrapOrderItem.class.isAssignableFrom(orderItem.getClass())) { final GiftWrapOrderItem giftItem = (GiftWrapOrderItem) orderItem; for (OrderItem wrappedItem : giftItem.getWrappedItems()) { wrappedItem.setGiftWrapOrderItem(null); wrappedItem = save(wrappedItem); } } em.remove(orderItem); em.flush(); } public OrderItem create(final OrderItemType orderItemType) { final OrderItem item = (OrderItem) entityConfiguration.createEntityInstance(orderItemType.getType()); item.setOrderItemType(orderItemType); return item; } public PersonalMessage createPersonalMessage() { PersonalMessage personalMessage = (PersonalMessage) entityConfiguration.createEntityInstance(PersonalMessage.class.getName()); return personalMessage; } public OrderItem saveOrderItem(final OrderItem orderItem) { return em.merge(orderItem); } public OrderItemPriceDetail createOrderItemPriceDetail() { return new OrderItemPriceDetailImpl(); } public OrderItemQualifier createOrderItemQualifier() { return new OrderItemQualifierImpl(); } public OrderItemPriceDetail initializeOrderItemPriceDetails(OrderItem item) { OrderItemPriceDetail detail = createOrderItemPriceDetail(); detail.setOrderItem(item); detail.setQuantity(item.getQuantity()); detail.setUseSalePrice(item.getIsOnSale()); item.getOrderItemPriceDetails().add(detail); return detail; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_dao_OrderItemDaoImpl.java
1,689
public class URLBlobStore extends AbstractComponent implements BlobStore { private final Executor executor; private final URL path; private final int bufferSizeInBytes; /** * Constructs new read-only URL-based blob store * <p/> * The following settings are supported * <dl> * <dt>buffer_size</dt> * <dd>- size of the read buffer, defaults to 100KB</dd> * </dl> * * @param settings settings * @param executor executor for read operations * @param path base URL */ public URLBlobStore(Settings settings, Executor executor, URL path) { super(settings); this.path = path; this.bufferSizeInBytes = (int) settings.getAsBytesSize("buffer_size", new ByteSizeValue(100, ByteSizeUnit.KB)).bytes(); this.executor = executor; } /** * {@inheritDoc} */ @Override public String toString() { return path.toString(); } /** * Returns base URL * * @return base URL */ public URL path() { return path; } /** * Returns read buffer size * * @return read buffer size */ public int bufferSizeInBytes() { return this.bufferSizeInBytes; } /** * Returns executor used for read operations * * @return executor */ public Executor executor() { return executor; } /** * {@inheritDoc} */ @Override public ImmutableBlobContainer immutableBlobContainer(BlobPath path) { try { return new URLImmutableBlobContainer(this, path, buildPath(path)); } catch (MalformedURLException ex) { throw new BlobStoreException("malformed URL " + path, ex); } } /** * This operation is not supported by URL Blob Store * * @param path */ @Override public void delete(BlobPath path) { throw new UnsupportedOperationException("URL repository is read only"); } /** * {@inheritDoc} */ @Override public void close() { // nothing to do here... } /** * Builds URL using base URL and specified path * * @param path relative path * @return Base URL + path * @throws MalformedURLException */ private URL buildPath(BlobPath path) throws MalformedURLException { String[] paths = path.toArray(); if (paths.length == 0) { return path(); } URL blobPath = new URL(this.path, paths[0] + "/"); if (paths.length > 1) { for (int i = 1; i < paths.length; i++) { blobPath = new URL(blobPath, paths[i] + "/"); } } return blobPath; } }
1no label
src_main_java_org_elasticsearch_common_blobstore_url_URLBlobStore.java
634
public class OIndexTxAwareOneValue extends OIndexTxAware<OIdentifiable> { public OIndexTxAwareOneValue(final ODatabaseRecord iDatabase, final OIndex<OIdentifiable> iDelegate) { super(iDatabase, iDelegate); } @Override public void checkEntry(final OIdentifiable iRecord, final Object iKey) { // CHECK IF ALREADY EXISTS IN TX String storageType = database.getStorage().getType(); if (storageType.equals(OEngineMemory.NAME) || storageType.equals(OEngineLocal.NAME) || !database.getTransaction().isActive()) { final OIdentifiable previousRecord = get(iKey); if (previousRecord != null && !previousRecord.equals(iRecord)) throw new ORecordDuplicatedException(String.format( "Cannot index record %s: found duplicated key '%s' in index '%s' previously assigned to the record %s", iRecord, iKey, getName(), previousRecord), previousRecord.getIdentity()); super.checkEntry(iRecord, iKey); } } @Override public OIdentifiable get(final Object key) { final OTransactionIndexChanges indexChanges = database.getTransaction().getIndexChanges(delegate.getName()); if (indexChanges == null) return super.get(key); OIdentifiable result; if (!indexChanges.cleared) // BEGIN FROM THE UNDERLYING RESULT SET result = super.get(key); else // BEGIN FROM EMPTY RESULT SET result = null; // FILTER RESULT SET WITH TRANSACTIONAL CHANGES return filterIndexChanges(indexChanges, Collections.singletonMap(key, result), null).get(key); } @Override public boolean contains(final Object key) { final OTransactionIndexChanges indexChanges = database.getTransaction().getIndexChanges(delegate.getName()); if (indexChanges == null) return super.get(key) != null; OIdentifiable result; if (!indexChanges.cleared) // BEGIN FROM THE UNDERLYING RESULT SET result = (OIdentifiable) super.get(key); else // BEGIN FROM EMPTY RESULT SET result = null; // FILTER RESULT SET WITH TRANSACTIONAL CHANGES return filterIndexChanges(indexChanges, Collections.singletonMap(key, result), null).get(key) != null; } @Override public Collection<OIdentifiable> getValues(final Collection<?> iKeys) { final Collection<?> keys = new ArrayList<Object>(iKeys); final Set<OIdentifiable> result = new HashSet<OIdentifiable>(); final OTransactionIndexChanges indexChanges = database.getTransaction().getIndexChanges(delegate.getName()); if (indexChanges == null) { result.addAll(super.getValues(keys)); return result; } final Set<Object> keysToRemove = new HashSet<Object>(); final Map<Object, OIdentifiable> keyValueEntries = new HashMap<Object, OIdentifiable>(); for (final Object key : keys) { if (indexChanges.cleared) keysToRemove.add(key); keyValueEntries.put(key, null); } final Map<Object, OIdentifiable> keyResult = filterIndexChanges(indexChanges, keyValueEntries, keysToRemove); keys.removeAll(keysToRemove); result.addAll(keyResult.values()); if (!keys.isEmpty()) result.addAll(super.getValues(keys)); return result; } @Override public Collection<ODocument> getEntries(final Collection<?> iKeys) { final Collection<?> keys = new ArrayList<Object>(iKeys); final Set<ODocument> result = new ODocumentFieldsHashSet(); final OTransactionIndexChanges indexChanges = database.getTransaction().getIndexChanges(delegate.getName()); if (indexChanges == null) { result.addAll(super.getEntries(keys)); return result; } final Set<Object> keysToRemove = new HashSet<Object>(); final Map<Object, OIdentifiable> keyValueEntries = new HashMap<Object, OIdentifiable>(); for (final Object key : keys) { if (indexChanges.cleared) keysToRemove.add(key); keyValueEntries.put(key, null); } final Map<Object, OIdentifiable> keyResult = filterIndexChanges(indexChanges, keyValueEntries, keysToRemove); for (Map.Entry<Object, OIdentifiable> keyResultEntry : keyResult.entrySet()) { final ODocument document = new ODocument(); document.field("key", keyResultEntry.getKey()); document.field("rid", keyResultEntry.getValue().getIdentity()); document.unsetDirty(); result.add(document); } keys.removeAll(keysToRemove); if (!keys.isEmpty()) result.addAll(super.getEntries(keys)); return result; } protected Map<Object, OIdentifiable> filterIndexChanges(OTransactionIndexChanges indexChanges, Map<Object, OIdentifiable> keyValueEntries, final Set<Object> keysToRemove) { final Map<Object, OIdentifiable> result = new HashMap<Object, OIdentifiable>(); for (Map.Entry<Object, OIdentifiable> keyValueEntry : keyValueEntries.entrySet()) { OIdentifiable keyResult = keyValueEntry.getValue(); Object key = keyValueEntry.getKey(); // CHECK FOR THE RECEIVED KEY if (indexChanges.containsChangesPerKey(key)) { final OTransactionIndexChangesPerKey value = indexChanges.getChangesPerKey(key); if (value != null) { for (final OTransactionIndexEntry entry : value.entries) { if (entry.operation == OPERATION.REMOVE) { if (entry.value == null || entry.value.equals(keyResult)) { // REMOVE THE ENTIRE KEY, SO RESULT SET IS EMPTY if (keysToRemove != null) keysToRemove.add(key); keyResult = null; } } else if (entry.operation == OPERATION.PUT) { // ADD ALSO THIS RID if (keysToRemove != null) keysToRemove.add(key); keyResult = entry.value; } } } } if (keyResult != null) result.put(key, keyResult.getIdentity()); } return result; } @Override public Collection<ODocument> getEntriesBetween(Object rangeFrom, Object rangeTo) { final OTransactionIndexChanges indexChanges = database.getTransaction().getIndexChanges(delegate.getName()); if (indexChanges == null) return super.getEntriesBetween(rangeFrom, rangeTo); final OIndexDefinition indexDefinition = getDefinition(); Object compRangeFrom = rangeFrom; Object compRangeTo = rangeTo; if (indexDefinition instanceof OCompositeIndexDefinition || indexDefinition.getParamCount() > 1) { int keySize = indexDefinition.getParamCount(); final OCompositeKey fullKeyFrom = new OCompositeKey((Comparable) rangeFrom); final OCompositeKey fullKeyTo = new OCompositeKey((Comparable) rangeTo); while (fullKeyFrom.getKeys().size() < keySize) fullKeyFrom.addKey(new OAlwaysLessKey()); while (fullKeyTo.getKeys().size() < keySize) fullKeyTo.addKey(new OAlwaysGreaterKey()); compRangeFrom = fullKeyFrom; compRangeTo = fullKeyTo; } final Collection<OTransactionIndexChangesPerKey> rangeChanges = indexChanges.getChangesForKeys(compRangeFrom, compRangeTo); if (rangeChanges.isEmpty()) return super.getEntriesBetween(rangeFrom, rangeTo); final Map<Object, OIdentifiable> keyValueEntries = new HashMap<Object, OIdentifiable>(); if (indexChanges.cleared) { for (OTransactionIndexChangesPerKey changesPerKey : rangeChanges) keyValueEntries.put(changesPerKey.key, null); } else { final Collection<ODocument> storedEntries = super.getEntriesBetween(rangeFrom, rangeTo); for (ODocument entry : storedEntries) keyValueEntries.put(entry.field("key"), entry.<OIdentifiable> field("rid")); for (OTransactionIndexChangesPerKey changesPerKey : rangeChanges) if (!keyValueEntries.containsKey(changesPerKey.key)) keyValueEntries.put(changesPerKey.key, null); } final Map<Object, OIdentifiable> keyValuesResult = filterIndexChanges(indexChanges, keyValueEntries, null); final Set<ODocument> result = new ODocumentFieldsHashSet(); for (Map.Entry<Object, OIdentifiable> keyResultEntry : keyValuesResult.entrySet()) { final ODocument document = new ODocument(); document.field("key", keyResultEntry.getKey()); document.field("rid", keyResultEntry.getValue().getIdentity()); document.unsetDirty(); result.add(document); } return result; } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_OIndexTxAwareOneValue.java
2,149
protected class AllTermWeight extends SpanWeight { public AllTermWeight(AllTermQuery query, IndexSearcher searcher) throws IOException { super(query, searcher); } @Override public AllTermSpanScorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException { if (this.stats == null) { return null; } SimScorer sloppySimScorer = similarity.simScorer(stats, context); return new AllTermSpanScorer((TermSpans) query.getSpans(context, acceptDocs, termContexts), this, sloppySimScorer); } protected class AllTermSpanScorer extends SpanScorer { protected DocsAndPositionsEnum positions; protected float payloadScore; protected int payloadsSeen; public AllTermSpanScorer(TermSpans spans, Weight weight, Similarity.SimScorer docScorer) throws IOException { super(spans, weight, docScorer); positions = spans.getPostings(); } @Override protected boolean setFreqCurrentDoc() throws IOException { if (!more) { return false; } doc = spans.doc(); freq = 0.0f; numMatches = 0; payloadScore = 0; payloadsSeen = 0; do { int matchLength = spans.end() - spans.start(); freq += docScorer.computeSlopFactor(matchLength); numMatches++; processPayload(); more = spans.next();// this moves positions to the next match } while (more && (doc == spans.doc())); return true; } protected void processPayload() throws IOException { final BytesRef payload; if ((payload = positions.getPayload()) != null) { payloadScore += decodeFloat(payload.bytes, payload.offset); payloadsSeen++; } else { // zero out the payload? } } /** * @return {@link #getSpanScore()} * {@link #getPayloadScore()} * @throws IOException */ @Override public float score() throws IOException { return getSpanScore() * getPayloadScore(); } /** * Returns the SpanScorer score only. * <p/> * Should not be overridden without good cause! * * @return the score for just the Span part w/o the payload * @throws IOException * @see #score() */ protected float getSpanScore() throws IOException { return super.score(); } /** * The score for the payload */ protected float getPayloadScore() { return payloadsSeen > 0 ? (payloadScore / payloadsSeen) : 1; } } @Override public Explanation explain(AtomicReaderContext context, int doc) throws IOException{ AllTermSpanScorer scorer = scorer(context, true, false, context.reader().getLiveDocs()); if (scorer != null) { int newDoc = scorer.advance(doc); if (newDoc == doc) { float freq = scorer.sloppyFreq(); SimScorer docScorer = similarity.simScorer(stats, context); ComplexExplanation inner = new ComplexExplanation(); inner.setDescription("weight("+getQuery()+" in "+doc+") [" + similarity.getClass().getSimpleName() + "], result of:"); Explanation scoreExplanation = docScorer.explain(doc, new Explanation(freq, "phraseFreq=" + freq)); inner.addDetail(scoreExplanation); inner.setValue(scoreExplanation.getValue()); inner.setMatch(true); ComplexExplanation result = new ComplexExplanation(); result.addDetail(inner); Explanation payloadBoost = new Explanation(); result.addDetail(payloadBoost); final float payloadScore = scorer.getPayloadScore(); payloadBoost.setValue(payloadScore); // GSI: I suppose we could toString the payload, but I don't think that // would be a good idea payloadBoost.setDescription("allPayload(...)"); result.setValue(inner.getValue() * payloadScore); result.setDescription("btq, product of:"); return result; } } return new ComplexExplanation(false, 0.0f, "no matching term"); } }
0true
src_main_java_org_elasticsearch_common_lucene_all_AllTermQuery.java
573
public class TransportOpenIndexAction extends TransportMasterNodeOperationAction<OpenIndexRequest, OpenIndexResponse> { private final MetaDataIndexStateService indexStateService; private final DestructiveOperations destructiveOperations; @Inject public TransportOpenIndexAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool, MetaDataIndexStateService indexStateService, NodeSettingsService nodeSettingsService) { super(settings, transportService, clusterService, threadPool); this.indexStateService = indexStateService; this.destructiveOperations = new DestructiveOperations(logger, settings, nodeSettingsService); } @Override protected String executor() { // we go async right away... return ThreadPool.Names.SAME; } @Override protected String transportAction() { return OpenIndexAction.NAME; } @Override protected OpenIndexRequest newRequest() { return new OpenIndexRequest(); } @Override protected OpenIndexResponse newResponse() { return new OpenIndexResponse(); } @Override protected void doExecute(OpenIndexRequest request, ActionListener<OpenIndexResponse> listener) { destructiveOperations.failDestructive(request.indices()); super.doExecute(request, listener); } @Override protected ClusterBlockException checkBlock(OpenIndexRequest request, ClusterState state) { return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA, request.indices()); } @Override protected void masterOperation(final OpenIndexRequest request, final ClusterState state, final ActionListener<OpenIndexResponse> listener) throws ElasticsearchException { request.indices(state.metaData().concreteIndices(request.indices(), request.indicesOptions())); OpenIndexClusterStateUpdateRequest updateRequest = new OpenIndexClusterStateUpdateRequest() .ackTimeout(request.timeout()).masterNodeTimeout(request.masterNodeTimeout()) .indices(request.indices()); indexStateService.openIndex(updateRequest, new ClusterStateUpdateListener() { @Override public void onResponse(ClusterStateUpdateResponse response) { listener.onResponse(new OpenIndexResponse(response.isAcknowledged())); } @Override public void onFailure(Throwable t) { logger.debug("failed to open indices [{}]", t, request.indices()); listener.onFailure(t); } }); } }
1no label
src_main_java_org_elasticsearch_action_admin_indices_open_TransportOpenIndexAction.java
857
public class OfferServiceTest extends TestCase { protected OfferServiceImpl offerService; protected CustomerOfferDao customerOfferDaoMock; protected OfferCodeDao offerCodeDaoMock; protected OfferDao offerDaoMock; protected OrderItemDao orderItemDaoMock; protected OrderService orderServiceMock; protected OrderItemService orderItemServiceMock; protected FulfillmentGroupItemDao fgItemDaoMock; protected OfferDataItemProvider dataProvider = new OfferDataItemProvider(); protected OfferTimeZoneProcessor offerTimeZoneProcessorMock; private FulfillmentGroupService fgServiceMock; private OrderMultishipOptionService multishipOptionServiceMock; @Override protected void setUp() throws Exception { offerService = new OfferServiceImpl(); customerOfferDaoMock = EasyMock.createMock(CustomerOfferDao.class); orderServiceMock = EasyMock.createMock(OrderService.class); offerCodeDaoMock = EasyMock.createMock(OfferCodeDao.class); offerDaoMock = EasyMock.createMock(OfferDao.class); orderItemDaoMock = EasyMock.createMock(OrderItemDao.class); offerService.setCustomerOfferDao(customerOfferDaoMock); offerService.setOfferCodeDao(offerCodeDaoMock); offerService.setOfferDao(offerDaoMock); offerService.setOrderService(orderServiceMock); orderItemServiceMock = EasyMock.createMock(OrderItemService.class); fgItemDaoMock = EasyMock.createMock(FulfillmentGroupItemDao.class); fgServiceMock = EasyMock.createMock(FulfillmentGroupService.class); multishipOptionServiceMock = EasyMock.createMock(OrderMultishipOptionService.class); offerTimeZoneProcessorMock = EasyMock.createMock(OfferTimeZoneProcessor.class); OrderOfferProcessorImpl orderProcessor = new OrderOfferProcessorImpl(); orderProcessor.setOfferDao(offerDaoMock); orderProcessor.setOrderItemDao(orderItemDaoMock); orderProcessor.setPromotableItemFactory(new PromotableItemFactoryImpl()); orderProcessor.setOfferTimeZoneProcessor(offerTimeZoneProcessorMock); offerService.setOrderOfferProcessor(orderProcessor); ItemOfferProcessor itemProcessor = new ItemOfferProcessorImpl(); itemProcessor.setOfferDao(offerDaoMock); itemProcessor.setPromotableItemFactory(new PromotableItemFactoryImpl()); offerService.setItemOfferProcessor(itemProcessor); FulfillmentGroupOfferProcessor fgProcessor = new FulfillmentGroupOfferProcessorImpl(); fgProcessor.setOfferDao(offerDaoMock); fgProcessor.setPromotableItemFactory(new PromotableItemFactoryImpl()); offerService.setFulfillmentGroupOfferProcessor(fgProcessor); offerService.setPromotableItemFactory(new PromotableItemFactoryImpl()); } public void replay() { EasyMock.replay(customerOfferDaoMock); EasyMock.replay(offerCodeDaoMock); EasyMock.replay(offerDaoMock); EasyMock.replay(orderItemDaoMock); EasyMock.replay(orderServiceMock); EasyMock.replay(orderItemServiceMock); EasyMock.replay(fgItemDaoMock); EasyMock.replay(fgServiceMock); EasyMock.replay(multishipOptionServiceMock); EasyMock.replay(offerTimeZoneProcessorMock); } public void verify() { EasyMock.verify(customerOfferDaoMock); EasyMock.verify(offerCodeDaoMock); EasyMock.verify(offerDaoMock); EasyMock.verify(orderItemDaoMock); EasyMock.verify(orderServiceMock); EasyMock.verify(orderItemServiceMock); EasyMock.verify(fgItemDaoMock); EasyMock.verify(fgServiceMock); EasyMock.verify(multishipOptionServiceMock); EasyMock.verify(offerTimeZoneProcessorMock); } public void testApplyOffersToOrder_Order() throws Exception { final ThreadLocal<Order> myOrder = new ThreadLocal<Order>(); EasyMock.expect(offerDaoMock.createOrderItemPriceDetailAdjustment()).andAnswer(OfferDataItemProvider.getCreateOrderItemPriceDetailAdjustmentAnswer()).anyTimes(); CandidateOrderOfferAnswer candidateOrderOfferAnswer = new CandidateOrderOfferAnswer(); OrderAdjustmentAnswer orderAdjustmentAnswer = new OrderAdjustmentAnswer(); EasyMock.expect(offerDaoMock.createOrderAdjustment()).andAnswer(orderAdjustmentAnswer).atLeastOnce(); OrderItemPriceDetailAnswer orderItemPriceDetailAnswer = new OrderItemPriceDetailAnswer(); EasyMock.expect(orderItemDaoMock.createOrderItemPriceDetail()).andAnswer(orderItemPriceDetailAnswer).atLeastOnce(); OrderItemQualifierAnswer orderItemQualifierAnswer = new OrderItemQualifierAnswer(); EasyMock.expect(orderItemDaoMock.createOrderItemQualifier()).andAnswer(orderItemQualifierAnswer).atLeastOnce(); CandidateItemOfferAnswer candidateItemOfferAnswer = new CandidateItemOfferAnswer(); OrderItemAdjustmentAnswer orderItemAdjustmentAnswer = new OrderItemAdjustmentAnswer(); EasyMock.expect(fgServiceMock.addItemToFulfillmentGroup(EasyMock.isA(FulfillmentGroupItemRequest.class), EasyMock.eq(false))).andAnswer(OfferDataItemProvider.getAddItemToFulfillmentGroupAnswer()).anyTimes(); EasyMock.expect(orderServiceMock.removeItem(EasyMock.isA(Long.class), EasyMock.isA(Long.class), EasyMock.eq(false))).andAnswer(OfferDataItemProvider.getRemoveItemFromOrderAnswer()).anyTimes(); EasyMock.expect(orderServiceMock.save(EasyMock.isA(Order.class),EasyMock.isA(Boolean.class))).andAnswer(OfferDataItemProvider.getSaveOrderAnswer()).anyTimes(); EasyMock.expect(orderServiceMock.findOrderById(EasyMock.isA(Long.class))).andAnswer(new IAnswer<Order>() { @Override public Order answer() throws Throwable { return myOrder.get(); } }).anyTimes(); EasyMock.expect(orderServiceMock.getAutomaticallyMergeLikeItems()).andReturn(true).anyTimes(); EasyMock.expect(orderItemServiceMock.saveOrderItem(EasyMock.isA(OrderItem.class))).andAnswer(OfferDataItemProvider.getSaveOrderItemAnswer()).anyTimes(); EasyMock.expect(fgItemDaoMock.save(EasyMock.isA(FulfillmentGroupItem.class))).andAnswer(OfferDataItemProvider.getSaveFulfillmentGroupItemAnswer()).anyTimes(); EasyMock.expect(multishipOptionServiceMock.findOrderMultishipOptions(EasyMock.isA(Long.class))).andAnswer(new IAnswer<List<OrderMultishipOption>>() { @Override public List<OrderMultishipOption> answer() throws Throwable { return new ArrayList<OrderMultishipOption>(); } }).anyTimes(); multishipOptionServiceMock.deleteAllOrderMultishipOptions(EasyMock.isA(Order.class)); EasyMock.expectLastCall().anyTimes(); EasyMock.expect(fgServiceMock.collapseToOneFulfillmentGroup(EasyMock.isA(Order.class), EasyMock.eq(false))).andAnswer(OfferDataItemProvider.getSameOrderAnswer()).anyTimes(); EasyMock.expect(fgItemDaoMock.create()).andAnswer(OfferDataItemProvider.getCreateFulfillmentGroupItemAnswer()).anyTimes(); fgItemDaoMock.delete(EasyMock.isA(FulfillmentGroupItem.class)); EasyMock.expectLastCall().anyTimes(); EasyMock.expect(offerTimeZoneProcessorMock.getTimeZone(EasyMock.isA(OfferImpl.class))).andReturn(TimeZone.getTimeZone("CST")).anyTimes(); replay(); Order order = dataProvider.createBasicOrder(); myOrder.set(order); List<Offer> offers = dataProvider.createOrderBasedOffer("order.subTotal.getAmount()>126", OfferDiscountType.PERCENT_OFF); offerService.applyOffersToOrder(offers, order); int adjustmentCount = order.getOrderAdjustments().size(); assertTrue(adjustmentCount == 1); assertTrue(order.getSubTotal().subtract(order.getOrderAdjustmentsValue()).equals(new Money(116.95D))); order = dataProvider.createBasicOrder(); myOrder.set(order); offers = dataProvider.createOrderBasedOffer("order.subTotal.getAmount()>126", OfferDiscountType.PERCENT_OFF); List<Offer> offers2 = dataProvider.createItemBasedOfferWithItemCriteria( "order.subTotal.getAmount()>20", OfferDiscountType.PERCENT_OFF, "([MVEL.eval(\"toUpperCase()\",\"test1\"), MVEL.eval(\"toUpperCase()\",\"test2\")] contains MVEL.eval(\"toUpperCase()\", discreteOrderItem.category.name))", "([MVEL.eval(\"toUpperCase()\",\"test1\"), MVEL.eval(\"toUpperCase()\",\"test2\")] contains MVEL.eval(\"toUpperCase()\", discreteOrderItem.category.name))" ); offers.addAll(offers2); offerService.applyOffersToOrder(offers, order); //with the item offers in play, the subtotal restriction for the order offer is no longer valid adjustmentCount = countItemAdjustments(order); int qualifierCount = countItemQualifiers(order); assertTrue(adjustmentCount == 2); assertTrue(qualifierCount == 2); adjustmentCount = order.getOrderAdjustments().size(); assertTrue(adjustmentCount == 0); //assertTrue(order.getSubTotal().equals(new Money(124.95D))); order = dataProvider.createBasicOrder(); myOrder.set(order); OfferRule orderRule = new OfferRuleImpl(); //orderRule.setMatchRule("order.subTotal.getAmount()>124"); orderRule.setMatchRule("order.subTotal.getAmount()>100"); offers.get(0).getOfferMatchRules().put(OfferRuleType.ORDER.getType(), orderRule); offerService.applyOffersToOrder(offers, order); //now that the order restriction has been lessened, even with the item level discounts applied, // the order offer still qualifies adjustmentCount = countItemAdjustments(order); qualifierCount = countItemQualifiers(order); assertTrue(adjustmentCount == 2); assertTrue(qualifierCount == 2); adjustmentCount = order.getOrderAdjustments().size(); assertTrue(adjustmentCount == 1); assertTrue(order.getSubTotal().subtract(order.getOrderAdjustmentsValue()).equals(new Money(112.45D))); assertTrue(order.getSubTotal().equals(new Money(124.95D))); order = dataProvider.createBasicPromotableOrder().getOrder(); myOrder.set(order); //offers.get(0).setCombinableWithOtherOffers(false); List<Offer> offers3 = dataProvider.createOrderBasedOffer("order.subTotal.getAmount()>20", OfferDiscountType.AMOUNT_OFF); offers.addAll(offers3); offerService.applyOffersToOrder(offers, order); adjustmentCount = order.getOrderAdjustments().size(); assertTrue(adjustmentCount == 2); order = dataProvider.createBasicPromotableOrder().getOrder(); myOrder.set(order); offers.get(0).setCombinableWithOtherOffers(false); offerService.applyOffersToOrder(offers, order); //there is a non combinable order offer now adjustmentCount = countItemAdjustments(order); qualifierCount = countItemQualifiers(order); assertTrue(adjustmentCount == 2); assertTrue(qualifierCount == 2); adjustmentCount = order.getOrderAdjustments().size(); assertTrue(adjustmentCount == 1); assertTrue(order.getSubTotal().subtract(order.getOrderAdjustmentsValue()).equals(new Money(112.45D))); assertTrue(order.getSubTotal().equals(new Money(124.95D))); order = dataProvider.createBasicPromotableOrder().getOrder(); myOrder.set(order); offers.get(0).setTotalitarianOffer(true); offerService.applyOffersToOrder(offers, order); //there is a totalitarian order offer now - it is better than the item offers - the item offers are removed adjustmentCount = countItemAdjustments(order); qualifierCount = countItemQualifiers(order); assertTrue(adjustmentCount == 0); assertTrue(qualifierCount == 0); adjustmentCount = order.getOrderAdjustments().size(); assertTrue(adjustmentCount == 1); assertTrue(order.getSubTotal().subtract(order.getOrderAdjustmentsValue()).equals(new Money(116.95D))); assertTrue(order.getSubTotal().equals(new Money(129.95D))); order = dataProvider.createBasicPromotableOrder().getOrder(); myOrder.set(order); offers.get(0).setValue(new BigDecimal(".05")); offers.get(2).setValue(new BigDecimal(".01")); offers.get(2).setDiscountType(OfferDiscountType.PERCENT_OFF); offerService.applyOffersToOrder(offers, order); //even though the first order offer is totalitarian, it is worth less than the order item offer, so it is removed. //the other order offer is still valid, however, and is included. adjustmentCount = countItemAdjustments(order); assertTrue(adjustmentCount == 2); adjustmentCount = order.getOrderAdjustments().size(); assertTrue(adjustmentCount == 1); assertTrue(order.getSubTotal().subtract(order.getOrderAdjustmentsValue()).equals(new Money(124.94D))); assertTrue(order.getSubTotal().equals(new Money(124.95D))); verify(); } private int countItemAdjustments(Order order) { int adjustmentCount = 0; for (OrderItem item : order.getOrderItems()) { for (OrderItemPriceDetail detail : item.getOrderItemPriceDetails()) { if (detail.getOrderItemPriceDetailAdjustments() != null) { adjustmentCount += detail.getOrderItemPriceDetailAdjustments().size(); } } } return adjustmentCount; } private int countItemQualifiers(Order order) { int qualifierCount = 0; for (OrderItem item : order.getOrderItems()) { for (OrderItemQualifier qualifier : item.getOrderItemQualifiers()) { qualifierCount = qualifierCount += qualifier.getQuantity(); } } return qualifierCount; } public void testApplyOffersToOrder_Items() throws Exception { final ThreadLocal<Order> myOrder = new ThreadLocal<Order>(); EasyMock.expect(offerDaoMock.createOrderItemPriceDetailAdjustment()).andAnswer(OfferDataItemProvider.getCreateOrderItemPriceDetailAdjustmentAnswer()).anyTimes(); CandidateItemOfferAnswer answer = new CandidateItemOfferAnswer(); OrderItemAdjustmentAnswer answer2 = new OrderItemAdjustmentAnswer(); OrderItemPriceDetailAnswer orderItemPriceDetailAnswer = new OrderItemPriceDetailAnswer(); EasyMock.expect(orderItemDaoMock.createOrderItemPriceDetail()).andAnswer(orderItemPriceDetailAnswer).atLeastOnce(); OrderItemQualifierAnswer orderItemQualifierAnswer = new OrderItemQualifierAnswer(); EasyMock.expect(orderItemDaoMock.createOrderItemQualifier()).andAnswer(orderItemQualifierAnswer).atLeastOnce(); EasyMock.expect(orderServiceMock.getAutomaticallyMergeLikeItems()).andReturn(true).anyTimes(); EasyMock.expect(orderServiceMock.save(EasyMock.isA(Order.class),EasyMock.isA(Boolean.class))).andAnswer(OfferDataItemProvider.getSaveOrderAnswer()).anyTimes(); EasyMock.expect(orderItemServiceMock.saveOrderItem(EasyMock.isA(OrderItem.class))).andAnswer(OfferDataItemProvider.getSaveOrderItemAnswer()).anyTimes(); EasyMock.expect(fgItemDaoMock.save(EasyMock.isA(FulfillmentGroupItem.class))).andAnswer(OfferDataItemProvider.getSaveFulfillmentGroupItemAnswer()).anyTimes(); EasyMock.expect(fgServiceMock.addItemToFulfillmentGroup(EasyMock.isA(FulfillmentGroupItemRequest.class), EasyMock.eq(false))).andAnswer(OfferDataItemProvider.getAddItemToFulfillmentGroupAnswer()).anyTimes(); EasyMock.expect(orderServiceMock.removeItem(EasyMock.isA(Long.class), EasyMock.isA(Long.class), EasyMock.eq(false))).andAnswer(OfferDataItemProvider.getRemoveItemFromOrderAnswer()).anyTimes(); EasyMock.expect(multishipOptionServiceMock.findOrderMultishipOptions(EasyMock.isA(Long.class))).andAnswer(new IAnswer<List<OrderMultishipOption>>() { @Override public List<OrderMultishipOption> answer() throws Throwable { return new ArrayList<OrderMultishipOption>(); } }).anyTimes(); EasyMock.expect(orderServiceMock.findOrderById(EasyMock.isA(Long.class))).andAnswer(new IAnswer<Order>() { @Override public Order answer() throws Throwable { return myOrder.get(); } }).anyTimes(); multishipOptionServiceMock.deleteAllOrderMultishipOptions(EasyMock.isA(Order.class)); EasyMock.expectLastCall().anyTimes(); EasyMock.expect(fgServiceMock.collapseToOneFulfillmentGroup(EasyMock.isA(Order.class), EasyMock.eq(false))).andAnswer(OfferDataItemProvider.getSameOrderAnswer()).anyTimes(); EasyMock.expect(fgItemDaoMock.create()).andAnswer(OfferDataItemProvider.getCreateFulfillmentGroupItemAnswer()).anyTimes(); fgItemDaoMock.delete(EasyMock.isA(FulfillmentGroupItem.class)); EasyMock.expectLastCall().anyTimes(); EasyMock.expect(offerTimeZoneProcessorMock.getTimeZone(EasyMock.isA(OfferImpl.class))).andReturn(TimeZone.getTimeZone("CST")).anyTimes(); replay(); Order order = dataProvider.createBasicPromotableOrder().getOrder(); myOrder.set(order); List<Offer> offers = dataProvider.createItemBasedOfferWithItemCriteria( "order.subTotal.getAmount()>20", OfferDiscountType.PERCENT_OFF, "([MVEL.eval(\"toUpperCase()\",\"test1\"), MVEL.eval(\"toUpperCase()\",\"test2\")] contains MVEL.eval(\"toUpperCase()\", discreteOrderItem.category.name))", "([MVEL.eval(\"toUpperCase()\",\"test1\"), MVEL.eval(\"toUpperCase()\",\"test2\")] contains MVEL.eval(\"toUpperCase()\", discreteOrderItem.category.name))" ); offerService.applyOffersToOrder(offers, order); int adjustmentCount = countItemAdjustments(order); assertTrue(adjustmentCount == 2); order = dataProvider.createBasicPromotableOrder().getOrder(); myOrder.set(order); offers = dataProvider.createItemBasedOfferWithItemCriteria( "order.subTotal.getAmount()>20", OfferDiscountType.PERCENT_OFF, "([MVEL.eval(\"toUpperCase()\",\"test1\"), MVEL.eval(\"toUpperCase()\",\"test2\")] contains MVEL.eval(\"toUpperCase()\", discreteOrderItem.category.name))", "([MVEL.eval(\"toUpperCase()\",\"test5\"), MVEL.eval(\"toUpperCase()\",\"test6\")] contains MVEL.eval(\"toUpperCase()\", discreteOrderItem.category.name))" ); offerService.applyOffersToOrder(offers, order); adjustmentCount = countItemAdjustments(order); //Qualifiers are there, but the targets are not, so no adjustments assertTrue(adjustmentCount == 0); verify(); } public void testBuildOfferListForOrder() throws Exception { EasyMock.expect(customerOfferDaoMock.readCustomerOffersByCustomer(EasyMock.isA(Customer.class))).andReturn(new ArrayList<CustomerOffer>()); EasyMock.expect(offerDaoMock.readOffersByAutomaticDeliveryType()).andReturn(dataProvider.createCustomerBasedOffer(null, dataProvider.yesterday(), dataProvider.tomorrow(), OfferDiscountType.PERCENT_OFF)); replay(); Order order = dataProvider.createBasicPromotableOrder().getOrder(); List<Offer> offers = offerService.buildOfferListForOrder(order); assertTrue(offers.size() == 1); verify(); } public class CandidateItemOfferAnswer implements IAnswer<CandidateItemOffer> { @Override public CandidateItemOffer answer() throws Throwable { return new CandidateItemOfferImpl(); } } public class OrderItemAdjustmentAnswer implements IAnswer<OrderItemAdjustment> { @Override public OrderItemAdjustment answer() throws Throwable { return new OrderItemAdjustmentImpl(); } } public class CandidateOrderOfferAnswer implements IAnswer<CandidateOrderOffer> { @Override public CandidateOrderOffer answer() throws Throwable { return new CandidateOrderOfferImpl(); } } public class OrderAdjustmentAnswer implements IAnswer<OrderAdjustment> { @Override public OrderAdjustment answer() throws Throwable { return new OrderAdjustmentImpl(); } } public class OrderItemPriceDetailAnswer implements IAnswer<OrderItemPriceDetail> { @Override public OrderItemPriceDetail answer() throws Throwable { return new OrderItemPriceDetailImpl(); } } public class OrderItemQualifierAnswer implements IAnswer<OrderItemQualifier> { @Override public OrderItemQualifier answer() throws Throwable { return new OrderItemQualifierImpl(); } } }
0true
core_broadleaf-framework_src_test_java_org_broadleafcommerce_core_offer_service_OfferServiceTest.java
262
public interface EmailService { public boolean sendTemplateEmail(String emailAddress, EmailInfo emailInfo, HashMap<String,Object> props); public boolean sendTemplateEmail(EmailTarget emailTarget, EmailInfo emailInfo, HashMap<String,Object> props); public boolean sendBasicEmail(EmailInfo emailInfo, EmailTarget emailTarget, HashMap<String,Object> props); }
0true
common_src_main_java_org_broadleafcommerce_common_email_service_EmailService.java