Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
3,087
static class GetResult { private final boolean exists; private final long version; private final Translog.Source source; private final Versions.DocIdAndVersion docIdAndVersion; private final Searcher searcher; public static final GetResult NOT_EXISTS = new GetResult(false, Versions.NOT_FOUND, null); public GetResult(boolean exists, long version, @Nullable Translog.Source source) { this.source = source; this.exists = exists; this.version = version; this.docIdAndVersion = null; this.searcher = null; } public GetResult(Searcher searcher, Versions.DocIdAndVersion docIdAndVersion) { this.exists = true; this.source = null; this.version = docIdAndVersion.version; this.docIdAndVersion = docIdAndVersion; this.searcher = searcher; } public boolean exists() { return exists; } public long version() { return this.version; } @Nullable public Translog.Source source() { return source; } public Searcher searcher() { return this.searcher; } public Versions.DocIdAndVersion docIdAndVersion() { return docIdAndVersion; } public void release() { if (searcher != null) { searcher.release(); } } }
0true
src_main_java_org_elasticsearch_index_engine_Engine.java
3,521
public class ParseContext { /** Fork of {@link org.apache.lucene.document.Document} with additional functionality. */ public static class Document implements Iterable<IndexableField> { private final List<IndexableField> fields; private ObjectObjectMap<Object, IndexableField> keyedFields; public Document() { fields = Lists.newArrayList(); } @Override public Iterator<IndexableField> iterator() { return fields.iterator(); } public List<IndexableField> getFields() { return fields; } public void add(IndexableField field) { fields.add(field); } /** Add fields so that they can later be fetched using {@link #getByKey(Object)}. */ public void addWithKey(Object key, IndexableField field) { if (keyedFields == null) { keyedFields = new ObjectObjectOpenHashMap<Object, IndexableField>(); } else if (keyedFields.containsKey(key)) { throw new ElasticsearchIllegalStateException("Only one field can be stored per key"); } keyedFields.put(key, field); add(field); } /** Get back fields that have been previously added with {@link #addWithKey(Object, IndexableField)}. */ public IndexableField getByKey(Object key) { return keyedFields == null ? null : keyedFields.get(key); } public IndexableField[] getFields(String name) { List<IndexableField> f = new ArrayList<IndexableField>(); for (IndexableField field : fields) { if (field.name().equals(name)) { f.add(field); } } return f.toArray(new IndexableField[f.size()]); } public IndexableField getField(String name) { for (IndexableField field : fields) { if (field.name().equals(name)) { return field; } } return null; } public String get(String name) { for (IndexableField f : fields) { if (f.name().equals(name) && f.stringValue() != null) { return f.stringValue(); } } return null; } public BytesRef getBinaryValue(String name) { for (IndexableField f : fields) { if (f.name().equals(name) && f.binaryValue() != null) { return f.binaryValue(); } } return null; } } private final DocumentMapper docMapper; private final DocumentMapperParser docMapperParser; private final ContentPath path; private XContentParser parser; private Document document; private List<Document> documents = Lists.newArrayList(); private Analyzer analyzer; private final String index; @Nullable private final Settings indexSettings; private SourceToParse sourceToParse; private BytesReference source; private String id; private DocumentMapper.ParseListener listener; private Field uid, version; private StringBuilder stringBuilder = new StringBuilder(); private Map<String, String> ignoredValues = new HashMap<String, String>(); private boolean mappingsModified = false; private boolean withinNewMapper = false; private boolean withinCopyTo = false; private boolean externalValueSet; private Object externalValue; private AllEntries allEntries = new AllEntries(); private float docBoost = 1.0f; public ParseContext(String index, @Nullable Settings indexSettings, DocumentMapperParser docMapperParser, DocumentMapper docMapper, ContentPath path) { this.index = index; this.indexSettings = indexSettings; this.docMapper = docMapper; this.docMapperParser = docMapperParser; this.path = path; } public void reset(XContentParser parser, Document document, SourceToParse source, DocumentMapper.ParseListener listener) { this.parser = parser; this.document = document; if (document != null) { this.documents = Lists.newArrayList(); this.documents.add(document); } else { this.documents = null; } this.analyzer = null; this.uid = null; this.version = null; this.id = null; this.sourceToParse = source; this.source = source == null ? null : sourceToParse.source(); this.path.reset(); this.mappingsModified = false; this.withinNewMapper = false; this.listener = listener == null ? DocumentMapper.ParseListener.EMPTY : listener; this.allEntries = new AllEntries(); this.ignoredValues.clear(); this.docBoost = 1.0f; } public boolean flyweight() { return sourceToParse.flyweight(); } public DocumentMapperParser docMapperParser() { return this.docMapperParser; } public boolean mappingsModified() { return this.mappingsModified; } public void setMappingsModified() { this.mappingsModified = true; } public void setWithinNewMapper() { this.withinNewMapper = true; } public void clearWithinNewMapper() { this.withinNewMapper = false; } public boolean isWithinNewMapper() { return withinNewMapper; } public void setWithinCopyTo() { this.withinCopyTo = true; } public void clearWithinCopyTo() { this.withinCopyTo = false; } public boolean isWithinCopyTo() { return withinCopyTo; } public String index() { return this.index; } @Nullable public Settings indexSettings() { return this.indexSettings; } public String type() { return sourceToParse.type(); } public SourceToParse sourceToParse() { return this.sourceToParse; } public BytesReference source() { return source; } // only should be used by SourceFieldMapper to update with a compressed source public void source(BytesReference source) { this.source = source; } public ContentPath path() { return this.path; } public XContentParser parser() { return this.parser; } public DocumentMapper.ParseListener listener() { return this.listener; } public Document rootDoc() { return documents.get(0); } public List<Document> docs() { return this.documents; } public Document doc() { return this.document; } public void addDoc(Document doc) { this.documents.add(doc); } public Document switchDoc(Document doc) { Document prev = this.document; this.document = doc; return prev; } public RootObjectMapper root() { return docMapper.root(); } public DocumentMapper docMapper() { return this.docMapper; } public AnalysisService analysisService() { return docMapperParser.analysisService; } public String id() { return id; } public void ignoredValue(String indexName, String value) { ignoredValues.put(indexName, value); } public String ignoredValue(String indexName) { return ignoredValues.get(indexName); } /** * Really, just the id mapper should set this. */ public void id(String id) { this.id = id; } public Field uid() { return this.uid; } /** * Really, just the uid mapper should set this. */ public void uid(Field uid) { this.uid = uid; } public Field version() { return this.version; } public void version(Field version) { this.version = version; } public boolean includeInAll(Boolean includeInAll, FieldMapper mapper) { return includeInAll(includeInAll, mapper.fieldType().indexed()); } /** * Is all included or not. Will always disable it if {@link org.elasticsearch.index.mapper.internal.AllFieldMapper#enabled()} * is <tt>false</tt>. If its enabled, then will return <tt>true</tt> only if the specific flag is <tt>null</tt> or * its actual value (so, if not set, defaults to "true") and the field is indexed. */ private boolean includeInAll(Boolean specificIncludeInAll, boolean indexed) { if (withinCopyTo) { return false; } if (!docMapper.allFieldMapper().enabled()) { return false; } // not explicitly set if (specificIncludeInAll == null) { return indexed; } return specificIncludeInAll; } public AllEntries allEntries() { return this.allEntries; } public Analyzer analyzer() { return this.analyzer; } public void analyzer(Analyzer analyzer) { this.analyzer = analyzer; } public void externalValue(Object externalValue) { this.externalValueSet = true; this.externalValue = externalValue; } public boolean externalValueSet() { return this.externalValueSet; } public Object externalValue() { externalValueSet = false; return externalValue; } public float docBoost() { return this.docBoost; } public void docBoost(float docBoost) { this.docBoost = docBoost; } /** * A string builder that can be used to construct complex names for example. * Its better to reuse the. */ public StringBuilder stringBuilder() { stringBuilder.setLength(0); return this.stringBuilder; } }
1no label
src_main_java_org_elasticsearch_index_mapper_ParseContext.java
459
private static class TreeKeyIterator implements Iterator<OIdentifiable> { private final boolean autoConvertToRecord; private OSBTreeMapEntryIterator<OIdentifiable, Boolean> entryIterator; public TreeKeyIterator(OTreeInternal<OIdentifiable, Boolean> tree, boolean autoConvertToRecord) { entryIterator = new OSBTreeMapEntryIterator<OIdentifiable, Boolean>(tree); this.autoConvertToRecord = autoConvertToRecord; } @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public OIdentifiable next() { final OIdentifiable identifiable = entryIterator.next().getKey(); if (autoConvertToRecord) return identifiable.getRecord(); else return identifiable; } @Override public void remove() { entryIterator.remove(); } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_record_ridset_sbtree_OSBTreeRIDSet.java
514
public class KillMemberThread extends TestThread { @Override public void doRun() throws Exception { while (!stopTest) { try { Thread.sleep(TimeUnit.SECONDS.toMillis(KILL_DELAY_SECONDS)); } catch (InterruptedException e) { } int index = random.nextInt(CLUSTER_SIZE); HazelcastInstance instance = instances.remove(index); instance.shutdown(); HazelcastInstance newInstance = newHazelcastInstance(createClusterConfig()); instances.add(newInstance); } } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_stress_StressTestSupport.java
1,743
public class LZFCompressedStreamInput extends CompressedStreamInput<LZFCompressorContext> { private final BufferRecycler recycler; private final ChunkDecoder decoder; // scratch area buffer private byte[] inputBuffer; public LZFCompressedStreamInput(StreamInput in, ChunkDecoder decoder) throws IOException { super(in, LZFCompressorContext.INSTANCE); this.recycler = BufferRecycler.instance(); this.decoder = decoder; this.uncompressed = recycler.allocDecodeBuffer(LZFChunk.MAX_CHUNK_LEN); this.inputBuffer = recycler.allocInputBuffer(LZFChunk.MAX_CHUNK_LEN); } @Override public void readHeader(StreamInput in) throws IOException { // nothing to do here, each chunk has a header } @Override public int uncompress(StreamInput in, byte[] out) throws IOException { return decoder.decodeChunk(in, inputBuffer, out); } @Override protected void doClose() throws IOException { byte[] buf = inputBuffer; if (buf != null) { inputBuffer = null; recycler.releaseInputBuffer(buf); } buf = uncompressed; if (buf != null) { uncompressed = null; recycler.releaseDecodeBuffer(uncompressed); } } }
0true
src_main_java_org_elasticsearch_common_compress_lzf_LZFCompressedStreamInput.java
230
assertTrueEventually(new AssertTask() { public void run() throws Exception { assertTrue(map.containsKey(targetUuid)); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceExecuteTest.java
898
public interface PromotableOrderItem extends Serializable { /** * Adds the item to the rule variables map. * @param ruleVars */ void updateRuleVariables(Map<String, Object> ruleVars); /** * Called by pricing engine to reset the state of this item. */ void resetPriceDetails(); /** * Returns true if this item can receive item level discounts. * @return */ boolean isDiscountingAllowed(); /** * Returns true if this PromotableOrderItem contains other items */ boolean isOrderItemContainer(); /** * Returns an OrderItemContainer for this OrderItem or null if this item is not * an instance of OrderItemContainer. */ OrderItemContainer getOrderItemContainer(); /** * Returns the salePrice without adjustments */ Money getSalePriceBeforeAdjustments(); /** * Returns the retailPrice without adjustments */ Money getRetailPriceBeforeAdjustments(); /** * Returns true if the item has a sale price that is lower than the retail price. */ boolean isOnSale(); /** * Returns the list of priceDetails associated with this item. * @return */ List<PromotableOrderItemPriceDetail> getPromotableOrderItemPriceDetails(); /** * Return the salePriceBeforeAdjustments if the passed in param is true. * Otherwise return the retailPriceBeforeAdjustments. * @return */ Money getPriceBeforeAdjustments(boolean applyToSalePrice); /** * Returns the basePrice of the item (baseSalePrice or baseRetailPrice) * @return */ Money getCurrentBasePrice(); /** * Returns the quantity for this orderItem * @return */ int getQuantity(); /** * Returns the currency of the related order. * @return */ BroadleafCurrency getCurrency(); /** * Effectively deletes all priceDetails associated with this item and r */ void removeAllItemAdjustments(); /** * Merges any priceDetails that share the same adjustments. */ void mergeLikeDetails(); /** * Returns the id of the contained OrderItem */ Long getOrderItemId(); /** * Returns the value of all adjustments. */ Money calculateTotalAdjustmentValue(); /** * Returns the final total for this item taking into account the finalized * adjustments. Intended to be called after the adjustments have been * finalized. */ Money calculateTotalWithAdjustments(); /** * Returns the total for this item if not adjustments applied. */ Money calculateTotalWithoutAdjustments(); /** * Creates a new detail with the associated quantity. Intended for use as part of the PriceDetail split. * @param quantity * @return */ PromotableOrderItemPriceDetail createNewDetail(int quantity); /** * Returns the underlying orderItem. Manipulation of the underlying orderItem is not recommended. * This method is intended for unit test and read only access although that is not strictly enforced. * @return */ OrderItem getOrderItem(); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_domain_PromotableOrderItem.java
1,575
ItemListener itemListener = new ItemListener() { public void itemAdded(ItemEvent item) { totalAddedItemCount.incrementAndGet(); } public void itemRemoved(ItemEvent item) { totalRemovedItemCount.incrementAndGet(); } };
0true
hazelcast_src_main_java_com_hazelcast_jmx_SetMBean.java
90
class ConvertStringProposal extends CorrectionProposal { private ConvertStringProposal(String name, Change change) { super(name, change, null); } static void addConvertToVerbatimProposal(Collection<ICompletionProposal> proposals, IFile file, Tree.CompilationUnit cu, Node node, IDocument doc) { if (node instanceof Tree.StringLiteral) { Tree.StringLiteral literal = (Tree.StringLiteral) node; Token token = node.getToken(); if (token.getType()==CeylonLexer.ASTRING_LITERAL || token.getType()==CeylonLexer.STRING_LITERAL) { String text = "\"\"\"" + literal.getText() + "\"\"\""; int offset = node.getStartIndex(); int length = node.getStopIndex() - node.getStartIndex() + 1; String reindented = getConvertedText(text, token.getCharPositionInLine()+3, doc); TextFileChange change = new TextFileChange("Convert to Verbatim String", file); change.setEdit(new ReplaceEdit(offset, length, reindented)); proposals.add(new ConvertStringProposal("Convert to verbatim string", change)); } } } static void addConvertFromVerbatimProposal(Collection<ICompletionProposal> proposals, IFile file, Tree.CompilationUnit cu, Node node, IDocument doc) { if (node instanceof Tree.StringLiteral) { Tree.StringLiteral literal = (Tree.StringLiteral) node; Token token = node.getToken(); if (token.getType()==CeylonLexer.AVERBATIM_STRING || token.getType()==CeylonLexer.VERBATIM_STRING) { String text = "\"" + literal.getText() .replace("\\", "\\\\") .replace("\"", "\\\"") .replace("`", "\\`") + "\""; int offset = node.getStartIndex(); int length = node.getStopIndex() - node.getStartIndex() + 1; String reindented = getConvertedText(text, token.getCharPositionInLine()+1, doc); TextFileChange change = new TextFileChange("Convert to Ordinary String", file); change.setEdit(new ReplaceEdit(offset, length, reindented)); proposals.add(new ConvertStringProposal("Convert to ordinary string", change)); } } } private static String getConvertedText(String text, int indentation, IDocument doc) { StringBuilder result = new StringBuilder(); for (String line: text.split("\n|\r\n?")) { if (result.length() == 0) { //the first line of the string result.append(line); } else { for (int i = 0; i<indentation; i++) { result.append(" "); } result.append(line); } result.append(Indents.getDefaultLineDelimiter(doc)); } result.setLength(result.length()-1); return result.toString(); } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertStringProposal.java
188
public class UserTransactionImpl extends BaseSpringTransactionImpl implements UserTransaction { public UserTransactionImpl( GraphDatabaseAPI neo4j) { super( neo4j ); } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_UserTransactionImpl.java
734
public class CollectionContainsRequest extends CollectionRequest { private Set<Data> valueSet; public CollectionContainsRequest() { } public CollectionContainsRequest(String name, Set<Data> valueSet) { super(name); this.valueSet = valueSet; } public CollectionContainsRequest(String name, Data value) { super(name); valueSet = new HashSet<Data>(1); valueSet.add(value); } @Override protected Operation prepareOperation() { return new CollectionContainsOperation(name, valueSet); } @Override public int getClassId() { return CollectionPortableHook.COLLECTION_CONTAINS; } public void write(PortableWriter writer) throws IOException { super.write(writer); final ObjectDataOutput out = writer.getRawDataOutput(); out.writeInt(valueSet.size()); for (Data value : valueSet) { value.writeData(out); } } public void read(PortableReader reader) throws IOException { super.read(reader); final ObjectDataInput in = reader.getRawDataInput(); final int size = in.readInt(); valueSet = new HashSet<Data>(size); for (int i = 0; i < size; i++) { final Data value = new Data(); value.readData(in); valueSet.add(value); } } @Override public String getRequiredAction() { return ActionConstants.ACTION_READ; } }
0true
hazelcast_src_main_java_com_hazelcast_collection_client_CollectionContainsRequest.java
530
public class TransportFlushAction extends TransportBroadcastOperationAction<FlushRequest, FlushResponse, ShardFlushRequest, ShardFlushResponse> { private final IndicesService indicesService; @Inject public TransportFlushAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, IndicesService indicesService) { super(settings, threadPool, clusterService, transportService); this.indicesService = indicesService; } @Override protected String executor() { return ThreadPool.Names.FLUSH; } @Override protected String transportAction() { return FlushAction.NAME; } @Override protected FlushRequest newRequest() { return new FlushRequest(); } @Override protected FlushResponse newResponse(FlushRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) { int successfulShards = 0; int failedShards = 0; List<ShardOperationFailedException> shardFailures = null; for (int i = 0; i < shardsResponses.length(); i++) { Object shardResponse = shardsResponses.get(i); if (shardResponse == null) { // a non active shard, ignore } else if (shardResponse instanceof BroadcastShardOperationFailedException) { failedShards++; if (shardFailures == null) { shardFailures = newArrayList(); } shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse)); } else { successfulShards++; } } return new FlushResponse(shardsResponses.length(), successfulShards, failedShards, shardFailures); } @Override protected ShardFlushRequest newShardRequest() { return new ShardFlushRequest(); } @Override protected ShardFlushRequest newShardRequest(ShardRouting shard, FlushRequest request) { return new ShardFlushRequest(shard.index(), shard.id(), request); } @Override protected ShardFlushResponse newShardResponse() { return new ShardFlushResponse(); } @Override protected ShardFlushResponse shardOperation(ShardFlushRequest request) throws ElasticsearchException { IndexShard indexShard = indicesService.indexServiceSafe(request.index()).shardSafe(request.shardId()); indexShard.flush(new Engine.Flush().type(request.full() ? Engine.Flush.Type.NEW_WRITER : Engine.Flush.Type.COMMIT_TRANSLOG).force(request.force())); return new ShardFlushResponse(request.index(), request.shardId()); } /** * The refresh request works against *all* shards. */ @Override protected GroupShardsIterator shards(ClusterState clusterState, FlushRequest request, String[] concreteIndices) { return clusterState.routingTable().allActiveShardsGrouped(concreteIndices, true); } @Override protected ClusterBlockException checkGlobalBlock(ClusterState state, FlushRequest request) { return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA); } @Override protected ClusterBlockException checkRequestBlock(ClusterState state, FlushRequest countRequest, String[] concreteIndices) { return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA, concreteIndices); } }
1no label
src_main_java_org_elasticsearch_action_admin_indices_flush_TransportFlushAction.java
3,191
public abstract class XFieldComparatorSource extends FieldComparatorSource { /** UTF-8 term containing a single code point: {@link Character#MAX_CODE_POINT} which will compare greater than all other index terms * since {@link Character#MAX_CODE_POINT} is a noncharacter and thus shouldn't appear in an index term. */ public static final BytesRef MAX_TERM; static { MAX_TERM = new BytesRef(); final char[] chars = Character.toChars(Character.MAX_CODE_POINT); UnicodeUtil.UTF16toUTF8(chars, 0, chars.length, MAX_TERM); } /** Whether missing values should be sorted first. */ protected final boolean sortMissingFirst(Object missingValue) { return "_first".equals(missingValue); } /** Whether missing values should be sorted last, this is the default. */ protected final boolean sortMissingLast(Object missingValue) { return missingValue == null || "_last".equals(missingValue); } /** Return the missing object value according to the reduced type of the comparator. */ protected final Object missingObject(Object missingValue, boolean reversed) { if (sortMissingFirst(missingValue) || sortMissingLast(missingValue)) { final boolean min = sortMissingFirst(missingValue) ^ reversed; switch (reducedType()) { case INT: return min ? Integer.MIN_VALUE : Integer.MAX_VALUE; case LONG: return min ? Long.MIN_VALUE : Long.MAX_VALUE; case FLOAT: return min ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY; case DOUBLE: return min ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; case STRING: case STRING_VAL: return min ? null : MAX_TERM; default: throw new UnsupportedOperationException("Unsupported reduced type: " + reducedType()); } } else { switch (reducedType()) { case INT: if (missingValue instanceof Number) { return ((Number) missingValue).intValue(); } else { return Integer.parseInt(missingValue.toString()); } case LONG: if (missingValue instanceof Number) { return ((Number) missingValue).longValue(); } else { return Long.parseLong(missingValue.toString()); } case FLOAT: if (missingValue instanceof Number) { return ((Number) missingValue).floatValue(); } else { return Float.parseFloat(missingValue.toString()); } case DOUBLE: if (missingValue instanceof Number) { return ((Number) missingValue).doubleValue(); } else { return Double.parseDouble(missingValue.toString()); } case STRING: case STRING_VAL: if (missingValue instanceof BytesRef) { return (BytesRef) missingValue; } else if (missingValue instanceof byte[]) { return new BytesRef((byte[]) missingValue); } else { return new BytesRef(missingValue.toString()); } default: throw new UnsupportedOperationException("Unsupported reduced type: " + reducedType()); } } } public abstract SortField.Type reducedType(); }
0true
src_main_java_org_elasticsearch_index_fielddata_IndexFieldData.java
39
public class SimpleCommandParser extends TypeAwareCommandParser { public SimpleCommandParser(TextCommandConstants.TextCommandType type) { super(type); } public TextCommand parser(SocketTextReader socketTextReader, String cmd, int space) { if (type == QUIT) { return new SimpleCommand(type); } else if (type == STATS) { return new StatsCommand(); } else if (type == VERSION) { return new VersionCommand(type); } else { return new ErrorCommand(UNKNOWN); } } }
0true
hazelcast_src_main_java_com_hazelcast_ascii_memcache_SimpleCommandParser.java
541
public interface ORecordHook { public enum DISTRIBUTED_EXECUTION_MODE { TARGET_NODE, SOURCE_NODE, BOTH } public enum HOOK_POSITION { FIRST, EARLY, REGULAR, LATE, LAST } public enum TYPE { ANY, BEFORE_CREATE, BEFORE_READ, BEFORE_UPDATE, BEFORE_DELETE, AFTER_CREATE, AFTER_READ, AFTER_UPDATE, AFTER_DELETE, CREATE_FAILED, READ_FAILED, UPDATE_FAILED, DELETE_FAILED, CREATE_REPLICATED, READ_REPLICATED, UPDATE_REPLICATED, DELETE_REPLICATED, BEFORE_REPLICA_ADD, AFTER_REPLICA_ADD, BEFORE_REPLICA_UPDATE, AFTER_REPLICA_UPDATE, BEFORE_REPLICA_DELETE, AFTER_REPLICA_DELETE, REPLICA_ADD_FAILED, REPLICA_UPDATE_FAILED, REPLICA_DELETE_FAILED } public enum RESULT { RECORD_NOT_CHANGED, RECORD_CHANGED, SKIP } public RESULT onTrigger(TYPE iType, ORecord<?> iRecord); public DISTRIBUTED_EXECUTION_MODE getDistributedExecutionMode(); }
0true
core_src_main_java_com_orientechnologies_orient_core_hook_ORecordHook.java
315
public interface Configuration { public boolean has(ConfigOption option, String... umbrellaElements); public<O> O get(ConfigOption<O> option, String... umbrellaElements); public Set<String> getContainedNamespaces(ConfigNamespace umbrella, String... umbrellaElements); public Map<String,Object> getSubset(ConfigNamespace umbrella, String... umbrellaElements); public Configuration restrictTo(final String... umbrellaElements); //-------------------- public static final Configuration EMPTY = new Configuration() { @Override public boolean has(ConfigOption option, String... umbrellaElements) { return false; } @Override public <O> O get(ConfigOption<O> option, String... umbrellaElements) { return option.getDefaultValue(); } @Override public Set<String> getContainedNamespaces(ConfigNamespace umbrella, String... umbrellaElements) { return Sets.newHashSet(); } @Override public Map<String, Object> getSubset(ConfigNamespace umbrella, String... umbrellaElements) { return Maps.newHashMap(); } @Override public Configuration restrictTo(String... umbrellaElements) { return EMPTY; } }; }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_Configuration.java
1,581
pMap = BLCMapUtils.keyedMap(properties, new TypedClosure<String, Property>() { @Override public String getKey(Property value) { return value.getName(); } });
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_ClassMetadata.java
937
public class OfferTimeZoneType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, OfferTimeZoneType> TYPES = new LinkedHashMap<String, OfferTimeZoneType>(); public static final OfferTimeZoneType SERVER = new OfferTimeZoneType("SERVER", "Server"); public static final OfferTimeZoneType APPLICATION = new OfferTimeZoneType("APPLICATION", "Application Supplied"); public static final OfferTimeZoneType CST = new OfferTimeZoneType("CST", "CST", true); public static final OfferTimeZoneType UTC = new OfferTimeZoneType("UTC", "UTC", true); public static OfferTimeZoneType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; private Boolean javaStandardTimeZone; public OfferTimeZoneType() { //do nothing } public OfferTimeZoneType(final String type, final String friendlyType) { this(type, friendlyType, false); } public OfferTimeZoneType(final String type, final String friendlyType, Boolean javaStandardTimeZone) { this.friendlyType = friendlyType; setType(type); setJavaStandardTimeZone(javaStandardTimeZone); } public void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } public Boolean getJavaStandardTimeZone() { return javaStandardTimeZone; } public void setJavaStandardTimeZone(Boolean javaStandardTimeZone) { this.javaStandardTimeZone = javaStandardTimeZone; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OfferTimeZoneType other = (OfferTimeZoneType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_type_OfferTimeZoneType.java
3,496
public class FieldMappersLookup implements Iterable<FieldMapper> { private volatile ImmutableList<FieldMapper> mappers; private volatile ImmutableOpenMap<String, FieldMappers> name; private volatile ImmutableOpenMap<String, FieldMappers> indexName; private volatile ImmutableOpenMap<String, FieldMappers> fullName; public FieldMappersLookup() { this.mappers = ImmutableList.of(); this.fullName = ImmutableOpenMap.of(); this.name = ImmutableOpenMap.of(); this.indexName = ImmutableOpenMap.of(); } /** * Adds a new set of mappers. */ public void addNewMappers(Iterable<FieldMapper> newMappers) { final ImmutableOpenMap.Builder<String, FieldMappers> tempName = ImmutableOpenMap.builder(name); final ImmutableOpenMap.Builder<String, FieldMappers> tempIndexName = ImmutableOpenMap.builder(indexName); final ImmutableOpenMap.Builder<String, FieldMappers> tempFullName = ImmutableOpenMap.builder(fullName); for (FieldMapper fieldMapper : newMappers) { FieldMappers mappers = tempName.get(fieldMapper.names().name()); if (mappers == null) { mappers = new FieldMappers(fieldMapper); } else { mappers = mappers.concat(fieldMapper); } tempName.put(fieldMapper.names().name(), mappers); mappers = tempIndexName.get(fieldMapper.names().indexName()); if (mappers == null) { mappers = new FieldMappers(fieldMapper); } else { mappers = mappers.concat(fieldMapper); } tempIndexName.put(fieldMapper.names().indexName(), mappers); mappers = tempFullName.get(fieldMapper.names().fullName()); if (mappers == null) { mappers = new FieldMappers(fieldMapper); } else { mappers = mappers.concat(fieldMapper); } tempFullName.put(fieldMapper.names().fullName(), mappers); } this.mappers = ImmutableList.<FieldMapper>builder().addAll(this.mappers).addAll(newMappers).build(); this.name = tempName.build(); this.indexName = tempIndexName.build(); this.fullName = tempFullName.build(); } /** * Removes the set of mappers. */ public void removeMappers(Iterable<FieldMapper> mappersToRemove) { List<FieldMapper> tempMappers = new ArrayList<FieldMapper>(this.mappers); ImmutableOpenMap.Builder<String, FieldMappers> tempName = ImmutableOpenMap.builder(this.name); ImmutableOpenMap.Builder<String, FieldMappers> tempIndexName = ImmutableOpenMap.builder(this.indexName); ImmutableOpenMap.Builder<String, FieldMappers> tempFullName = ImmutableOpenMap.builder(this.fullName); for (FieldMapper mapper : mappersToRemove) { FieldMappers mappers = tempName.get(mapper.names().name()); if (mappers != null) { mappers = mappers.remove(mapper); if (mappers.isEmpty()) { tempName.remove(mapper.names().name()); } else { tempName.put(mapper.names().name(), mappers); } } mappers = tempIndexName.get(mapper.names().indexName()); if (mappers != null) { mappers = mappers.remove(mapper); if (mappers.isEmpty()) { tempIndexName.remove(mapper.names().indexName()); } else { tempIndexName.put(mapper.names().indexName(), mappers); } } mappers = tempFullName.get(mapper.names().fullName()); if (mappers != null) { mappers = mappers.remove(mapper); if (mappers.isEmpty()) { tempFullName.remove(mapper.names().fullName()); } else { tempFullName.put(mapper.names().fullName(), mappers); } } tempMappers.remove(mapper); } this.mappers = ImmutableList.copyOf(tempMappers); this.name = tempName.build(); this.indexName = tempIndexName.build(); this.fullName = tempFullName.build(); } @Override public UnmodifiableIterator<FieldMapper> iterator() { return mappers.iterator(); } /** * The list of all mappers. */ public ImmutableList<FieldMapper> mappers() { return this.mappers; } /** * Is there a mapper (based on unique {@link FieldMapper} identity)? */ public boolean hasMapper(FieldMapper fieldMapper) { return mappers.contains(fieldMapper); } /** * Returns the field mappers based on the mapper name. */ public FieldMappers name(String name) { return this.name.get(name); } /** * Returns the field mappers based on the mapper index name. */ public FieldMappers indexName(String indexName) { return this.indexName.get(indexName); } /** * Returns the field mappers based on the mapper full name. */ public FieldMappers fullName(String fullName) { return this.fullName.get(fullName); } /** * Returns a set of the index names of a simple match regex like pattern against full name, name and index name. */ public Set<String> simpleMatchToIndexNames(String pattern) { Set<String> fields = Sets.newHashSet(); for (FieldMapper fieldMapper : mappers) { if (Regex.simpleMatch(pattern, fieldMapper.names().fullName())) { fields.add(fieldMapper.names().indexName()); } else if (Regex.simpleMatch(pattern, fieldMapper.names().indexName())) { fields.add(fieldMapper.names().indexName()); } else if (Regex.simpleMatch(pattern, fieldMapper.names().name())) { fields.add(fieldMapper.names().indexName()); } } return fields; } /** * Returns a set of the full names of a simple match regex like pattern against full name, name and index name. */ public Set<String> simpleMatchToFullName(String pattern) { Set<String> fields = Sets.newHashSet(); for (FieldMapper fieldMapper : mappers) { if (Regex.simpleMatch(pattern, fieldMapper.names().fullName())) { fields.add(fieldMapper.names().fullName()); } else if (Regex.simpleMatch(pattern, fieldMapper.names().indexName())) { fields.add(fieldMapper.names().fullName()); } else if (Regex.simpleMatch(pattern, fieldMapper.names().name())) { fields.add(fieldMapper.names().fullName()); } } return fields; } /** * Tries to find first based on {@link #fullName(String)}, then by {@link #indexName(String)}, and last * by {@link #name(String)}. */ @Nullable public FieldMappers smartName(String name) { FieldMappers fieldMappers = fullName(name); if (fieldMappers != null) { return fieldMappers; } fieldMappers = indexName(name); if (fieldMappers != null) { return fieldMappers; } return name(name); } /** * Tries to find first based on {@link #fullName(String)}, then by {@link #indexName(String)}, and last * by {@link #name(String)} and return the first mapper for it (see {@link org.elasticsearch.index.mapper.FieldMappers#mapper()}). */ @Nullable public FieldMapper smartNameFieldMapper(String name) { FieldMappers fieldMappers = smartName(name); if (fieldMappers == null) { return null; } return fieldMappers.mapper(); } }
0true
src_main_java_org_elasticsearch_index_mapper_FieldMappersLookup.java
1,495
public class AllocationExplanation implements Streamable { public static final AllocationExplanation EMPTY = new AllocationExplanation(); /** * Instances of this class keep messages and informations about nodes of an allocation */ public static class NodeExplanation { private final DiscoveryNode node; private final String description; /** * Creates a new {@link NodeExplanation} * * @param node node referenced by {@link This} {@link NodeExplanation} * @param description a message associated with the given node */ public NodeExplanation(DiscoveryNode node, String description) { this.node = node; this.description = description; } /** * The node referenced by the explanation * @return referenced node */ public DiscoveryNode node() { return node; } /** * Get the explanation for the node * @return explanation for the node */ public String description() { return description; } } private final Map<ShardId, List<NodeExplanation>> explanations = Maps.newHashMap(); /** * Create and add a node explanation to this explanation referencing a shard * @param shardId id the of the referenced shard * @param nodeExplanation Explanation itself * @return AllocationExplanation involving the explanation */ public AllocationExplanation add(ShardId shardId, NodeExplanation nodeExplanation) { List<NodeExplanation> list = explanations.get(shardId); if (list == null) { list = Lists.newArrayList(); explanations.put(shardId, list); } list.add(nodeExplanation); return this; } /** * List of explanations involved by this AllocationExplanation * @return Map of shard ids and corresponding explanations */ public Map<ShardId, List<NodeExplanation>> explanations() { return this.explanations; } /** * Read an {@link AllocationExplanation} from an {@link StreamInput} * @param in {@link StreamInput} to read from * @return a new {@link AllocationExplanation} read from the stream * @throws IOException if something bad happened while reading */ public static AllocationExplanation readAllocationExplanation(StreamInput in) throws IOException { AllocationExplanation e = new AllocationExplanation(); e.readFrom(in); return e; } @Override public void readFrom(StreamInput in) throws IOException { int size = in.readVInt(); for (int i = 0; i < size; i++) { ShardId shardId = ShardId.readShardId(in); int size2 = in.readVInt(); List<NodeExplanation> ne = Lists.newArrayListWithCapacity(size2); for (int j = 0; j < size2; j++) { DiscoveryNode node = null; if (in.readBoolean()) { node = DiscoveryNode.readNode(in); } ne.add(new NodeExplanation(node, in.readString())); } explanations.put(shardId, ne); } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVInt(explanations.size()); for (Map.Entry<ShardId, List<NodeExplanation>> entry : explanations.entrySet()) { entry.getKey().writeTo(out); out.writeVInt(entry.getValue().size()); for (NodeExplanation nodeExplanation : entry.getValue()) { if (nodeExplanation.node() == null) { out.writeBoolean(false); } else { out.writeBoolean(true); nodeExplanation.node().writeTo(out); } out.writeString(nodeExplanation.description()); } } } }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_AllocationExplanation.java
1,751
private static class PartitionAwareTestEntryProcessor implements EntryProcessor<Object, Object>, HazelcastInstanceAware { private String name; private transient HazelcastInstance hz; private PartitionAwareTestEntryProcessor(String name) { this.name = name; } @Override public Object process(Map.Entry<Object, Object> entry) { hz.getMap(name).put(entry.getKey(), entry.getValue()); return null; } @Override public EntryBackupProcessor<Object, Object> getBackupProcessor() { return null; } @Override public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { this.hz = hazelcastInstance; } }
0true
hazelcast_src_test_java_com_hazelcast_map_EntryProcessorTest.java
1,411
@XmlRootElement(name = "productOptionAllowedValue") @XmlAccessorType(value = XmlAccessType.FIELD) public class ProductOptionValueWrapper extends BaseWrapper implements APIWrapper<ProductOptionValue> { @XmlElement protected String attributeValue; @XmlElement protected Money priceAdjustment; @XmlElement protected Long productOptionId; @Override public void wrapDetails(ProductOptionValue model, HttpServletRequest request) { this.attributeValue = model.getAttributeValue(); this.priceAdjustment = model.getPriceAdjustment(); this.productOptionId = model.getProductOption().getId(); } @Override public void wrapSummary(ProductOptionValue model, HttpServletRequest request) { wrapDetails(model, request); } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_wrapper_ProductOptionValueWrapper.java
5,426
static class BytesValues extends org.elasticsearch.index.fielddata.BytesValues { private final FieldDataSource source; private final SearchScript script; private final BytesRef scratch; public BytesValues(FieldDataSource source, SearchScript script) { super(true); this.source = source; this.script = script; scratch = new BytesRef(); } @Override public int setDocument(int docId) { return source.bytesValues().setDocument(docId); } @Override public BytesRef nextValue() { BytesRef value = source.bytesValues().nextValue(); script.setNextVar("_value", value.utf8ToString()); scratch.copyChars(script.run().toString()); return scratch; } }
1no label
src_main_java_org_elasticsearch_search_aggregations_support_FieldDataSource.java
3,393
static final class SortedSetOrdinals implements Ordinals { // We don't store SortedSetDocValues as a member because Ordinals must be thread-safe private final AtomicReader reader; private final String field; private final long numOrds; public SortedSetOrdinals(AtomicReader reader, String field, long numOrds) { super(); this.reader = reader; this.field = field; this.numOrds = numOrds; } @Override public long getMemorySizeInBytes() { // Ordinals can't be distinguished from the atomic field data instance return -1; } @Override public boolean isMultiValued() { return true; } @Override public int getNumDocs() { return reader.maxDoc(); } @Override public long getNumOrds() { return numOrds; } @Override public long getMaxOrd() { return 1 + numOrds; } @Override public Docs ordinals() { final SortedSetDocValues values = getValuesNoException(reader, field); assert values.getValueCount() == numOrds; return new SortedSetDocs(this, values); } }
0true
src_main_java_org_elasticsearch_index_fielddata_plain_SortedSetDVAtomicFieldData.java
204
public static class TwoPhaseCommit extends Commit { TwoPhaseCommit( int identifier, long txId, long timeWritten ) { super( identifier, txId, timeWritten, "2PC" ); } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogEntry.java
115
static final class EmptyTask extends ForkJoinTask<Void> { private static final long serialVersionUID = -7721805057305804111L; EmptyTask() { status = ForkJoinTask.NORMAL; } // force done public final Void getRawResult() { return null; } public final void setRawResult(Void x) {} public final boolean exec() { return true; } }
0true
src_main_java_jsr166e_ForkJoinPool.java
1,033
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_ORDER_ITEM") @Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements") @AdminPresentationMergeOverrides( { @AdminPresentationMergeOverride(name = "", mergeEntries = @AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.READONLY, booleanOverrideValue = true)) } ) @AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "OrderItemImpl_baseOrderItem") public class OrderItemImpl implements OrderItem, Cloneable, AdminMainEntity, CurrencyCodeIdentifiable { private static final Log LOG = LogFactory.getLog(OrderItemImpl.class); private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "OrderItemId") @GenericGenerator( name="OrderItemId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="OrderItemImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.order.domain.OrderItemImpl") } ) @Column(name = "ORDER_ITEM_ID") @AdminPresentation(visibility = VisibilityEnum.HIDDEN_ALL) protected Long id; @ManyToOne(targetEntity = CategoryImpl.class) @JoinColumn(name = "CATEGORY_ID") @Index(name="ORDERITEM_CATEGORY_INDEX", columnNames={"CATEGORY_ID"}) @NotFound(action = NotFoundAction.IGNORE) @AdminPresentation(friendlyName = "OrderItemImpl_Category", order=Presentation.FieldOrder.CATEGORY, group = Presentation.Group.Name.Catalog, groupOrder = Presentation.Group.Order.Catalog) @AdminPresentationToOneLookup() protected Category category; @ManyToOne(targetEntity = OrderImpl.class) @JoinColumn(name = "ORDER_ID") @Index(name="ORDERITEM_ORDER_INDEX", columnNames={"ORDER_ID"}) @AdminPresentation(excluded = true) protected Order order; @Column(name = "PRICE", precision = 19, scale = 5) @AdminPresentation(friendlyName = "OrderItemImpl_Item_Price", order = Presentation.FieldOrder.PRICE, group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing, fieldType = SupportedFieldType.MONEY, prominent = true, gridOrder = 3000) protected BigDecimal price; @Column(name = "QUANTITY", nullable = false) @AdminPresentation(friendlyName = "OrderItemImpl_Item_Quantity", order = Presentation.FieldOrder.QUANTITY, group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing, prominent = true, gridOrder = 2000) protected int quantity; @Column(name = "RETAIL_PRICE", precision=19, scale=5) @AdminPresentation(friendlyName = "OrderItemImpl_Item_Retail_Price", order = Presentation.FieldOrder.RETAILPRICE, group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing, fieldType = SupportedFieldType.MONEY, prominent = true, gridOrder = 4000) protected BigDecimal retailPrice; @Column(name = "SALE_PRICE", precision=19, scale=5) @AdminPresentation(friendlyName = "OrderItemImpl_Item_Sale_Price", order = Presentation.FieldOrder.SALEPRICE, group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing, fieldType = SupportedFieldType.MONEY) protected BigDecimal salePrice; @Column(name = "NAME") @AdminPresentation(friendlyName = "OrderItemImpl_Item_Name", order=Presentation.FieldOrder.NAME, group = Presentation.Group.Name.Description, prominent=true, gridOrder = 1000, groupOrder = Presentation.Group.Order.Description) protected String name; @ManyToOne(targetEntity = PersonalMessageImpl.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "PERSONAL_MESSAGE_ID") @Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements") @Index(name="ORDERITEM_MESSAGE_INDEX", columnNames={"PERSONAL_MESSAGE_ID"}) protected PersonalMessage personalMessage; @ManyToOne(targetEntity = GiftWrapOrderItemImpl.class, cascade = { CascadeType.MERGE, CascadeType.PERSIST }) @JoinColumn(name = "GIFT_WRAP_ITEM_ID", nullable = true) @Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements") @Index(name="ORDERITEM_GIFT_INDEX", columnNames={"GIFT_WRAP_ITEM_ID"}) @AdminPresentation(excluded = true) protected GiftWrapOrderItem giftWrapOrderItem; @OneToMany(mappedBy = "orderItem", targetEntity = OrderItemAdjustmentImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "blOrderElements") @AdminPresentationCollection(friendlyName="OrderItemImpl_Adjustments", order = Presentation.FieldOrder.ADJUSTMENTS, tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced) protected List<OrderItemAdjustment> orderItemAdjustments = new ArrayList<OrderItemAdjustment>(); @OneToMany(mappedBy = "orderItem", targetEntity = OrderItemQualifierImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "blOrderElements") protected List<OrderItemQualifier> orderItemQualifiers = new ArrayList<OrderItemQualifier>(); @OneToMany(mappedBy = "orderItem", targetEntity = CandidateItemOfferImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "blOrderElements") protected List<CandidateItemOffer> candidateItemOffers = new ArrayList<CandidateItemOffer>(); @OneToMany(mappedBy = "orderItem", targetEntity = OrderItemPriceDetailImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true) @Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements") @AdminPresentationCollection(friendlyName="OrderItemImpl_Price_Details", order = Presentation.FieldOrder.PRICEDETAILS, tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced) protected List<OrderItemPriceDetail> orderItemPriceDetails = new ArrayList<OrderItemPriceDetail>(); @Column(name = "ORDER_ITEM_TYPE") @Index(name="ORDERITEM_TYPE_INDEX", columnNames={"ORDER_ITEM_TYPE"}) protected String orderItemType; @Column(name = "ITEM_TAXABLE_FLAG") protected Boolean itemTaxable; @Column(name = "RETAIL_PRICE_OVERRIDE") protected Boolean retailPriceOverride; @Column(name = "SALE_PRICE_OVERRIDE") protected Boolean salePriceOverride; @Column(name = "DISCOUNTS_ALLOWED") @AdminPresentation(friendlyName = "OrderItemImpl_Discounts_Allowed", order=Presentation.FieldOrder.DISCOUNTALLOWED, tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced) protected Boolean discountsAllowed; @OneToMany(mappedBy = "orderItem", targetEntity = OrderItemAttributeImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true) @Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements") @MapKey(name="name") @AdminPresentationMap(friendlyName = "OrderItemImpl_Attributes", tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, deleteEntityUponRemove = true, forceFreeFormKeys = true, keyPropertyFriendlyName = "OrderItemAttributeImpl_Attribute_Name" ) protected Map<String, OrderItemAttribute> orderItemAttributeMap = new HashMap<String, OrderItemAttribute>(); @Column(name = "TOTAL_TAX") @AdminPresentation(friendlyName = "OrderItemImpl_Total_Tax", order = Presentation.FieldOrder.TOTALTAX, group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing, fieldType = SupportedFieldType.MONEY) protected BigDecimal totalTax; @Override public Money getRetailPrice() { if (retailPrice == null) { updateSaleAndRetailPrices(); } return convertToMoney(retailPrice); } @Override public void setRetailPrice(Money retailPrice) { this.retailPrice = Money.toAmount(retailPrice); } @Override public Money getSalePrice() { if (salePrice == null) { updateSaleAndRetailPrices(); } if (salePrice != null) { Money returnPrice = convertToMoney(salePrice); if (retailPrice != null && returnPrice.greaterThan(getRetailPrice())) { return getRetailPrice(); } else { return returnPrice; } } else { return getRetailPrice(); } } @Override public void setSalePrice(Money salePrice) { this.salePrice = Money.toAmount(salePrice); } @Override public Money getPrice() { return getAveragePrice(); } @Override public void setPrice(Money finalPrice) { setRetailPrice(finalPrice); setSalePrice(finalPrice); setRetailPriceOverride(true); setSalePriceOverride(true); setDiscountingAllowed(false); this.price = Money.toAmount(finalPrice); } @Override public Money getTaxablePrice() { Money taxablePrice = BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, getOrder().getCurrency()); if (isTaxable() == null || isTaxable()) { taxablePrice = getAveragePrice(); } return taxablePrice; } @Override public int getQuantity() { return quantity; } @Override public void setQuantity(int quantity) { this.quantity = quantity; } @Override public Category getCategory() { return category; } @Override public void setCategory(Category category) { this.category = category; } @Override public List<CandidateItemOffer> getCandidateItemOffers() { return candidateItemOffers; } @Override public void setCandidateItemOffers(List<CandidateItemOffer> candidateItemOffers) { this.candidateItemOffers = candidateItemOffers; } @Override public PersonalMessage getPersonalMessage() { return personalMessage; } @Override public void setPersonalMessage(PersonalMessage personalMessage) { this.personalMessage = personalMessage; } @Override public Order getOrder() { return order; } @Override public void setOrder(Order order) { this.order = order; } @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 boolean isInCategory(String categoryName) { Category currentCategory = category; if (currentCategory != null) { if (currentCategory.getName().equals(categoryName)) { return true; } while ((currentCategory = currentCategory.getDefaultParentCategory()) != null) { if (currentCategory.getName().equals(categoryName)) { return true; } } } return false; } @Override public List<OrderItemQualifier> getOrderItemQualifiers() { return this.orderItemQualifiers; } @Override public void setOrderItemQualifiers(List<OrderItemQualifier> orderItemQualifiers) { this.orderItemQualifiers = orderItemQualifiers; } @Override public List<OrderItemAdjustment> getOrderItemAdjustments() { return this.orderItemAdjustments; } @Override public void setOrderItemAdjustments(List<OrderItemAdjustment> orderItemAdjustments) { this.orderItemAdjustments = orderItemAdjustments; } @Override public Money getAdjustmentValue() { return getAverageAdjustmentValue(); } @Override public GiftWrapOrderItem getGiftWrapOrderItem() { return giftWrapOrderItem; } @Override public void setGiftWrapOrderItem(GiftWrapOrderItem giftWrapOrderItem) { this.giftWrapOrderItem = giftWrapOrderItem; } @Override public OrderItemType getOrderItemType() { return convertOrderItemType(orderItemType); } @Override public void setOrderItemType(OrderItemType orderItemType) { this.orderItemType = orderItemType.getType(); } @Override public boolean getIsOnSale() { if (getSalePrice() != null) { return !getSalePrice().equals(getRetailPrice()); } else { return false; } } @Override public boolean getIsDiscounted() { if (getPrice() != null) { return !getPrice().equals(getRetailPrice()); } else { return false; } } @Override public boolean updateSaleAndRetailPrices() { if (salePrice == null) { salePrice = retailPrice; } return false; } @Override public void finalizePrice() { price = getAveragePrice().getAmount(); } @Override public void assignFinalPrice() { Money finalPrice = getTotalPrice().divide(quantity); price = finalPrice.getAmount(); } @Override public Money getPriceBeforeAdjustments(boolean allowSalesPrice) { boolean retailPriceOverride = false; for (OrderItemPriceDetail oipd : getOrderItemPriceDetails()) { if (oipd.getUseSalePrice() == false) { retailPriceOverride = true; break; } } if (allowSalesPrice && !retailPriceOverride) { return getSalePrice(); } else { return getRetailPrice(); } } @Override public void addCandidateItemOffer(CandidateItemOffer candidateItemOffer) { getCandidateItemOffers().add(candidateItemOffer); } @Override public void removeAllCandidateItemOffers() { if (getCandidateItemOffers() != null) { for (CandidateItemOffer candidate : getCandidateItemOffers()) { candidate.setOrderItem(null); } getCandidateItemOffers().clear(); } } @Override public int removeAllAdjustments() { int removedAdjustmentCount = 0; if (getOrderItemAdjustments() != null) { for (OrderItemAdjustment adjustment : getOrderItemAdjustments()) { adjustment.setOrderItem(null); } removedAdjustmentCount = getOrderItemAdjustments().size(); getOrderItemAdjustments().clear(); } assignFinalPrice(); return removedAdjustmentCount; } /** * A list of arbitrary attributes added to this item. */ @Override public Map<String,OrderItemAttribute> getOrderItemAttributes() { return orderItemAttributeMap; } /** * Sets the map of order item attributes. * * @param orderItemAttributes */ @Override public void setOrderItemAttributes(Map<String,OrderItemAttribute> orderItemAttributes) { this.orderItemAttributeMap = orderItemAttributes; } @Override public Boolean isTaxable() { return itemTaxable == null ? true : itemTaxable; } @Override public void setTaxable(Boolean taxable) { this.itemTaxable = taxable; } @Override public void setOrderItemPriceDetails(List<OrderItemPriceDetail> orderItemPriceDetails) { this.orderItemPriceDetails = orderItemPriceDetails; } @Override public boolean isDiscountingAllowed() { if (discountsAllowed == null) { return true; } else { return discountsAllowed.booleanValue(); } } @Override public void setDiscountingAllowed(boolean discountsAllowed) { this.discountsAllowed = discountsAllowed; } @Override public Money getAveragePrice() { if (quantity == 0) { return price == null ? null : BroadleafCurrencyUtils.getMoney(price, getOrder().getCurrency()); } return getTotalPrice().divide(quantity); } @Override public Money getAverageAdjustmentValue() { if (quantity == 0) { return null; } return getTotalAdjustmentValue().divide(quantity); } @Override public Money getTotalAdjustmentValue() { Money totalAdjustmentValue = BroadleafCurrencyUtils.getMoney(getOrder().getCurrency()); List<OrderItemPriceDetail> priceDetails = getOrderItemPriceDetails(); if (priceDetails != null) { for (OrderItemPriceDetail priceDetail : getOrderItemPriceDetails()) { totalAdjustmentValue = totalAdjustmentValue.add(priceDetail.getTotalAdjustmentValue()); } } return totalAdjustmentValue; } @Override public Money getTotalPrice() { Money returnValue = convertToMoney(BigDecimal.ZERO); if (orderItemPriceDetails != null && orderItemPriceDetails.size() > 0) { for (OrderItemPriceDetail oipd : orderItemPriceDetails) { returnValue = returnValue.add(oipd.getTotalAdjustedPrice()); } } else { if (price != null) { returnValue = convertToMoney(price).multiply(quantity); } else { return getSalePrice().multiply(quantity); } } return returnValue; } @Override public Money getTotalPriceBeforeAdjustments(boolean allowSalesPrice) { return getPriceBeforeAdjustments(allowSalesPrice).multiply(getQuantity()); } @Override public void setRetailPriceOverride(boolean override) { this.retailPriceOverride = Boolean.valueOf(override); } @Override public boolean isRetailPriceOverride() { if (retailPriceOverride == null) { return false; } else { return retailPriceOverride.booleanValue(); } } @Override public void setSalePriceOverride(boolean override) { this.salePriceOverride = Boolean.valueOf(override); } @Override public boolean isSalePriceOverride() { if (salePriceOverride == null) { return false; } else { return salePriceOverride.booleanValue(); } } @Override public List<OrderItemPriceDetail> getOrderItemPriceDetails() { return orderItemPriceDetails; } @Override public String getMainEntityName() { return getName(); } @Override public String getCurrencyCode() { if (getOrder().getCurrency() != null) { return getOrder().getCurrency().getCurrencyCode(); } return null; } public void checkCloneable(OrderItem orderItem) throws CloneNotSupportedException, SecurityException, NoSuchMethodException { Method cloneMethod = orderItem.getClass().getMethod("clone", new Class[]{}); if (cloneMethod.getDeclaringClass().getName().startsWith("org.broadleafcommerce") && !orderItem.getClass().getName().startsWith("org.broadleafcommerce")) { //subclass is not implementing the clone method throw new CloneNotSupportedException("Custom extensions and implementations should implement clone in " + "order to guarantee split and merge operations are performed accurately"); } } protected Money convertToMoney(BigDecimal amount) { return amount == null ? null : BroadleafCurrencyUtils.getMoney(amount, getOrder().getCurrency()); } protected OrderItemType convertOrderItemType(String type) { return OrderItemType.getInstance(type); } @Override public OrderItem clone() { //this is likely an extended class - instantiate from the fully qualified name via reflection OrderItemImpl clonedOrderItem; try { clonedOrderItem = (OrderItemImpl) Class.forName(this.getClass().getName()).newInstance(); try { checkCloneable(clonedOrderItem); } catch (CloneNotSupportedException e) { LOG.warn("Clone implementation missing in inheritance hierarchy outside of Broadleaf: " + clonedOrderItem.getClass().getName(), e); } if (candidateItemOffers != null) { for (CandidateItemOffer candidate : candidateItemOffers) { CandidateItemOffer clone = candidate.clone(); clone.setOrderItem(clonedOrderItem); clonedOrderItem.getCandidateItemOffers().add(clone); } } if (orderItemAttributeMap != null && !orderItemAttributeMap.isEmpty()) { for (OrderItemAttribute attribute : orderItemAttributeMap.values()) { OrderItemAttribute clone = attribute.clone(); clone.setOrderItem(clonedOrderItem); clonedOrderItem.getOrderItemAttributes().put(clone.getName(), clone); } } clonedOrderItem.setCategory(category); clonedOrderItem.setGiftWrapOrderItem(giftWrapOrderItem); clonedOrderItem.setName(name); clonedOrderItem.setOrder(order); clonedOrderItem.setOrderItemType(convertOrderItemType(orderItemType)); clonedOrderItem.setPersonalMessage(personalMessage); clonedOrderItem.setQuantity(quantity); clonedOrderItem.retailPrice = retailPrice; clonedOrderItem.salePrice = salePrice; clonedOrderItem.discountsAllowed = discountsAllowed; clonedOrderItem.salePriceOverride = salePriceOverride; clonedOrderItem.retailPriceOverride = retailPriceOverride; } catch (Exception e) { throw new RuntimeException(e); } return clonedOrderItem; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((category == null) ? 0 : category.hashCode()); result = prime * result + ((giftWrapOrderItem == null) ? 0 : giftWrapOrderItem.hashCode()); result = prime * result + ((order == null) ? 0 : order.hashCode()); result = prime * result + ((orderItemType == null) ? 0 : orderItemType.hashCode()); result = prime * result + ((personalMessage == null) ? 0 : personalMessage.hashCode()); result = prime * result + ((price == null) ? 0 : price.hashCode()); result = prime * result + quantity; result = prime * result + ((retailPrice == null) ? 0 : retailPrice.hashCode()); result = prime * result + ((salePrice == null) ? 0 : salePrice.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } OrderItemImpl other = (OrderItemImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (category == null) { if (other.category != null) { return false; } } else if (!category.equals(other.category)) { return false; } if (giftWrapOrderItem == null) { if (other.giftWrapOrderItem != null) { return false; } } else if (!giftWrapOrderItem.equals(other.giftWrapOrderItem)) { return false; } if (order == null) { if (other.order != null) { return false; } } else if (!order.equals(other.order)) { return false; } if (orderItemType == null) { if (other.orderItemType != null) { return false; } } else if (!orderItemType.equals(other.orderItemType)) { return false; } if (personalMessage == null) { if (other.personalMessage != null) { return false; } } else if (!personalMessage.equals(other.personalMessage)) { return false; } if (price == null) { if (other.price != null) { return false; } } else if (!price.equals(other.price)) { return false; } if (quantity != other.quantity) { return false; } if (retailPrice == null) { if (other.retailPrice != null) { return false; } } else if (!retailPrice.equals(other.retailPrice)) { return false; } if (salePrice == null) { if (other.salePrice != null) { return false; } } else if (!salePrice.equals(other.salePrice)) { return false; } return true; } public static class Presentation { public static class Tab { public static class Name { public static final String Advanced = "OrderImpl_Advanced"; } public static class Order { public static final int Advanced = 2000; } } public static class Group { public static class Name { public static final String Description = "OrderItemImpl_Description"; public static final String Pricing = "OrderItemImpl_Pricing"; public static final String Catalog = "OrderItemImpl_Catalog"; } public static class Order { public static final int Description = 1000; public static final int Pricing = 2000; public static final int Catalog = 3000; } } public static class FieldOrder { public static final int NAME = 1000; public static final int PRICE = 2000; public static final int QUANTITY = 3000; public static final int RETAILPRICE = 4000; public static final int SALEPRICE = 5000; public static final int TOTALTAX = 6000; public static final int CATEGORY = 1000; public static final int PRICEDETAILS = 1000; public static final int ADJUSTMENTS = 2000; public static final int DISCOUNTALLOWED = 3000; } } @Override public boolean isSkuActive() { //abstract method, by default return true return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_OrderItemImpl.java
1,524
public class RoutingNodesIntegrityTests extends ElasticsearchAllocationTestCase { private final ESLogger logger = Loggers.getLogger(IndexBalanceTests.class); @Test public void testBalanceAllNodesStarted() { AllocationService strategy = createAllocationService(settingsBuilder() .put("cluster.routing.allocation.node_concurrent_recoveries", 10) .put("cluster.routing.allocation.node_initial_primaries_recoveries", 10) .put("cluster.routing.allocation.allow_rebalance", "always") .put("cluster.routing.allocation.cluster_concurrent_rebalance", -1).build()); logger.info("Building initial routing table"); MetaData metaData = MetaData.builder().put(IndexMetaData.builder("test").numberOfShards(3).numberOfReplicas(1)) .put(IndexMetaData.builder("test1").numberOfShards(3).numberOfReplicas(1)).build(); RoutingTable routingTable = RoutingTable.builder().addAsNew(metaData.index("test")).addAsNew(metaData.index("test1")).build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); RoutingNodes routingNodes = clusterState.routingNodes(); logger.info("Adding three node and performing rerouting"); clusterState = ClusterState.builder(clusterState) .nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2")).put(newNode("node3"))).build(); routingNodes = clusterState.routingNodes(); assertThat(assertShardStats(routingNodes), equalTo(true)); // all shards are unassigned. so no inactive shards or primaries. assertThat(routingNodes.hasInactiveShards(), equalTo(false)); assertThat(routingNodes.hasInactivePrimaries(), equalTo(false)); assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(true)); RoutingTable prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(assertShardStats(routingNodes), equalTo(true)); assertThat(routingNodes.hasInactiveShards(), equalTo(true)); assertThat(routingNodes.hasInactivePrimaries(), equalTo(true)); assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false)); logger.info("Another round of rebalancing"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())).build(); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); logger.info("Reroute, nothing should change"); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); logger.info("Start the more shards"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(assertShardStats(routingNodes), equalTo(true)); assertThat(routingNodes.hasInactiveShards(), equalTo(false)); assertThat(routingNodes.hasInactivePrimaries(), equalTo(false)); assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false)); routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); } @Test public void testBalanceIncrementallyStartNodes() { AllocationService strategy = createAllocationService(settingsBuilder() .put("cluster.routing.allocation.node_concurrent_recoveries", 10) .put("cluster.routing.allocation.node_initial_primaries_recoveries", 10) .put("cluster.routing.allocation.allow_rebalance", "always") .put("cluster.routing.allocation.cluster_concurrent_rebalance", -1).build()); logger.info("Building initial routing table"); MetaData metaData = MetaData.builder().put(IndexMetaData.builder("test").numberOfShards(3).numberOfReplicas(1)) .put(IndexMetaData.builder("test1").numberOfShards(3).numberOfReplicas(1)).build(); RoutingTable routingTable = RoutingTable.builder().addAsNew(metaData.index("test")).addAsNew(metaData.index("test1")).build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("Adding one node and performing rerouting"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1"))).build(); RoutingTable prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); logger.info("Add another node and perform rerouting, nothing will happen since primary not started"); clusterState = ClusterState.builder(clusterState) .nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node2"))).build(); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); logger.info("Start the primary shard"); RoutingNodes routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); logger.info("Reroute, nothing should change"); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); logger.info("Start the backup shard"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); logger.info("Add another node and perform rerouting, nothing will happen since primary not started"); clusterState = ClusterState.builder(clusterState) .nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node3"))).build(); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); logger.info("Reroute, nothing should change"); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); logger.info("Start the backup shard"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(3)); routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test1").shards().size(), equalTo(3)); assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(4)); assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(4)); assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(4)); assertThat(routingNodes.node("node1").shardsWithState("test", STARTED).size(), equalTo(2)); assertThat(routingNodes.node("node2").shardsWithState("test", STARTED).size(), equalTo(2)); assertThat(routingNodes.node("node3").shardsWithState("test", STARTED).size(), equalTo(2)); assertThat(routingNodes.node("node1").shardsWithState("test1", STARTED).size(), equalTo(2)); assertThat(routingNodes.node("node2").shardsWithState("test1", STARTED).size(), equalTo(2)); assertThat(routingNodes.node("node3").shardsWithState("test1", STARTED).size(), equalTo(2)); } @Test public void testBalanceAllNodesStartedAddIndex() { AllocationService strategy = createAllocationService(settingsBuilder() .put("cluster.routing.allocation.node_concurrent_recoveries", 1) .put("cluster.routing.allocation.node_initial_primaries_recoveries", 3) .put("cluster.routing.allocation.allow_rebalance", "always") .put("cluster.routing.allocation.cluster_concurrent_rebalance", -1).build()); logger.info("Building initial routing table"); MetaData metaData = MetaData.builder().put(IndexMetaData.builder("test").numberOfShards(3).numberOfReplicas(1)).build(); RoutingTable routingTable = RoutingTable.builder().addAsNew(metaData.index("test")).build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("Adding three node and performing rerouting"); clusterState = ClusterState.builder(clusterState) .nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2")).put(newNode("node3"))).build(); RoutingNodes routingNodes = clusterState.routingNodes(); assertThat(assertShardStats(routingNodes), equalTo(true)); assertThat(routingNodes.hasInactiveShards(), equalTo(false)); assertThat(routingNodes.hasInactivePrimaries(), equalTo(false)); assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(true)); RoutingTable prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(assertShardStats(routingNodes), equalTo(true)); assertThat(routingNodes.hasInactiveShards(), equalTo(true)); assertThat(routingNodes.hasInactivePrimaries(), equalTo(true)); assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false)); logger.info("Another round of rebalancing"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())).build(); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable == routingTable, equalTo(true)); routingNodes = clusterState.routingNodes(); assertThat(routingNodes.node("node1").numberOfShardsWithState(INITIALIZING), equalTo(1)); assertThat(routingNodes.node("node2").numberOfShardsWithState(INITIALIZING), equalTo(1)); assertThat(routingNodes.node("node3").numberOfShardsWithState(INITIALIZING), equalTo(1)); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(assertShardStats(routingNodes), equalTo(true)); assertThat(routingNodes.hasInactiveShards(), equalTo(true)); assertThat(routingNodes.hasInactivePrimaries(), equalTo(false)); assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false)); assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(1)); assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(1)); assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(1)); logger.info("Reroute, nothing should change"); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); assertThat(prevRoutingTable == routingTable, equalTo(true)); logger.info("Start the more shards"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(assertShardStats(routingNodes), equalTo(true)); assertThat(routingNodes.hasInactiveShards(), equalTo(false)); assertThat(routingNodes.hasInactivePrimaries(), equalTo(false)); assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false)); assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(2)); assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(2)); assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(2)); assertThat(routingNodes.node("node1").shardsWithState("test", STARTED).size(), equalTo(2)); assertThat(routingNodes.node("node2").shardsWithState("test", STARTED).size(), equalTo(2)); assertThat(routingNodes.node("node3").shardsWithState("test", STARTED).size(), equalTo(2)); logger.info("Add new index 3 shards 1 replica"); prevRoutingTable = routingTable; metaData = MetaData.builder(metaData) .put(IndexMetaData.builder("test1").settings(ImmutableSettings.settingsBuilder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 3) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) )) .build(); routingTable = RoutingTable.builder(routingTable) .addAsNew(metaData.index("test1")) .build(); clusterState = ClusterState.builder(clusterState).metaData(metaData).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(assertShardStats(routingNodes), equalTo(true)); assertThat(routingNodes.hasInactiveShards(), equalTo(false)); assertThat(routingNodes.hasInactivePrimaries(), equalTo(false)); assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(true)); assertThat(routingTable.index("test1").shards().size(), equalTo(3)); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); logger.info("Reroute, assign"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())).build(); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(assertShardStats(routingNodes), equalTo(true)); assertThat(routingNodes.hasInactiveShards(), equalTo(true)); assertThat(routingNodes.hasInactivePrimaries(), equalTo(true)); assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false)); assertThat(prevRoutingTable == routingTable, equalTo(true)); logger.info("Reroute, start the primaries"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(assertShardStats(routingNodes), equalTo(true)); assertThat(routingNodes.hasInactiveShards(), equalTo(true)); assertThat(routingNodes.hasInactivePrimaries(), equalTo(false)); assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false)); logger.info("Reroute, start the replicas"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(assertShardStats(routingNodes), equalTo(true)); assertThat(routingNodes.hasInactiveShards(), equalTo(false)); assertThat(routingNodes.hasInactivePrimaries(), equalTo(false)); assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false)); assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(4)); assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(4)); assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(4)); assertThat(routingNodes.node("node1").shardsWithState("test1", STARTED).size(), equalTo(2)); assertThat(routingNodes.node("node2").shardsWithState("test1", STARTED).size(), equalTo(2)); assertThat(routingNodes.node("node3").shardsWithState("test1", STARTED).size(), equalTo(2)); logger.info("kill one node"); IndexShardRoutingTable indexShardRoutingTable = routingTable.index("test").shard(0); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).remove(indexShardRoutingTable.primaryShard().currentNodeId())).build(); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(assertShardStats(routingNodes), equalTo(true)); assertThat(routingNodes.hasInactiveShards(), equalTo(true)); // replica got promoted to primary assertThat(routingNodes.hasInactivePrimaries(), equalTo(false)); assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false)); logger.info("Start Recovering shards round 1"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(assertShardStats(routingNodes), equalTo(true)); assertThat(routingNodes.hasInactiveShards(), equalTo(true)); assertThat(routingNodes.hasInactivePrimaries(), equalTo(false)); assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false)); logger.info("Start Recovering shards round 2"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(assertShardStats(routingNodes), equalTo(true)); assertThat(routingNodes.hasInactiveShards(), equalTo(false)); assertThat(routingNodes.hasInactivePrimaries(), equalTo(false)); assertThat(routingNodes.hasUnassignedPrimaries(), equalTo(false)); } private boolean assertShardStats(RoutingNodes routingNodes) { return RoutingNodes.assertShardStats(routingNodes); } }
0true
src_test_java_org_elasticsearch_cluster_routing_allocation_RoutingNodesIntegrityTests.java
10
private class MessageReceiver extends SimpleChannelHandler { @Override public void channelOpen( ChannelHandlerContext ctx, ChannelStateEvent e ) throws Exception { Channel ctxChannel = ctx.getChannel(); openedChannel( getURI( (InetSocketAddress) ctxChannel.getRemoteAddress() ), ctxChannel ); channels.add( ctxChannel ); } @Override public void messageReceived( ChannelHandlerContext ctx, MessageEvent event ) throws Exception { if (!bindingDetected) { InetSocketAddress local = ((InetSocketAddress)event.getChannel().getLocalAddress()); bindingDetected = true; listeningAt( getURI( local ) ); } final Message message = (Message) event.getMessage(); // Fix FROM header since sender cannot know it's correct IP/hostname InetSocketAddress remote = (InetSocketAddress) ctx.getChannel().getRemoteAddress(); String remoteAddress = remote.getAddress().getHostAddress(); URI fromHeader = URI.create( message.getHeader( Message.FROM ) ); fromHeader = URI.create(fromHeader.getScheme()+"://"+remoteAddress + ":" + fromHeader.getPort()); message.setHeader( Message.FROM, fromHeader.toASCIIString() ); msgLog.debug( "Received:" + message ); receive( message ); } @Override public void channelDisconnected( ChannelHandlerContext ctx, ChannelStateEvent e ) throws Exception { closedChannel( getURI( (InetSocketAddress) ctx.getChannel().getRemoteAddress() ) ); } @Override public void channelClosed( ChannelHandlerContext ctx, ChannelStateEvent e ) throws Exception { closedChannel( getURI( (InetSocketAddress) ctx.getChannel().getRemoteAddress() ) ); channels.remove( ctx.getChannel() ); } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e ) throws Exception { if ( !(e.getCause() instanceof ConnectException) ) { msgLog.error( "Receive exception:", e.getCause() ); } } }
1no label
enterprise_cluster_src_main_java_org_neo4j_cluster_com_NetworkReceiver.java
670
constructors[COLLECTION_TXN_REMOVE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new CollectionTxnRemoveOperation(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
578
public abstract class OIndexAbstract<T> extends OSharedResourceAdaptiveExternal implements OIndexInternal<T> { protected final OModificationLock modificationLock = new OModificationLock(); protected static final String CONFIG_MAP_RID = "mapRid"; protected static final String CONFIG_CLUSTERS = "clusters"; private String name; protected String type; private String algorithm; protected String valueContainerAlgorithm; protected final OIndexEngine<T> indexEngine; private Set<String> clustersToIndex = new HashSet<String>(); private OIndexDefinition indexDefinition; private final String databaseName; @ODocumentInstance protected ODocument configuration; private volatile boolean rebuilding = false; private Thread rebuildThread = null; private ThreadLocal<IndexTxSnapshot> txSnapshot = new ThreadLocal<IndexTxSnapshot>() { @Override protected IndexTxSnapshot initialValue() { return new IndexTxSnapshot(); } }; public OIndexAbstract(final String type, String algorithm, final OIndexEngine<T> indexEngine, String valueContainerAlgorithm) { super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean(), OGlobalConfiguration.MVRBTREE_TIMEOUT .getValueAsInteger(), true); acquireExclusiveLock(); try { databaseName = ODatabaseRecordThreadLocal.INSTANCE.get().getName(); this.type = type; this.indexEngine = indexEngine; this.algorithm = algorithm; this.valueContainerAlgorithm = valueContainerAlgorithm; indexEngine.init(); } finally { releaseExclusiveLock(); } } protected Object getCollatingValue(final Object key) { if (key != null && getDefinition() != null) return getDefinition().getCollate().transform(key); return key; } public void flush() { acquireSharedLock(); try { indexEngine.flush(); } finally { releaseSharedLock(); } } @Override public boolean hasRangeQuerySupport() { acquireSharedLock(); try { return indexEngine.hasRangeQuerySupport(); } finally { releaseSharedLock(); } } /** * Creates the index. * * @param clusterIndexName * Cluster name where to place the TreeMap * @param clustersToIndex * @param rebuild * @param progressListener */ public OIndexInternal<?> create(final String name, final OIndexDefinition indexDefinition, final String clusterIndexName, final Set<String> clustersToIndex, boolean rebuild, final OProgressListener progressListener, final OStreamSerializer valueSerializer) { acquireExclusiveLock(); try { this.name = name; configuration = new ODocument(); this.indexDefinition = indexDefinition; if (clustersToIndex != null) this.clustersToIndex = new HashSet<String>(clustersToIndex); else this.clustersToIndex = new HashSet<String>(clustersToIndex); indexEngine.create(this.name, indexDefinition, clusterIndexName, valueSerializer, isAutomatic()); if (rebuild) rebuild(progressListener); updateConfiguration(); } catch (Exception e) { indexEngine.delete(); if (e instanceof OIndexException) throw (OIndexException) e; throw new OIndexException("Cannot create the index '" + name + "'", e); } finally { releaseExclusiveLock(); } return this; } public boolean loadFromConfiguration(final ODocument config) { acquireExclusiveLock(); try { configuration = config; clustersToIndex.clear(); IndexMetadata indexMetadata = loadMetadata(configuration); name = indexMetadata.getName(); indexDefinition = indexMetadata.getIndexDefinition(); clustersToIndex.addAll(indexMetadata.getClustersToIndex()); algorithm = indexMetadata.getAlgorithm(); valueContainerAlgorithm = indexMetadata.getValueContainerAlgorithm(); final ORID rid = config.field(CONFIG_MAP_RID, ORID.class); try { indexEngine.load(rid, name, indexDefinition, isAutomatic()); } catch (Exception e) { if (onCorruptionRepairDatabase(null, "load", "Index will be rebuilt")) { if (isAutomatic() && getDatabase().getStorage() instanceof OStorageEmbedded) // AUTOMATIC REBUILD IT OLogManager.instance().warn(this, "Cannot load index '%s' from storage (rid=%s): rebuilt it from scratch", getName(), rid); try { rebuild(); } catch (Throwable t) { OLogManager.instance().error(this, "Cannot rebuild index '%s' from storage (rid=%s) because '" + t + "'. The index will be removed in configuration", getName(), rid); // REMOVE IT return false; } } } return true; } finally { releaseExclusiveLock(); } } @Override public IndexMetadata loadMetadata(ODocument config) { String indexName = config.field(OIndexInternal.CONFIG_NAME); final ODocument indexDefinitionDoc = config.field(OIndexInternal.INDEX_DEFINITION); OIndexDefinition loadedIndexDefinition = null; if (indexDefinitionDoc != null) { try { final String indexDefClassName = config.field(OIndexInternal.INDEX_DEFINITION_CLASS); final Class<?> indexDefClass = Class.forName(indexDefClassName); loadedIndexDefinition = (OIndexDefinition) indexDefClass.getDeclaredConstructor().newInstance(); loadedIndexDefinition.fromStream(indexDefinitionDoc); } catch (final ClassNotFoundException e) { throw new OIndexException("Error during deserialization of index definition", e); } catch (final NoSuchMethodException e) { throw new OIndexException("Error during deserialization of index definition", e); } catch (final InvocationTargetException e) { throw new OIndexException("Error during deserialization of index definition", e); } catch (final InstantiationException e) { throw new OIndexException("Error during deserialization of index definition", e); } catch (final IllegalAccessException e) { throw new OIndexException("Error during deserialization of index definition", e); } } else { // @COMPATIBILITY 1.0rc6 new index model was implemented final Boolean isAutomatic = config.field(OIndexInternal.CONFIG_AUTOMATIC); if (Boolean.TRUE.equals(isAutomatic)) { final int pos = indexName.lastIndexOf('.'); if (pos < 0) throw new OIndexException("Can not convert from old index model to new one. " + "Invalid index name. Dot (.) separator should be present."); final String className = indexName.substring(0, pos); final String propertyName = indexName.substring(pos + 1); final String keyTypeStr = config.field(OIndexInternal.CONFIG_KEYTYPE); if (keyTypeStr == null) throw new OIndexException("Can not convert from old index model to new one. " + "Index key type is absent."); final OType keyType = OType.valueOf(keyTypeStr.toUpperCase(Locale.ENGLISH)); loadedIndexDefinition = new OPropertyIndexDefinition(className, propertyName, keyType); config.removeField(OIndexInternal.CONFIG_AUTOMATIC); config.removeField(OIndexInternal.CONFIG_KEYTYPE); } else if (config.field(OIndexInternal.CONFIG_KEYTYPE) != null) { final String keyTypeStr = config.field(OIndexInternal.CONFIG_KEYTYPE); final OType keyType = OType.valueOf(keyTypeStr.toUpperCase(Locale.ENGLISH)); loadedIndexDefinition = new OSimpleKeyIndexDefinition(keyType); config.removeField(OIndexInternal.CONFIG_KEYTYPE); } } final Set<String> clusters = new HashSet<String>((Collection<String>) config.field(CONFIG_CLUSTERS, OType.EMBEDDEDSET)); return new IndexMetadata(indexName, loadedIndexDefinition, clusters, type, algorithm, valueContainerAlgorithm); } public boolean contains(Object key) { checkForRebuild(); key = getCollatingValue(key); acquireSharedLock(); try { return indexEngine.contains(key); } finally { releaseSharedLock(); } } /** * Returns a set of records with key between the range passed as parameter. Range bounds are included. * <p/> * In case of {@link com.orientechnologies.common.collection.OCompositeKey}s partial keys can be used as values boundaries. * * @param iRangeFrom * Starting range * @param iRangeTo * Ending range * @return a set of records with key between the range passed as parameter. Range bounds are included. * @see com.orientechnologies.common.collection.OCompositeKey#compareTo(com.orientechnologies.common.collection.OCompositeKey) * @see #getValuesBetween(Object, boolean, Object, boolean) */ public Collection<OIdentifiable> getValuesBetween(final Object iRangeFrom, final Object iRangeTo) { checkForRebuild(); return getValuesBetween(iRangeFrom, true, iRangeTo, true); } /** * Returns a set of documents with key between the range passed as parameter. Range bounds are included. * * @param iRangeFrom * Starting range * @param iRangeTo * Ending range * @see #getEntriesBetween(Object, Object, boolean) * @return */ public Collection<ODocument> getEntriesBetween(final Object iRangeFrom, final Object iRangeTo) { checkForRebuild(); return getEntriesBetween(iRangeFrom, iRangeTo, true); } public Collection<OIdentifiable> getValuesMajor(final Object fromKey, final boolean isInclusive) { checkForRebuild(); final Set<OIdentifiable> result = new HashSet<OIdentifiable>(); getValuesMajor(fromKey, isInclusive, new IndexValuesResultListener() { @Override public boolean addResult(OIdentifiable value) { result.add(value); return true; } }); return result; } public Collection<OIdentifiable> getValuesMinor(final Object toKey, final boolean isInclusive) { checkForRebuild(); final Set<OIdentifiable> result = new HashSet<OIdentifiable>(); getValuesMinor(toKey, isInclusive, new IndexValuesResultListener() { @Override public boolean addResult(OIdentifiable value) { result.add(value); return true; } }); return result; } public Collection<ODocument> getEntriesMajor(final Object fromKey, final boolean isInclusive) { checkForRebuild(); final Set<ODocument> result = new ODocumentFieldsHashSet(); getEntriesMajor(fromKey, isInclusive, new IndexEntriesResultListener() { @Override public boolean addResult(ODocument entry) { result.add(entry); return true; } }); return result; } public Collection<ODocument> getEntriesMinor(final Object toKey, final boolean isInclusive) { checkForRebuild(); final Set<ODocument> result = new ODocumentFieldsHashSet(); getEntriesMinor(toKey, isInclusive, new IndexEntriesResultListener() { @Override public boolean addResult(ODocument entry) { result.add(entry); return true; } }); return result; } /** * Returns a set of records with key between the range passed as parameter. * <p/> * In case of {@link com.orientechnologies.common.collection.OCompositeKey}s partial keys can be used as values boundaries. * * @param iRangeFrom * Starting range * @param iFromInclusive * Indicates whether start range boundary is included in result. * @param iRangeTo * Ending range * @param iToInclusive * Indicates whether end range boundary is included in result. * @return Returns a set of records with key between the range passed as parameter. * @see com.orientechnologies.common.collection.OCompositeKey#compareTo(com.orientechnologies.common.collection.OCompositeKey) */ public Collection<OIdentifiable> getValuesBetween(Object iRangeFrom, final boolean iFromInclusive, Object iRangeTo, final boolean iToInclusive) { checkForRebuild(); iRangeFrom = getCollatingValue(iRangeFrom); iRangeTo = getCollatingValue(iRangeTo); final Set<OIdentifiable> result = new HashSet<OIdentifiable>(); getValuesBetween(iRangeFrom, iFromInclusive, iRangeTo, iToInclusive, new IndexValuesResultListener() { @Override public boolean addResult(OIdentifiable value) { result.add(value); return true; } }); return result; } public Collection<ODocument> getEntriesBetween(Object iRangeFrom, Object iRangeTo, final boolean iInclusive) { checkForRebuild(); iRangeFrom = getCollatingValue(iRangeFrom); iRangeTo = getCollatingValue(iRangeTo); final Set<ODocument> result = new ODocumentFieldsHashSet(); getEntriesBetween(iRangeFrom, iRangeTo, iInclusive, new IndexEntriesResultListener() { @Override public boolean addResult(ODocument entry) { result.add(entry); return true; } }); return result; } public Collection<OIdentifiable> getValues(final Collection<?> iKeys) { checkForRebuild(); final Set<OIdentifiable> result = new HashSet<OIdentifiable>(); getValues(iKeys, new IndexValuesResultListener() { @Override public boolean addResult(OIdentifiable value) { result.add(value); return true; } }); return result; } public Collection<ODocument> getEntries(final Collection<?> iKeys) { checkForRebuild(); final Set<ODocument> result = new ODocumentFieldsHashSet(); getEntries(iKeys, new IndexEntriesResultListener() { @Override public boolean addResult(ODocument entry) { result.add(entry); return true; } }); return result; } public ORID getIdentity() { acquireSharedLock(); try { return indexEngine.getIdentity(); } finally { releaseSharedLock(); } } public long rebuild() { return rebuild(new OIndexRebuildOutputListener(this)); } @Override public void setRebuildingFlag() { rebuilding = true; } @Override public void close() { acquireSharedLock(); try { indexEngine.close(); } finally { releaseSharedLock(); } } /** * Populates the index with all the existent records. Uses the massive insert intent to speed up and keep the consumed memory low. */ public long rebuild(final OProgressListener iProgressListener) { long documentIndexed = 0; final boolean intentInstalled = getDatabase().declareIntent(new OIntentMassiveInsert()); modificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { rebuildThread = Thread.currentThread(); rebuilding = true; try { indexEngine.clear(); } catch (Exception e) { // IGNORE EXCEPTION: IF THE REBUILD WAS LAUNCHED IN CASE OF RID INVALID CLEAR ALWAYS GOES IN ERROR } int documentNum = 0; long documentTotal = 0; for (final String cluster : clustersToIndex) documentTotal += getDatabase().countClusterElements(cluster); if (iProgressListener != null) iProgressListener.onBegin(this, documentTotal); for (final String clusterName : clustersToIndex) try { for (final ORecord<?> record : getDatabase().browseCluster(clusterName)) { if (Thread.interrupted()) throw new OCommandExecutionException("The index rebuild has been interrupted"); if (record instanceof ODocument) { final ODocument doc = (ODocument) record; if (indexDefinition == null) throw new OConfigurationException("Index '" + name + "' cannot be rebuilt because has no a valid definition (" + indexDefinition + ")"); final Object fieldValue = indexDefinition.getDocumentValueToIndex(doc); if (fieldValue != null) { try { if (fieldValue instanceof Collection) { for (final Object fieldValueItem : (Collection<?>) fieldValue) { put(fieldValueItem, doc); } } else put(fieldValue, doc); } catch (OIndexException e) { OLogManager.instance().error( this, "Exception during index rebuild. Exception was caused by following key/ value pair - key %s, value %s." + " Rebuild will continue from this point.", e, fieldValue, doc.getIdentity()); } ++documentIndexed; } } documentNum++; if (iProgressListener != null) iProgressListener.onProgress(this, documentNum, documentNum * 100f / documentTotal); } } catch (NoSuchElementException e) { // END OF CLUSTER REACHED, IGNORE IT } flush(); unload(); if (iProgressListener != null) iProgressListener.onCompletition(this, true); } catch (final Exception e) { if (iProgressListener != null) iProgressListener.onCompletition(this, false); try { indexEngine.clear(); } catch (Exception e2) { // IGNORE EXCEPTION: IF THE REBUILD WAS LAUNCHED IN CASE OF RID INVALID CLEAR ALWAYS GOES IN ERROR } throw new OIndexException("Error on rebuilding the index for clusters: " + clustersToIndex, e); } finally { rebuilding = false; rebuildThread = null; if (intentInstalled) getDatabase().declareIntent(null); releaseExclusiveLock(); } } finally { modificationLock.releaseModificationLock(); } return documentIndexed; } public boolean remove(final Object key, final OIdentifiable value) { checkForRebuild(); modificationLock.requestModificationLock(); try { return remove(key); } finally { modificationLock.releaseModificationLock(); } } public boolean remove(final Object key) { checkForRebuild(); modificationLock.requestModificationLock(); try { acquireSharedLock(); try { return indexEngine.remove(key); } finally { releaseSharedLock(); } } finally { modificationLock.releaseModificationLock(); } } public OIndex<T> clear() { checkForRebuild(); modificationLock.requestModificationLock(); try { acquireSharedLock(); try { indexEngine.clear(); return this; } finally { releaseSharedLock(); } } finally { modificationLock.releaseModificationLock(); } } public OIndexInternal<T> delete() { modificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { indexEngine.delete(); if (valueContainerAlgorithm.equals(ODefaultIndexFactory.SBTREEBONSAI_VALUE_CONTAINER)) { final OStorage storage = getDatabase().getStorage(); if (storage instanceof OStorageLocal) { final ODiskCache diskCache = ((OStorageLocal) storage).getDiskCache(); try { final String fileName = getName() + OIndexRIDContainer.INDEX_FILE_EXTENSION; if (diskCache.exists(fileName)) { final long fileId = diskCache.openFile(fileName); diskCache.deleteFile(fileId); } } catch (IOException e) { OLogManager.instance().error(this, "Can't delete file for value containers", e); } } } return this; } finally { releaseExclusiveLock(); } } finally { modificationLock.releaseModificationLock(); } } @Override public void deleteWithoutIndexLoad(String indexName) { modificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { indexEngine.deleteWithoutLoad(indexName); } finally { releaseExclusiveLock(); } } finally { modificationLock.releaseModificationLock(); } } public Iterator<Entry<Object, T>> iterator() { checkForRebuild(); acquireSharedLock(); try { return indexEngine.iterator(); } finally { releaseSharedLock(); } } public Iterator<Entry<Object, T>> inverseIterator() { checkForRebuild(); acquireSharedLock(); try { return indexEngine.inverseIterator(); } finally { releaseSharedLock(); } } public Iterable<Object> keys() { checkForRebuild(); acquireSharedLock(); try { return indexEngine.keys(); } finally { releaseSharedLock(); } } public String getName() { return name; } public String getType() { return type; } @Override public String getAlgorithm() { return algorithm; } @Override public String toString() { return name; } public OIndexInternal<T> getInternal() { return this; } public Set<String> getClusters() { acquireSharedLock(); try { return Collections.unmodifiableSet(clustersToIndex); } finally { releaseSharedLock(); } } public OIndexAbstract<T> addCluster(final String clusterName) { acquireExclusiveLock(); try { if (clustersToIndex.add(clusterName)) updateConfiguration(); return this; } finally { releaseExclusiveLock(); } } public OIndexAbstract<T> removeCluster(String iClusterName) { acquireExclusiveLock(); try { if (clustersToIndex.remove(iClusterName)) updateConfiguration(); return this; } finally { releaseExclusiveLock(); } } public void checkEntry(final OIdentifiable iRecord, final Object iKey) { } public void unload() { acquireSharedLock(); try { indexEngine.unload(); } finally { releaseSharedLock(); } } public ODocument updateConfiguration() { acquireExclusiveLock(); try { configuration.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); try { configuration.field(OIndexInternal.CONFIG_TYPE, type); configuration.field(OIndexInternal.CONFIG_NAME, name); if (indexDefinition != null) { final ODocument indexDefDocument = indexDefinition.toStream(); if (!indexDefDocument.hasOwners()) indexDefDocument.addOwner(configuration); configuration.field(OIndexInternal.INDEX_DEFINITION, indexDefDocument, OType.EMBEDDED); configuration.field(OIndexInternal.INDEX_DEFINITION_CLASS, indexDefinition.getClass().getName()); } else { configuration.removeField(OIndexInternal.INDEX_DEFINITION); configuration.removeField(OIndexInternal.INDEX_DEFINITION_CLASS); } configuration.field(CONFIG_CLUSTERS, clustersToIndex, OType.EMBEDDEDSET); configuration.field(CONFIG_MAP_RID, indexEngine.getIdentity()); configuration.field(ALGORITHM, algorithm); configuration.field(VALUE_CONTAINER_ALGORITHM, valueContainerAlgorithm); } finally { configuration.setInternalStatus(ORecordElement.STATUS.LOADED); } } finally { releaseExclusiveLock(); } return configuration; } @SuppressWarnings("unchecked") public void addTxOperation(final ODocument operationDocument) { checkForRebuild(); if (operationDocument == null) return; acquireExclusiveLock(); try { indexEngine.startTransaction(); final IndexTxSnapshot indexTxSnapshot = txSnapshot.get(); final Boolean clearAll = operationDocument.field("clear"); if (clearAll != null && clearAll) { indexTxSnapshot.clear = true; indexTxSnapshot.indexSnapshot.clear(); } final Collection<ODocument> entries = operationDocument.field("entries"); final Map<Object, Object> snapshot = indexTxSnapshot.indexSnapshot; for (final ODocument entry : entries) { final String serializedKey = OStringSerializerHelper.decode((String) entry.field("k")); final Object key; try { final ODocument keyContainer = new ODocument(); keyContainer.setLazyLoad(false); keyContainer.fromString(serializedKey); final Object storedKey = keyContainer.field("key"); if (storedKey instanceof List) key = new OCompositeKey((List<? extends Comparable<?>>) storedKey); else if (Boolean.TRUE.equals(keyContainer.field("binary"))) { key = OStreamSerializerAnyStreamable.INSTANCE.fromStream((byte[]) storedKey); } else key = storedKey; } catch (IOException ioe) { throw new OTransactionException("Error during index changes deserialization. ", ioe); } final List<ODocument> operations = entry.field("ops"); if (operations != null) { for (final ODocument op : operations) { final int operation = (Integer) op.rawField("o"); final OIdentifiable value = op.field("v", OType.LINK); if (operation == OPERATION.PUT.ordinal()) putInSnapshot(key, value, snapshot); else if (operation == OPERATION.REMOVE.ordinal()) { if (value == null) removeFromSnapshot(key, snapshot); else { removeFromSnapshot(key, value, snapshot); } } } } } } finally { indexEngine.stopTransaction(); releaseExclusiveLock(); } } @Override public void commit() { acquireExclusiveLock(); try { final IndexTxSnapshot indexTxSnapshot = txSnapshot.get(); if (indexTxSnapshot.clear) clear(); commitSnapshot(indexTxSnapshot.indexSnapshot); } finally { releaseExclusiveLock(); } } @Override public void preCommit() { txSnapshot.set(new IndexTxSnapshot()); } @Override public void postCommit() { txSnapshot.set(new IndexTxSnapshot()); } protected abstract void commitSnapshot(Map<Object, Object> snapshot); protected abstract void putInSnapshot(Object key, OIdentifiable value, Map<Object, Object> snapshot); protected abstract void removeFromSnapshot(Object key, OIdentifiable value, Map<Object, Object> snapshot); protected void removeFromSnapshot(Object key, Map<Object, Object> snapshot) { snapshot.put(key, RemovedValue.INSTANCE); } public ODocument getConfiguration() { acquireSharedLock(); try { return configuration; } finally { releaseSharedLock(); } } public boolean isAutomatic() { acquireSharedLock(); try { return indexDefinition != null && indexDefinition.getClassName() != null; } finally { releaseSharedLock(); } } public void onCreate(final ODatabase iDatabase) { } public void onDelete(final ODatabase iDatabase) { } public void onOpen(final ODatabase iDatabase) { } public void onBeforeTxBegin(final ODatabase iDatabase) { acquireSharedLock(); try { indexEngine.beforeTxBegin(); } finally { releaseSharedLock(); } } public void onBeforeTxRollback(final ODatabase iDatabase) { } public boolean onCorruptionRepairDatabase(final ODatabase database, final String reason, String whatWillbeFixed) { if (reason.equals("load")) return true; return false; } public void onAfterTxRollback(final ODatabase database) { acquireSharedLock(); try { indexEngine.afterTxRollback(); } finally { releaseSharedLock(); } } public void onBeforeTxCommit(final ODatabase database) { } public void onAfterTxCommit(final ODatabase iDatabase) { acquireSharedLock(); try { indexEngine.afterTxCommit(); } finally { releaseSharedLock(); } } public void onClose(final ODatabase iDatabase) { if (isRebuiding()) return; acquireSharedLock(); try { indexEngine.closeDb(); } finally { releaseSharedLock(); } } protected void checkForKeyType(final Object iKey) { if (indexDefinition == null) { // RECOGNIZE THE KEY TYPE AT RUN-TIME final OType type = OType.getTypeByClass(iKey.getClass()); if (type == null) return; indexDefinition = new OSimpleKeyIndexDefinition(type); updateConfiguration(); } } protected ODatabaseRecord getDatabase() { return ODatabaseRecordThreadLocal.INSTANCE.get(); } public OType[] getKeyTypes() { acquireSharedLock(); try { if (indexDefinition == null) return null; return indexDefinition.getTypes(); } finally { releaseSharedLock(); } } public OIndexDefinition getDefinition() { acquireSharedLock(); try { return indexDefinition; } finally { releaseSharedLock(); } } public void freeze(boolean throwException) { modificationLock.prohibitModifications(throwException); } public void release() { modificationLock.allowModifications(); } public void acquireModificationLock() { modificationLock.requestModificationLock(); } public void releaseModificationLock() { try { modificationLock.releaseModificationLock(); } catch (IllegalMonitorStateException e) { OLogManager.instance().error(this, "Error on releasing index lock against %s", e, getName()); throw e; } } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final OIndexAbstract<?> that = (OIndexAbstract<?>) o; if (!name.equals(that.name)) return false; return true; } @Override public int hashCode() { return name.hashCode(); } public String getDatabaseName() { return databaseName; } public boolean isRebuiding() { return rebuilding; } protected void checkForRebuild() { if (rebuilding && !Thread.currentThread().equals(rebuildThread)) { throw new OIndexException("Index " + name + " is rebuilding now and can not be used."); } } protected static final class RemovedValue { public static final RemovedValue INSTANCE = new RemovedValue(); } protected static final class IndexTxSnapshot { public Map<Object, Object> indexSnapshot = new HashMap<Object, Object>(); public boolean clear = false; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_index_OIndexAbstract.java
3,430
public class IndexShardGatewaySnapshotNotAllowedException extends IndexShardGatewayException { public IndexShardGatewaySnapshotNotAllowedException(ShardId shardId, String msg) { super(shardId, msg); } }
0true
src_main_java_org_elasticsearch_index_gateway_IndexShardGatewaySnapshotNotAllowedException.java
1,206
public final class PartitionAwareKey<K,P> implements PartitionAware<Object>, DataSerializable { private K key; private P partitionKey; /** * Creates a new PartitionAwareKey. * * @param key the key * @param partitionKey the partitionKey * @throws IllegalArgumentException if key or partitionKey is null. */ public PartitionAwareKey(K key, P partitionKey) { this.key = ValidationUtil.isNotNull(key,"key"); this.partitionKey = ValidationUtil.isNotNull(partitionKey,"partitionKey"); } //constructor needed for deserialization. private PartitionAwareKey(){ } public K getKey() { return key; } @Override public P getPartitionKey() { return partitionKey; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeObject(key); out.writeObject(partitionKey); } @Override public void readData(ObjectDataInput in) throws IOException { this.key = in.readObject(); this.partitionKey = in.readObject(); } @Override public boolean equals(Object thatObject) { if (this == thatObject) return true; if (thatObject == null || getClass() != thatObject.getClass()) return false; PartitionAwareKey that = (PartitionAwareKey) thatObject; if (!key.equals(that.key)) return false; if (!partitionKey.equals(that.partitionKey)) return false; return true; } @Override public int hashCode() { int result = key.hashCode(); result = 31 * result + partitionKey.hashCode(); return result; } @Override public String toString() { return "PartitionAwareKey{" + "key=" + key + ", partitionKey=" + partitionKey + '}'; } }
0true
hazelcast_src_main_java_com_hazelcast_core_PartitionAwareKey.java
2,379
KILO { @Override public long toSingles(long size) { return x(size, C1 / C0, MAX / (C1 / C0)); } @Override public long toKilo(long size) { return size; } @Override public long toMega(long size) { return size / (C2 / C1); } @Override public long toGiga(long size) { return size / (C3 / C1); } @Override public long toTera(long size) { return size / (C4 / C1); } @Override public long toPeta(long size) { return size / (C5 / C1); } },
0true
src_main_java_org_elasticsearch_common_unit_SizeUnit.java
1,680
runnable = new Runnable() { public void run() { map.putAsync(null, "value", 1, TimeUnit.SECONDS); } };
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
218
Collections.sort(orderedColumns, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o1.getValue().compareTo(o2.getValue()); } });
0true
tools_src_main_java_com_orientechnologies_orient_console_OTableFormatter.java
97
final Thread thread = new Thread() { public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } hz1.getLifecycleService().terminate(); } };
0true
hazelcast-client_src_test_java_com_hazelcast_client_ClientIssueTest.java
1,030
public class Config { private URL configurationUrl; private File configurationFile; private ClassLoader classLoader; private Properties properties = new Properties(); private String instanceName = null; private GroupConfig groupConfig = new GroupConfig(); private NetworkConfig networkConfig = new NetworkConfig(); private final Map<String, MapConfig> mapConfigs = new ConcurrentHashMap<String, MapConfig>(); private final Map<String, TopicConfig> topicConfigs = new ConcurrentHashMap<String, TopicConfig>(); private final Map<String, QueueConfig> queueConfigs = new ConcurrentHashMap<String, QueueConfig>(); private final Map<String, MultiMapConfig> multiMapConfigs = new ConcurrentHashMap<String, MultiMapConfig>(); private final Map<String, ListConfig> listConfigs = new ConcurrentHashMap<String, ListConfig>(); private final Map<String, SetConfig> setConfigs = new ConcurrentHashMap<String, SetConfig>(); private final Map<String, ExecutorConfig> executorConfigs = new ConcurrentHashMap<String, ExecutorConfig>(); private final Map<String, SemaphoreConfig> semaphoreConfigs = new ConcurrentHashMap<String, SemaphoreConfig>(); private final Map<String, ReplicatedMapConfig> replicatedMapConfigs = new ConcurrentHashMap<String, ReplicatedMapConfig>(); private final Map<String, WanReplicationConfig> wanReplicationConfigs = new ConcurrentHashMap<String, WanReplicationConfig>(); private final Map<String, JobTrackerConfig> jobTrackerConfigs = new ConcurrentHashMap<String, JobTrackerConfig>(); private ServicesConfig servicesConfig = new ServicesConfig(); private SecurityConfig securityConfig = new SecurityConfig(); private final List<ListenerConfig> listenerConfigs = new LinkedList<ListenerConfig>(); private PartitionGroupConfig partitionGroupConfig = new PartitionGroupConfig(); private ManagementCenterConfig managementCenterConfig = new ManagementCenterConfig(); private SerializationConfig serializationConfig = new SerializationConfig(); private ManagedContext managedContext; private ConcurrentMap<String, Object> userContext = new ConcurrentHashMap<String, Object>(); private MemberAttributeConfig memberAttributeConfig = new MemberAttributeConfig(); private String licenseKey; public Config() { } public Config(String instanceName){ this.instanceName = instanceName; } /** * Returns the class-loader that will be used in serialization. * <p> If null, then thread context class-loader will be used instead. * * @return the class-loader */ public ClassLoader getClassLoader() { return classLoader; } /** * Sets the class-loader to be used during de-serialization * and as context class-loader of Hazelcast internal threads. * * <p> * If not set (or set to null); thread context class-loader * will be used in required places. * * <p> * Default value is null. * * @param classLoader class-loader to be used during de-serialization * @return Config instance */ public Config setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; return this; } public String getProperty(String name) { String value = properties.getProperty(name); return value != null ? value : System.getProperty(name); } public Config setProperty(String name, String value) { properties.put(name, value); return this; } public MemberAttributeConfig getMemberAttributeConfig() { return memberAttributeConfig; } public void setMemberAttributeConfig(MemberAttributeConfig memberAttributeConfig) { this.memberAttributeConfig = memberAttributeConfig; } public Properties getProperties() { return properties; } public Config setProperties(Properties properties) { this.properties = properties; return this; } public String getInstanceName() { return instanceName; } public Config setInstanceName(String instanceName) { this.instanceName = instanceName; return this; } public GroupConfig getGroupConfig() { return groupConfig; } public Config setGroupConfig(GroupConfig groupConfig) { this.groupConfig = groupConfig; return this; } public NetworkConfig getNetworkConfig() { return networkConfig; } public Config setNetworkConfig(NetworkConfig networkConfig) { this.networkConfig = networkConfig; return this; } public MapConfig findMapConfig(String name){ name = getBaseName(name); MapConfig config; if ((config = lookupByPattern(mapConfigs, name)) != null) return config.getAsReadOnly(); return getMapConfig("default").getAsReadOnly(); } public MapConfig getMapConfig(String name) { name = getBaseName(name); MapConfig config; if ((config = lookupByPattern(mapConfigs, name)) != null) return config; MapConfig defConfig = mapConfigs.get("default"); if (defConfig == null) { defConfig = new MapConfig(); defConfig.setName("default"); addMapConfig(defConfig); } config = new MapConfig(defConfig); config.setName(name); addMapConfig(config); return config; } public Config addMapConfig(MapConfig mapConfig) { mapConfigs.put(mapConfig.getName(), mapConfig); return this; } /** * @return the mapConfigs */ public Map<String, MapConfig> getMapConfigs() { return mapConfigs; } /** * @param mapConfigs the mapConfigs to set */ public Config setMapConfigs(Map<String, MapConfig> mapConfigs) { this.mapConfigs.clear(); this.mapConfigs.putAll(mapConfigs); for (final Entry<String, MapConfig> entry : this.mapConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; } public QueueConfig findQueueConfig(String name){ name = getBaseName(name); QueueConfig config; if ((config = lookupByPattern(queueConfigs, name)) != null) return config.getAsReadOnly(); return getQueueConfig("default").getAsReadOnly(); } public QueueConfig getQueueConfig(String name) { name = getBaseName(name); QueueConfig config; if ((config = lookupByPattern(queueConfigs, name)) != null) return config; QueueConfig defConfig = queueConfigs.get("default"); if (defConfig == null) { defConfig = new QueueConfig(); defConfig.setName("default"); addQueueConfig(defConfig); } config = new QueueConfig(defConfig); config.setName(name); addQueueConfig(config); return config; } public Config addQueueConfig(QueueConfig queueConfig) { queueConfigs.put(queueConfig.getName(), queueConfig); return this; } public Map<String, QueueConfig> getQueueConfigs() { return queueConfigs; } public Config setQueueConfigs(Map<String, QueueConfig> queueConfigs) { this.queueConfigs.clear(); this.queueConfigs.putAll(queueConfigs); for (Entry<String, QueueConfig> entry : queueConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; } public ListConfig findListConfig(String name){ name = getBaseName(name); ListConfig config; if ((config = lookupByPattern(listConfigs, name)) != null) return config.getAsReadOnly(); return getListConfig("default").getAsReadOnly(); } public ListConfig getListConfig(String name) { name = getBaseName(name); ListConfig config; if ((config = lookupByPattern(listConfigs, name)) != null) return config; ListConfig defConfig = listConfigs.get("default"); if (defConfig == null) { defConfig = new ListConfig(); defConfig.setName("default"); addListConfig(defConfig); } config = new ListConfig(defConfig); config.setName(name); addListConfig(config); return config; } public Config addListConfig(ListConfig listConfig) { listConfigs.put(listConfig.getName(), listConfig); return this; } public Map<String, ListConfig> getListConfigs() { return listConfigs; } public Config setListConfigs(Map<String, ListConfig> listConfigs) { this.listConfigs.clear(); this.listConfigs.putAll(listConfigs); for (Entry<String, ListConfig> entry : listConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; } public SetConfig findSetConfig(String name){ name = getBaseName(name); SetConfig config; if ((config = lookupByPattern(setConfigs, name)) != null) return config.getAsReadOnly(); return getSetConfig("default").getAsReadOnly(); } public SetConfig getSetConfig(String name) { name = getBaseName(name); SetConfig config; if ((config = lookupByPattern(setConfigs, name)) != null) return config; SetConfig defConfig = setConfigs.get("default"); if (defConfig == null) { defConfig = new SetConfig(); defConfig.setName("default"); addSetConfig(defConfig); } config = new SetConfig(defConfig); config.setName(name); addSetConfig(config); return config; } public Config addSetConfig(SetConfig setConfig) { setConfigs.put(setConfig.getName(), setConfig); return this; } public Map<String, SetConfig> getSetConfigs() { return setConfigs; } public Config setSetConfigs(Map<String, SetConfig> setConfigs) { this.setConfigs.clear(); this.setConfigs.putAll(setConfigs); for (Entry<String, SetConfig> entry : setConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; } public MultiMapConfig findMultiMapConfig(String name){ name = getBaseName(name); MultiMapConfig config; if ((config = lookupByPattern(multiMapConfigs, name)) != null) return config.getAsReadOnly(); return getMultiMapConfig("default").getAsReadOnly(); } public MultiMapConfig getMultiMapConfig(String name) { name = getBaseName(name); MultiMapConfig config; if ((config = lookupByPattern(multiMapConfigs, name)) != null) return config; MultiMapConfig defConfig = multiMapConfigs.get("default"); if (defConfig == null) { defConfig = new MultiMapConfig(); defConfig.setName("default"); addMultiMapConfig(defConfig); } config = new MultiMapConfig(defConfig); config.setName(name); addMultiMapConfig(config); return config; } public Config addMultiMapConfig(MultiMapConfig multiMapConfig) { multiMapConfigs.put(multiMapConfig.getName(), multiMapConfig); return this; } public Map<String, MultiMapConfig> getMultiMapConfigs() { return multiMapConfigs; } public Config setMultiMapConfigs(Map<String, MultiMapConfig> multiMapConfigs) { this.multiMapConfigs.clear(); this.multiMapConfigs.putAll(multiMapConfigs); for (final Entry<String, MultiMapConfig> entry : this.multiMapConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; } public ReplicatedMapConfig findReplicatedMapConfig(String name){ ReplicatedMapConfig config; if ((config = lookupByPattern(replicatedMapConfigs, name)) != null) return config.getAsReadOnly(); return getReplicatedMapConfig("default").getAsReadOnly(); } public ReplicatedMapConfig getReplicatedMapConfig(String name) { ReplicatedMapConfig config; if ((config = lookupByPattern(replicatedMapConfigs, name)) != null) return config; ReplicatedMapConfig defConfig = replicatedMapConfigs.get("default"); if (defConfig == null) { defConfig = new ReplicatedMapConfig(); defConfig.setName("default"); addReplicatedMapConfig(defConfig); } config = new ReplicatedMapConfig(defConfig); config.setName(name); addReplicatedMapConfig(config); return config; } public Config addReplicatedMapConfig(ReplicatedMapConfig replicatedMapConfig) { replicatedMapConfigs.put(replicatedMapConfig.getName(), replicatedMapConfig); return this; } public Map<String, ReplicatedMapConfig> getReplicatedMapConfigs() { return replicatedMapConfigs; } public Config setReplicatedMapConfigs(Map<String, ReplicatedMapConfig> replicatedMapConfigs) { this.replicatedMapConfigs.clear(); this.replicatedMapConfigs.putAll(replicatedMapConfigs); for (final Entry<String, ReplicatedMapConfig> entry : this.replicatedMapConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; } public TopicConfig findTopicConfig(String name){ name = getBaseName(name); TopicConfig config; if ((config = lookupByPattern(topicConfigs, name)) != null) return config.getAsReadOnly(); return getTopicConfig("default").getAsReadOnly(); } public TopicConfig getTopicConfig(String name) { name = getBaseName(name); TopicConfig config; if ((config = lookupByPattern(topicConfigs, name)) != null) { return config; } TopicConfig defConfig = topicConfigs.get("default"); if (defConfig == null) { defConfig = new TopicConfig(); defConfig.setName("default"); addTopicConfig(defConfig); } config = new TopicConfig(defConfig); config.setName(name); addTopicConfig(config); return config; } public Config addTopicConfig(TopicConfig topicConfig) { topicConfigs.put(topicConfig.getName(), topicConfig); return this; } /** * @return the topicConfigs */ public Map<String, TopicConfig> getTopicConfigs() { return topicConfigs; } /** * @param mapTopicConfigs the topicConfigs to set */ public Config setTopicConfigs(Map<String, TopicConfig> mapTopicConfigs) { this.topicConfigs.clear(); this.topicConfigs.putAll(mapTopicConfigs); for (final Entry<String, TopicConfig> entry : this.topicConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; } public ExecutorConfig findExecutorConfig(String name){ name = getBaseName(name); ExecutorConfig config; if ((config = lookupByPattern(executorConfigs, name)) != null) return config.getAsReadOnly(); return getExecutorConfig("default").getAsReadOnly(); } /** * Returns the ExecutorConfig for the given name * * @param name name of the executor config * @return ExecutorConfig */ public ExecutorConfig getExecutorConfig(String name) { name = getBaseName(name); ExecutorConfig config; if ((config = lookupByPattern(executorConfigs, name)) != null) return config; ExecutorConfig defConfig = executorConfigs.get("default"); if (defConfig == null) { defConfig = new ExecutorConfig(); defConfig.setName("default"); addExecutorConfig(defConfig); } config = new ExecutorConfig(defConfig); config.setName(name); addExecutorConfig(config); return config; } /** * Adds a new ExecutorConfig by name * * @param executorConfig executor config to add * @return this config instance */ public Config addExecutorConfig(ExecutorConfig executorConfig) { this.executorConfigs.put(executorConfig.getName(), executorConfig); return this; } public Map<String, ExecutorConfig> getExecutorConfigs() { return executorConfigs; } public Config setExecutorConfigs(Map<String, ExecutorConfig> executorConfigs) { this.executorConfigs.clear(); this.executorConfigs.putAll(executorConfigs); for (Entry<String, ExecutorConfig> entry : executorConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; } public SemaphoreConfig findSemaphoreConfig(String name){ name = getBaseName(name); SemaphoreConfig config; if ((config = lookupByPattern(semaphoreConfigs, name)) != null) return config.getAsReadOnly(); return getSemaphoreConfig("default").getAsReadOnly(); } /** * Returns the SemaphoreConfig for the given name * * @param name name of the semaphore config * @return SemaphoreConfig */ public SemaphoreConfig getSemaphoreConfig(String name) { name = getBaseName(name); SemaphoreConfig config; if ((config = lookupByPattern(semaphoreConfigs, name)) != null) return config; SemaphoreConfig defConfig = semaphoreConfigs.get("default"); if (defConfig == null) { defConfig = new SemaphoreConfig(); defConfig.setName("default"); addSemaphoreConfig(defConfig); } config = new SemaphoreConfig(defConfig); config.setName(name); addSemaphoreConfig(config); return config; } /** * Adds a new SemaphoreConfig by name * * @param semaphoreConfig semaphore config to add * @return this config instance */ public Config addSemaphoreConfig(SemaphoreConfig semaphoreConfig) { this.semaphoreConfigs.put(semaphoreConfig.getName(), semaphoreConfig); return this; } /** * Returns the collection of semaphore configs. * * @return collection of semaphore configs. */ public Collection<SemaphoreConfig> getSemaphoreConfigs() { return semaphoreConfigs.values(); } public Config setSemaphoreConfigs(Map<String, SemaphoreConfig> semaphoreConfigs) { this.semaphoreConfigs.clear(); this.semaphoreConfigs.putAll(semaphoreConfigs); for (final Entry<String, SemaphoreConfig> entry : this.semaphoreConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; } public WanReplicationConfig getWanReplicationConfig(String name) { return wanReplicationConfigs.get(name); } public Config addWanReplicationConfig(WanReplicationConfig wanReplicationConfig) { wanReplicationConfigs.put(wanReplicationConfig.getName(), wanReplicationConfig); return this; } public Map<String, WanReplicationConfig> getWanReplicationConfigs() { return wanReplicationConfigs; } public Config setWanReplicationConfigs(Map<String, WanReplicationConfig> wanReplicationConfigs) { this.wanReplicationConfigs.clear(); this.wanReplicationConfigs.putAll(wanReplicationConfigs); return this; } public JobTrackerConfig findJobTrackerConfig(String name) { name = getBaseName(name); JobTrackerConfig config; if ((config = lookupByPattern(jobTrackerConfigs, name)) != null) return config.getAsReadOnly(); return getJobTrackerConfig(name); } public JobTrackerConfig getJobTrackerConfig(String name) { name = getBaseName(name); JobTrackerConfig config; if ((config = lookupByPattern(jobTrackerConfigs, name)) != null) return config; JobTrackerConfig defConfig = jobTrackerConfigs.get("default"); if (defConfig == null) { defConfig = new JobTrackerConfig(); defConfig.setName("default"); addJobTrackerConfig(defConfig); } config = new JobTrackerConfig(defConfig); config.setName(name); addJobTrackerConfig(config); return config; } public Config addJobTrackerConfig(JobTrackerConfig jobTrackerConfig) { jobTrackerConfigs.put(jobTrackerConfig.getName(), jobTrackerConfig); return this; } public Map<String, JobTrackerConfig> getJobTrackerConfigs() { return jobTrackerConfigs; } public Config setJobTrackerConfigs(Map<String, JobTrackerConfig> jobTrackerConfigs) { this.jobTrackerConfigs.clear(); this.jobTrackerConfigs.putAll(jobTrackerConfigs); for (final Entry<String, JobTrackerConfig> entry : this.jobTrackerConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; } public ManagementCenterConfig getManagementCenterConfig() { return managementCenterConfig; } public Config setManagementCenterConfig(ManagementCenterConfig managementCenterConfig) { this.managementCenterConfig = managementCenterConfig; return this; } public ServicesConfig getServicesConfig() { return servicesConfig; } public Config setServicesConfig(ServicesConfig servicesConfig) { this.servicesConfig = servicesConfig; return this; } public SecurityConfig getSecurityConfig() { return securityConfig; } public Config setSecurityConfig(SecurityConfig securityConfig) { this.securityConfig = securityConfig; return this; } public Config addListenerConfig(ListenerConfig listenerConfig) { getListenerConfigs().add(listenerConfig); return this; } public List<ListenerConfig> getListenerConfigs() { return listenerConfigs; } public Config setListenerConfigs(List<ListenerConfig> listenerConfigs) { this.listenerConfigs.clear(); this.listenerConfigs.addAll(listenerConfigs); return this; } public SerializationConfig getSerializationConfig() { return serializationConfig; } public Config setSerializationConfig(SerializationConfig serializationConfig) { this.serializationConfig = serializationConfig; return this; } public PartitionGroupConfig getPartitionGroupConfig() { return partitionGroupConfig; } public Config setPartitionGroupConfig(PartitionGroupConfig partitionGroupConfig) { this.partitionGroupConfig = partitionGroupConfig; return this; } public ManagedContext getManagedContext() { return managedContext; } public Config setManagedContext(final ManagedContext managedContext) { this.managedContext = managedContext; return this; } public ConcurrentMap<String, Object> getUserContext() { return userContext; } public Config setUserContext(ConcurrentMap<String, Object> userContext) { if(userContext == null){ throw new IllegalArgumentException("userContext can't be null"); } this.userContext = userContext; return this; } /** * @return the configurationUrl */ public URL getConfigurationUrl() { return configurationUrl; } /** * @param configurationUrl the configurationUrl to set */ public Config setConfigurationUrl(URL configurationUrl) { this.configurationUrl = configurationUrl; return this; } /** * @return the configurationFile */ public File getConfigurationFile() { return configurationFile; } /** * @param configurationFile the configurationFile to set */ public Config setConfigurationFile(File configurationFile) { this.configurationFile = configurationFile; return this; } public String getLicenseKey() { return licenseKey; } public Config setLicenseKey(final String licenseKey) { this.licenseKey = licenseKey; return this; } private static <T> T lookupByPattern(Map<String, T> map, String name) { T t = map.get(name); if (t == null) { for (Map.Entry<String,T> entry : map.entrySet()) { String pattern = entry.getKey(); T value = entry.getValue(); if (nameMatches(name, pattern)) { return value; } } } return t; } public static boolean nameMatches(final String name, final String pattern) { final int index = pattern.indexOf('*'); if (index == -1) { return name.equals(pattern); } else { final String firstPart = pattern.substring(0, index); final int indexFirstPart = name.indexOf(firstPart, 0); if (indexFirstPart == -1) { return false; } final String secondPart = pattern.substring(index + 1); final int indexSecondPart = name.indexOf(secondPart, index + 1); return indexSecondPart != -1; } } /** * @param config * @return true if config is compatible with this one, * false if config belongs to another group * @throws RuntimeException if map, queue, topic configs are incompatible */ public boolean isCompatible(final Config config) { if (config == null) { throw new IllegalArgumentException("Expected not null config"); } if (!this.groupConfig.getName().equals(config.getGroupConfig().getName())) { return false; } if (!this.groupConfig.getPassword().equals(config.getGroupConfig().getPassword())) { throw new HazelcastException("Incompatible group password"); } checkMapConfigCompatible(config); return true; } private void checkMapConfigCompatible(final Config config) { Set<String> mapConfigNames = new HashSet<String>(mapConfigs.keySet()); mapConfigNames.addAll(config.mapConfigs.keySet()); for (final String name : mapConfigNames) { final MapConfig thisMapConfig = lookupByPattern(mapConfigs, name); final MapConfig thatMapConfig = lookupByPattern(config.mapConfigs, name); if (thisMapConfig != null && thatMapConfig != null && !thisMapConfig.isCompatible(thatMapConfig)) { throw new HazelcastException(format("Incompatible map config this:\n{0}\nanother:\n{1}", thisMapConfig, thatMapConfig)); } } } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("Config"); sb.append("{groupConfig=").append(groupConfig); sb.append(", properties=").append(properties); sb.append(", networkConfig=").append(networkConfig); sb.append(", mapConfigs=").append(mapConfigs); sb.append(", topicConfigs=").append(topicConfigs); sb.append(", queueConfigs=").append(queueConfigs); sb.append(", multiMapConfigs=").append(multiMapConfigs); sb.append(", executorConfigs=").append(executorConfigs); sb.append(", semaphoreConfigs=").append(semaphoreConfigs); sb.append(", wanReplicationConfigs=").append(wanReplicationConfigs); sb.append(", listenerConfigs=").append(listenerConfigs); sb.append(", partitionGroupConfig=").append(partitionGroupConfig); sb.append(", managementCenterConfig=").append(managementCenterConfig); sb.append(", securityConfig=").append(securityConfig); sb.append('}'); return sb.toString(); } }
1no label
hazelcast_src_main_java_com_hazelcast_config_Config.java
36
public class SetCommandParser extends TypeAwareCommandParser { public SetCommandParser(TextCommandConstants.TextCommandType type) { super(type); } public TextCommand parser(SocketTextReader socketTextReader, String cmd, int space) { StringTokenizer st = new StringTokenizer(cmd); st.nextToken(); String key = null; int valueLen = 0; int flag = 0; int expiration = 0; boolean noReply = false; if (st.hasMoreTokens()) { key = st.nextToken(); } else { return new ErrorCommand(ERROR_CLIENT); } if (st.hasMoreTokens()) { flag = Integer.parseInt(st.nextToken()); } else { return new ErrorCommand(ERROR_CLIENT); } if (st.hasMoreTokens()) { expiration = Integer.parseInt(st.nextToken()); } else { return new ErrorCommand(ERROR_CLIENT); } if (st.hasMoreTokens()) { valueLen = Integer.parseInt(st.nextToken()); } else { return new ErrorCommand(ERROR_CLIENT); } if (st.hasMoreTokens()) { noReply = "noreply".equals(st.nextToken()); } return new SetCommand(type, key, flag, expiration, valueLen, noReply); } }
0true
hazelcast_src_main_java_com_hazelcast_ascii_memcache_SetCommandParser.java
1,321
public interface SearchRedirectDao { public SearchRedirect findSearchRedirectBySearchTerm(String uri); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_redirect_dao_SearchRedirectDao.java
797
public static class Match implements Streamable { private Text index; private Text id; private float score; private Map<String, HighlightField> hl; public Match(Text index, Text id, float score, Map<String, HighlightField> hl) { this.id = id; this.score = score; this.index = index; this.hl = hl; } public Match(Text index, Text id, float score) { this.id = id; this.score = score; this.index = index; } Match() { } public Text getIndex() { return index; } public Text getId() { return id; } public float getScore() { return score; } public Map<String, HighlightField> getHighlightFields() { return hl; } @Override public void readFrom(StreamInput in) throws IOException { id = in.readText(); index = in.readText(); score = in.readFloat(); int size = in.readVInt(); if (size > 0) { hl = new HashMap<String, HighlightField>(size); for (int j = 0; j < size; j++) { hl.put(in.readString(), HighlightField.readHighlightField(in)); } } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeText(id); out.writeText(index); out.writeFloat(score); if (hl != null) { out.writeVInt(hl.size()); for (Map.Entry<String, HighlightField> entry : hl.entrySet()) { out.writeString(entry.getKey()); entry.getValue().writeTo(out); } } else { out.writeVInt(0); } } }
0true
src_main_java_org_elasticsearch_action_percolate_PercolateResponse.java
416
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface AdminPresentationMap { /** * <p>Optional - field name will be used if not specified</p> * * <p>The friendly name to present to a user for this field in a GUI. If supporting i18N, * the friendly name may be a key to retrieve a localized friendly name using * the GWT support for i18N.</p> * * @return the friendly name */ String friendlyName() default ""; /** * <p>Optional - only required if you wish to apply security to this field</p> * * <p>If a security level is specified, it is registered with the SecurityManager. * The SecurityManager checks the permission of the current user to * determine if this field should be disabled based on the specified level.</p> * * @return the security level */ String securityLevel() default ""; /** * <p>Optional - fields are not excluded by default</p> * * <p>Specify if this field should be excluded from inclusion in the * admin presentation layer</p> * * @return whether or not the field should be excluded */ boolean excluded() default false; /** * Optional - only required if you want to make the field immutable * * Explicityly specify whether or not this field is mutable. * * @return whether or not this field is read only */ boolean readOnly() default false; /** * <p>Optional - only required if you want to make the field ignore caching</p> * * <p>Explicitly specify whether or not this field will use server-side * caching during inspection</p> * * @return whether or not this field uses caching */ boolean useServerSideInspectionCache() default true; /** * <p>Optional - only required if you want to specify ordering for this field</p> * * <p>The order in which this field will appear in a GUI relative to other collections from the same class</p> * * @return the display order */ int order() default 99999; /** * Optional - only required if you want the field to appear under a different tab * * Specify a GUI tab for this field * * @return the tab for this field */ String tab() default "General"; /** * Optional - only required if you want to order the appearance of the tabs in the UI * * Specify an order for this tab. Tabs will be sorted int he resulting form in * ascending order based on this parameter. * * The default tab will render with an order of 100. * * @return the order for this tab */ int tabOrder() default 100; /** * <p>Optional - only required if the type for the key of this map * is other than java.lang.String, or if the map is not a generic * type from which the key type can be derived</p> * * <p>The type for the key of this map</p> * * @return The type for the key of this map */ Class<?> keyClass() default void.class; /** * <p>Optional - only required if you wish to specify a key different from the one on the * {@link MapKey} annotation for the same field. * * @return the property for the key */ String mapKeyValueProperty() default ""; /** * <p>Optional - only required if the key field title for this * map should be translated to another lang, or should be * something other than the constant "Key"</p> * * <p>The friendly name to present to a user for this key field title in a GUI. If supporting i18N, * the friendly name may be a key to retrieve a localized friendly name using * the GWT support for i18N.</p> * * @return the friendly name */ String keyPropertyFriendlyName() default "Key"; /** * <p>Optional - only required if the type for the value of this map * is other than java.lang.String, or if the map is not a generic * type from which the value type can be derived, or if there is * not a @ManyToMany annotation used from which a targetEntity * can be inferred.</p> * * <p>The type for the value of this map</p> * * @return The type for the value of this map */ Class<?> valueClass() default void.class; /** * <p>Optional - only required if the value class is a * JPA managed type and the persisted entity should * be deleted upon removal from this map</p> * * <p>Whether or not a complex (JPA managed) value should * be deleted upon removal from this map</p> * * @return Whether or not a complex value is deleted upon map removal */ boolean deleteEntityUponRemove() default false; /** * <p>Optional - only required if the value property for this map * is simple (Not JPA managed - e.g. java.lang.String) and if the * value field title for this map should be translated to another lang, or * should be something other than the constant "Value"</p> * * <p>The friendly name to present to a user for this value field title in a GUI. If supporting i18N, * the friendly name may be a key to retrieve a localized friendly name using * the GWT support for i18N.</p> * * @return the friendly name */ String valuePropertyFriendlyName() default "Value"; /** * <p>Optional - only required if the value type cannot be derived from the map * declaration in the JPA managed entity and the value type is complex (JPA managed entity)</p> * * <p>Whether or not the value type for the map is complex (JPA managed entity), rather than an simple * type (e.g. java.lang.String). This can usually be inferred from the parameterized type of the map * (if available), or from the targetEntity property of a @ManyToMany annotation for the map (if available).</p> * * @return Whether or not the value type for the map is complex */ UnspecifiedBooleanType isSimpleValue() default UnspecifiedBooleanType.UNSPECIFIED; /** * <p>Optional - only required if the value type for the map is complex (JPA managed) and one of the fields * of the complex value provides a URL value that points to a resolvable image url.</p> * * <p>The field name of complex value that provides an image url</p> * * @return The field name of complex value that provides an image url */ String mediaField() default ""; /** * <p>Optional - only required when the user should select from a list of pre-defined * keys when adding/editing this map. Either this value, or the mapKeyOptionEntityClass * should be user - not both.</p> * * <p>Specify the keys available for the user to select from</p> * * @return the array of keys from which the user can select */ AdminPresentationMapKey[] keys() default {}; /** * <p>Optional - only required when you want to allow the user to create his/her own * key value, rather than select from a pre-defined list. The default is to * force selection from a pre-defined list.</p> * * @return whether or not the user will create their own key values. */ boolean forceFreeFormKeys() default false; /** * <p>Optional - only required with a complex value class that has a bi-directional * association back to the parent class containing the map. This can generally * be inferred by the system from a "mappedBy" attribute for maps of a OneToMany * type. For map configurations without a mappedBy value, or if you wish to * explicitly set a bi-directional association field on the complex value, use * this property.</p> * * @return the bi-directional association field on the complex value, if any */ String manyToField() default ""; /** * <p>Optional - only required when the user should select from a list of database * persisted values for keys when adding/editing this map. Either this value, or the * keys parameter should be user - not both</p> * * <p>Specify the entity class that represents the table in the database that contains * the key values for this map</p> * * @return the entity class for the map keys */ Class<?> mapKeyOptionEntityClass() default void.class; /** * <p>Optional - only required when the user should select from a list of database * persisted values for keys when adding/editing this map.</p> * * <p>Specify the field in the option entity class that contains the value that will * be shown to the user. This can be the same field as the value field. This option * does not support i18n out-of-the-box.</p> * * @return the display field in the entity class */ String mapKeyOptionEntityDisplayField() default ""; /** * <p>Optional - only required when the user should select from a list of database * persisted values for keys when adding/editing this map.</p> * * <p>Specify the field in the option entity class that contains the value that will * actually be saved for the selected key. This can be the same field as the display * field.</p> * * @return the value field in the entity class */ String mapKeyOptionEntityValueField() default ""; /** * <p>Optional - only required if you need to specially handle crud operations for this * specific collection on the server</p> * * <p>Custom string values that will be passed to the server during CRUD operations on this * collection. These criteria values can be detected in a custom persistence handler * (@CustomPersistenceHandler) in order to engage special handling through custom server * side code for this collection.</p> * * @return the custom string array to pass to the server during CRUD operations */ String[] customCriteria() default {}; /** * <p>Optional - only required if a special operation type is required for a CRUD operation. This * setting is not normally changed and is an advanced setting</p> * * <p>The operation type for a CRUD operation</p> * * @return the operation type */ AdminPresentationOperationTypes operationTypes() default @AdminPresentationOperationTypes(addType = OperationType.MAP, fetchType = OperationType.MAP, inspectType = OperationType.MAP, removeType = OperationType.MAP, updateType = OperationType.MAP); /** * <p>Optional - propertyName , only required if you want hide the field based on this property's value</p> * * <p>If the property is defined and found to be set to false, in the AppConfiguraionService, then this field will be excluded in the * admin presentation layer</p> * * @return name of the property */ String showIfProperty() default ""; /** * Optional - If you have FieldType set to SupportedFieldType.MONEY, * * then you can specify a money currency property field. * * @return the currency property field */ String currencyCodeField() default ""; }
0true
common_src_main_java_org_broadleafcommerce_common_presentation_AdminPresentationMap.java
1,586
public abstract class LoggerFactorySupport implements LoggerFactory { final ConcurrentMap<String, ILogger> mapLoggers = new ConcurrentHashMap<String, ILogger>(100); final ConstructorFunction<String, ILogger> loggerConstructor = new ConstructorFunction<String, ILogger>() { public ILogger createNew(String key) { return createLogger(key); } }; @Override public final ILogger getLogger(String name) { return ConcurrencyUtil.getOrPutIfAbsent(mapLoggers, name, loggerConstructor); } protected abstract ILogger createLogger(String name); }
0true
hazelcast_src_main_java_com_hazelcast_logging_LoggerFactorySupport.java
3,153
public interface PerValueEstimator { /** * @return the number of bytes for the given term */ public long bytesPerValue(BytesRef term); /** * Execute any pre-loading estimations for the terms. May also * optionally wrap a {@link TermsEnum} in a * {@link RamAccountingTermsEnum} * which will estimate the memory on a per-term basis. * * @param terms terms to be estimated * @return A TermsEnum for the given terms * @throws IOException */ public TermsEnum beforeLoad(Terms terms) throws IOException; /** * Possibly adjust a circuit breaker after field data has been loaded, * now that the actual amount of memory used by the field data is known * * @param termsEnum terms that were loaded * @param actualUsed actual field data memory usage */ public void afterLoad(TermsEnum termsEnum, long actualUsed); }
0true
src_main_java_org_elasticsearch_index_fielddata_AbstractIndexFieldData.java
5,877
public class QueryParseElement implements SearchParseElement { @Override public void parse(XContentParser parser, SearchContext context) throws Exception { context.parsedQuery(context.queryParserService().parse(parser)); } }
1no label
src_main_java_org_elasticsearch_search_query_QueryParseElement.java
9
static final class AsyncAccept<T> extends Async { final T arg; final Action<? super T> fn; final CompletableFuture<Void> dst; AsyncAccept(T arg, Action<? super T> fn, CompletableFuture<Void> dst) { this.arg = arg; this.fn = fn; this.dst = dst; } public final boolean exec() { CompletableFuture<Void> d; Throwable ex; if ((d = this.dst) != null && d.result == null) { try { fn.accept(arg); ex = null; } catch (Throwable rex) { ex = rex; } d.internalComplete(null, ex); } return true; } private static final long serialVersionUID = 5232453952276885070L; }
0true
src_main_java_jsr166e_CompletableFuture.java
1,429
public abstract class DynamicSkuPricingInterceptor implements WebRequestInterceptor { @Resource(name = "blDynamicSkuPricingService") protected DynamicSkuPricingService skuPricingService; @Override public void preHandle(WebRequest request) throws Exception { SkuPricingConsiderationContext.setSkuPricingConsiderationContext(getPricingConsiderations(request)); SkuPricingConsiderationContext.setSkuPricingService(getDynamicSkuPricingService(request)); } public DynamicSkuPricingService getDynamicSkuPricingService(WebRequest request) { return skuPricingService; } /** * Override to supply your own considerations to pass to the {@link SkuPricingConsiderationContext}. * @param request * @return considerations that the {@link DynamicSkuPricingService} will evaluate when implementing custom pricing */ @SuppressWarnings("rawtypes") public abstract HashMap getPricingConsiderations(WebRequest request); @Override public void afterCompletion(WebRequest request, Exception ex) throws Exception { // unimplemented } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_catalog_DynamicSkuPricingInterceptor.java
1,173
public class OQueryOperatorContains extends OQueryOperatorEqualityNotNulls { public OQueryOperatorContains() { super("CONTAINS", 5, false); } @Override @SuppressWarnings("unchecked") protected boolean evaluateExpression(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft, final Object iRight, OCommandContext iContext) { final OSQLFilterCondition condition; if (iCondition.getLeft() instanceof OSQLFilterCondition) condition = (OSQLFilterCondition) iCondition.getLeft(); else if (iCondition.getRight() instanceof OSQLFilterCondition) condition = (OSQLFilterCondition) iCondition.getRight(); else condition = null; if (iLeft instanceof Iterable<?>) { final Iterable<Object> iterable = (Iterable<Object>) iLeft; if (condition != null) { // CHECK AGAINST A CONDITION for (final Object o : iterable) { final OIdentifiable id; if (o instanceof OIdentifiable) id = (OIdentifiable) o; else if (o instanceof Map<?, ?>) { final Iterator<OIdentifiable> iter = ((Map<?, OIdentifiable>) o).values().iterator(); id = iter.hasNext() ? iter.next() : null; } else if (o instanceof Iterable<?>) { final Iterator<OIdentifiable> iter = ((Iterable<OIdentifiable>) o).iterator(); id = iter.hasNext() ? iter.next() : null; } else continue; if ((Boolean) condition.evaluate(id, null, iContext) == Boolean.TRUE) return true; } } else { // CHECK AGAINST A SINGLE VALUE for (final Object o : iterable) { if (OQueryOperatorEquals.equals(iRight, o)) return true; } } } else if (iRight instanceof Iterable<?>) { // CHECK AGAINST A CONDITION final Iterable<OIdentifiable> iterable = (Iterable<OIdentifiable>) iRight; if (condition != null) { for (final OIdentifiable o : iterable) { if ((Boolean) condition.evaluate(o, null, iContext) == Boolean.TRUE) return true; } } else { // CHECK AGAINST A SINGLE VALUE for (final Object o : iterable) { if (OQueryOperatorEquals.equals(iLeft, o)) return true; } } } return false; } @Override public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) { if (!(iLeft instanceof OSQLFilterCondition) && !(iRight instanceof OSQLFilterCondition)) return OIndexReuseType.INDEX_METHOD; return OIndexReuseType.NO_INDEX; } @Override public Object executeIndexQuery(OCommandContext iContext, OIndex<?> index, INDEX_OPERATION_TYPE iOperationType, List<Object> keyParams, IndexResultListener resultListener, int fetchLimit) { final OIndexDefinition indexDefinition = index.getDefinition(); final OIndexInternal<?> internalIndex = index.getInternal(); if (!internalIndex.canBeUsedInEqualityOperators()) return null; final Object result; if (indexDefinition.getParamCount() == 1) { final Object key; if (indexDefinition instanceof OIndexDefinitionMultiValue) key = ((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(keyParams.get(0)); else key = indexDefinition.createValue(keyParams); if (key == null) return null; final Object indexResult; if (iOperationType == INDEX_OPERATION_TYPE.GET) indexResult = index.get(key); else { if (internalIndex.hasRangeQuerySupport()) return index.count(key); else return null; } result = convertIndexResult(indexResult); } else { // in case of composite keys several items can be returned in case of we perform search // using part of composite key stored in index. final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition; final Object keyOne = compositeIndexDefinition.createSingleValue(keyParams); if (keyOne == null) return null; final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams); if (internalIndex.hasRangeQuerySupport()) { if (resultListener != null) { index.getValuesBetween(keyOne, true, keyTwo, true, resultListener); result = resultListener.getResult(); } else result = index.getValuesBetween(keyOne, true, keyTwo, true); } else { int indexParamCount = indexDefinition.getParamCount(); if (indexParamCount == keyParams.size()) { final Object indexResult; if (iOperationType == INDEX_OPERATION_TYPE.GET) indexResult = index.get(keyOne); else { if (internalIndex.hasRangeQuerySupport()) return index.count(keyOne); else return null; } result = convertIndexResult(indexResult); } else return null; } } updateProfiler(iContext, index, keyParams, indexDefinition); return result; } private Object convertIndexResult(Object indexResult) { Object result; if (indexResult instanceof Collection) result = (Collection<?>) indexResult; else if (indexResult == null) result = Collections.emptyList(); else result = Collections.singletonList((OIdentifiable) indexResult); return result; } @Override public ORID getBeginRidRange(Object iLeft, Object iRight) { return null; } @Override public ORID getEndRidRange(Object iLeft, Object iRight) { return null; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryOperatorContains.java
1,321
awaitBusy(new Predicate<Object>() { public boolean apply(Object obj) { ClusterState state = client().admin().cluster().prepareState().setLocal(true).execute().actionGet().getState(); return state.blocks().hasGlobalBlock(Discovery.NO_MASTER_BLOCK); } });
0true
src_test_java_org_elasticsearch_cluster_MinimumMasterNodesTests.java
566
private class SqlFileFilter implements FilenameFilter { @Override public boolean accept(File dir, String name) { return name.endsWith(".sql"); } }
0true
common_src_main_java_org_broadleafcommerce_common_util_sql_HibernateToolTask.java
1,660
ex.execute(new Runnable() { public void run() { for (int j = (n * chunk); j < (n + 1) * chunk; j++) { map.remove(j); try { Thread.sleep(1); } catch (InterruptedException ignored) { } } latch.countDown(); } });
0true
hazelcast_src_test_java_com_hazelcast_map_BackupTest.java
226
public class SystemPropertyRuntimeEnvironmentKeyResolver implements RuntimeEnvironmentKeyResolver { protected String environmentKey = "runtime.environment"; public SystemPropertyRuntimeEnvironmentKeyResolver() { // EMPTY } public String resolveRuntimeEnvironmentKey() { return System.getProperty(environmentKey); } public void setEnvironmentKey(String environmentKey) { this.environmentKey = environmentKey; } }
0true
common_src_main_java_org_broadleafcommerce_common_config_SystemPropertyRuntimeEnvironmentKeyResolver.java
470
public class SandBoxType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, SandBoxType> TYPES = new LinkedHashMap<String, SandBoxType>(); public static final SandBoxType USER = new SandBoxType("USER", "User"); public static final SandBoxType APPROVAL = new SandBoxType("APPROVAL", "Approval"); public static final SandBoxType PRODUCTION = new SandBoxType("PRODUCTION", "Production"); public static SandBoxType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public SandBoxType() { //do nothing } public SandBoxType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } else { throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName()); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SandBoxType other = (SandBoxType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
common_src_main_java_org_broadleafcommerce_common_sandbox_domain_SandBoxType.java
52
public class ClusterManager extends LifecycleAdapter { public static class Builder { private final File root; private final Provider provider = clusterOfSize( 3 ); private final Map<String, String> commonConfig = emptyMap(); private final Map<Integer, Map<String,String>> instanceConfig = new HashMap<>(); private HighlyAvailableGraphDatabaseFactory factory = new HighlyAvailableGraphDatabaseFactory(); private StoreDirInitializer initializer; public Builder( File root ) { this.root = root; } public Builder withSeedDir( final File seedDir ) { return withStoreDirInitializer( new StoreDirInitializer() { @Override public void initializeStoreDir( int serverId, File storeDir ) throws IOException { copyRecursively( seedDir, storeDir ); } } ); } public Builder withStoreDirInitializer( StoreDirInitializer initializer ) { this.initializer = initializer; return this; } public Builder withDbFactory( HighlyAvailableGraphDatabaseFactory dbFactory ) { this.factory = dbFactory; return this; } public ClusterManager build() { return new ClusterManager( this ); } } public interface StoreDirInitializer { void initializeStoreDir( int serverId, File storeDir ) throws IOException; } /** * Provides a specification of which clusters to start in {@link ClusterManager#start()}. */ public interface Provider { Clusters clusters() throws Throwable; } /** * Provider pointing out an XML file to read. * * @param clustersXml the XML file containing the cluster specifications. */ public static Provider fromXml( final URI clustersXml ) { return new Provider() { @Override public Clusters clusters() throws Exception { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document clustersXmlDoc = documentBuilder.parse( clustersXml.toURL().openStream() ); return new ClustersXMLSerializer( documentBuilder ).read( clustersXmlDoc ); } }; } /** * Provides a cluster specification with default values * * @param memberCount the total number of members in the cluster to start. */ public static Provider clusterOfSize( int memberCount ) { Clusters.Cluster cluster = new Clusters.Cluster( "neo4j.ha" ); for ( int i = 0; i < memberCount; i++ ) { cluster.getMembers().add( new Clusters.Member( 5001 + i, true ) ); } final Clusters clusters = new Clusters(); clusters.getClusters().add( cluster ); return provided( clusters ); } /** * Provides a cluster specification with default values * @param haMemberCount the total number of members in the cluster to start. */ public static Provider clusterWithAdditionalClients( int haMemberCount, int additionalClientCount ) { Clusters.Cluster cluster = new Clusters.Cluster( "neo4j.ha" ); int counter = 0; for ( int i = 0; i < haMemberCount; i++, counter++ ) { cluster.getMembers().add( new Clusters.Member( 5001 + counter, true ) ); } for ( int i = 0; i < additionalClientCount; i++, counter++ ) { cluster.getMembers().add( new Clusters.Member( 5001 + counter, false ) ); } final Clusters clusters = new Clusters(); clusters.getClusters().add( cluster ); return provided( clusters ); } /** * Provides a cluster specification with default values * @param haMemberCount the total number of members in the cluster to start. */ public static Provider clusterWithAdditionalArbiters( int haMemberCount, int arbiterCount) { Clusters.Cluster cluster = new Clusters.Cluster( "neo4j.ha" ); int counter = 0; for ( int i = 0; i < arbiterCount; i++, counter++ ) { cluster.getMembers().add( new Clusters.Member( 5001 + counter, false ) ); } for ( int i = 0; i < haMemberCount; i++, counter++ ) { cluster.getMembers().add( new Clusters.Member( 5001 + counter, true ) ); } final Clusters clusters = new Clusters(); clusters.getClusters().add( cluster ); return provided( clusters ); } public static Provider provided( final Clusters clusters ) { return new Provider() { @Override public Clusters clusters() throws Throwable { return clusters; } }; } LifeSupport life; private final File root; private final Map<String, String> commonConfig; private final Map<Integer, Map<String, String>> instanceConfig; private final Map<String, ManagedCluster> clusterMap = new HashMap<>(); private final Provider clustersProvider; private final HighlyAvailableGraphDatabaseFactory dbFactory; private final StoreDirInitializer storeDirInitializer; public ClusterManager( Provider clustersProvider, File root, Map<String, String> commonConfig, Map<Integer, Map<String, String>> instanceConfig, HighlyAvailableGraphDatabaseFactory dbFactory ) { this.clustersProvider = clustersProvider; this.root = root; this.commonConfig = commonConfig; this.instanceConfig = instanceConfig; this.dbFactory = dbFactory; this.storeDirInitializer = null; } private ClusterManager( Builder builder ) { this.clustersProvider = builder.provider; this.root = builder.root; this.commonConfig = builder.commonConfig; this.instanceConfig = builder.instanceConfig; this.dbFactory = builder.factory; this.storeDirInitializer = builder.initializer; } public ClusterManager( Provider clustersProvider, File root, Map<String, String> commonConfig, Map<Integer, Map<String, String>> instanceConfig ) { this( clustersProvider, root, commonConfig, instanceConfig, new HighlyAvailableGraphDatabaseFactory() ); } public ClusterManager( Provider clustersProvider, File root, Map<String, String> commonConfig ) { this( clustersProvider, root, commonConfig, Collections.<Integer, Map<String, String>>emptyMap(), new HighlyAvailableGraphDatabaseFactory() ); } @Override public void start() throws Throwable { Clusters clusters = clustersProvider.clusters(); life = new LifeSupport(); // Started so instances added here will be started immediately, and in case of exceptions they can be // shutdown() or stop()ped properly life.start(); for ( int i = 0; i < clusters.getClusters().size(); i++ ) { Clusters.Cluster cluster = clusters.getClusters().get( i ); ManagedCluster managedCluster = new ManagedCluster( cluster ); clusterMap.put( cluster.getName(), managedCluster ); life.add( managedCluster ); } } @Override public void stop() throws Throwable { life.stop(); } @Override public void shutdown() throws Throwable { life.shutdown(); } /** * Represent one cluster. It can retrieve the current master, random slave * or all members. It can also temporarily fail an instance or shut it down. */ public class ManagedCluster extends LifecycleAdapter { private final Clusters.Cluster spec; private final String name; private final Map<Integer, HighlyAvailableGraphDatabaseProxy> members = new ConcurrentHashMap<>(); private final List<ClusterMembers> arbiters = new ArrayList<>( ); ManagedCluster( Clusters.Cluster spec ) throws URISyntaxException, IOException { this.spec = spec; this.name = spec.getName(); for ( int i = 0; i < spec.getMembers().size(); i++ ) { startMember( i + 1 ); } for ( HighlyAvailableGraphDatabaseProxy member : members.values() ) { insertInitialData( member.get(), name, member.get().getConfig().get( ClusterSettings.server_id ) ); } } public String getInitialHostsConfigString() { StringBuilder result = new StringBuilder(); for ( HighlyAvailableGraphDatabase member : getAllMembers() ) { result.append( result.length() > 0 ? "," : "" ).append( ":" ) .append( member.getDependencyResolver().resolveDependency( ClusterClient.class ).getClusterServer().getPort() ); } return result.toString(); } @Override public void stop() throws Throwable { for ( HighlyAvailableGraphDatabaseProxy member : members.values() ) { member.get().shutdown(); } } /** * @return all started members in this cluster. */ public Iterable<HighlyAvailableGraphDatabase> getAllMembers() { return Iterables.map( new Function<HighlyAvailableGraphDatabaseProxy, HighlyAvailableGraphDatabase>() { @Override public HighlyAvailableGraphDatabase apply( HighlyAvailableGraphDatabaseProxy from ) { return from.get(); } }, members.values() ); } public Iterable<ClusterMembers> getArbiters() { return arbiters; } /** * @return the current master in the cluster. * @throws IllegalStateException if there's no current master. */ public HighlyAvailableGraphDatabase getMaster() { for ( HighlyAvailableGraphDatabase graphDatabaseService : getAllMembers() ) { if ( graphDatabaseService.isMaster() ) { return graphDatabaseService; } } throw new IllegalStateException( "No master found in cluster " + name ); } /** * @param except do not return any of the dbs found in this array * @return a slave in this cluster. * @throws IllegalStateException if no slave was found in this cluster. */ public HighlyAvailableGraphDatabase getAnySlave( HighlyAvailableGraphDatabase... except ) { Set<HighlyAvailableGraphDatabase> exceptSet = new HashSet<>( asList( except ) ); for ( HighlyAvailableGraphDatabase graphDatabaseService : getAllMembers() ) { if ( graphDatabaseService.getInstanceState().equals( "SLAVE" ) && !exceptSet.contains( graphDatabaseService ) ) { return graphDatabaseService; } } throw new IllegalStateException( "No slave found in cluster " + name ); } /** * @param serverId the server id to return the db for. * @return the {@link HighlyAvailableGraphDatabase} with the given server id. * @throws IllegalStateException if that db isn't started or no such * db exists in the cluster. */ public HighlyAvailableGraphDatabase getMemberByServerId( int serverId ) { HighlyAvailableGraphDatabase db = members.get( serverId ).get(); if ( db == null ) { throw new IllegalStateException( "Db " + serverId + " not found at the moment in " + name ); } return db; } /** * Shuts down a member of this cluster. A {@link RepairKit} is returned * which is able to restore the instance (i.e. start it again). * * @param db the {@link HighlyAvailableGraphDatabase} to shut down. * @return a {@link RepairKit} which can start it again. * @throws IllegalArgumentException if the given db isn't a member of this cluster. */ public RepairKit shutdown( HighlyAvailableGraphDatabase db ) { assertMember( db ); int serverId = db.getDependencyResolver().resolveDependency( Config.class ).get( ClusterSettings.server_id ); members.remove( serverId ); life.remove( db ); db.shutdown(); return new StartDatabaseAgainKit( this, serverId ); } private void assertMember( HighlyAvailableGraphDatabase db ) { for ( HighlyAvailableGraphDatabaseProxy highlyAvailableGraphDatabaseProxy : members.values() ) { if ( highlyAvailableGraphDatabaseProxy.get().equals( db ) ) { return; } } throw new IllegalArgumentException( "Db " + db + " not a member of this cluster " + name ); } /** * WARNING: beware of hacks. * <p/> * Fails a member of this cluster by making it not respond to heart beats. * A {@link RepairKit} is returned which is able to repair the instance * (i.e start the network) again. * * @param db the {@link HighlyAvailableGraphDatabase} to fail. * @return a {@link RepairKit} which can repair the failure. * @throws IllegalArgumentException if the given db isn't a member of this cluster. */ public RepairKit fail( HighlyAvailableGraphDatabase db ) throws Throwable { assertMember( db ); ClusterClient clusterClient = db.getDependencyResolver().resolveDependency( ClusterClient.class ); LifeSupport clusterClientLife = (LifeSupport) accessible( clusterClient.getClass().getDeclaredField( "life" ) ).get( clusterClient ); NetworkReceiver receiver = instance( NetworkReceiver.class, clusterClientLife.getLifecycleInstances() ); receiver.stop(); ExecutorLifecycleAdapter statemachineExecutor = instance(ExecutorLifecycleAdapter.class, clusterClientLife.getLifecycleInstances()); statemachineExecutor.stop(); NetworkSender sender = instance( NetworkSender.class, clusterClientLife.getLifecycleInstances() ); sender.stop(); List<Lifecycle> stoppedServices = new ArrayList<>(); stoppedServices.add( sender ); stoppedServices.add(statemachineExecutor); stoppedServices.add( receiver ); return new StartNetworkAgainKit( db, stoppedServices ); } private void startMember( int serverId ) throws URISyntaxException, IOException { Clusters.Member member = spec.getMembers().get( serverId-1 ); StringBuilder initialHosts = new StringBuilder( spec.getMembers().get( 0 ).getHost() ); for (int i = 1; i < spec.getMembers().size(); i++) { initialHosts.append( "," ).append( spec.getMembers().get( i ).getHost() ); } File parent = new File( root, name ); URI clusterUri = new URI( "cluster://" + member.getHost() ); if ( member.isFullHaMember() ) { int clusterPort = clusterUri.getPort(); int haPort = clusterUri.getPort() + 3000; File storeDir = new File( parent, "server" + serverId ); if ( storeDirInitializer != null) { storeDirInitializer.initializeStoreDir( serverId, storeDir ); } GraphDatabaseBuilder graphDatabaseBuilder = dbFactory.newHighlyAvailableDatabaseBuilder( storeDir.getAbsolutePath() ). setConfig( ClusterSettings.cluster_name, name ). setConfig( ClusterSettings.initial_hosts, initialHosts.toString() ). setConfig( ClusterSettings.server_id, serverId + "" ). setConfig( ClusterSettings.cluster_server, "0.0.0.0:"+clusterPort). setConfig( HaSettings.ha_server, ":" + haPort ). setConfig( OnlineBackupSettings.online_backup_enabled, Settings.FALSE ). setConfig( commonConfig ); if ( instanceConfig.containsKey( serverId ) ) { graphDatabaseBuilder.setConfig( instanceConfig.get( serverId ) ); } config( graphDatabaseBuilder, name, serverId ); final HighlyAvailableGraphDatabaseProxy graphDatabase = new HighlyAvailableGraphDatabaseProxy( graphDatabaseBuilder ); members.put( serverId, graphDatabase ); life.add( new LifecycleAdapter() { @Override public void stop() throws Throwable { graphDatabase.get().shutdown(); } } ); } else { Map<String, String> config = MapUtil.stringMap( ClusterSettings.cluster_name.name(), name, ClusterSettings.initial_hosts.name(), initialHosts.toString(), ClusterSettings.server_id.name(), serverId + "", ClusterSettings.cluster_server.name(), "0.0.0.0:"+clusterUri.getPort(), GraphDatabaseSettings.store_dir.name(), new File( parent, "arbiter" + serverId ).getAbsolutePath() ); Config config1 = new Config( config ); Logging clientLogging =life.add( new LogbackService( config1, new LoggerContext() ) ); ObjectStreamFactory objectStreamFactory = new ObjectStreamFactory(); ClusterClient clusterClient = new ClusterClient( ClusterClient.adapt( config1 ), clientLogging, new NotElectableElectionCredentialsProvider(), objectStreamFactory, objectStreamFactory ); arbiters.add(new ClusterMembers(clusterClient, clusterClient, new ClusterMemberEvents() { @Override public void addClusterMemberListener( ClusterMemberListener listener ) { // noop } @Override public void removeClusterMemberListener( ClusterMemberListener listener ) { // noop } }, clusterClient.getServerId() )); life.add( new FutureLifecycleAdapter<>( clusterClient ) ); } } /** * Will await a condition for the default max time. * * @param predicate {@link Predicate} that should return true * signalling that the condition has been met. * @throws IllegalStateException if the condition wasn't met * during within the max time. */ public void await( Predicate<ManagedCluster> predicate ) { await( predicate, 60 ); } /** * Will await a condition for the given max time. * * @param predicate {@link Predicate} that should return true * signalling that the condition has been met. * @throws IllegalStateException if the condition wasn't met * during within the max time. */ public void await( Predicate<ManagedCluster> predicate, int maxSeconds ) { long end = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis( maxSeconds ); while ( System.currentTimeMillis() < end ) { if ( predicate.accept( this ) ) { return; } try { Thread.sleep( 100 ); } catch ( InterruptedException e ) { // Ignore } } String state = printState( this ); throw new IllegalStateException( format( "Awaited condition never met, waited %s for %s:%n%s", maxSeconds, predicate, state ) ); } /** * The total number of members of the cluster. */ public int size() { return spec.getMembers().size(); } public int getServerId( HighlyAvailableGraphDatabase member ) { assertMember( member ); return member.getConfig().get( ClusterSettings.server_id ); } public File getStoreDir( HighlyAvailableGraphDatabase member ) { assertMember( member ); return member.getConfig().get( GraphDatabaseSettings.store_dir ); } public void sync( HighlyAvailableGraphDatabase... except ) { Set<HighlyAvailableGraphDatabase> exceptSet = new HashSet<>( asList( except ) ); for ( HighlyAvailableGraphDatabase db : getAllMembers() ) { if ( !exceptSet.contains( db ) ) { db.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates(); } } } } private static final class HighlyAvailableGraphDatabaseProxy { private GraphDatabaseService result; private Future<GraphDatabaseService> untilThen; private final ExecutorService executor; public HighlyAvailableGraphDatabaseProxy( final GraphDatabaseBuilder graphDatabaseBuilder ) { Callable<GraphDatabaseService> starter = new Callable<GraphDatabaseService>() { @Override public GraphDatabaseService call() throws Exception { return graphDatabaseBuilder.newGraphDatabase(); } }; executor = Executors.newFixedThreadPool( 1 ); untilThen = executor.submit( starter ); } public HighlyAvailableGraphDatabase get() { if ( result == null ) { try { result = untilThen.get(); } catch ( InterruptedException | ExecutionException e ) { throw new RuntimeException( e ); } finally { executor.shutdownNow(); } } return (HighlyAvailableGraphDatabase) result; } } private static final class FutureLifecycleAdapter<T extends Lifecycle> extends LifecycleAdapter { private final T wrapped; private Future<Void> currentFuture; private final ExecutorService starter; public FutureLifecycleAdapter( T toWrap) { wrapped = toWrap; starter = Executors.newFixedThreadPool( 1 ); } @Override public void init() throws Throwable { currentFuture = starter.submit( new Callable<Void>() { @Override public Void call() throws Exception { try { wrapped.init(); } catch ( Throwable throwable ) { throw new RuntimeException( throwable ); } return null; } } ); } @Override public void start() throws Throwable { currentFuture.get(); currentFuture = starter.submit( new Callable<Void>() { @Override public Void call() throws Exception { try { wrapped.start(); } catch ( Throwable throwable ) { throw new RuntimeException( throwable ); } return null; } } ); } @Override public void stop() throws Throwable { currentFuture.get(); currentFuture = starter.submit( new Callable<Void>() { @Override public Void call() throws Exception { try { wrapped.stop(); } catch ( Throwable throwable ) { throw new RuntimeException( throwable ); } return null; } } ); } @Override public void shutdown() throws Throwable { currentFuture = starter.submit( new Callable<Void>() { @Override public Void call() throws Exception { try { wrapped.shutdown(); } catch ( Throwable throwable ) { throw new RuntimeException( throwable ); } return null; } } ); currentFuture.get(); starter.shutdownNow(); } } /** * The current master sees this many slaves as available. * * @param count number of slaves to see as available. */ public static Predicate<ManagedCluster> masterSeesSlavesAsAvailable( final int count ) { return new Predicate<ClusterManager.ManagedCluster>() { @Override public boolean accept( ManagedCluster cluster ) { return count( cluster.getMaster().getDependencyResolver().resolveDependency( Slaves.class ).getSlaves () ) >= count; } @Override public String toString() { return "Master should see " + count + " slaves as available"; } }; } /** * The current master sees all slaves in the cluster as available. * Based on the total number of members in the cluster. */ public static Predicate<ManagedCluster> masterSeesAllSlavesAsAvailable() { return new Predicate<ClusterManager.ManagedCluster>() { @Override public boolean accept( ManagedCluster cluster ) { return count( cluster.getMaster().getDependencyResolver().resolveDependency( Slaves.class ).getSlaves () ) >= cluster.size() - 1; } @Override public String toString() { return "Master should see all slaves as available"; } }; } /** * There must be a master available. Optionally exceptions, useful for when awaiting a * re-election of a different master. */ public static Predicate<ManagedCluster> masterAvailable( HighlyAvailableGraphDatabase... except ) { final Set<HighlyAvailableGraphDatabase> exceptSet = new HashSet<>( asList( except ) ); return new Predicate<ClusterManager.ManagedCluster>() { @Override public boolean accept( ManagedCluster cluster ) { for ( HighlyAvailableGraphDatabase graphDatabaseService : cluster.getAllMembers() ) { if ( !exceptSet.contains( graphDatabaseService )) { if ( graphDatabaseService.isMaster() ) { return true; } } } return false; } @Override public String toString() { return "There's an available master"; } }; } /** * The current master sees this many slaves as available. * @param count number of slaves to see as available. */ public static Predicate<ManagedCluster> masterSeesMembers( final int count ) { return new Predicate<ClusterManager.ManagedCluster>() { @Override public boolean accept( ManagedCluster cluster ) { ClusterMembers members = cluster.getMaster().getDependencyResolver().resolveDependency( ClusterMembers.class ); return Iterables.count(members.getMembers()) == count; } @Override public String toString() { return "Master should see " + count + " members"; } }; } public static Predicate<ManagedCluster> allSeesAllAsAvailable() { return new Predicate<ManagedCluster>() { @Override public boolean accept( ManagedCluster cluster ) { if (!allSeesAllAsJoined().accept( cluster )) return false; for ( HighlyAvailableGraphDatabase database : cluster.getAllMembers() ) { ClusterMembers members = database.getDependencyResolver().resolveDependency( ClusterMembers.class ); for ( ClusterMember clusterMember : members.getMembers() ) { if ( clusterMember.getHARole().equals( "UNKNOWN" ) ) { return false; } } } // Everyone sees everyone else as available! return true; } @Override public String toString() { return "All instances should see all others as available"; } }; } public static Predicate<ManagedCluster> allSeesAllAsJoined( ) { return new Predicate<ManagedCluster>() { @Override public boolean accept( ManagedCluster cluster ) { int nrOfMembers = cluster.size(); for ( HighlyAvailableGraphDatabase database : cluster.getAllMembers() ) { ClusterMembers members = database.getDependencyResolver().resolveDependency( ClusterMembers.class ); if (Iterables.count( members.getMembers() ) < nrOfMembers) return false; } for ( ClusterMembers clusterMembers : cluster.getArbiters() ) { if (Iterables.count(clusterMembers.getMembers()) < nrOfMembers) { return false; } } // Everyone sees everyone else as joined! return true; } @Override public String toString() { return "All instances should see all others as joined"; } }; } public static Predicate<ManagedCluster> allAvailabilityGuardsReleased() { return new Predicate<ManagedCluster>() { @Override public boolean accept( ManagedCluster item ) { for ( HighlyAvailableGraphDatabaseProxy member : item.members.values() ) { try { member.get().beginTx().close(); } catch ( TransactionFailureException e ) { return false; } } return true; } }; } private static String printState(ManagedCluster cluster) { StringBuilder buf = new StringBuilder(); for ( HighlyAvailableGraphDatabase database : cluster.getAllMembers() ) { ClusterMembers members = database.getDependencyResolver().resolveDependency( ClusterMembers.class ); for ( ClusterMember clusterMember : members.getMembers() ) { buf.append( clusterMember.getInstanceId() ).append( ":" ).append( clusterMember.getHARole() ) .append( "\n" ); } buf.append( "\n" ); } return buf.toString(); } @SuppressWarnings("unchecked") private <T> T instance( Class<T> classToFind, Iterable<?> from ) { for ( Object item : from ) { if ( classToFind.isAssignableFrom( item.getClass() ) ) { return (T) item; } } fail( "Couldn't find the network instance to fail. Internal field, so fragile sensitive to changes though" ); return null; // it will never get here. } private Field accessible( Field field ) { field.setAccessible( true ); return field; } public ManagedCluster getCluster( String name ) { if ( !clusterMap.containsKey( name ) ) { throw new IllegalArgumentException( name ); } return clusterMap.get( name ); } public ManagedCluster getDefaultCluster() { return getCluster( "neo4j.ha" ); } protected void config( GraphDatabaseBuilder builder, String clusterName, int serverId ) { } protected void insertInitialData( GraphDatabaseService db, String name, int serverId ) { } public interface RepairKit { HighlyAvailableGraphDatabase repair() throws Throwable; } private class StartNetworkAgainKit implements RepairKit { private final HighlyAvailableGraphDatabase db; private final Iterable<Lifecycle> stoppedServices; StartNetworkAgainKit( HighlyAvailableGraphDatabase db, Iterable<Lifecycle> stoppedServices ) { this.db = db; this.stoppedServices = stoppedServices; } @Override public HighlyAvailableGraphDatabase repair() throws Throwable { for ( Lifecycle stoppedService : stoppedServices ) { stoppedService.start(); } return db; } } private class StartDatabaseAgainKit implements RepairKit { private final int serverId; private final ManagedCluster cluster; public StartDatabaseAgainKit( ManagedCluster cluster, int serverId ) { this.cluster = cluster; this.serverId = serverId; } @Override public HighlyAvailableGraphDatabase repair() throws Throwable { cluster.startMember( serverId ); return cluster.getMemberByServerId( serverId ); } } }
1no label
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterManager.java
2,999
public interface IdCache extends IndexComponent, CloseableComponent { // we need to "inject" the index service to not create cyclic dep void setIndexService(IndexService indexService); void clear(); void clear(Object coreCacheKey); void refresh(List<AtomicReaderContext> readers) throws IOException; IdReaderCache reader(AtomicReader reader); }
0true
src_main_java_org_elasticsearch_index_cache_id_IdCache.java
1,010
protected class ShardSingleOperationRequest extends TransportRequest { private Request request; private int shardId; ShardSingleOperationRequest() { } public ShardSingleOperationRequest(Request request, int shardId) { super(request); this.request = request; this.shardId = shardId; } public Request request() { return request; } public int shardId() { return shardId; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); request = newRequest(); request.readFrom(in); shardId = in.readVInt(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); request.writeTo(out); out.writeVInt(shardId); } }
0true
src_main_java_org_elasticsearch_action_support_single_custom_TransportSingleCustomOperationAction.java
500
indexStateService.closeIndex(updateRequest, new ClusterStateUpdateListener() { @Override public void onResponse(ClusterStateUpdateResponse response) { listener.onResponse(new CloseIndexResponse(response.isAcknowledged())); } @Override public void onFailure(Throwable t) { logger.debug("failed to close indices [{}]", t, request.indices()); listener.onFailure(t); } });
1no label
src_main_java_org_elasticsearch_action_admin_indices_close_TransportCloseIndexAction.java
444
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) { changed.value = true; } });
0true
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedSetTest.java
1,455
public class OCommandExecutorSQLCreateEdge extends OCommandExecutorSQLSetAware { public static final String NAME = "CREATE EDGE"; private String from; private String to; private OClass clazz; private String clusterName; private LinkedHashMap<String, Object> fields; @SuppressWarnings("unchecked") public OCommandExecutorSQLCreateEdge parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); init((OCommandRequestText) iRequest); parserRequiredKeyword("CREATE"); parserRequiredKeyword("EDGE"); String className = null; String temp = parseOptionalWord(true); while (temp != null) { if (temp.equals("CLUSTER")) { clusterName = parserRequiredWord(false); } else if (temp.equals(KEYWORD_FROM)) { from = parserRequiredWord(false, "Syntax error", " =><,\r\n"); } else if (temp.equals("TO")) { to = parserRequiredWord(false, "Syntax error", " =><,\r\n"); } else if (temp.equals(KEYWORD_SET)) { fields = new LinkedHashMap<String, Object>(); parseSetFields(fields); } else if (temp.equals(KEYWORD_CONTENT)) { parseContent(); } else if (className == null && temp.length() > 0) className = temp; temp = parseOptionalWord(true); if (parserIsEnded()) break; } if (className == null) // ASSIGN DEFAULT CLASS className = "E"; // GET/CHECK CLASS NAME clazz = database.getMetadata().getSchema().getClass(className); if (clazz == null) throw new OCommandSQLParsingException("Class " + className + " was not found"); return this; } /** * Execute the command and return the ODocument object created. */ public Object execute(final Map<Object, Object> iArgs) { if (clazz == null) throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet"); final OrientBaseGraph graph = OGraphCommandExecutorSQLFactory.getGraph(); final Set<ORID> fromIds = OSQLEngine.getInstance().parseRIDTarget(graph.getRawGraph(), from); final Set<ORID> toIds = OSQLEngine.getInstance().parseRIDTarget(graph.getRawGraph(), to); // CREATE EDGES final List<Object> edges = new ArrayList<Object>(); for (ORID from : fromIds) { final OrientVertex fromVertex = graph.getVertex(from); if (fromVertex == null) throw new OCommandExecutionException("Source vertex '" + from + "' not exists"); for (ORID to : toIds) { final OrientVertex toVertex; if (from.equals(to)) { toVertex = fromVertex; } else { toVertex = graph.getVertex(to); } final String clsName = clazz.getName(); if (fields != null) // EVALUATE FIELDS for (Entry<String, Object> f : fields.entrySet()) { if (f.getValue() instanceof OSQLFunctionRuntime) fields.put(f.getKey(), ((OSQLFunctionRuntime) f.getValue()).getValue(to, context)); } final OrientEdge edge = fromVertex.addEdge(null, toVertex, clsName, clusterName, fields); if (fields != null && !fields.isEmpty()) { if (!edge.getRecord().getIdentity().isValid()) edge.convertToDocument(); OSQLHelper.bindParameters(edge.getRecord(), fields, new OCommandParameters(iArgs), context); } if (content != null) { if (!edge.getRecord().getIdentity().isValid()) // LIGHTWEIGHT EDGE, TRANSFORM IT BEFORE edge.convertToDocument(); edge.getRecord().merge(content, true, false); } edge.save(clusterName); edges.add(edge); } } return edges; } @Override public String getSyntax() { return "CREATE EDGE [<class>] [CLUSTER <cluster>] FROM <rid>|(<query>|[<rid>]*) TO <rid>|(<query>|[<rid>]*) [SET <field> = <expression>[,]*]|CONTENT {<JSON>}"; } }
1no label
graphdb_src_main_java_com_orientechnologies_orient_graph_sql_OCommandExecutorSQLCreateEdge.java
1,269
@Deprecated public class TaxActivity extends BaseActivity<PricingContext> { protected TaxModule taxModule; protected TaxService taxService; @Override public PricingContext execute(PricingContext context) throws Exception { Order order = context.getSeedData(); if (taxService != null) { order = taxService.calculateTaxForOrder(order); } else if (taxModule != null) { order = taxModule.calculateTaxForOrder(order); } context.setSeedData(order); return context; } public void setTaxModule(TaxModule taxModule) { this.taxModule = taxModule; } public void setTaxService(TaxService taxService) { this.taxService = taxService; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_service_workflow_TaxActivity.java
1,769
public class ShapesAvailability { public static final boolean SPATIAL4J_AVAILABLE; public static final boolean JTS_AVAILABLE; static { boolean xSPATIAL4J_AVAILABLE; try { Classes.getDefaultClassLoader().loadClass("com.spatial4j.core.shape.impl.PointImpl"); xSPATIAL4J_AVAILABLE = true; } catch (Throwable t) { xSPATIAL4J_AVAILABLE = false; } SPATIAL4J_AVAILABLE = xSPATIAL4J_AVAILABLE; boolean xJTS_AVAILABLE; try { Classes.getDefaultClassLoader().loadClass("com.vividsolutions.jts.geom.GeometryFactory"); xJTS_AVAILABLE = true; } catch (Throwable t) { xJTS_AVAILABLE = false; } JTS_AVAILABLE = xJTS_AVAILABLE; } private ShapesAvailability() { } }
0true
src_main_java_org_elasticsearch_common_geo_ShapesAvailability.java
368
public static class TimeConsumingMapper implements Mapper<Integer, Integer, String, Integer> { @Override public void map(Integer key, Integer value, Context<String, Integer> collector) { try { Thread.sleep(1000); } catch (Exception ignore) { } collector.emit(String.valueOf(key), value); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_ClientMapReduceTest.java
1,394
public interface RegionCache { Object get(final Object key); boolean put(final Object key, final Object value, final Object currentVersion); boolean update(final Object key, final Object value, final Object currentVersion, final Object previousVersion, final SoftLock lock); boolean remove(final Object key); SoftLock tryLock(final Object key, final Object version); void unlock(final Object key, SoftLock lock); boolean contains(final Object key); void clear(); long size(); long getSizeInMemory(); Map asMap(); }
0true
hazelcast-hibernate_hazelcast-hibernate4_src_main_java_com_hazelcast_hibernate_RegionCache.java
3,479
rootObjectMapper.traverse(new ObjectMapperListener() { @Override public void objectMapper(ObjectMapper objectMapper) { objectMappers.put(objectMapper.fullPath(), objectMapper); } });
0true
src_main_java_org_elasticsearch_index_mapper_DocumentMapper.java
399
public class ORecordOperation implements OSerializableStream { private static final long serialVersionUID = 1L; public static final byte LOADED = 0; public static final byte UPDATED = 1; public static final byte DELETED = 2; public static final byte CREATED = 3; public byte type; public OIdentifiable record; public int dataSegmentId = 0; // DEFAULT ONE public ORecordOperation() { } public ORecordOperation(final OIdentifiable iRecord, final byte iStatus) { // CLONE RECORD AND CONTENT this.record = iRecord; this.type = iStatus; } @Override public int hashCode() { return record.getIdentity().hashCode(); } @Override public boolean equals(final Object obj) { if (!(obj instanceof ORecordOperation)) return false; return record.equals(((ORecordOperation) obj).record); } @Override public String toString() { return new StringBuilder().append("ORecordOperation [record=").append(record).append(", type=").append(getName(type)) .append("]").toString(); } public ORecordInternal<?> getRecord() { return (ORecordInternal<?>) (record != null ? record.getRecord() : null); } public byte[] toStream() throws OSerializationException { try { final OMemoryStream stream = new OMemoryStream(); stream.set(type); ((ORecordId) record.getIdentity()).toStream(stream); switch (type) { case CREATED: case UPDATED: stream.set(((ORecordInternal<?>) record.getRecord()).getRecordType()); stream.set(((ORecordInternal<?>) record.getRecord()).toStream()); break; } return stream.toByteArray(); } catch (Exception e) { throw new OSerializationException("Cannot serialize record operation", e); } } public OSerializableStream fromStream(final byte[] iStream) throws OSerializationException { try { final OMemoryStream stream = new OMemoryStream(iStream); type = stream.getAsByte(); final ORecordId rid = new ORecordId().fromStream(stream); switch (type) { case CREATED: case UPDATED: record = Orient.instance().getRecordFactoryManager().newInstance(stream.getAsByte()); ((ORecordInternal<?>) record).fill(rid, OVersionFactory.instance().createVersion(), stream.getAsByteArray(), true); break; } return this; } catch (Exception e) { throw new OSerializationException("Cannot deserialize record operation", e); } } public static String getName(final int type) { String operation = "?"; switch (type) { case ORecordOperation.CREATED: operation = "CREATE"; break; case ORecordOperation.UPDATED: operation = "UPDATE"; break; case ORecordOperation.DELETED: operation = "DELETE"; break; case ORecordOperation.LOADED: operation = "READ"; break; } return operation; } public static byte getId(String iName) { iName = iName.toUpperCase(); if (iName.startsWith("CREAT")) return ORecordOperation.CREATED; else if (iName.startsWith("UPDAT")) return ORecordOperation.UPDATED; else if (iName.startsWith("DELET")) return ORecordOperation.DELETED; else if (iName.startsWith("READ")) return ORecordOperation.LOADED; return -1; } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_record_ORecordOperation.java
1,199
public interface SecurePaymentInfoService { public Referenced findSecurePaymentInfo(String referenceNumber, PaymentInfoType paymentInfoType) throws WorkflowException; public Referenced save(Referenced securePaymentInfo); public Referenced create(PaymentInfoType paymentInfoType); public void remove(Referenced securePaymentInfo); public void findAndRemoveSecurePaymentInfo(String referenceNumber, PaymentInfoType paymentInfoType) throws WorkflowException; }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_service_SecurePaymentInfoService.java
658
public class OMemoryHashMapIndexEngine<V> implements OIndexEngine<V> { private final ConcurrentMap<Object, V> concurrentHashMap = new ConcurrentHashMap<Object, V>(); private volatile ORID identity; @Override public void init() { } @Override public void flush() { } @Override public void create(String indexName, OIndexDefinition indexDefinition, String clusterIndexName, OStreamSerializer valueSerializer, boolean isAutomatic) { final ODatabaseRecord database = getDatabase(); final ORecordBytes identityRecord = new ORecordBytes(); database.save(identityRecord, clusterIndexName); identity = identityRecord.getIdentity(); } @Override public void delete() { } @Override public void deleteWithoutLoad(String indexName) { } @Override public void load(ORID indexRid, String indexName, OIndexDefinition indexDefinition, boolean isAutomatic) { } @Override public boolean contains(Object key) { return concurrentHashMap.containsKey(key); } @Override public boolean remove(Object key) { return concurrentHashMap.remove(key) != null; } @Override public ORID getIdentity() { return identity; } @Override public void clear() { concurrentHashMap.clear(); } @Override public Iterator<Map.Entry<Object, V>> iterator() { return concurrentHashMap.entrySet().iterator(); } @Override public Iterator<Map.Entry<Object, V>> inverseIterator() { throw new UnsupportedOperationException("inverseIterator"); } @Override public Iterator<V> valuesIterator() { throw new UnsupportedOperationException("valuesIterator"); } @Override public Iterator<V> inverseValuesIterator() { throw new UnsupportedOperationException("inverseValuesIterator"); } @Override public Iterable<Object> keys() { return concurrentHashMap.keySet(); } @Override public void unload() { } @Override public void startTransaction() { } @Override public void stopTransaction() { } @Override public void afterTxRollback() { } @Override public void afterTxCommit() { } @Override public void closeDb() { } @Override public void close() { } @Override public void beforeTxBegin() { } @Override public V get(Object key) { return concurrentHashMap.get(key); } @Override public void put(Object key, V value) { concurrentHashMap.put(key, value); } @Override public void getValuesBetween(Object rangeFrom, boolean fromInclusive, Object rangeTo, boolean toInclusive, ValuesTransformer<V> transformer, ValuesResultListener valuesResultListener) { throw new UnsupportedOperationException("getValuesBetween"); } @Override public void getValuesMajor(Object fromKey, boolean isInclusive, ValuesTransformer<V> transformer, ValuesResultListener valuesResultListener) { throw new UnsupportedOperationException("getValuesMajor"); } @Override public void getValuesMinor(Object toKey, boolean isInclusive, ValuesTransformer<V> transformer, ValuesResultListener valuesResultListener) { throw new UnsupportedOperationException("getValuesMinor"); } @Override public void getEntriesMajor(Object fromKey, boolean isInclusive, ValuesTransformer<V> transformer, EntriesResultListener entriesResultListener) { throw new UnsupportedOperationException("getEntriesMajor"); } @Override public void getEntriesMinor(Object toKey, boolean isInclusive, ValuesTransformer<V> transformer, EntriesResultListener entriesResultListener) { throw new UnsupportedOperationException("getEntriesMinor"); } @Override public void getEntriesBetween(Object iRangeFrom, Object iRangeTo, boolean iInclusive, ValuesTransformer<V> transformer, EntriesResultListener entriesResultListener) { throw new UnsupportedOperationException("getEntriesBetween"); } @Override public long size(ValuesTransformer<V> transformer) { if (transformer == null) return concurrentHashMap.size(); else { long counter = 0; for (V value : concurrentHashMap.values()) { counter += transformer.transformFromValue(value).size(); } return counter; } } @Override public long count(Object rangeFrom, boolean fromInclusive, Object rangeTo, boolean toInclusive, int maxValuesToFetch, ValuesTransformer<V> transformer) { throw new UnsupportedOperationException("count"); } @Override public boolean hasRangeQuerySupport() { return false; } private ODatabaseRecord getDatabase() { return ODatabaseRecordThreadLocal.INSTANCE.get(); } }
1no label
core_src_main_java_com_orientechnologies_orient_core_index_engine_OMemoryHashMapIndexEngine.java
348
static class TestComparator implements Comparator<Map.Entry>, Serializable { int ascending = 1; IterationType iterationType = IterationType.ENTRY; TestComparator() { } TestComparator(boolean ascending, IterationType iterationType) { this.ascending = ascending ? 1 : -1; this.iterationType = iterationType; } public int compare(Map.Entry e1, Map.Entry e2) { Map.Entry<Integer, Integer> o1 = e1; Map.Entry<Integer, Integer> o2 = e2; switch (iterationType) { case KEY: return (o1.getKey() - o2.getKey()) * ascending; case VALUE: return (o1.getValue() - o2.getValue()) * ascending; default: int result = (o1.getValue() - o2.getValue()) * ascending; if (result != 0) { return result; } return (o1.getKey() - o2.getKey()) * ascending; } } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientSortLimitTest.java
318
public class OStorageDataConfiguration extends OStorageSegmentConfiguration { private static final long serialVersionUID = 1L; public OStorageDataHoleConfiguration holeFile; private static final String START_SIZE = "1Mb"; private static final String INCREMENT_SIZE = "100%"; public OStorageDataConfiguration(final OStorageConfiguration iRoot, final String iSegmentName, final int iId) { super(iRoot, iSegmentName, iId); fileStartSize = START_SIZE; fileIncrementSize = INCREMENT_SIZE; } public OStorageDataConfiguration(final OStorageConfiguration iRoot, final String iSegmentName, final int iId, final String iDirectory) { super(iRoot, iSegmentName, iId, iDirectory); fileStartSize = START_SIZE; fileIncrementSize = INCREMENT_SIZE; } @Override public void setRoot(final OStorageConfiguration root) { super.setRoot(root); holeFile.parent = this; } }
0true
core_src_main_java_com_orientechnologies_orient_core_config_OStorageDataConfiguration.java
93
interface ClientExceptionConverter { Object convert(Throwable t); }
0true
hazelcast_src_main_java_com_hazelcast_client_ClientExceptionConverter.java
1,401
clusterService.submitStateUpdateTask("delete-index [" + request.index + "]", Priority.URGENT, new TimeoutClusterStateUpdateTask() { @Override public TimeValue timeout() { return request.masterTimeout; } @Override public void onFailure(String source, Throwable t) { listener.onFailure(t); } @Override public ClusterState execute(final ClusterState currentState) { if (!currentState.metaData().hasConcreteIndex(request.index)) { throw new IndexMissingException(new Index(request.index)); } logger.info("[{}] deleting index", request.index); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(currentState.routingTable()); routingTableBuilder.remove(request.index); MetaData newMetaData = MetaData.builder(currentState.metaData()) .remove(request.index) .build(); RoutingAllocation.Result routingResult = allocationService.reroute( ClusterState.builder(currentState).routingTable(routingTableBuilder).metaData(newMetaData).build()); ClusterBlocks blocks = ClusterBlocks.builder().blocks(currentState.blocks()).removeIndexBlocks(request.index).build(); // wait for events from all nodes that it has been removed from their respective metadata... int count = currentState.nodes().size(); // add the notifications that the store was deleted from *data* nodes count += currentState.nodes().dataNodes().size(); final AtomicInteger counter = new AtomicInteger(count); // this listener will be notified once we get back a notification based on the cluster state change below. final NodeIndexDeletedAction.Listener nodeIndexDeleteListener = new NodeIndexDeletedAction.Listener() { @Override public void onNodeIndexDeleted(String index, String nodeId) { if (index.equals(request.index)) { if (counter.decrementAndGet() == 0) { listener.onResponse(new Response(true)); nodeIndexDeletedAction.remove(this); } } } @Override public void onNodeIndexStoreDeleted(String index, String nodeId) { if (index.equals(request.index)) { if (counter.decrementAndGet() == 0) { listener.onResponse(new Response(true)); nodeIndexDeletedAction.remove(this); } } } }; nodeIndexDeletedAction.add(nodeIndexDeleteListener); listener.future = threadPool.schedule(request.timeout, ThreadPool.Names.SAME, new Runnable() { @Override public void run() { listener.onResponse(new Response(false)); nodeIndexDeletedAction.remove(nodeIndexDeleteListener); } }); return ClusterState.builder(currentState).routingResult(routingResult).metaData(newMetaData).blocks(blocks).build(); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { } });
0true
src_main_java_org_elasticsearch_cluster_metadata_MetaDataDeleteIndexService.java
5,128
aggregators[i] = new Aggregator(first.name(), BucketAggregationMode.MULTI_BUCKETS, AggregatorFactories.EMPTY, 1, first.context(), first.parent()) { ObjectArray<Aggregator> aggregators; { aggregators = BigArrays.newObjectArray(estimatedBucketsCount, context.pageCacheRecycler()); aggregators.set(0, first); for (long i = 1; i < estimatedBucketsCount; ++i) { aggregators.set(i, createAndRegisterContextAware(parent.context(), factory, parent, estimatedBucketsCount)); } } @Override public boolean shouldCollect() { return first.shouldCollect(); } @Override protected void doPostCollection() { for (long i = 0; i < aggregators.size(); ++i) { final Aggregator aggregator = aggregators.get(i); if (aggregator != null) { aggregator.postCollection(); } } } @Override public void collect(int doc, long owningBucketOrdinal) throws IOException { aggregators = BigArrays.grow(aggregators, owningBucketOrdinal + 1); Aggregator aggregator = aggregators.get(owningBucketOrdinal); if (aggregator == null) { aggregator = createAndRegisterContextAware(parent.context(), factory, parent, estimatedBucketsCount); aggregators.set(owningBucketOrdinal, aggregator); } aggregator.collect(doc, 0); } @Override public void setNextReader(AtomicReaderContext reader) { } @Override public InternalAggregation buildAggregation(long owningBucketOrdinal) { return aggregators.get(owningBucketOrdinal).buildAggregation(0); } @Override public InternalAggregation buildEmptyAggregation() { return first.buildEmptyAggregation(); } @Override public void doRelease() { Releasables.release(aggregators); } };
1no label
src_main_java_org_elasticsearch_search_aggregations_AggregatorFactories.java
3,089
static interface IndexingOperation extends Operation { ParsedDocument parsedDoc(); List<Document> docs(); DocumentMapper docMapper(); }
0true
src_main_java_org_elasticsearch_index_engine_Engine.java
1,344
public interface OWALRecord { int toStream(byte[] content, int offset); int fromStream(byte[] content, int offset); int serializedSize(); boolean isUpdateMasterRecord(); OLogSequenceNumber getLsn(); void setLsn(OLogSequenceNumber lsn); }
0true
core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_wal_OWALRecord.java
3,244
private static class InnerSource extends IndexFieldData.XFieldComparatorSource { private final SearchScript script; private InnerSource(SearchScript script) { this.script = script; } @Override public FieldComparator<? extends Number> newComparator(String fieldname, int numHits, int sortPos, boolean reversed) throws IOException { return new DoubleScriptDataComparator(numHits, script); } @Override public SortField.Type reducedType() { return SortField.Type.DOUBLE; } }
0true
src_main_java_org_elasticsearch_index_fielddata_fieldcomparator_DoubleScriptDataComparator.java
409
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.REMOVE); Assert.assertEquals(event.getOldValue(), "value2"); Assert.assertEquals(event.getKey().intValue(), 1); Assert.assertNull(event.getValue()); changed.value = true; } });
0true
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedListTest.java
1,403
listener.future = threadPool.schedule(request.timeout, ThreadPool.Names.SAME, new Runnable() { @Override public void run() { listener.onResponse(new Response(false)); nodeIndexDeletedAction.remove(nodeIndexDeleteListener); } });
0true
src_main_java_org_elasticsearch_cluster_metadata_MetaDataDeleteIndexService.java
2,566
private class ClusterGroup { private Queue<LocalDiscovery> members = ConcurrentCollections.newQueue(); Queue<LocalDiscovery> members() { return members; } }
0true
src_main_java_org_elasticsearch_discovery_local_LocalDiscovery.java
623
final class SplitBrainHandler implements Runnable { final Node node; final AtomicBoolean inProgress = new AtomicBoolean(false); public SplitBrainHandler(Node node) { this.node = node; } @Override public void run() { if (node.isMaster() && node.joined() && node.isActive() && !node.clusterService.isJoinInProgress() && inProgress.compareAndSet(false, true)) { try { searchForOtherClusters(); } finally { inProgress.set(false); } } } private void searchForOtherClusters() { Joiner joiner = node.getJoiner(); if (joiner != null) { joiner.searchForOtherClusters(); } } }
0true
hazelcast_src_main_java_com_hazelcast_cluster_SplitBrainHandler.java
1,674
public interface ImmutableBlobContainer extends BlobContainer { interface WriterListener { void onCompleted(); void onFailure(Throwable t); } void writeBlob(String blobName, InputStream is, long sizeInBytes, WriterListener listener); void writeBlob(String blobName, InputStream is, long sizeInBytes) throws IOException; }
0true
src_main_java_org_elasticsearch_common_blobstore_ImmutableBlobContainer.java
692
client.bulk(bulkRequest, new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse response) { try { listener.afterBulk(executionId, bulkRequest, response); } finally { semaphore.release(); } } @Override public void onFailure(Throwable e) { try { listener.afterBulk(executionId, bulkRequest, e); } finally { semaphore.release(); } } });
0true
src_main_java_org_elasticsearch_action_bulk_BulkProcessor.java
369
public class GetRepositoriesRequest extends MasterNodeReadOperationRequest<GetRepositoriesRequest> { private String[] repositories = Strings.EMPTY_ARRAY; GetRepositoriesRequest() { } /** * Constructs a new get repositories request with a list of repositories. * <p/> * If the list of repositories is empty or it contains a single element "_all", all registered repositories * are returned. * * @param repositories list of repositories */ public GetRepositoriesRequest(String[] repositories) { this.repositories = repositories; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (repositories == null) { validationException = addValidationError("repositories is null", validationException); } return validationException; } /** * The names of the repositories. * * @return list of repositories */ public String[] repositories() { return this.repositories; } /** * Sets the list or repositories. * <p/> * If the list of repositories is empty or it contains a single element "_all", all registered repositories * are returned. * * @param repositories list of repositories * @return this request */ public GetRepositoriesRequest repositories(String[] repositories) { this.repositories = repositories; return this; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); repositories = in.readStringArray(); readLocal(in, Version.V_1_0_0_RC2); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeStringArray(repositories); writeLocal(out, Version.V_1_0_0_RC2); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_repositories_get_GetRepositoriesRequest.java
104
CONTAINS_REGEX { @Override public boolean evaluate(Object value, Object condition) { this.preevaluate(value,condition); if (value == null) return false; return evaluateRaw(value.toString(),(String)condition); } @Override public boolean evaluateRaw(String value, String regex) { for (String token : tokenize(value.toLowerCase())) { if (REGEX.evaluateRaw(token,regex)) return true; } return false; } @Override public boolean isValidCondition(Object condition) { return condition != null && condition instanceof String && StringUtils.isNotBlank(condition.toString()); } },
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Text.java
1,247
addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); map.get(random.nextInt(SIZE)); } }, 100);
0true
hazelcast_src_main_java_com_hazelcast_examples_AllTest.java
419
public class RestoreSnapshotRequest extends MasterNodeOperationRequest<RestoreSnapshotRequest> { private String snapshot; private String repository; private String[] indices = Strings.EMPTY_ARRAY; private IndicesOptions indicesOptions = IndicesOptions.strict(); private String renamePattern; private String renameReplacement; private boolean waitForCompletion; private boolean includeGlobalState = true; private Settings settings = EMPTY_SETTINGS; RestoreSnapshotRequest() { } /** * Constructs a new put repository request with the provided repository and snapshot names. * * @param repository repository name * @param snapshot snapshot name */ public RestoreSnapshotRequest(String repository, String snapshot) { this.snapshot = snapshot; this.repository = repository; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (snapshot == null) { validationException = addValidationError("name is missing", validationException); } if (repository == null) { validationException = addValidationError("repository is missing", validationException); } if (indices == null) { validationException = addValidationError("indices are missing", validationException); } if (indicesOptions == null) { validationException = addValidationError("indicesOptions is missing", validationException); } if (settings == null) { validationException = addValidationError("settings are missing", validationException); } return validationException; } /** * Sets the name of the snapshot. * * @param snapshot snapshot name * @return this request */ public RestoreSnapshotRequest snapshot(String snapshot) { this.snapshot = snapshot; return this; } /** * Returns the name of the snapshot. * * @return snapshot name */ public String snapshot() { return this.snapshot; } /** * Sets repository name * * @param repository repository name * @return this request */ public RestoreSnapshotRequest repository(String repository) { this.repository = repository; return this; } /** * Returns repository name * * @return repository name */ public String repository() { return this.repository; } /** * Sets the list of indices that should be restored from snapshot * <p/> * The list of indices supports multi-index syntax. For example: "+test*" ,"-test42" will index all indices with * prefix "test" except index "test42". Aliases are not supported. An empty list or {"_all"} will restore all open * indices in the snapshot. * * @param indices list of indices * @return this request */ public RestoreSnapshotRequest indices(String... indices) { this.indices = indices; return this; } /** * Sets the list of indices that should be restored from snapshot * <p/> * The list of indices supports multi-index syntax. For example: "+test*" ,"-test42" will index all indices with * prefix "test" except index "test42". Aliases are not supported. An empty list or {"_all"} will restore all open * indices in the snapshot. * * @param indices list of indices * @return this request */ public RestoreSnapshotRequest indices(List<String> indices) { this.indices = indices.toArray(new String[indices.size()]); return this; } /** * Returns list of indices that should be restored from snapshot * * @return */ public String[] indices() { return indices; } /** * Specifies what type of requested indices to ignore and how to deal with wildcard expressions. * For example indices that don't exist. * * @return the desired behaviour regarding indices to ignore and wildcard indices expression */ public IndicesOptions indicesOptions() { return indicesOptions; } /** * Specifies what type of requested indices to ignore and how to deal with wildcard expressions. * For example indices that don't exist. * * @param indicesOptions the desired behaviour regarding indices to ignore and wildcard indices expressions * @return this request */ public RestoreSnapshotRequest indicesOptions(IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; return this; } /** * Sets rename pattern that should be applied to restored indices. * <p/> * Indices that match the rename pattern will be renamed according to {@link #renameReplacement(String)}. The * rename pattern is applied according to the {@link java.util.regex.Matcher#appendReplacement(StringBuffer, String)} * The request will fail if two or more indices will be renamed into the same name. * * @param renamePattern rename pattern * @return this request */ public RestoreSnapshotRequest renamePattern(String renamePattern) { this.renamePattern = renamePattern; return this; } /** * Returns rename pattern * * @return rename pattern */ public String renamePattern() { return renamePattern; } /** * Sets rename replacement * <p/> * See {@link #renamePattern(String)} for more information. * * @param renameReplacement rename replacement * @return */ public RestoreSnapshotRequest renameReplacement(String renameReplacement) { this.renameReplacement = renameReplacement; return this; } /** * Returns rename replacement * * @return rename replacement */ public String renameReplacement() { return renameReplacement; } /** * If this parameter is set to true the operation will wait for completion of restore process before returning. * * @param waitForCompletion if true the operation will wait for completion * @return this request */ public RestoreSnapshotRequest waitForCompletion(boolean waitForCompletion) { this.waitForCompletion = waitForCompletion; return this; } /** * Returns wait for completion setting * * @return true if the operation will wait for completion */ public boolean waitForCompletion() { return waitForCompletion; } /** * Sets repository-specific restore settings. * <p/> * See repository documentation for more information. * * @param settings repository-specific snapshot settings * @return this request */ public RestoreSnapshotRequest settings(Settings settings) { this.settings = settings; return this; } /** * Sets repository-specific restore settings. * <p/> * See repository documentation for more information. * * @param settings repository-specific snapshot settings * @return this request */ public RestoreSnapshotRequest settings(Settings.Builder settings) { this.settings = settings.build(); return this; } /** * Sets repository-specific restore settings in JSON, YAML or properties format * <p/> * See repository documentation for more information. * * @param source repository-specific snapshot settings * @return this request */ public RestoreSnapshotRequest settings(String source) { this.settings = ImmutableSettings.settingsBuilder().loadFromSource(source).build(); return this; } /** * Sets repository-specific restore settings * <p/> * See repository documentation for more information. * * @param source repository-specific snapshot settings * @return this request */ public RestoreSnapshotRequest settings(Map<String, Object> source) { try { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); builder.map(source); settings(builder.string()); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); } return this; } /** * Returns repository-specific restore settings * * @return restore settings */ public Settings settings() { return this.settings; } /** * If set to true the restore procedure will restore global cluster state. * <p/> * The global cluster state includes persistent settings and index template definitions. * * @param includeGlobalState true if global state should be restored from the snapshot * @return this request */ public RestoreSnapshotRequest includeGlobalState(boolean includeGlobalState) { this.includeGlobalState = includeGlobalState; return this; } /** * Returns true if global state should be restored from this snapshot * * @return true if global state should be restored */ public boolean includeGlobalState() { return includeGlobalState; } /** * Parses restore definition * * @param source restore definition * @return this request */ public RestoreSnapshotRequest source(XContentBuilder source) { try { return source(source.bytes()); } catch (Exception e) { throw new ElasticsearchIllegalArgumentException("Failed to build json for repository request", e); } } /** * Parses restore definition * * @param source restore definition * @return this request */ public RestoreSnapshotRequest source(Map source) { boolean ignoreUnavailable = IndicesOptions.lenient().ignoreUnavailable(); boolean allowNoIndices = IndicesOptions.lenient().allowNoIndices(); boolean expandWildcardsOpen = IndicesOptions.lenient().expandWildcardsOpen(); boolean expandWildcardsClosed = IndicesOptions.lenient().expandWildcardsClosed(); for (Map.Entry<String, Object> entry : ((Map<String, Object>) source).entrySet()) { String name = entry.getKey(); if (name.equals("indices")) { if (entry.getValue() instanceof String) { indices(Strings.splitStringByCommaToArray((String) entry.getValue())); } else if (entry.getValue() instanceof ArrayList) { indices((ArrayList<String>) entry.getValue()); } else { throw new ElasticsearchIllegalArgumentException("malformed indices section, should be an array of strings"); } } else if (name.equals("ignore_unavailable") || name.equals("ignoreUnavailable")) { ignoreUnavailable = nodeBooleanValue(entry.getValue()); } else if (name.equals("allow_no_indices") || name.equals("allowNoIndices")) { allowNoIndices = nodeBooleanValue(entry.getValue()); } else if (name.equals("expand_wildcards_open") || name.equals("expandWildcardsOpen")) { expandWildcardsOpen = nodeBooleanValue(entry.getValue()); } else if (name.equals("expand_wildcards_closed") || name.equals("expandWildcardsClosed")) { expandWildcardsClosed = nodeBooleanValue(entry.getValue()); } else if (name.equals("settings")) { if (!(entry.getValue() instanceof Map)) { throw new ElasticsearchIllegalArgumentException("malformed settings section, should indices an inner object"); } settings((Map<String, Object>) entry.getValue()); } else if (name.equals("include_global_state")) { includeGlobalState = nodeBooleanValue(entry.getValue()); } else if (name.equals("rename_pattern")) { if (entry.getValue() instanceof String) { renamePattern((String) entry.getValue()); } else { throw new ElasticsearchIllegalArgumentException("malformed rename_pattern"); } } else if (name.equals("rename_replacement")) { if (entry.getValue() instanceof String) { renameReplacement((String) entry.getValue()); } else { throw new ElasticsearchIllegalArgumentException("malformed rename_replacement"); } } else { throw new ElasticsearchIllegalArgumentException("Unknown parameter " + name); } } indicesOptions(IndicesOptions.fromOptions(ignoreUnavailable, allowNoIndices, expandWildcardsOpen, expandWildcardsClosed)); return this; } /** * Parses restore definition * <p/> * JSON, YAML and properties formats are supported * * @param source restore definition * @return this request */ public RestoreSnapshotRequest source(String source) { if (hasLength(source)) { try { return source(XContentFactory.xContent(source).createParser(source).mapOrderedAndClose()); } catch (Exception e) { throw new ElasticsearchIllegalArgumentException("failed to parse repository source [" + source + "]", e); } } return this; } /** * Parses restore definition * <p/> * JSON, YAML and properties formats are supported * * @param source restore definition * @return this request */ public RestoreSnapshotRequest source(byte[] source) { return source(source, 0, source.length); } /** * Parses restore definition * <p/> * JSON, YAML and properties formats are supported * * @param source restore definition * @param offset offset * @param length length * @return this request */ public RestoreSnapshotRequest source(byte[] source, int offset, int length) { if (length > 0) { try { return source(XContentFactory.xContent(source, offset, length).createParser(source, offset, length).mapOrderedAndClose()); } catch (IOException e) { throw new ElasticsearchIllegalArgumentException("failed to parse repository source", e); } } return this; } /** * Parses restore definition * <p/> * JSON, YAML and properties formats are supported * * @param source restore definition * @return this request */ public RestoreSnapshotRequest source(BytesReference source) { try { return source(XContentFactory.xContent(source).createParser(source).mapOrderedAndClose()); } catch (IOException e) { throw new ElasticsearchIllegalArgumentException("failed to parse template source", e); } } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); snapshot = in.readString(); repository = in.readString(); indices = in.readStringArray(); indicesOptions = IndicesOptions.readIndicesOptions(in); renamePattern = in.readOptionalString(); renameReplacement = in.readOptionalString(); waitForCompletion = in.readBoolean(); includeGlobalState = in.readBoolean(); settings = readSettingsFromStream(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(snapshot); out.writeString(repository); out.writeStringArray(indices); indicesOptions.writeIndicesOptions(out); out.writeOptionalString(renamePattern); out.writeOptionalString(renameReplacement); out.writeBoolean(waitForCompletion); out.writeBoolean(includeGlobalState); writeSettingsToStream(settings, out); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_restore_RestoreSnapshotRequest.java
1,142
public class ChildSearchAndIndexingBenchmark { static int PARENT_COUNT = (int) SizeValue.parseSizeValue("1m").singles(); static int NUM_CHILDREN_PER_PARENT = 12; static int QUERY_VALUE_RATIO_PER_PARENT = 3; static int QUERY_COUNT = 50; static String indexName = "test"; static Random random = new Random(); public static void main(String[] args) throws Exception { Settings settings = settingsBuilder() .put("refresh_interval", "-1") .put("gateway.type", "local") .put(SETTING_NUMBER_OF_SHARDS, 1) .put(SETTING_NUMBER_OF_REPLICAS, 0) .build(); String clusterName = ChildSearchAndIndexingBenchmark.class.getSimpleName(); Node node1 = nodeBuilder().settings(settingsBuilder().put(settings).put("name", "node1")) .clusterName(clusterName) .node(); Client client = node1.client(); client.admin().cluster().prepareHealth(indexName).setWaitForGreenStatus().setTimeout("10s").execute().actionGet(); try { client.admin().indices().create(createIndexRequest(indexName)).actionGet(); client.admin().indices().preparePutMapping(indexName).setType("child").setSource(XContentFactory.jsonBuilder().startObject().startObject("child") .startObject("_parent").field("type", "parent").endObject() .endObject().endObject()).execute().actionGet(); Thread.sleep(5000); long startTime = System.currentTimeMillis(); ParentChildIndexGenerator generator = new ParentChildIndexGenerator(client, PARENT_COUNT, NUM_CHILDREN_PER_PARENT, QUERY_VALUE_RATIO_PER_PARENT); generator.index(); System.out.println("--> Indexing took " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds."); } catch (IndexAlreadyExistsException e) { System.out.println("--> Index already exists, ignoring indexing phase, waiting for green"); ClusterHealthResponse clusterHealthResponse = client.admin().cluster().prepareHealth(indexName).setWaitForGreenStatus().setTimeout("10m").execute().actionGet(); if (clusterHealthResponse.isTimedOut()) { System.err.println("--> Timed out waiting for cluster health"); } } client.admin().indices().prepareRefresh().execute().actionGet(); System.out.println("--> Number of docs in index: " + client.prepareCount().setQuery(matchAllQuery()).execute().actionGet().getCount()); SearchThread searchThread = new SearchThread(client); new Thread(searchThread).start(); IndexThread indexThread = new IndexThread(client); new Thread(indexThread).start(); System.in.read(); indexThread.stop(); searchThread.stop(); client.close(); node1.close(); } static class IndexThread implements Runnable { private final Client client; private volatile boolean run = true; IndexThread(Client client) { this.client = client; } @Override public void run() { while (run) { int childIdLimit = PARENT_COUNT * NUM_CHILDREN_PER_PARENT; for (int childId = 1; run && childId < childIdLimit;) { try { for (int j = 0; j < 8; j++) { GetResponse getResponse = client .prepareGet(indexName, "child", String.valueOf(++childId)) .setFields("_source", "_parent") .setRouting("1") // Doesn't matter what value, since there is only one shard .get(); client.prepareIndex(indexName, "child", Integer.toString(childId) + "_" + j) .setParent(getResponse.getField("_parent").getValue().toString()) .setSource(getResponse.getSource()) .get(); } client.admin().indices().prepareRefresh(indexName).execute().actionGet(); Thread.sleep(1000); if (childId % 500 == 0) { NodesStatsResponse statsResponse = client.admin().cluster().prepareNodesStats() .clear().setIndices(true).execute().actionGet(); System.out.println("Deleted docs: " + statsResponse.getAt(0).getIndices().getDocs().getDeleted()); } } catch (Throwable e) { e.printStackTrace(); } } } } public void stop() { run = false; } } 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
849
public class ContainsRequest extends ReadRequest { private Data expected; public ContainsRequest() { } public ContainsRequest(String name, Data expected) { super(name); this.expected = expected; } @Override protected Operation prepareOperation() { return new ContainsOperation(name, expected); } @Override public int getClassId() { return AtomicReferencePortableHook.CONTAINS; } @Override public void write(PortableWriter writer) throws IOException { super.write(writer); ObjectDataOutput out = writer.getRawDataOutput(); writeNullableData(out, expected); } @Override public void read(PortableReader reader) throws IOException { super.read(reader); ObjectDataInput in = reader.getRawDataInput(); expected = readNullableData(in); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_ContainsRequest.java
1,408
public class MetaDataIndexAliasesService extends AbstractComponent { private final ClusterService clusterService; private final IndicesService indicesService; @Inject public MetaDataIndexAliasesService(Settings settings, ClusterService clusterService, IndicesService indicesService) { super(settings); this.clusterService = clusterService; this.indicesService = indicesService; } public void indicesAliases(final IndicesAliasesClusterStateUpdateRequest request, final ClusterStateUpdateListener listener) { clusterService.submitStateUpdateTask("index-aliases", 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(final ClusterState currentState) { List<String> indicesToClose = Lists.newArrayList(); Map<String, IndexService> indices = Maps.newHashMap(); try { for (AliasAction aliasAction : request.actions()) { if (!Strings.hasText(aliasAction.alias()) || !Strings.hasText(aliasAction.index())) { throw new ElasticsearchIllegalArgumentException("Index name and alias name are required"); } if (!currentState.metaData().hasIndex(aliasAction.index())) { throw new IndexMissingException(new Index(aliasAction.index())); } if (currentState.metaData().hasIndex(aliasAction.alias())) { throw new InvalidAliasNameException(new Index(aliasAction.index()), aliasAction.alias(), "an index exists with the same name as the alias"); } if (aliasAction.indexRouting() != null && aliasAction.indexRouting().indexOf(',') != -1) { throw new ElasticsearchIllegalArgumentException("alias [" + aliasAction.alias() + "] has several routing values associated with it"); } } boolean changed = false; MetaData.Builder builder = MetaData.builder(currentState.metaData()); for (AliasAction aliasAction : request.actions()) { IndexMetaData indexMetaData = builder.get(aliasAction.index()); if (indexMetaData == null) { throw new IndexMissingException(new Index(aliasAction.index())); } // TODO: not copy (putAll) IndexMetaData.Builder indexMetaDataBuilder = IndexMetaData.builder(indexMetaData); if (aliasAction.actionType() == AliasAction.Type.ADD) { String filter = aliasAction.filter(); if (Strings.hasLength(filter)) { // parse the filter, in order to validate it IndexService indexService = indices.get(indexMetaData.index()); if (indexService == null) { indexService = indicesService.indexService(indexMetaData.index()); if (indexService == null) { // temporarily create the index and add mappings so we have can parse the filter try { indexService = indicesService.createIndex(indexMetaData.index(), indexMetaData.settings(), clusterService.localNode().id()); if (indexMetaData.mappings().containsKey(MapperService.DEFAULT_MAPPING)) { indexService.mapperService().merge(MapperService.DEFAULT_MAPPING, indexMetaData.mappings().get(MapperService.DEFAULT_MAPPING).source(), false); } for (ObjectCursor<MappingMetaData> cursor : indexMetaData.mappings().values()) { MappingMetaData mappingMetaData = cursor.value; indexService.mapperService().merge(mappingMetaData.type(), mappingMetaData.source(), false); } } catch (Exception e) { logger.warn("[{}] failed to temporary create in order to apply alias action", e, indexMetaData.index()); continue; } indicesToClose.add(indexMetaData.index()); } indices.put(indexMetaData.index(), indexService); } // now, parse the filter IndexQueryParserService indexQueryParser = indexService.queryParserService(); try { XContentParser parser = XContentFactory.xContent(filter).createParser(filter); try { indexQueryParser.parseInnerFilter(parser); } finally { parser.close(); } } catch (Throwable e) { throw new ElasticsearchIllegalArgumentException("failed to parse filter for [" + aliasAction.alias() + "]", e); } } AliasMetaData newAliasMd = AliasMetaData.newAliasMetaDataBuilder( aliasAction.alias()) .filter(filter) .indexRouting(aliasAction.indexRouting()) .searchRouting(aliasAction.searchRouting()) .build(); // Check if this alias already exists AliasMetaData aliasMd = indexMetaData.aliases().get(aliasAction.alias()); if (aliasMd != null && aliasMd.equals(newAliasMd)) { // It's the same alias - ignore it continue; } indexMetaDataBuilder.putAlias(newAliasMd); } else if (aliasAction.actionType() == AliasAction.Type.REMOVE) { if (!indexMetaData.aliases().containsKey(aliasAction.alias())) { // This alias doesn't exist - ignore continue; } indexMetaDataBuilder.removerAlias(aliasAction.alias()); } changed = true; builder.put(indexMetaDataBuilder); } if (changed) { ClusterState updatedState = ClusterState.builder(currentState).metaData(builder).build(); // even though changes happened, they resulted in 0 actual changes to metadata // i.e. remove and add the same alias to the same index if (!updatedState.metaData().aliases().equals(currentState.metaData().aliases())) { return updatedState; } } return currentState; } finally { for (String index : indicesToClose) { indicesService.removeIndex(index, "created for alias processing"); } } } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { } }); } }
1no label
src_main_java_org_elasticsearch_cluster_metadata_MetaDataIndexAliasesService.java
332
public class TransportNodesInfoAction extends TransportNodesOperationAction<NodesInfoRequest, NodesInfoResponse, TransportNodesInfoAction.NodeInfoRequest, NodeInfo> { private final NodeService nodeService; @Inject public TransportNodesInfoAction(Settings settings, ClusterName clusterName, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, NodeService nodeService) { super(settings, clusterName, threadPool, clusterService, transportService); this.nodeService = nodeService; } @Override protected String executor() { return ThreadPool.Names.MANAGEMENT; } @Override protected String transportAction() { return NodesInfoAction.NAME; } @Override protected NodesInfoResponse newResponse(NodesInfoRequest nodesInfoRequest, AtomicReferenceArray responses) { final List<NodeInfo> nodesInfos = new ArrayList<NodeInfo>(); for (int i = 0; i < responses.length(); i++) { Object resp = responses.get(i); if (resp instanceof NodeInfo) { nodesInfos.add((NodeInfo) resp); } } return new NodesInfoResponse(clusterName, nodesInfos.toArray(new NodeInfo[nodesInfos.size()])); } @Override protected NodesInfoRequest newRequest() { return new NodesInfoRequest(); } @Override protected NodeInfoRequest newNodeRequest() { return new NodeInfoRequest(); } @Override protected NodeInfoRequest newNodeRequest(String nodeId, NodesInfoRequest request) { return new NodeInfoRequest(nodeId, request); } @Override protected NodeInfo newNodeResponse() { return new NodeInfo(); } @Override protected NodeInfo nodeOperation(NodeInfoRequest nodeRequest) throws ElasticsearchException { NodesInfoRequest request = nodeRequest.request; return nodeService.info(request.settings(), request.os(), request.process(), request.jvm(), request.threadPool(), request.network(), request.transport(), request.http(), request.plugin()); } @Override protected boolean accumulateExceptions() { return false; } static class NodeInfoRequest extends NodeOperationRequest { NodesInfoRequest request; NodeInfoRequest() { } NodeInfoRequest(String nodeId, NodesInfoRequest request) { super(request, nodeId); this.request = request; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); request = new NodesInfoRequest(); request.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); request.writeTo(out); } } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_info_TransportNodesInfoAction.java
964
public class LockPortableHook implements PortableHook { public static final int FACTORY_ID = FactoryIdHelper.getFactoryId(FactoryIdHelper.LOCK_PORTABLE_FACTORY, -15); public static final int LOCK = 1; public static final int UNLOCK = 2; public static final int IS_LOCKED = 3; public static final int GET_LOCK_COUNT = 5; public static final int GET_REMAINING_LEASE = 6; public static final int CONDITION_BEFORE_AWAIT = 7; public static final int CONDITION_AWAIT = 8; public static final int CONDITION_SIGNAL = 9; @Override public int getFactoryId() { return FACTORY_ID; } @Override public PortableFactory createFactory() { return new PortableFactory() { public Portable create(int classId) { switch (classId) { case LOCK: return new LockRequest(); case UNLOCK: return new UnlockRequest(); case IS_LOCKED: return new IsLockedRequest(); case GET_LOCK_COUNT: return new GetLockCountRequest(); case GET_REMAINING_LEASE: return new GetRemainingLeaseRequest(); case CONDITION_BEFORE_AWAIT: return new BeforeAwaitRequest(); case CONDITION_AWAIT: return new AwaitRequest(); case CONDITION_SIGNAL: return new SignalRequest(); default: return null; } } }; } @Override public Collection<ClassDefinition> getBuiltinDefinitions() { return null; } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_lock_client_LockPortableHook.java
1,998
assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertEquals(TestEventBasedMapStore.STORE_EVENTS.LOAD, testMapStore.getEvents().poll()); } });
0true
hazelcast_src_test_java_com_hazelcast_map_mapstore_MapStoreTest.java
757
private static final class PagePathItemUnit { private final OBonsaiBucketPointer bucketPointer; private final int itemIndex; private PagePathItemUnit(OBonsaiBucketPointer bucketPointer, int itemIndex) { this.bucketPointer = bucketPointer; this.itemIndex = itemIndex; } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_sbtreebonsai_local_OSBTreeBonsai.java
1,942
public class MapGetEntryViewRequest extends KeyBasedClientRequest implements Portable, RetryableRequest, SecureRequest { private String name; private Data key; public MapGetEntryViewRequest() { } public MapGetEntryViewRequest(String name, Data key) { this.name = name; this.key = key; } public Object getKey() { return key; } protected Operation prepareOperation() { GetEntryViewOperation op = new GetEntryViewOperation(name, key); return op; } public String getServiceName() { return MapService.SERVICE_NAME; } @Override public int getFactoryId() { return MapPortableHook.F_ID; } @Override public int getClassId() { return MapPortableHook.GET_ENTRY_VIEW; } @Override public void write(PortableWriter writer) throws IOException { writer.writeUTF("n", name); final ObjectDataOutput out = writer.getRawDataOutput(); key.writeData(out); } @Override 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_MapGetEntryViewRequest.java
1,822
@Component("blRuleFieldPersistenceProvider") @Scope("prototype") public class RuleFieldPersistenceProvider extends FieldPersistenceProviderAdapter { protected boolean canHandlePersistence(PopulateValueRequest populateValueRequest, Serializable instance) { return populateValueRequest.getMetadata().getFieldType() == SupportedFieldType.RULE_WITH_QUANTITY || populateValueRequest.getMetadata().getFieldType() == SupportedFieldType.RULE_SIMPLE; } protected boolean canHandleExtraction(ExtractValueRequest extractValueRequest, Property property) { return extractValueRequest.getMetadata().getFieldType() == SupportedFieldType.RULE_WITH_QUANTITY || extractValueRequest.getMetadata().getFieldType() == SupportedFieldType.RULE_SIMPLE; } @Resource(name = "blRuleBuilderFieldServiceFactory") protected RuleBuilderFieldServiceFactory ruleBuilderFieldServiceFactory; @Override public FieldProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) throws PersistenceException { if (!canHandlePersistence(populateValueRequest, instance)) { return FieldProviderResponse.NOT_HANDLED; } try { switch (populateValueRequest.getMetadata().getFieldType()) { case RULE_WITH_QUANTITY:{ //currently, this only works with Collection fields Class<?> valueType = getListFieldType(instance, populateValueRequest .getFieldManager(), populateValueRequest.getProperty(), populateValueRequest.getPersistenceManager()); if (valueType == null) { throw new IllegalAccessException("Unable to determine the valueType for the rule field (" + populateValueRequest.getProperty().getName() + ")"); } DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator(); Collection<QuantityBasedRule> rules; try { rules = (Collection<QuantityBasedRule>) populateValueRequest.getFieldManager().getFieldValue (instance, populateValueRequest.getProperty().getName()); } catch (FieldNotAvailableException e) { throw new IllegalArgumentException(e); } //AntiSamy HTML encodes the rule JSON - pass the unHTMLEncoded version populateQuantityBaseRuleCollection(translator, RuleIdentifier.ENTITY_KEY_MAP.get (populateValueRequest.getMetadata().getRuleIdentifier()), populateValueRequest.getMetadata().getRuleIdentifier(), populateValueRequest.getProperty().getUnHtmlEncodedValue(), rules, valueType); break; } case RULE_SIMPLE:{ DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator(); //AntiSamy HTML encodes the rule JSON - pass the unHTMLEncoded version DataWrapper dw = convertJsonToDataWrapper(populateValueRequest.getProperty().getUnHtmlEncodedValue()); if (dw == null || StringUtils.isEmpty(dw.getError())) { String mvel = convertMatchRuleJsonToMvel(translator, RuleIdentifier.ENTITY_KEY_MAP.get(populateValueRequest.getMetadata().getRuleIdentifier()), populateValueRequest.getMetadata().getRuleIdentifier(), dw); Class<?> valueType = null; //is this a regular field? if (!populateValueRequest.getProperty().getName().contains(FieldManager.MAPFIELDSEPARATOR)) { valueType = populateValueRequest.getReturnType(); } else { String valueClassName = populateValueRequest.getMetadata().getMapFieldValueClass(); if (valueClassName != null) { valueType = Class.forName(valueClassName); } if (valueType == null) { valueType = populateValueRequest.getReturnType(); } } if (valueType == null) { throw new IllegalAccessException("Unable to determine the valueType for the rule field (" + populateValueRequest.getProperty().getName() + ")"); } //This is a simple String field (or String map field) if (String.class.isAssignableFrom(valueType)) { populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), mvel); } if (SimpleRule.class.isAssignableFrom(valueType)) { //see if there's an existing rule SimpleRule rule; try { rule = (SimpleRule) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName()); } catch (FieldNotAvailableException e) { throw new IllegalArgumentException(e); } if (mvel == null) { //cause the rule to be deleted populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), null); } else if (rule != null) { rule.setMatchRule(mvel); } else { //create a new instance, persist and set rule = (SimpleRule) valueType.newInstance(); rule.setMatchRule(mvel); populateValueRequest.getPersistenceManager().getDynamicEntityDao().persist(rule); populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), rule); } } } break; } } } catch (Exception e) { throw new PersistenceException(e); } return FieldProviderResponse.HANDLED; } @Override public FieldProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException { if (!canHandleExtraction(extractValueRequest, property)) { return FieldProviderResponse.NOT_HANDLED; } String val = null; ObjectMapper mapper = new ObjectMapper(); MVELToDataWrapperTranslator translator = new MVELToDataWrapperTranslator(); if (extractValueRequest.getMetadata().getFieldType()== SupportedFieldType.RULE_SIMPLE) { if (extractValueRequest.getRequestedValue() != null) { if (extractValueRequest.getRequestedValue() instanceof String) { val = (String) extractValueRequest.getRequestedValue(); property.setValue(val); property.setDisplayValue(extractValueRequest.getDisplayVal()); } if (extractValueRequest.getRequestedValue() instanceof SimpleRule) { SimpleRule simpleRule = (SimpleRule) extractValueRequest.getRequestedValue(); if (simpleRule != null) { val = simpleRule.getMatchRule(); property.setValue(val); property.setDisplayValue(extractValueRequest.getDisplayVal()); } } } Property jsonProperty = convertSimpleRuleToJson(translator, mapper, val, property.getName() + "Json", extractValueRequest.getMetadata().getRuleIdentifier()); extractValueRequest.getProps().add(jsonProperty); } if (extractValueRequest.getMetadata().getFieldType()==SupportedFieldType.RULE_WITH_QUANTITY) { if (extractValueRequest.getRequestedValue() != null) { if (extractValueRequest.getRequestedValue() instanceof Collection) { //these quantity rules are in a list - this is a special, valid case for quantity rules Property jsonProperty = convertQuantityBasedRuleToJson(translator, mapper, (Collection<QuantityBasedRule>) extractValueRequest .getRequestedValue(), extractValueRequest.getMetadata().getName() + "Json", extractValueRequest.getMetadata() .getRuleIdentifier()); extractValueRequest.getProps().add(jsonProperty); } else { //TODO support a single quantity based rule throw new UnsupportedOperationException("RULE_WITH_QUANTITY type is currently only supported" + "on collection fields. A single field with this type is not currently supported."); } } } return FieldProviderResponse.HANDLED; } @Override public FieldProviderResponse filterProperties(AddFilterPropertiesRequest addFilterPropertiesRequest, Map<String, FieldMetadata> properties) { //This may contain rule Json fields - convert and filter out List<Property> propertyList = new ArrayList<Property>(); propertyList.addAll(Arrays.asList(addFilterPropertiesRequest.getEntity().getProperties())); Iterator<Property> itr = propertyList.iterator(); List<Property> additionalProperties = new ArrayList<Property>(); while(itr.hasNext()) { Property prop = itr.next(); if (prop.getName().endsWith("Json")) { for (Map.Entry<String, FieldMetadata> entry : properties.entrySet()) { if (prop.getName().startsWith(entry.getKey())) { BasicFieldMetadata originalFM = (BasicFieldMetadata) entry.getValue(); if (originalFM.getFieldType() == SupportedFieldType.RULE_SIMPLE || originalFM.getFieldType() == SupportedFieldType.RULE_WITH_QUANTITY) { Property originalProp = addFilterPropertiesRequest.getEntity().findProperty(entry.getKey()); if (originalProp == null) { originalProp = new Property(); originalProp.setName(entry.getKey()); additionalProperties.add(originalProp); } originalProp.setValue(prop.getValue()); originalProp.setRawValue(prop.getRawValue()); originalProp.setUnHtmlEncodedValue(prop.getUnHtmlEncodedValue()); itr.remove(); break; } } } } } propertyList.addAll(additionalProperties); addFilterPropertiesRequest.getEntity().setProperties(propertyList.toArray(new Property[propertyList.size()])); return FieldProviderResponse.HANDLED; } protected Property convertQuantityBasedRuleToJson(MVELToDataWrapperTranslator translator, ObjectMapper mapper, Collection<QuantityBasedRule> quantityBasedRules, String jsonProp, String fieldService) { int k=0; Entity[] targetItemCriterias = new Entity[quantityBasedRules.size()]; for (QuantityBasedRule quantityBasedRule : quantityBasedRules) { Property[] properties = new Property[3]; Property mvelProperty = new Property(); mvelProperty.setName("matchRule"); mvelProperty.setValue(quantityBasedRule.getMatchRule()); Property quantityProperty = new Property(); quantityProperty.setName("quantity"); quantityProperty.setValue(quantityBasedRule.getQuantity().toString()); Property idProperty = new Property(); idProperty.setName("id"); idProperty.setValue(String.valueOf(quantityBasedRule.getId())); properties[0] = mvelProperty; properties[1] = quantityProperty; properties[2] = idProperty; Entity criteria = new Entity(); criteria.setProperties(properties); targetItemCriterias[k] = criteria; k++; } String json; try { DataWrapper oiWrapper = translator.createRuleData(targetItemCriterias, "matchRule", "quantity", "id", ruleBuilderFieldServiceFactory.createInstance(fieldService)); json = mapper.writeValueAsString(oiWrapper); } catch (Exception e) { throw new RuntimeException(e); } Property p = new Property(); p.setName(jsonProp); p.setValue(json); return p; } protected Property convertSimpleRuleToJson(MVELToDataWrapperTranslator translator, ObjectMapper mapper, String matchRule, String jsonProp, String fieldService) { Entity[] matchCriteria = new Entity[1]; Property[] properties = new Property[1]; Property mvelProperty = new Property(); mvelProperty.setName("matchRule"); mvelProperty.setValue(matchRule == null?"":matchRule); properties[0] = mvelProperty; Entity criteria = new Entity(); criteria.setProperties(properties); matchCriteria[0] = criteria; String json; try { DataWrapper orderWrapper = translator.createRuleData(matchCriteria, "matchRule", null, null, ruleBuilderFieldServiceFactory.createInstance(fieldService)); json = mapper.writeValueAsString(orderWrapper); } catch (Exception e) { throw new RuntimeException(e); } Property p = new Property(); p.setName(jsonProp); p.setValue(json); return p; } protected void populateQuantityBaseRuleCollection(DataDTOToMVELTranslator translator, String entityKey, String fieldService, String jsonPropertyValue, Collection<QuantityBasedRule> criteriaList, Class<?> memberType) { if (!StringUtils.isEmpty(jsonPropertyValue)) { DataWrapper dw = convertJsonToDataWrapper(jsonPropertyValue); if (dw != null && StringUtils.isEmpty(dw.getError())) { List<QuantityBasedRule> updatedRules = new ArrayList<QuantityBasedRule>(); for (DataDTO dto : dw.getData()) { if (dto.getId() != null) { checkId: { //updates are comprehensive, even data that was not changed //is submitted here //Update Existing Criteria for (QuantityBasedRule quantityBasedRule : criteriaList) { if (dto.getId().equals(quantityBasedRule.getId())){ //don't update if the data has not changed if (!quantityBasedRule.getQuantity().equals(dto.getQuantity())) { quantityBasedRule.setQuantity(dto.getQuantity()); } try { String mvel = translator.createMVEL(entityKey, dto, ruleBuilderFieldServiceFactory.createInstance(fieldService)); if (!quantityBasedRule.getMatchRule().equals(mvel)) { quantityBasedRule.setMatchRule(mvel); } } catch (MVELTranslationException e) { throw new RuntimeException(e); } updatedRules.add(quantityBasedRule); break checkId; } } throw new IllegalArgumentException("Unable to update the rule of type (" + memberType.getName() + ") because an update was requested for id (" + dto.getId() + "), which does not exist."); } } else { //Create a new Criteria QuantityBasedRule quantityBasedRule; try { quantityBasedRule = (QuantityBasedRule) memberType.newInstance(); quantityBasedRule.setQuantity(dto.getQuantity()); quantityBasedRule.setMatchRule(translator.createMVEL(entityKey, dto, ruleBuilderFieldServiceFactory.createInstance(fieldService))); if (StringUtils.isEmpty(quantityBasedRule.getMatchRule()) && !StringUtils.isEmpty(dw.getRawMvel())) { quantityBasedRule.setMatchRule(dw.getRawMvel()); } } catch (Exception e) { throw new RuntimeException(e); } criteriaList.add(quantityBasedRule); updatedRules.add(quantityBasedRule); } } //if an item was not included in the comprehensive submit from the client, we can assume that the //listing was deleted, so we remove it here. Iterator<QuantityBasedRule> itr = criteriaList.iterator(); while(itr.hasNext()) { checkForRemove: { QuantityBasedRule original = itr.next(); for (QuantityBasedRule quantityBasedRule : updatedRules) { if (String.valueOf(original.getId()).equals(String.valueOf(quantityBasedRule.getId()))) { break checkForRemove; } } itr.remove(); } } } } } protected DataWrapper convertJsonToDataWrapper(String json) { ObjectMapper mapper = new ObjectMapper(); DataDTODeserializer dtoDeserializer = new DataDTODeserializer(); SimpleModule module = new SimpleModule("DataDTODeserializerModule", new Version(1, 0, 0, null)); module.addDeserializer(DataDTO.class, dtoDeserializer); mapper.registerModule(module); if (json == null || "[]".equals(json)){ return null; } try { return mapper.readValue(json, DataWrapper.class); } catch (IOException e) { throw new RuntimeException(e); } } protected String convertMatchRuleJsonToMvel(DataDTOToMVELTranslator translator, String entityKey, String fieldService, DataWrapper dw) { String mvel = null; //there can only be one DataDTO for an appliesTo* rule if (dw != null && dw.getData().size() == 1) { DataDTO dto = dw.getData().get(0); try { mvel = translator.createMVEL(entityKey, dto, ruleBuilderFieldServiceFactory.createInstance(fieldService)); } catch (MVELTranslationException e) { throw new RuntimeException(e); } } return mvel; } @Override public int getOrder() { return FieldPersistenceProvider.RULE; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_provider_RuleFieldPersistenceProvider.java
1,671
@Repository("blAdminRoleDao") public class AdminRoleDaoImpl implements AdminRoleDao { @PersistenceContext(unitName = "blPU") protected EntityManager em; @Resource(name="blEntityConfiguration") protected EntityConfiguration entityConfiguration; public void deleteAdminRole(AdminRole role) { if (!em.contains(role)) { role = readAdminRoleById(role.getId()); } em.remove(role); } public AdminRole readAdminRoleById(Long id) { return (AdminRole) em.find(entityConfiguration.lookupEntityClass("org.broadleafcommerce.openadmin.server.security.domain.AdminRole"), id); } public AdminRole saveAdminRole(AdminRole role) { return em.merge(role); } @SuppressWarnings("unchecked") public List<AdminRole> readAllAdminRoles() { Query query = em.createNamedQuery("BC_READ_ALL_ADMIN_ROLES"); List<AdminRole> roles = query.getResultList(); return roles; } }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_security_dao_AdminRoleDaoImpl.java
1,462
@Test public class SQLCreateVertexAndEdgeTest { private OGraphDatabase database; private String url; public SQLCreateVertexAndEdgeTest() { this("memory:testgraph"); } public SQLCreateVertexAndEdgeTest(String iURL) { url = iURL; database = new OGraphDatabase(iURL); } @BeforeMethod public void init() { if (url.startsWith("memory")) database.create(); else database.open("admin", "admin"); } @AfterMethod public void deinit() { database.close(); } @Test public void testCreateEdgeDefaultClass() { database.command(new OCommandSQL("create class V1 extends V")).execute(); database.command(new OCommandSQL("create class E1 extends E")).execute(); database.getMetadata().getSchema().reload(); // VERTEXES ODocument v1 = database.command(new OCommandSQL("create vertex")).execute(); Assert.assertEquals(v1.getClassName(), OGraphDatabase.VERTEX_ALIAS); ODocument v2 = database.command(new OCommandSQL("create vertex V1")).execute(); Assert.assertEquals(v2.getClassName(), "V1"); ODocument v3 = database.command(new OCommandSQL("create vertex set brand = 'fiat'")).execute(); Assert.assertEquals(v3.getClassName(), OGraphDatabase.VERTEX_ALIAS); Assert.assertEquals(v3.field("brand"), "fiat"); ODocument v4 = database.command(new OCommandSQL("create vertex V1 set brand = 'fiat',name = 'wow'")).execute(); Assert.assertEquals(v4.getClassName(), "V1"); Assert.assertEquals(v4.field("brand"), "fiat"); Assert.assertEquals(v4.field("name"), "wow"); ODocument v5 = database.command(new OCommandSQL("create vertex V1 cluster default")).execute(); Assert.assertEquals(v5.getClassName(), "V1"); Assert.assertEquals(v5.getIdentity().getClusterId(), database.getDefaultClusterId()); // EDGES List<Object> edges = database.command(new OCommandSQL("create edge from " + v1.getIdentity() + " to " + v2.getIdentity())) .execute(); Assert.assertFalse(edges.isEmpty()); edges = database.command(new OCommandSQL("create edge E1 from " + v1.getIdentity() + " to " + v3.getIdentity())).execute(); Assert.assertFalse(edges.isEmpty()); edges = database.command( new OCommandSQL("create edge from " + v1.getIdentity() + " to " + v4.getIdentity() + " set weight = 3")).execute(); Assert.assertFalse(edges.isEmpty()); ODocument e3 = ((OIdentifiable) edges.get(0)).getRecord(); Assert.assertEquals(e3.getClassName(), OGraphDatabase.EDGE_ALIAS); Assert.assertEquals(e3.field("out"), v1); Assert.assertEquals(e3.field("in"), v4); Assert.assertEquals(e3.field("weight"), 3); edges = database.command( new OCommandSQL("create edge E1 from " + v2.getIdentity() + " to " + v3.getIdentity() + " set weight = 10")).execute(); Assert.assertFalse(edges.isEmpty()); ODocument e4 = ((OIdentifiable) edges.get(0)).getRecord(); Assert.assertEquals(e4.getClassName(), "E1"); Assert.assertEquals(e4.field("out"), v2); Assert.assertEquals(e4.field("in"), v3); Assert.assertEquals(e4.field("weight"), 10); edges = database .command( new OCommandSQL("create edge e1 cluster default from " + v3.getIdentity() + " to " + v5.getIdentity() + " set weight = 17")).execute(); Assert.assertFalse(edges.isEmpty()); ODocument e5 = ((OIdentifiable) edges.get(0)).getRecord(); Assert.assertEquals(e5.getClassName(), "E1"); Assert.assertEquals(e5.getIdentity().getClusterId(), database.getDefaultClusterId()); } }
0true
graphdb_src_test_java_com_orientechnologies_orient_graph_sql_SQLCreateVertexAndEdgeTest.java
375
public class ODatabaseFlat extends ODatabaseRecordTx { public ODatabaseFlat(String iURL) { super(iURL, ORecordFlat.RECORD_TYPE); } @SuppressWarnings("unchecked") @Override public ORecordIteratorCluster<ORecordFlat> browseCluster(final String iClusterName) { return super.browseCluster(iClusterName, ORecordFlat.class); } @Override public ORecordIteratorCluster<ORecordFlat> browseCluster(String iClusterName, OClusterPosition startClusterPosition, OClusterPosition endClusterPosition, boolean loadTombstones) { return super.browseCluster(iClusterName, ORecordFlat.class, startClusterPosition, endClusterPosition, loadTombstones); } @SuppressWarnings("unchecked") @Override public ORecordFlat newInstance() { return new ORecordFlat(); } @Override public ODatabaseRecord commit() { try { return super.commit(); } finally { getTransaction().close(); } } @Override public ODatabaseRecord rollback() { try { return super.rollback(); } finally { getTransaction().close(); } } }
1no label
core_src_main_java_com_orientechnologies_orient_core_db_record_ODatabaseFlat.java
817
getDatabase().getStorage().callInLock(new Callable<Object>() { @Override public Object call() throws Exception { // READ CURRENT SCHEMA VERSION final Integer schemaVersion = (Integer) document.field("schemaVersion"); if (schemaVersion == null) { OLogManager .instance() .error( this, "Database's schema is empty! Recreating the system classes and allow the opening of the database but double check the integrity of the database"); return null; } else if (schemaVersion.intValue() != CURRENT_VERSION_NUMBER) { // HANDLE SCHEMA UPGRADE throw new OConfigurationException( "Database schema is different. Please export your old database with the previous version of OrientDB and reimport it using the current one."); } // REGISTER ALL THE CLASSES classes.clear(); OClassImpl cls; Collection<ODocument> storedClasses = document.field("classes"); for (ODocument c : storedClasses) { cls = new OClassImpl(me, c); cls.fromStream(); classes.put(cls.getName().toLowerCase(), cls); if (cls.getShortName() != null) classes.put(cls.getShortName().toLowerCase(), cls); } // REBUILD THE INHERITANCE TREE String superClassName; OClass superClass; for (ODocument c : storedClasses) { superClassName = c.field("superClass"); if (superClassName != null) { // HAS A SUPER CLASS cls = (OClassImpl) classes.get(((String) c.field("name")).toLowerCase()); superClass = classes.get(superClassName.toLowerCase()); if (superClass == null) throw new OConfigurationException("Super class '" + superClassName + "' was declared in class '" + cls.getName() + "' but was not found in schema. Remove the dependency or create the class to continue."); cls.setSuperClassInternal(superClass); } } return null; } }, true);
0true
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OSchemaShared.java
448
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) { changed.value = true; } });
0true
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedSetTest.java
1,845
return new Provider<T>() { public T get() { final Errors errors = new Errors(dependency); try { T t = callInContext(new ContextualCallable<T>() { public T call(InternalContext context) throws ErrorsException { context.setDependency(dependency); try { return factory.get(errors, context, dependency); } finally { context.setDependency(null); } } }); errors.throwIfNewErrors(0); return t; } catch (ErrorsException e) { throw new ProvisionException(errors.merge(e.getErrors()).getMessages()); } } @Override public String toString() { return factory.toString(); } };
0true
src_main_java_org_elasticsearch_common_inject_InjectorImpl.java