Unnamed: 0
int64
0
6.45k
func
stringlengths
37
161k
target
class label
2 classes
project
stringlengths
33
167
1,830
@Service("blEntityValidatorService") public class EntityValidatorServiceImpl implements EntityValidatorService, ApplicationContextAware { @Resource(name = "blGlobalEntityPropertyValidators") protected List<GlobalPropertyValidator> globalEntityValidators; protected ApplicationContext applicationContext; @Override public void validate(Entity entity, Serializable instance, Map<String, FieldMetadata> propertiesMetadata, boolean validateUnsubmittedProperties) { List<String> types = getTypeHierarchy(entity); //validate each individual property according to their validation configuration for (Entry<String, FieldMetadata> metadataEntry : propertiesMetadata.entrySet()) { FieldMetadata metadata = metadataEntry.getValue(); //Don't test this field if it was not inherited from our polymorphic type (or supertype) if (types.contains(metadata.getInheritedFromType())) { Property property = entity.getPMap().get(metadataEntry.getKey()); // This property should be set to false only in the case where we are adding a member to a collection // that has type of lookup. In this case, we don't have the properties from the target in our entity, // and we don't need to validate them. if (!validateUnsubmittedProperties && property == null) { continue; } //for radio buttons, it's possible that the entity property was never populated in the first place from the POST //and so it will be null String propertyName = metadataEntry.getKey(); String propertyValue = (property == null) ? null : property.getValue(); if (metadata instanceof BasicFieldMetadata) { //First execute the global field validators if (CollectionUtils.isNotEmpty(globalEntityValidators)) { for (GlobalPropertyValidator validator : globalEntityValidators) { PropertyValidationResult result = validator.validate(entity, instance, propertiesMetadata, (BasicFieldMetadata)metadata, propertyName, propertyValue); if (!result.isValid()) { entity.addValidationError(propertyName, result.getErrorMessage()); } } } //Now execute the validators configured for this particular field Map<String, Map<String, String>> validations = ((BasicFieldMetadata) metadata).getValidationConfigurations(); for (Map.Entry<String, Map<String, String>> validation : validations.entrySet()) { String validationImplementation = validation.getKey(); Map<String, String> configuration = validation.getValue(); PropertyValidator validator = null; //attempt bean resolution to find the validator if (applicationContext.containsBean(validationImplementation)) { validator = applicationContext.getBean(validationImplementation, PropertyValidator.class); } //not a bean, attempt to instantiate the class if (validator == null) { try { validator = (PropertyValidator) Class.forName(validationImplementation).newInstance(); } catch (Exception e) { //do nothing } } if (validator == null) { throw new PersistenceException("Could not find validator: " + validationImplementation + " for property: " + propertyName); } PropertyValidationResult result = validator.validate(entity, instance, propertiesMetadata, configuration, (BasicFieldMetadata)metadata, propertyName, propertyValue); if (!result.isValid()) { entity.addValidationError(propertyName, result.getErrorMessage()); } } } } } } protected List<String> getTypeHierarchy(Entity entity) { List<String> types = new ArrayList<String>(); Class<?> myType; try { myType = Class.forName(entity.getType()[0]); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } types.add(myType.getName()); boolean eof = false; while (!eof) { myType = myType.getSuperclass(); if (myType != null && !myType.getName().equals(Object.class.getName())) { types.add(myType.getName()); } else { eof = true; } } return types; } @Override public List<GlobalPropertyValidator> getGlobalEntityValidators() { return globalEntityValidators; } @Override public void setGlobalEntityValidators(List<GlobalPropertyValidator> globalEntityValidators) { this.globalEntityValidators = globalEntityValidators; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_validation_EntityValidatorServiceImpl.java
736
public class CollectionRemoveListenerRequest extends BaseClientRemoveListenerRequest { private String serviceName; public CollectionRemoveListenerRequest() { } public CollectionRemoveListenerRequest(String name, String registrationId, String serviceName) { super(name, registrationId); this.serviceName = serviceName; } public Object call() throws Exception { final ClientEngine clientEngine = getClientEngine(); final EventService eventService = clientEngine.getEventService(); return eventService.deregisterListener(serviceName, name, registrationId); } public String getServiceName() { return serviceName; } public int getFactoryId() { return CollectionPortableHook.F_ID; } public int getClassId() { return CollectionPortableHook.COLLECTION_REMOVE_LISTENER; } public void write(PortableWriter writer) throws IOException { super.write(writer); writer.writeUTF("s", serviceName); } public void read(PortableReader reader) throws IOException { super.read(reader); serviceName = reader.readUTF("s"); } @Override public Permission getRequiredPermission() { return ActionConstants.getPermission(name, serviceName, ActionConstants.ACTION_LISTEN); } }
0true
hazelcast_src_main_java_com_hazelcast_collection_client_CollectionRemoveListenerRequest.java
803
multiGetAction.execute(multiGetRequest, new ActionListener<MultiGetResponse>() { @Override public void onResponse(MultiGetResponse multiGetItemResponses) { for (int i = 0; i < multiGetItemResponses.getResponses().length; i++) { MultiGetItemResponse itemResponse = multiGetItemResponses.getResponses()[i]; int slot = getRequestSlots.get(i); if (!itemResponse.isFailed()) { GetResponse getResponse = itemResponse.getResponse(); if (getResponse.isExists()) { PercolateRequest originalRequest = (PercolateRequest) percolateRequests.get(slot); percolateRequests.set(slot, new PercolateRequest(originalRequest, getResponse.getSourceAsBytesRef())); } else { logger.trace("mpercolate existing doc, item[{}] doesn't exist", slot); percolateRequests.set(slot, new DocumentMissingException(null, getResponse.getType(), getResponse.getId())); } } else { logger.trace("mpercolate existing doc, item[{}] failure {}", slot, itemResponse.getFailure()); percolateRequests.set(slot, itemResponse.getFailure()); } } new ASyncAction(percolateRequests, listener, clusterState).run(); } @Override public void onFailure(Throwable e) { listener.onFailure(e); } });
0true
src_main_java_org_elasticsearch_action_percolate_TransportMultiPercolateAction.java
295
new Thread() { public void run() { if (!l.tryLock()) { latch.countDown(); } try { if (l.tryLock(5, TimeUnit.SECONDS)) { latch.countDown(); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_lock_ClientLockTest.java
3,608
final class TransactionContextImpl implements TransactionContext { private final NodeEngineImpl nodeEngine; private final TransactionImpl transaction; private final TransactionManagerServiceImpl transactionManager; private final Map<TransactionalObjectKey, TransactionalObject> txnObjectMap = new HashMap<TransactionalObjectKey, TransactionalObject>(2); private XAResourceImpl xaResource; TransactionContextImpl(TransactionManagerServiceImpl transactionManagerService, NodeEngineImpl nodeEngine, TransactionOptions options, String ownerUuid) { this.transactionManager = transactionManagerService; this.nodeEngine = nodeEngine; this.transaction = new TransactionImpl(transactionManagerService, nodeEngine, options, ownerUuid); } @Override public XAResourceImpl getXaResource() { if (xaResource == null) { xaResource = new XAResourceImpl(transactionManager, this, nodeEngine); } return xaResource; } @Override public boolean isXAManaged() { return transaction.getXid() != null; } @Override public String getTxnId() { return transaction.getTxnId(); } @Override public void beginTransaction() { transaction.begin(); } @Override public void commitTransaction() throws TransactionException { if (transaction.getTransactionType().equals(TransactionOptions.TransactionType.TWO_PHASE)) { transaction.prepare(); } transaction.commit(); } @Override public void rollbackTransaction() { transaction.rollback(); } @SuppressWarnings("unchecked") @Override public <K, V> TransactionalMap<K, V> getMap(String name) { return (TransactionalMap<K, V>) getTransactionalObject(MapService.SERVICE_NAME, name); } @SuppressWarnings("unchecked") @Override public <E> TransactionalQueue<E> getQueue(String name) { return (TransactionalQueue<E>) getTransactionalObject(QueueService.SERVICE_NAME, name); } @SuppressWarnings("unchecked") @Override public <K, V> TransactionalMultiMap<K, V> getMultiMap(String name) { return (TransactionalMultiMap<K, V>) getTransactionalObject(MultiMapService.SERVICE_NAME, name); } @SuppressWarnings("unchecked") @Override public <E> TransactionalList<E> getList(String name) { return (TransactionalList<E>) getTransactionalObject(ListService.SERVICE_NAME, name); } @SuppressWarnings("unchecked") @Override public <E> TransactionalSet<E> getSet(String name) { return (TransactionalSet<E>) getTransactionalObject(SetService.SERVICE_NAME, name); } @SuppressWarnings("unchecked") @Override public TransactionalObject getTransactionalObject(String serviceName, String name) { if (transaction.getState() != Transaction.State.ACTIVE) { throw new TransactionNotActiveException("No transaction is found while accessing " + "transactional object -> " + serviceName + "[" + name + "]!"); } TransactionalObjectKey key = new TransactionalObjectKey(serviceName, name); TransactionalObject obj = txnObjectMap.get(key); if (obj != null) { return obj; } final Object service = nodeEngine.getService(serviceName); if (service instanceof TransactionalService) { nodeEngine.getProxyService().initializeDistributedObject(serviceName, name); obj = ((TransactionalService) service).createTransactionalObject(name, transaction); txnObjectMap.put(key, obj); } else { if (service == null) { if (!nodeEngine.isActive()) { throw new HazelcastInstanceNotActiveException(); } throw new IllegalArgumentException("Unknown Service[" + serviceName + "]!"); } throw new IllegalArgumentException("Service[" + serviceName + "] is not transactional!"); } return obj; } Transaction getTransaction() { return transaction; } private static class TransactionalObjectKey { private final String serviceName; private final String name; TransactionalObjectKey(String serviceName, String name) { this.serviceName = serviceName; this.name = name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TransactionalObjectKey)) { return false; } TransactionalObjectKey that = (TransactionalObjectKey) o; if (!name.equals(that.name)) { return false; } if (!serviceName.equals(that.serviceName)) { return false; } return true; } @Override public int hashCode() { int result = serviceName.hashCode(); result = 31 * result + name.hashCode(); return result; } } }
1no label
hazelcast_src_main_java_com_hazelcast_transaction_impl_TransactionContextImpl.java
572
public class OpenIndexResponse extends AcknowledgedResponse { OpenIndexResponse() { } OpenIndexResponse(boolean acknowledged) { super(acknowledged); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); readAcknowledged(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); writeAcknowledged(out); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_open_OpenIndexResponse.java
512
public class OAllCacheEntriesAreUsedException extends ODatabaseException { public OAllCacheEntriesAreUsedException(String string) { super(string); } public OAllCacheEntriesAreUsedException(String message, Throwable cause) { super(message, cause); } }
0true
core_src_main_java_com_orientechnologies_orient_core_exception_OAllCacheEntriesAreUsedException.java
1,180
public class SimpleUuidBenchmark { private static long NUMBER_OF_ITERATIONS = 10000; private static int NUMBER_OF_THREADS = 100; public static void main(String[] args) throws Exception { StopWatch stopWatch = new StopWatch().start(); System.out.println("Running " + NUMBER_OF_ITERATIONS); for (long i = 0; i < NUMBER_OF_ITERATIONS; i++) { UUID.randomUUID().toString(); } System.out.println("Generated in " + stopWatch.stop().totalTime() + " TP Millis " + (NUMBER_OF_ITERATIONS / stopWatch.totalTime().millisFrac())); System.out.println("Generating using " + NUMBER_OF_THREADS + " threads with " + NUMBER_OF_ITERATIONS + " iterations"); final CountDownLatch latch = new CountDownLatch(NUMBER_OF_THREADS); Thread[] threads = new Thread[NUMBER_OF_THREADS]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread(new Runnable() { @Override public void run() { for (long i = 0; i < NUMBER_OF_ITERATIONS; i++) { UUID.randomUUID().toString(); } latch.countDown(); } }); } stopWatch = new StopWatch().start(); for (Thread thread : threads) { thread.start(); } latch.await(); stopWatch.stop(); System.out.println("Generate in " + stopWatch.totalTime() + " TP Millis " + ((NUMBER_OF_ITERATIONS * NUMBER_OF_THREADS) / stopWatch.totalTime().millisFrac())); } }
0true
src_test_java_org_elasticsearch_benchmark_uuid_SimpleUuidBenchmark.java
329
public class AttributePreserveInsert extends BaseHandler { public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) { if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) { return null; } Node node1 = nodeList1.get(0); Node node2 = nodeList2.get(0); NamedNodeMap attributes2 = node2.getAttributes(); Comparator<Object> nameCompare = new Comparator<Object>() { public int compare(Object arg0, Object arg1) { return ((Node) arg0).getNodeName().compareTo(((Node) arg1).getNodeName()); } }; Node[] tempNodes = {}; tempNodes = exhaustedNodes.toArray(tempNodes); Arrays.sort(tempNodes, nameCompare); int length = attributes2.getLength(); for (int j = 0; j < length; j++) { Node temp = attributes2.item(j); int pos = Arrays.binarySearch(tempNodes, temp, nameCompare); if (pos < 0) { ((Element) node1).setAttributeNode((Attr) node1.getOwnerDocument().importNode(temp.cloneNode(true), true)); } } return null; } }
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_handlers_AttributePreserveInsert.java
1,785
@Service("blCriteriaTranslator") public class CriteriaTranslatorImpl implements CriteriaTranslator { @Override public TypedQuery<Serializable> translateCountQuery(DynamicEntityDao dynamicEntityDao, String ceilingEntity, List<FilterMapping> filterMappings) { return constructQuery(dynamicEntityDao, ceilingEntity, filterMappings, true, null, null); } @Override public TypedQuery<Serializable> translateQuery(DynamicEntityDao dynamicEntityDao, String ceilingEntity, List<FilterMapping> filterMappings, Integer firstResult, Integer maxResults) { return constructQuery(dynamicEntityDao, ceilingEntity, filterMappings, false, firstResult, maxResults); } /** * Determines the appropriate entity in this current class tree to use as the ceiling entity for the query. Because * we filter with AND instead of OR, we throw an exception if an attempt to utilize properties from mutually exclusive * class trees is made as it would be impossible for such a query to return results. * * @param dynamicEntityDao * @param ceilingMarker * @param filterMappings * @return the root class * @throws NoPossibleResultsException */ @SuppressWarnings("unchecked") protected Class<Serializable> determineRoot(DynamicEntityDao dynamicEntityDao, Class<Serializable> ceilingMarker, List<FilterMapping> filterMappings) throws NoPossibleResultsException { Class<?>[] polyEntities = dynamicEntityDao.getAllPolymorphicEntitiesFromCeiling(ceilingMarker); ClassTree root = dynamicEntityDao.getClassTree(polyEntities); List<ClassTree> parents = new ArrayList<ClassTree>(); for (FilterMapping mapping : filterMappings) { if (mapping.getInheritedFromClass() != null) { root = determineRootInternal(root, parents, mapping.getInheritedFromClass()); if (root == null) { throw new NoPossibleResultsException("AND filter on different class hierarchies produces no results"); } } } for (Class<?> clazz : polyEntities) { if (clazz.getName().equals(root.getFullyQualifiedClassname())) { return (Class<Serializable>) clazz; } } throw new IllegalStateException("Class didn't match - this should not occur"); } /** * Because of the restriction described in {@link #determineRoot(DynamicEntityDao, Class, List)}, we must check * that a class lies inside of the same tree as the current known root. Consider the following situation: * * Class C extends Class B, which extends Class A. * Class E extends Class D, which also extends Class A. * * We can allow filtering on properties that are either all in C/B/A or all in E/D/A. Filtering on properties across * C/B and E/D will always produce no results given an AND style of joining the filtered properties. * * @param root * @param parents * @param classToCheck * @return the (potentially new) root or null if invalid */ protected ClassTree determineRootInternal(ClassTree root, List<ClassTree> parents, Class<?> classToCheck) { // If the class to check is the current root or a parent of this root, we will continue to use the same root if (root.getFullyQualifiedClassname().equals(classToCheck.getName())) { return root; } for (ClassTree parent : parents) { if (parent.getFullyQualifiedClassname().equals(classToCheck.getName())) { return root; } } try { Class<?> rootClass = Class.forName(root.getFullyQualifiedClassname()); if (classToCheck.isAssignableFrom(rootClass)) { return root; } } catch (ClassNotFoundException e) { // Do nothing - we'll continue searching } parents.add(root); for (ClassTree child : root.getChildren()) { ClassTree result = child.find(classToCheck.getName()); if (result != null) { return result; } } return null; } @SuppressWarnings("unchecked") protected TypedQuery<Serializable> constructQuery(DynamicEntityDao dynamicEntityDao, String ceilingEntity, List<FilterMapping> filterMappings, boolean isCount, Integer firstResult, Integer maxResults) { CriteriaBuilder criteriaBuilder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder(); Class<Serializable> ceilingMarker; try { ceilingMarker = (Class<Serializable>) Class.forName(ceilingEntity); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } Class<Serializable> ceilingClass = determineRoot(dynamicEntityDao, ceilingMarker, filterMappings); CriteriaQuery<Serializable> criteria = criteriaBuilder.createQuery(ceilingMarker); Root<Serializable> original = criteria.from(ceilingClass); if (isCount) { criteria.select(criteriaBuilder.count(original)); } else { criteria.select(original); } List<Predicate> restrictions = new ArrayList<Predicate>(); List<Order> sorts = new ArrayList<Order>(); addRestrictions(ceilingEntity, filterMappings, criteriaBuilder, original, restrictions, sorts, criteria); criteria.where(restrictions.toArray(new Predicate[restrictions.size()])); if (!isCount) { criteria.orderBy(sorts.toArray(new Order[sorts.size()])); } TypedQuery<Serializable> response = dynamicEntityDao.getStandardEntityManager().createQuery(criteria); if (!isCount) { addPaging(response, firstResult, maxResults); } return response; } protected void addPaging(Query response, Integer firstResult, Integer maxResults) { if (firstResult != null) { response.setFirstResult(firstResult); } if (maxResults != null) { response.setMaxResults(maxResults); } } /** * This method is deprecated in favor of {@link #addRestrictions(String, List, CriteriaBuilder, Root, List, List, CriteriaQuery)} * It will be removed in Broadleaf version 3.1.0. * * @param ceilingEntity * @param filterMappings * @param criteriaBuilder * @param original * @param restrictions * @param sorts */ @Deprecated protected void addRestrictions(String ceilingEntity, List<FilterMapping> filterMappings, CriteriaBuilder criteriaBuilder, Root original, List<Predicate> restrictions, List<Order> sorts) { addRestrictions(ceilingEntity, filterMappings, criteriaBuilder, original, restrictions, sorts, null); } protected void addRestrictions(String ceilingEntity, List<FilterMapping> filterMappings, CriteriaBuilder criteriaBuilder, Root original, List<Predicate> restrictions, List<Order> sorts, CriteriaQuery criteria) { for (FilterMapping filterMapping : filterMappings) { Path explicitPath = null; if (filterMapping.getFieldPath() != null) { explicitPath = filterMapping.getRestriction().getFieldPathBuilder().getPath(original, filterMapping.getFieldPath(), criteriaBuilder); } if (filterMapping.getRestriction() != null) { List directValues = null; boolean shouldConvert = true; if (CollectionUtils.isNotEmpty(filterMapping.getFilterValues())) { directValues = filterMapping.getFilterValues(); } else if (CollectionUtils.isNotEmpty(filterMapping.getDirectFilterValues()) || (filterMapping.getDirectFilterValues() != null && filterMapping.getDirectFilterValues() instanceof EmptyFilterValues)) { directValues = filterMapping.getDirectFilterValues(); shouldConvert = false; } if (directValues != null) { Predicate predicate = filterMapping.getRestriction().buildPolymorphicRestriction(criteriaBuilder, original, ceilingEntity, filterMapping.getFullPropertyName(), explicitPath, directValues, shouldConvert, criteria, restrictions); restrictions.add(predicate); } } if (filterMapping.getSortDirection() != null) { Path sortPath = explicitPath; if (sortPath == null && !StringUtils.isEmpty(filterMapping.getFullPropertyName())) { FieldPathBuilder fieldPathBuilder = filterMapping.getRestriction().getFieldPathBuilder(); fieldPathBuilder.setCriteria(criteria); fieldPathBuilder.setRestrictions(restrictions); sortPath = filterMapping.getRestriction().getFieldPathBuilder().getPath(original, filterMapping.getFullPropertyName(), criteriaBuilder); } if (sortPath != null) { addSorting(criteriaBuilder, sorts, filterMapping, sortPath); } } } } protected void addSorting(CriteriaBuilder criteriaBuilder, List<Order> sorts, FilterMapping filterMapping, Path path) { if (SortDirection.ASCENDING == filterMapping.getSortDirection()) { sorts.add(criteriaBuilder.asc(path)); } else { sorts.add(criteriaBuilder.desc(path)); } } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_criteria_CriteriaTranslatorImpl.java
450
public class ClusterStatsResponse extends NodesOperationResponse<ClusterStatsNodeResponse> implements ToXContent { ClusterStatsNodes nodesStats; ClusterStatsIndices indicesStats; String clusterUUID; ClusterHealthStatus status; long timestamp; ClusterStatsResponse() { } public ClusterStatsResponse(long timestamp, ClusterName clusterName, String clusterUUID, ClusterStatsNodeResponse[] nodes) { super(clusterName, null); this.timestamp = timestamp; this.clusterUUID = clusterUUID; nodesStats = new ClusterStatsNodes(nodes); indicesStats = new ClusterStatsIndices(nodes); for (ClusterStatsNodeResponse response : nodes) { // only the master node populates the status if (response.clusterStatus() != null) { status = response.clusterStatus(); break; } } } public long getTimestamp() { return this.timestamp; } public ClusterHealthStatus getStatus() { return this.status; } public ClusterStatsNodes getNodesStats() { return nodesStats; } public ClusterStatsIndices getIndicesStats() { return indicesStats; } @Override public ClusterStatsNodeResponse[] getNodes() { throw new UnsupportedOperationException(); } @Override public Map<String, ClusterStatsNodeResponse> getNodesMap() { throw new UnsupportedOperationException(); } @Override public ClusterStatsNodeResponse getAt(int position) { throw new UnsupportedOperationException(); } @Override public Iterator<ClusterStatsNodeResponse> iterator() { throw new UnsupportedOperationException(); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); timestamp = in.readVLong(); status = null; if (in.readBoolean()) { // it may be that the master switched on us while doing the operation. In this case the status may be null. status = ClusterHealthStatus.fromValue(in.readByte()); } clusterUUID = in.readString(); nodesStats = ClusterStatsNodes.readNodeStats(in); indicesStats = ClusterStatsIndices.readIndicesStats(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVLong(timestamp); if (status == null) { out.writeBoolean(false); } else { out.writeBoolean(true); out.writeByte(status.value()); } out.writeString(clusterUUID); nodesStats.writeTo(out); indicesStats.writeTo(out); } static final class Fields { static final XContentBuilderString NODES = new XContentBuilderString("nodes"); static final XContentBuilderString INDICES = new XContentBuilderString("indices"); static final XContentBuilderString UUID = new XContentBuilderString("uuid"); static final XContentBuilderString CLUSTER_NAME = new XContentBuilderString("cluster_name"); static final XContentBuilderString STATUS = new XContentBuilderString("status"); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.field("timestamp", getTimestamp()); builder.field(Fields.CLUSTER_NAME, getClusterName().value()); if (params.paramAsBoolean("output_uuid", false)) { builder.field(Fields.UUID, clusterUUID); } if (status != null) { builder.field(Fields.STATUS, status.name().toLowerCase(Locale.ROOT)); } builder.startObject(Fields.INDICES); indicesStats.toXContent(builder, params); builder.endObject(); builder.startObject(Fields.NODES); nodesStats.toXContent(builder, params); builder.endObject(); return builder; } @Override public String toString() { try { XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint(); builder.startObject(); toXContent(builder, EMPTY_PARAMS); builder.endObject(); return builder.string(); } catch (IOException e) { return "{ \"error\" : \"" + e.getMessage() + "\"}"; } } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsResponse.java
1,590
public class SafeReducerOutputs { private final MultipleOutputs outputs; private final Reducer.Context context; private final boolean testing; public SafeReducerOutputs(final Reducer.Context context) { this.context = context; this.outputs = new MultipleOutputs(this.context); this.testing = this.context.getConfiguration().getBoolean(HadoopCompiler.TESTING, false); } public void write(final String type, final Writable key, final Writable value) throws IOException, InterruptedException { if (this.testing) { if (type.equals(Tokens.SIDEEFFECT)) this.context.write(key, value); } else this.outputs.write(type, key, value); } public void close() throws IOException, InterruptedException { this.outputs.close(); } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_util_SafeReducerOutputs.java
82
public static class Name { public static final String File_Details = "StaticAssetImpl_FileDetails_Tab"; public static final String Advanced = "StaticAssetImpl_Advanced_Tab"; }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_domain_StaticAssetImpl.java
1,272
nodesService.execute(new TransportClientNodesService.NodeListenerCallback<Response>() { @Override public void doWithNode(DiscoveryNode node, ActionListener<Response> listener) throws ElasticsearchException { proxy.execute(node, request, listener); } }, listener);
0true
src_main_java_org_elasticsearch_client_transport_support_InternalTransportClusterAdminClient.java
947
public abstract class MasterNodeReadOperationRequestBuilder<Request extends MasterNodeReadOperationRequest<Request>, Response extends ActionResponse, RequestBuilder extends MasterNodeReadOperationRequestBuilder<Request, Response, RequestBuilder>> extends MasterNodeOperationRequestBuilder<Request, Response, RequestBuilder> { protected MasterNodeReadOperationRequestBuilder(InternalGenericClient client, Request request) { super(client, request); } /** * Specifies if the request should be executed on local node rather than on master */ @SuppressWarnings("unchecked") public final RequestBuilder setLocal(boolean local) { request.local(local); return (RequestBuilder) this; } }
0true
src_main_java_org_elasticsearch_action_support_master_MasterNodeReadOperationRequestBuilder.java
163
public abstract class CountedCompleter<T> extends ForkJoinTask<T> { private static final long serialVersionUID = 5232453752276485070L; /** This task's completer, or null if none */ final CountedCompleter<?> completer; /** The number of pending tasks until completion */ volatile int pending; /** * Creates a new CountedCompleter with the given completer * and initial pending count. * * @param completer this task's completer, or {@code null} if none * @param initialPendingCount the initial pending count */ protected CountedCompleter(CountedCompleter<?> completer, int initialPendingCount) { this.completer = completer; this.pending = initialPendingCount; } /** * Creates a new CountedCompleter with the given completer * and an initial pending count of zero. * * @param completer this task's completer, or {@code null} if none */ protected CountedCompleter(CountedCompleter<?> completer) { this.completer = completer; } /** * Creates a new CountedCompleter with no completer * and an initial pending count of zero. */ protected CountedCompleter() { this.completer = null; } /** * The main computation performed by this task. */ public abstract void compute(); /** * Performs an action when method {@link #tryComplete} is invoked * and the pending count is zero, or when the unconditional * method {@link #complete} is invoked. By default, this method * does nothing. You can distinguish cases by checking the * identity of the given caller argument. If not equal to {@code * this}, then it is typically a subtask that may contain results * (and/or links to other results) to combine. * * @param caller the task invoking this method (which may * be this task itself) */ public void onCompletion(CountedCompleter<?> caller) { } /** * Performs an action when method {@link #completeExceptionally} * is invoked or method {@link #compute} throws an exception, and * this task has not otherwise already completed normally. On * entry to this method, this task {@link * ForkJoinTask#isCompletedAbnormally}. The return value of this * method controls further propagation: If {@code true} and this * task has a completer, then this completer is also completed * exceptionally. The default implementation of this method does * nothing except return {@code true}. * * @param ex the exception * @param caller the task invoking this method (which may * be this task itself) * @return true if this exception should be propagated to this * task's completer, if one exists */ public boolean onExceptionalCompletion(Throwable ex, CountedCompleter<?> caller) { return true; } /** * Returns the completer established in this task's constructor, * or {@code null} if none. * * @return the completer */ public final CountedCompleter<?> getCompleter() { return completer; } /** * Returns the current pending count. * * @return the current pending count */ public final int getPendingCount() { return pending; } /** * Sets the pending count to the given value. * * @param count the count */ public final void setPendingCount(int count) { pending = count; } /** * Adds (atomically) the given value to the pending count. * * @param delta the value to add */ public final void addToPendingCount(int delta) { int c; // note: can replace with intrinsic in jdk8 do {} while (!U.compareAndSwapInt(this, PENDING, c = pending, c+delta)); } /** * Sets (atomically) the pending count to the given count only if * it currently holds the given expected value. * * @param expected the expected value * @param count the new value * @return true if successful */ public final boolean compareAndSetPendingCount(int expected, int count) { return U.compareAndSwapInt(this, PENDING, expected, count); } /** * If the pending count is nonzero, (atomically) decrements it. * * @return the initial (undecremented) pending count holding on entry * to this method */ public final int decrementPendingCountUnlessZero() { int c; do {} while ((c = pending) != 0 && !U.compareAndSwapInt(this, PENDING, c, c - 1)); return c; } /** * Returns the root of the current computation; i.e., this * task if it has no completer, else its completer's root. * * @return the root of the current computation */ public final CountedCompleter<?> getRoot() { CountedCompleter<?> a = this, p; while ((p = a.completer) != null) a = p; return a; } /** * If the pending count is nonzero, decrements the count; * otherwise invokes {@link #onCompletion} and then similarly * tries to complete this task's completer, if one exists, * else marks this task as complete. */ public final void tryComplete() { CountedCompleter<?> a = this, s = a; for (int c;;) { if ((c = a.pending) == 0) { a.onCompletion(s); if ((a = (s = a).completer) == null) { s.quietlyComplete(); return; } } else if (U.compareAndSwapInt(a, PENDING, c, c - 1)) return; } } /** * Equivalent to {@link #tryComplete} but does not invoke {@link * #onCompletion} along the completion path: If the pending count * is nonzero, decrements the count; otherwise, similarly tries to * complete this task's completer, if one exists, else marks this * task as complete. This method may be useful in cases where * {@code onCompletion} should not, or need not, be invoked for * each completer in a computation. */ public final void propagateCompletion() { CountedCompleter<?> a = this, s = a; for (int c;;) { if ((c = a.pending) == 0) { if ((a = (s = a).completer) == null) { s.quietlyComplete(); return; } } else if (U.compareAndSwapInt(a, PENDING, c, c - 1)) return; } } /** * Regardless of pending count, invokes {@link #onCompletion}, * marks this task as complete and further triggers {@link * #tryComplete} on this task's completer, if one exists. The * given rawResult is used as an argument to {@link #setRawResult} * before invoking {@link #onCompletion} or marking this task as * complete; its value is meaningful only for classes overriding * {@code setRawResult}. * * <p>This method may be useful when forcing completion as soon as * any one (versus all) of several subtask results are obtained. * However, in the common (and recommended) case in which {@code * setRawResult} is not overridden, this effect can be obtained * more simply using {@code quietlyCompleteRoot();}. * * @param rawResult the raw result */ public void complete(T rawResult) { CountedCompleter<?> p; setRawResult(rawResult); onCompletion(this); quietlyComplete(); if ((p = completer) != null) p.tryComplete(); } /** * If this task's pending count is zero, returns this task; * otherwise decrements its pending count and returns {@code * null}. This method is designed to be used with {@link * #nextComplete} in completion traversal loops. * * @return this task, if pending count was zero, else {@code null} */ public final CountedCompleter<?> firstComplete() { for (int c;;) { if ((c = pending) == 0) return this; else if (U.compareAndSwapInt(this, PENDING, c, c - 1)) return null; } } /** * If this task does not have a completer, invokes {@link * ForkJoinTask#quietlyComplete} and returns {@code null}. Or, if * this task's pending count is non-zero, decrements its pending * count and returns {@code null}. Otherwise, returns the * completer. This method can be used as part of a completion * traversal loop for homogeneous task hierarchies: * * <pre> {@code * for (CountedCompleter<?> c = firstComplete(); * c != null; * c = c.nextComplete()) { * // ... process c ... * }}</pre> * * @return the completer, or {@code null} if none */ public final CountedCompleter<?> nextComplete() { CountedCompleter<?> p; if ((p = completer) != null) return p.firstComplete(); else { quietlyComplete(); return null; } } /** * Equivalent to {@code getRoot().quietlyComplete()}. */ public final void quietlyCompleteRoot() { for (CountedCompleter<?> a = this, p;;) { if ((p = a.completer) == null) { a.quietlyComplete(); return; } a = p; } } /** * Supports ForkJoinTask exception propagation. */ void internalPropagateException(Throwable ex) { CountedCompleter<?> a = this, s = a; while (a.onExceptionalCompletion(ex, s) && (a = (s = a).completer) != null && a.status >= 0) a.recordExceptionalCompletion(ex); } /** * Implements execution conventions for CountedCompleters. */ protected final boolean exec() { compute(); return false; } /** * Returns the result of the computation. By default, * returns {@code null}, which is appropriate for {@code Void} * actions, but in other cases should be overridden, almost * always to return a field or function of a field that * holds the result upon completion. * * @return the result of the computation */ public T getRawResult() { return null; } /** * A method that result-bearing CountedCompleters may optionally * use to help maintain result data. By default, does nothing. * Overrides are not recommended. However, if this method is * overridden to update existing objects or fields, then it must * in general be defined to be thread-safe. */ protected void setRawResult(T t) { } // Unsafe mechanics private static final sun.misc.Unsafe U; private static final long PENDING; static { try { U = getUnsafe(); PENDING = U.objectFieldOffset (CountedCompleter.class.getDeclaredField("pending")); } catch (Exception e) { throw new Error(e); } } /** * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. * Replace with a simple call to Unsafe.getUnsafe when integrating * into a jdk. * * @return a sun.misc.Unsafe */ private static sun.misc.Unsafe getUnsafe() { try { return sun.misc.Unsafe.getUnsafe(); } catch (SecurityException tryReflectionInstead) {} try { return java.security.AccessController.doPrivileged (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { public sun.misc.Unsafe run() throws Exception { Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; for (java.lang.reflect.Field f : k.getDeclaredFields()) { f.setAccessible(true); Object x = f.get(null); if (k.isInstance(x)) return k.cast(x); } throw new NoSuchFieldError("the Unsafe"); }}); } catch (java.security.PrivilegedActionException e) { throw new RuntimeException("Could not initialize intrinsics", e.getCause()); } } }
0true
src_main_java_jsr166y_CountedCompleter.java
3,729
public class ObjectMapper implements Mapper, AllFieldMapper.IncludeInAll { public static final String CONTENT_TYPE = "object"; public static final String NESTED_CONTENT_TYPE = "nested"; public static class Defaults { public static final boolean ENABLED = true; public static final Nested NESTED = Nested.NO; public static final Dynamic DYNAMIC = null; // not set, inherited from root public static final ContentPath.Type PATH_TYPE = ContentPath.Type.FULL; } public static enum Dynamic { TRUE, FALSE, STRICT } public static class Nested { public static final Nested NO = new Nested(false, false, false); public static Nested newNested(boolean includeInParent, boolean includeInRoot) { return new Nested(true, includeInParent, includeInRoot); } private final boolean nested; private final boolean includeInParent; private final boolean includeInRoot; private Nested(boolean nested, boolean includeInParent, boolean includeInRoot) { this.nested = nested; this.includeInParent = includeInParent; this.includeInRoot = includeInRoot; } public boolean isNested() { return nested; } public boolean isIncludeInParent() { return includeInParent; } public boolean isIncludeInRoot() { return includeInRoot; } } public static class Builder<T extends Builder, Y extends ObjectMapper> extends Mapper.Builder<T, Y> { protected boolean enabled = Defaults.ENABLED; protected Nested nested = Defaults.NESTED; protected Dynamic dynamic = Defaults.DYNAMIC; protected ContentPath.Type pathType = Defaults.PATH_TYPE; protected Boolean includeInAll; protected final List<Mapper.Builder> mappersBuilders = newArrayList(); public Builder(String name) { super(name); this.builder = (T) this; } public T enabled(boolean enabled) { this.enabled = enabled; return builder; } public T dynamic(Dynamic dynamic) { this.dynamic = dynamic; return builder; } public T nested(Nested nested) { this.nested = nested; return builder; } public T pathType(ContentPath.Type pathType) { this.pathType = pathType; return builder; } public T includeInAll(boolean includeInAll) { this.includeInAll = includeInAll; return builder; } public T add(Mapper.Builder builder) { mappersBuilders.add(builder); return this.builder; } @Override public Y build(BuilderContext context) { ContentPath.Type origPathType = context.path().pathType(); context.path().pathType(pathType); context.path().add(name); Map<String, Mapper> mappers = new HashMap<String, Mapper>(); for (Mapper.Builder builder : mappersBuilders) { Mapper mapper = builder.build(context); mappers.put(mapper.name(), mapper); } context.path().pathType(origPathType); context.path().remove(); ObjectMapper objectMapper = createMapper(name, context.path().fullPathAsText(name), enabled, nested, dynamic, pathType, mappers); objectMapper.includeInAllIfNotSet(includeInAll); return (Y) objectMapper; } protected ObjectMapper createMapper(String name, String fullPath, boolean enabled, Nested nested, Dynamic dynamic, ContentPath.Type pathType, Map<String, Mapper> mappers) { return new ObjectMapper(name, fullPath, enabled, nested, dynamic, pathType, mappers); } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { Map<String, Object> objectNode = node; ObjectMapper.Builder builder = createBuilder(name); boolean nested = false; boolean nestedIncludeInParent = false; boolean nestedIncludeInRoot = false; for (Map.Entry<String, Object> entry : objectNode.entrySet()) { String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("dynamic")) { String value = fieldNode.toString(); if (value.equalsIgnoreCase("strict")) { builder.dynamic(Dynamic.STRICT); } else { builder.dynamic(nodeBooleanValue(fieldNode) ? Dynamic.TRUE : Dynamic.FALSE); } } else if (fieldName.equals("type")) { String type = fieldNode.toString(); if (type.equals(CONTENT_TYPE)) { builder.nested = Nested.NO; } else if (type.equals(NESTED_CONTENT_TYPE)) { nested = true; } else { throw new MapperParsingException("Trying to parse an object but has a different type [" + type + "] for [" + name + "]"); } } else if (fieldName.equals("include_in_parent")) { nestedIncludeInParent = nodeBooleanValue(fieldNode); } else if (fieldName.equals("include_in_root")) { nestedIncludeInRoot = nodeBooleanValue(fieldNode); } else if (fieldName.equals("enabled")) { builder.enabled(nodeBooleanValue(fieldNode)); } else if (fieldName.equals("path")) { builder.pathType(parsePathType(name, fieldNode.toString())); } else if (fieldName.equals("properties")) { parseProperties(builder, (Map<String, Object>) fieldNode, parserContext); } else if (fieldName.equals("include_in_all")) { builder.includeInAll(nodeBooleanValue(fieldNode)); } else { processField(builder, fieldName, fieldNode); } } if (nested) { builder.nested = Nested.newNested(nestedIncludeInParent, nestedIncludeInRoot); } return builder; } private void parseProperties(ObjectMapper.Builder objBuilder, Map<String, Object> propsNode, ParserContext parserContext) { for (Map.Entry<String, Object> entry : propsNode.entrySet()) { String propName = entry.getKey(); Map<String, Object> propNode = (Map<String, Object>) entry.getValue(); String type; Object typeNode = propNode.get("type"); if (typeNode != null) { type = typeNode.toString(); } else { // lets see if we can derive this... if (propNode.get("properties") != null) { type = ObjectMapper.CONTENT_TYPE; } else if (propNode.size() == 1 && propNode.get("enabled") != null) { // if there is a single property with the enabled flag on it, make it an object // (usually, setting enabled to false to not index any type, including core values, which // non enabled object type supports). type = ObjectMapper.CONTENT_TYPE; } else { throw new MapperParsingException("No type specified for property [" + propName + "]"); } } Mapper.TypeParser typeParser = parserContext.typeParser(type); if (typeParser == null) { throw new MapperParsingException("No handler for type [" + type + "] declared on field [" + propName + "]"); } objBuilder.add(typeParser.parse(propName, propNode, parserContext)); } } protected Builder createBuilder(String name) { return object(name); } protected void processField(Builder builder, String fieldName, Object fieldNode) { } } private final String name; private final String fullPath; private final boolean enabled; private final Nested nested; private final String nestedTypePathAsString; private final BytesRef nestedTypePathAsBytes; private final Filter nestedTypeFilter; private volatile Dynamic dynamic; private final ContentPath.Type pathType; private Boolean includeInAll; private volatile ImmutableOpenMap<String, Mapper> mappers = ImmutableOpenMap.of(); private final Object mutex = new Object(); ObjectMapper(String name, String fullPath, boolean enabled, Nested nested, Dynamic dynamic, ContentPath.Type pathType, Map<String, Mapper> mappers) { this.name = name; this.fullPath = fullPath; this.enabled = enabled; this.nested = nested; this.dynamic = dynamic; this.pathType = pathType; if (mappers != null) { this.mappers = ImmutableOpenMap.builder(this.mappers).putAll(mappers).build(); } this.nestedTypePathAsString = "__" + fullPath; this.nestedTypePathAsBytes = new BytesRef(nestedTypePathAsString); this.nestedTypeFilter = new TermFilter(new Term(TypeFieldMapper.NAME, nestedTypePathAsBytes)); } @Override public String name() { return this.name; } @Override public void includeInAll(Boolean includeInAll) { if (includeInAll == null) { return; } this.includeInAll = includeInAll; // when called from outside, apply this on all the inner mappers for (ObjectObjectCursor<String, Mapper> cursor : mappers) { if (cursor.value instanceof AllFieldMapper.IncludeInAll) { ((AllFieldMapper.IncludeInAll) cursor.value).includeInAll(includeInAll); } } } @Override public void includeInAllIfNotSet(Boolean includeInAll) { if (this.includeInAll == null) { this.includeInAll = includeInAll; } // when called from outside, apply this on all the inner mappers for (ObjectObjectCursor<String, Mapper> cursor : mappers) { if (cursor.value instanceof AllFieldMapper.IncludeInAll) { ((AllFieldMapper.IncludeInAll) cursor.value).includeInAllIfNotSet(includeInAll); } } } @Override public void unsetIncludeInAll() { includeInAll = null; // when called from outside, apply this on all the inner mappers for (ObjectObjectCursor<String, Mapper> cursor : mappers) { if (cursor.value instanceof AllFieldMapper.IncludeInAll) { ((AllFieldMapper.IncludeInAll) cursor.value).unsetIncludeInAll(); } } } public Nested nested() { return this.nested; } public Filter nestedTypeFilter() { return this.nestedTypeFilter; } public ObjectMapper putMapper(Mapper mapper) { if (mapper instanceof AllFieldMapper.IncludeInAll) { ((AllFieldMapper.IncludeInAll) mapper).includeInAllIfNotSet(includeInAll); } synchronized (mutex) { this.mappers = ImmutableOpenMap.builder(this.mappers).fPut(mapper.name(), mapper).build(); } return this; } @Override public void traverse(FieldMapperListener fieldMapperListener) { for (ObjectObjectCursor<String, Mapper> cursor : mappers) { cursor.value.traverse(fieldMapperListener); } } @Override public void traverse(ObjectMapperListener objectMapperListener) { objectMapperListener.objectMapper(this); for (ObjectObjectCursor<String, Mapper> cursor : mappers) { cursor.value.traverse(objectMapperListener); } } public String fullPath() { return this.fullPath; } public BytesRef nestedTypePathAsBytes() { return nestedTypePathAsBytes; } public String nestedTypePathAsString() { return nestedTypePathAsString; } public final Dynamic dynamic() { return this.dynamic == null ? Dynamic.TRUE : this.dynamic; } protected boolean allowValue() { return true; } public void parse(ParseContext context) throws IOException { if (!enabled) { context.parser().skipChildren(); return; } XContentParser parser = context.parser(); String currentFieldName = parser.currentName(); XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.VALUE_NULL) { // the object is null ("obj1" : null), simply bail return; } if (token.isValue() && !allowValue()) { // if we are parsing an object but it is just a value, its only allowed on root level parsers with there // is a field name with the same name as the type throw new MapperParsingException("object mapping for [" + name + "] tried to parse as object, but found a concrete value"); } Document restoreDoc = null; if (nested.isNested()) { Document nestedDoc = new Document(); // pre add the uid field if possible (id was already provided) IndexableField uidField = context.doc().getField(UidFieldMapper.NAME); if (uidField != null) { // we don't need to add it as a full uid field in nested docs, since we don't need versioning // we also rely on this for UidField#loadVersion // this is a deeply nested field nestedDoc.add(new Field(UidFieldMapper.NAME, uidField.stringValue(), UidFieldMapper.Defaults.NESTED_FIELD_TYPE)); } // the type of the nested doc starts with __, so we can identify that its a nested one in filters // note, we don't prefix it with the type of the doc since it allows us to execute a nested query // across types (for example, with similar nested objects) nestedDoc.add(new Field(TypeFieldMapper.NAME, nestedTypePathAsString, TypeFieldMapper.Defaults.FIELD_TYPE)); restoreDoc = context.switchDoc(nestedDoc); context.addDoc(nestedDoc); } ContentPath.Type origPathType = context.path().pathType(); context.path().pathType(pathType); // if we are at the end of the previous object, advance if (token == XContentParser.Token.END_OBJECT) { token = parser.nextToken(); } if (token == XContentParser.Token.START_OBJECT) { // if we are just starting an OBJECT, advance, this is the object we are parsing, we need the name first token = parser.nextToken(); } while (token != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.START_OBJECT) { serializeObject(context, currentFieldName); } else if (token == XContentParser.Token.START_ARRAY) { serializeArray(context, currentFieldName); } else if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_NULL) { serializeNullValue(context, currentFieldName); } else if (token == null) { throw new MapperParsingException("object mapping for [" + name + "] tried to parse as object, but got EOF, has a concrete value been provided to it?"); } else if (token.isValue()) { serializeValue(context, currentFieldName, token); } token = parser.nextToken(); } // restore the enable path flag context.path().pathType(origPathType); if (nested.isNested()) { Document nestedDoc = context.switchDoc(restoreDoc); if (nested.isIncludeInParent()) { for (IndexableField field : nestedDoc.getFields()) { if (field.name().equals(UidFieldMapper.NAME) || field.name().equals(TypeFieldMapper.NAME)) { continue; } else { context.doc().add(field); } } } if (nested.isIncludeInRoot()) { // don't add it twice, if its included in parent, and we are handling the master doc... if (!(nested.isIncludeInParent() && context.doc() == context.rootDoc())) { for (IndexableField field : nestedDoc.getFields()) { if (field.name().equals(UidFieldMapper.NAME) || field.name().equals(TypeFieldMapper.NAME)) { continue; } else { context.rootDoc().add(field); } } } } } } private void serializeNullValue(ParseContext context, String lastFieldName) throws IOException { // we can only handle null values if we have mappings for them Mapper mapper = mappers.get(lastFieldName); if (mapper != null) { mapper.parse(context); } } private void serializeObject(final ParseContext context, String currentFieldName) throws IOException { if (currentFieldName == null) { throw new MapperParsingException("object mapping [" + name + "] trying to serialize an object with no field associated with it, current value [" + context.parser().textOrNull() + "]"); } context.path().add(currentFieldName); Mapper objectMapper = mappers.get(currentFieldName); if (objectMapper != null) { objectMapper.parse(context); } else { Dynamic dynamic = this.dynamic; if (dynamic == null) { dynamic = context.root().dynamic(); } if (dynamic == Dynamic.STRICT) { throw new StrictDynamicMappingException(fullPath, currentFieldName); } else if (dynamic == Dynamic.TRUE) { // we sync here just so we won't add it twice. Its not the end of the world // to sync here since next operations will get it before synchronized (mutex) { objectMapper = mappers.get(currentFieldName); if (objectMapper == null) { // remove the current field name from path, since template search and the object builder add it as well... context.path().remove(); Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "object"); if (builder == null) { builder = MapperBuilders.object(currentFieldName).enabled(true).pathType(pathType); // if this is a non root object, then explicitly set the dynamic behavior if set if (!(this instanceof RootObjectMapper) && this.dynamic != Defaults.DYNAMIC) { ((Builder) builder).dynamic(this.dynamic); } } BuilderContext builderContext = new BuilderContext(context.indexSettings(), context.path()); objectMapper = builder.build(builderContext); // ...now re add it context.path().add(currentFieldName); context.setMappingsModified(); if (context.isWithinNewMapper()) { // within a new mapper, no need to traverse, just parse objectMapper.parse(context); } else { // create a context of new mapper, so we batch aggregate all the changes within // this object mapper once, and traverse all of them to add them in a single go context.setWithinNewMapper(); try { objectMapper.parse(context); FieldMapperListener.Aggregator newFields = new FieldMapperListener.Aggregator(); ObjectMapperListener.Aggregator newObjects = new ObjectMapperListener.Aggregator(); objectMapper.traverse(newFields); objectMapper.traverse(newObjects); // callback on adding those fields! context.docMapper().addFieldMappers(newFields.mappers); context.docMapper().addObjectMappers(newObjects.mappers); } finally { context.clearWithinNewMapper(); } } // only put after we traversed and did the callbacks, so other parsing won't see it only after we // properly traversed it and adding the mappers putMapper(objectMapper); } else { objectMapper.parse(context); } } } else { // not dynamic, read everything up to end object context.parser().skipChildren(); } } context.path().remove(); } private void serializeArray(ParseContext context, String lastFieldName) throws IOException { String arrayFieldName = lastFieldName; Mapper mapper = mappers.get(lastFieldName); if (mapper != null && mapper instanceof ArrayValueMapperParser) { mapper.parse(context); } else { XContentParser parser = context.parser(); XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token == XContentParser.Token.START_OBJECT) { serializeObject(context, lastFieldName); } else if (token == XContentParser.Token.START_ARRAY) { serializeArray(context, lastFieldName); } else if (token == XContentParser.Token.FIELD_NAME) { lastFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_NULL) { serializeNullValue(context, lastFieldName); } else if (token == null) { throw new MapperParsingException("object mapping for [" + name + "] with array for [" + arrayFieldName + "] tried to parse as array, but got EOF, is there a mismatch in types for the same field?"); } else { serializeValue(context, lastFieldName, token); } } } } private void serializeValue(final ParseContext context, String currentFieldName, XContentParser.Token token) throws IOException { if (currentFieldName == null) { throw new MapperParsingException("object mapping [" + name + "] trying to serialize a value with no field associated with it, current value [" + context.parser().textOrNull() + "]"); } Mapper mapper = mappers.get(currentFieldName); if (mapper != null) { mapper.parse(context); } else { parseDynamicValue(context, currentFieldName, token); } } public void parseDynamicValue(final ParseContext context, String currentFieldName, XContentParser.Token token) throws IOException { Dynamic dynamic = this.dynamic; if (dynamic == null) { dynamic = context.root().dynamic(); } if (dynamic == Dynamic.STRICT) { throw new StrictDynamicMappingException(fullPath, currentFieldName); } if (dynamic == Dynamic.FALSE) { return; } // we sync here since we don't want to add this field twice to the document mapper // its not the end of the world, since we add it to the mappers once we create it // so next time we won't even get here for this field synchronized (mutex) { Mapper mapper = mappers.get(currentFieldName); if (mapper == null) { BuilderContext builderContext = new BuilderContext(context.indexSettings(), context.path()); if (token == XContentParser.Token.VALUE_STRING) { boolean resolved = false; // do a quick test to see if its fits a dynamic template, if so, use it. // we need to do it here so we can handle things like attachment templates, where calling // text (to see if its a date) causes the binary value to be cleared if (!resolved) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "string", null); if (builder != null) { mapper = builder.build(builderContext); resolved = true; } } if (!resolved && context.parser().textLength() == 0) { // empty string with no mapping, treat it like null value return; } if (!resolved && context.root().dateDetection()) { String text = context.parser().text(); // a safe check since "1" gets parsed as well if (Strings.countOccurrencesOf(text, ":") > 1 || Strings.countOccurrencesOf(text, "-") > 1 || Strings.countOccurrencesOf(text, "/") > 1) { for (FormatDateTimeFormatter dateTimeFormatter : context.root().dynamicDateTimeFormatters()) { try { dateTimeFormatter.parser().parseMillis(text); Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "date"); if (builder == null) { builder = dateField(currentFieldName).dateTimeFormatter(dateTimeFormatter); } mapper = builder.build(builderContext); resolved = true; break; } catch (Exception e) { // failure to parse this, continue } } } } if (!resolved && context.root().numericDetection()) { String text = context.parser().text(); try { Long.parseLong(text); Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "long"); if (builder == null) { builder = longField(currentFieldName); } mapper = builder.build(builderContext); resolved = true; } catch (Exception e) { // not a long number } if (!resolved) { try { Double.parseDouble(text); Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "double"); if (builder == null) { builder = doubleField(currentFieldName); } mapper = builder.build(builderContext); resolved = true; } catch (Exception e) { // not a long number } } } // DON'T do automatic ip detection logic, since it messes up with docs that have hosts and ips // check if its an ip // if (!resolved && text.indexOf('.') != -1) { // try { // IpFieldMapper.ipToLong(text); // XContentMapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "ip"); // if (builder == null) { // builder = ipField(currentFieldName); // } // mapper = builder.build(builderContext); // resolved = true; // } catch (Exception e) { // // failure to parse, not ip... // } // } if (!resolved) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "string"); if (builder == null) { builder = stringField(currentFieldName); } mapper = builder.build(builderContext); } } else if (token == XContentParser.Token.VALUE_NUMBER) { XContentParser.NumberType numberType = context.parser().numberType(); if (numberType == XContentParser.NumberType.INT) { if (context.parser().estimatedNumberType()) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "long"); if (builder == null) { builder = longField(currentFieldName); } mapper = builder.build(builderContext); } else { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "integer"); if (builder == null) { builder = integerField(currentFieldName); } mapper = builder.build(builderContext); } } else if (numberType == XContentParser.NumberType.LONG) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "long"); if (builder == null) { builder = longField(currentFieldName); } mapper = builder.build(builderContext); } else if (numberType == XContentParser.NumberType.FLOAT) { if (context.parser().estimatedNumberType()) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "double"); if (builder == null) { builder = doubleField(currentFieldName); } mapper = builder.build(builderContext); } else { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "float"); if (builder == null) { builder = floatField(currentFieldName); } mapper = builder.build(builderContext); } } else if (numberType == XContentParser.NumberType.DOUBLE) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "double"); if (builder == null) { builder = doubleField(currentFieldName); } mapper = builder.build(builderContext); } } else if (token == XContentParser.Token.VALUE_BOOLEAN) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "boolean"); if (builder == null) { builder = booleanField(currentFieldName); } mapper = builder.build(builderContext); } else if (token == XContentParser.Token.VALUE_EMBEDDED_OBJECT) { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, "binary"); if (builder == null) { builder = binaryField(currentFieldName); } mapper = builder.build(builderContext); } else { Mapper.Builder builder = context.root().findTemplateBuilder(context, currentFieldName, null); if (builder != null) { mapper = builder.build(builderContext); } else { // TODO how do we identify dynamically that its a binary value? throw new ElasticsearchIllegalStateException("Can't handle serializing a dynamic type with content token [" + token + "] and field name [" + currentFieldName + "]"); } } if (context.isWithinNewMapper()) { mapper.parse(context); } else { context.setWithinNewMapper(); try { mapper.parse(context); FieldMapperListener.Aggregator newFields = new FieldMapperListener.Aggregator(); mapper.traverse(newFields); context.docMapper().addFieldMappers(newFields.mappers); } finally { context.clearWithinNewMapper(); } } // only put after we traversed and did the callbacks, so other parsing won't see it only after we // properly traversed it and adding the mappers putMapper(mapper); context.setMappingsModified(); } else { mapper.parse(context); } } } @Override public void merge(final Mapper mergeWith, final MergeContext mergeContext) throws MergeMappingException { if (!(mergeWith instanceof ObjectMapper)) { mergeContext.addConflict("Can't merge a non object mapping [" + mergeWith.name() + "] with an object mapping [" + name() + "]"); return; } ObjectMapper mergeWithObject = (ObjectMapper) mergeWith; if (nested().isNested()) { if (!mergeWithObject.nested().isNested()) { mergeContext.addConflict("object mapping [" + name() + "] can't be changed from nested to non-nested"); return; } } else { if (mergeWithObject.nested().isNested()) { mergeContext.addConflict("object mapping [" + name() + "] can't be changed from non-nested to nested"); return; } } if (!mergeContext.mergeFlags().simulate()) { if (mergeWithObject.dynamic != null) { this.dynamic = mergeWithObject.dynamic; } } doMerge(mergeWithObject, mergeContext); List<Mapper> mappersToPut = new ArrayList<Mapper>(); FieldMapperListener.Aggregator newFieldMappers = new FieldMapperListener.Aggregator(); ObjectMapperListener.Aggregator newObjectMappers = new ObjectMapperListener.Aggregator(); synchronized (mutex) { for (ObjectObjectCursor<String, Mapper> cursor : mergeWithObject.mappers) { Mapper mergeWithMapper = cursor.value; Mapper mergeIntoMapper = mappers.get(mergeWithMapper.name()); if (mergeIntoMapper == null) { // no mapping, simply add it if not simulating if (!mergeContext.mergeFlags().simulate()) { mappersToPut.add(mergeWithMapper); mergeWithMapper.traverse(newFieldMappers); mergeWithMapper.traverse(newObjectMappers); } } else { mergeIntoMapper.merge(mergeWithMapper, mergeContext); } } if (!newFieldMappers.mappers.isEmpty()) { mergeContext.docMapper().addFieldMappers(newFieldMappers.mappers); } if (!newObjectMappers.mappers.isEmpty()) { mergeContext.docMapper().addObjectMappers(newObjectMappers.mappers); } // and the mappers only after the administration have been done, so it will not be visible to parser (which first try to read with no lock) for (Mapper mapper : mappersToPut) { putMapper(mapper); } } } protected void doMerge(ObjectMapper mergeWith, MergeContext mergeContext) { } @Override public void close() { for (ObjectObjectCursor<String, Mapper> cursor : mappers) { cursor.value.close(); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { toXContent(builder, params, null, Mapper.EMPTY_ARRAY); return builder; } public void toXContent(XContentBuilder builder, Params params, ToXContent custom, Mapper... additionalMappers) throws IOException { builder.startObject(name); if (nested.isNested()) { builder.field("type", NESTED_CONTENT_TYPE); if (nested.isIncludeInParent()) { builder.field("include_in_parent", true); } if (nested.isIncludeInRoot()) { builder.field("include_in_root", true); } } else if (mappers.isEmpty()) { // only write the object content type if there are no properties, otherwise, it is automatically detected builder.field("type", CONTENT_TYPE); } if (dynamic != null) { builder.field("dynamic", dynamic.name().toLowerCase(Locale.ROOT)); } if (enabled != Defaults.ENABLED) { builder.field("enabled", enabled); } if (pathType != Defaults.PATH_TYPE) { builder.field("path", pathType.name().toLowerCase(Locale.ROOT)); } if (includeInAll != null) { builder.field("include_in_all", includeInAll); } if (custom != null) { custom.toXContent(builder, params); } doXContent(builder, params); // sort the mappers so we get consistent serialization format TreeMap<String, Mapper> sortedMappers = new TreeMap<String, Mapper>(); for (ObjectObjectCursor<String, Mapper> cursor : mappers) { sortedMappers.put(cursor.key, cursor.value); } // check internal mappers first (this is only relevant for root object) for (Mapper mapper : sortedMappers.values()) { if (mapper instanceof InternalMapper) { mapper.toXContent(builder, params); } } if (additionalMappers != null && additionalMappers.length > 0) { TreeMap<String, Mapper> additionalSortedMappers = new TreeMap<String, Mapper>(); for (Mapper mapper : additionalMappers) { additionalSortedMappers.put(mapper.name(), mapper); } for (Mapper mapper : additionalSortedMappers.values()) { mapper.toXContent(builder, params); } } if (!mappers.isEmpty()) { builder.startObject("properties"); for (Mapper mapper : sortedMappers.values()) { if (!(mapper instanceof InternalMapper)) { mapper.toXContent(builder, params); } } builder.endObject(); } builder.endObject(); } protected void doXContent(XContentBuilder builder, Params params) throws IOException { } }
1no label
src_main_java_org_elasticsearch_index_mapper_object_ObjectMapper.java
138
static final class WNode { volatile WNode prev; volatile WNode next; volatile WNode cowait; // list of linked readers volatile Thread thread; // non-null while possibly parked volatile int status; // 0, WAITING, or CANCELLED final int mode; // RMODE or WMODE WNode(int m, WNode p) { mode = m; prev = p; } }
0true
src_main_java_jsr166e_StampedLock.java
310
new OConfigurationChangeCallback() { public void change(final Object iCurrentValue, final Object iNewValue) { if ((Boolean) iNewValue) Orient.instance().getProfiler().startRecording(); else Orient.instance().getProfiler().stopRecording(); } }),
0true
core_src_main_java_com_orientechnologies_orient_core_config_OGlobalConfiguration.java
591
public class IndexShardSegments implements Iterable<ShardSegments> { private final ShardId shardId; private final ShardSegments[] shards; IndexShardSegments(ShardId shardId, ShardSegments[] shards) { this.shardId = shardId; this.shards = shards; } public ShardId getShardId() { return this.shardId; } public ShardSegments getAt(int i) { return shards[i]; } public ShardSegments[] getShards() { return this.shards; } @Override public Iterator<ShardSegments> iterator() { return Iterators.forArray(shards); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_segments_IndexShardSegments.java
111
public class TestDeadlockDetection { @Test public void testDeadlockDetection() throws Exception { ResourceObject r1 = newResourceObject( "R1" ); ResourceObject r2 = newResourceObject( "R2" ); ResourceObject r3 = newResourceObject( "R3" ); ResourceObject r4 = newResourceObject( "R4" ); PlaceboTm tm = new PlaceboTm( null, null ); LockManager lm = new LockManagerImpl( new RagManager() ); tm.setLockManager( lm ); LockWorker t1 = new LockWorker( "T1", lm ); LockWorker t2 = new LockWorker( "T2", lm ); LockWorker t3 = new LockWorker( "T3", lm ); LockWorker t4 = new LockWorker( "T4", lm ); try { t1.getReadLock( r1, true ); t1.getReadLock( r4, true ); t2.getReadLock( r2, true ); t2.getReadLock( r3, true ); t3.getReadLock( r3, true ); t3.getWriteLock( r1, false ); // t3-r1-t1 // T3 t2.getWriteLock( r4, false ); // t2-r4-t1 t1.getWriteLock( r2, true ); assertTrue( t1.isLastGetLockDeadLock() ); // t1-r2-t2-r4-t1 // resolve and try one more time t1.releaseReadLock( r4 ); // will give r4 to t2 t1.getWriteLock( r2, false ); // t1-r2-t2 t2.releaseReadLock( r2 ); // will give r2 to t1 t1.getWriteLock( r4, false ); // t1-r4-t2 // T1 // dead lock t2.getWriteLock( r2, true ); // T2 assertTrue( t2.isLastGetLockDeadLock() ); // t2-r2-t3-r1-t1-r4-t2 or t2-r2-t1-r4-t2 t2.releaseWriteLock( r4 ); // give r4 to t1 t1.releaseWriteLock( r4 ); t2.getReadLock( r4, true ); t1.releaseWriteLock( r2 ); t1.getReadLock( r2, true ); t1.releaseReadLock( r1 ); // give r1 to t3 t3.getReadLock( r2, true ); t3.releaseWriteLock( r1 ); t1.getReadLock( r1, true ); // give r1->t1 t1.getWriteLock( r4, false ); t3.getWriteLock( r1, false ); t4.getReadLock( r2, true ); // deadlock t2.getWriteLock( r2, true ); assertTrue( t2.isLastGetLockDeadLock() ); // t2-r2-t3-r1-t1-r4-t2 // resolve t2.releaseReadLock( r4 ); t1.releaseWriteLock( r4 ); t1.releaseReadLock( r1 ); t2.getReadLock( r4, true ); // give r1 to t3 t3.releaseWriteLock( r1 ); t1.getReadLock( r1, true ); // give r1 to t1 t1.getWriteLock( r4, false ); t3.releaseReadLock( r2 ); t3.getWriteLock( r1, false ); // cleanup t2.releaseReadLock( r4 ); // give r4 to t1 t1.releaseWriteLock( r4 ); t1.releaseReadLock( r1 ); // give r1 to t3 t3.releaseWriteLock( r1 ); t1.releaseReadLock( r2 ); t4.releaseReadLock( r2 ); t2.releaseReadLock( r3 ); t3.releaseReadLock( r3 ); // -- special case... t1.getReadLock( r1, true ); t2.getReadLock( r1, true ); t1.getWriteLock( r1, false ); // t1->r1-t1&t2 t2.getWriteLock( r1, true ); assertTrue( t2.isLastGetLockDeadLock() ); // t2->r1->t1->r1->t2 t2.releaseReadLock( r1 ); t1.releaseReadLock( r1 ); t1.releaseWriteLock( r1 ); } catch ( Exception e ) { File file = new LockWorkFailureDump( getClass() ).dumpState( lm, new LockWorker[] { t1, t2, t3, t4 } ); throw new RuntimeException( "Failed, forensics information dumped to " + file.getAbsolutePath(), e ); } } public static class StressThread extends Thread { private static final Object READ = new Object(); private static final Object WRITE = new Object(); private static ResourceObject resources[] = new ResourceObject[10]; private final Random rand = new Random( currentTimeMillis() ); static { for ( int i = 0; i < resources.length; i++ ) resources[i] = new ResourceObject( "RX" + i ); } private final CountDownLatch startSignal; private final String name; private final int numberOfIterations; private final int depthCount; private final float readWriteRatio; private final LockManager lm; private volatile Exception error; private final Transaction tx = mock( Transaction.class ); public volatile Long startedWaiting = null; StressThread( String name, int numberOfIterations, int depthCount, float readWriteRatio, LockManager lm, CountDownLatch startSignal ) { super(); this.name = name; this.numberOfIterations = numberOfIterations; this.depthCount = depthCount; this.readWriteRatio = readWriteRatio; this.lm = lm; this.startSignal = startSignal; } @Override public void run() { try { startSignal.await(); java.util.Stack<Object> lockStack = new java.util.Stack<Object>(); java.util.Stack<ResourceObject> resourceStack = new java.util.Stack<ResourceObject>(); for ( int i = 0; i < numberOfIterations; i++ ) { try { int depth = depthCount; do { float f = rand.nextFloat(); int n = rand.nextInt( resources.length ); if ( f < readWriteRatio ) { startedWaiting = currentTimeMillis(); lm.getReadLock( resources[n], tx ); startedWaiting = null; lockStack.push( READ ); } else { startedWaiting = currentTimeMillis(); lm.getWriteLock( resources[n], tx ); startedWaiting = null; lockStack.push( WRITE ); } resourceStack.push( resources[n] ); } while ( --depth > 0 ); } catch ( DeadlockDetectedException e ) { // This is good } finally { releaseAllLocks( lockStack, resourceStack ); } } } catch ( Exception e ) { error = e; } } private void releaseAllLocks( Stack<Object> lockStack, Stack<ResourceObject> resourceStack ) { while ( !lockStack.isEmpty() ) { if ( lockStack.pop() == READ ) { lm.releaseReadLock( resourceStack.pop(), tx ); } else { lm.releaseWriteLock( resourceStack.pop(), tx ); } } } @Override public String toString() { return this.name; } } @Test public void testStressMultipleThreads() throws Exception { /* This test starts a bunch of threads, and randomly takes read or write locks on random resources. No thread should wait more than five seconds for a lock - if it does, we consider it a failure. Successful outcomes are when threads either finish with all their lock taking and releasing, or are terminated with a DeadlockDetectedException. */ for ( int i = 0; i < StressThread.resources.length; i++ ) { StressThread.resources[i] = new ResourceObject( "RX" + i ); } StressThread stressThreads[] = new StressThread[50]; PlaceboTm tm = new PlaceboTm( null, null ); LockManager lm = new LockManagerImpl( new RagManager() ); tm.setLockManager( lm ); CountDownLatch startSignal = new CountDownLatch( 1 ); for ( int i = 0; i < stressThreads.length; i++ ) { int numberOfIterations = 100; int depthCount = 10; float readWriteRatio = 0.80f; stressThreads[i] = new StressThread( "T" + i, numberOfIterations, depthCount, readWriteRatio, lm, startSignal ); } for ( Thread thread : stressThreads ) { thread.start(); } startSignal.countDown(); while ( anyAliveAndAllWell( stressThreads ) ) { throwErrorsIfAny( stressThreads ); sleepALittle(); } } private String diagnostics( StressThread culprit, StressThread[] stressThreads, long waited ) { StringBuilder builder = new StringBuilder(); for ( StressThread stressThread : stressThreads ) { if ( stressThread.isAlive() ) { if ( stressThread == culprit ) { builder.append( "This is the thread that waited too long. It waited: " ).append( waited ).append( " milliseconds" ); } for ( StackTraceElement element : stressThread.getStackTrace() ) { builder.append( element.toString() ).append( "\n" ); } } builder.append( "\n" ); } return builder.toString(); } private void throwErrorsIfAny( StressThread[] stressThreads ) throws Exception { for ( StressThread stressThread : stressThreads ) { if ( stressThread.error != null ) { throw stressThread.error; } } } private void sleepALittle() { try { Thread.sleep( 1000 ); } catch ( InterruptedException e ) { Thread.interrupted(); } } private boolean anyAliveAndAllWell( StressThread[] stressThreads ) { for ( StressThread stressThread : stressThreads ) { if ( stressThread.isAlive() ) { Long startedWaiting = stressThread.startedWaiting; if ( startedWaiting != null ) { long waitingTime = currentTimeMillis() - startedWaiting; if ( waitingTime > 5000 ) { fail( "One of the threads waited far too long. Diagnostics: \n" + diagnostics( stressThread, stressThreads, waitingTime) ); } } return true; } } return false; } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestDeadlockDetection.java
2
private static class Paths { private final String yamlPath; private final String dataPath; public Paths(String yamlPath, String dataPath) { this.yamlPath = yamlPath; this.dataPath = dataPath; } }
0true
titan-cassandra_src_test_java_com_thinkaurelius_titan_CassandraStorageSetup.java
1,692
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_ADMIN_PASSWORD_TOKEN") public class ForgotPasswordSecurityTokenImpl implements ForgotPasswordSecurityToken { private static final long serialVersionUID = 1L; @Id @Column(name = "PASSWORD_TOKEN", nullable = false) protected String token; @Column(name = "CREATE_DATE", nullable = false) @Temporal(TemporalType.TIMESTAMP) protected Date createDate; @Column(name = "TOKEN_USED_DATE") @Temporal(TemporalType.TIMESTAMP) protected Date tokenUsedDate; @Column(name = "ADMIN_USER_ID", nullable = false) protected Long adminUserId; @Column(name = "TOKEN_USED_FLAG", nullable = false) protected boolean tokenUsedFlag; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getTokenUsedDate() { return tokenUsedDate; } public void setTokenUsedDate(Date tokenUsedDate) { this.tokenUsedDate = tokenUsedDate; } public Long getAdminUserId() { return adminUserId; } public void setAdminUserId(Long adminUserId) { this.adminUserId = adminUserId; } public boolean isTokenUsedFlag() { return tokenUsedFlag; } public void setTokenUsedFlag(boolean tokenUsedFlag) { this.tokenUsedFlag = tokenUsedFlag; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ForgotPasswordSecurityTokenImpl that = (ForgotPasswordSecurityTokenImpl) o; if (token != null ? !token.equals(that.token) : that.token != null) return false; return true; } @Override public int hashCode() { return token != null ? token.hashCode() : 0; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_security_domain_ForgotPasswordSecurityTokenImpl.java
1,531
public class StartedRerouteAllocation extends RoutingAllocation { private final List<? extends ShardRouting> startedShards; public StartedRerouteAllocation(AllocationDeciders deciders, RoutingNodes routingNodes, DiscoveryNodes nodes, List<? extends ShardRouting> startedShards, ClusterInfo clusterInfo) { super(deciders, routingNodes, nodes, clusterInfo); this.startedShards = startedShards; } /** * Get started shards * @return list of started shards */ public List<? extends ShardRouting> startedShards() { return startedShards; } }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_StartedRerouteAllocation.java
409
public class DeleteSnapshotResponse extends AcknowledgedResponse { DeleteSnapshotResponse() { } DeleteSnapshotResponse(boolean acknowledged) { super(acknowledged); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); readAcknowledged(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); writeAcknowledged(out); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_delete_DeleteSnapshotResponse.java
1,211
public class PaymentInfoAdditionalFieldType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, PaymentInfoAdditionalFieldType> TYPES = new LinkedHashMap<String, PaymentInfoAdditionalFieldType>(); public static final PaymentInfoAdditionalFieldType NAME_ON_CARD = new PaymentInfoAdditionalFieldType("NAME_ON_CARD", "Cardholders Name"); public static final PaymentInfoAdditionalFieldType CARD_TYPE = new PaymentInfoAdditionalFieldType("CARD_TYPE", "Card Type"); public static final PaymentInfoAdditionalFieldType EXP_MONTH = new PaymentInfoAdditionalFieldType("EXP_MONTH", "Expiration Month"); public static final PaymentInfoAdditionalFieldType EXP_YEAR = new PaymentInfoAdditionalFieldType("EXP_YEAR", "Expiration Year"); // Generic Fields that can be used for multiple payment types public static final PaymentInfoAdditionalFieldType PAYMENT_TYPE = new PaymentInfoAdditionalFieldType("PAYMENT_TYPE", "Type of Payment"); public static final PaymentInfoAdditionalFieldType NAME_ON_ACCOUNT = new PaymentInfoAdditionalFieldType("NAME_ON_ACCOUNT", "Name on Account"); public static final PaymentInfoAdditionalFieldType ACCOUNT_TYPE = new PaymentInfoAdditionalFieldType("ACCOUNT_TYPE", "Account Type"); public static final PaymentInfoAdditionalFieldType LAST_FOUR = new PaymentInfoAdditionalFieldType("LAST_FOUR", "Last Four Digits ofAccount or CC"); public static final PaymentInfoAdditionalFieldType GIFT_CARD_NUM = new PaymentInfoAdditionalFieldType("GIFT_CARD_NUM", "Gift Card Number"); public static final PaymentInfoAdditionalFieldType EMAIL = new PaymentInfoAdditionalFieldType("EMAIL", "Email"); public static final PaymentInfoAdditionalFieldType ACCOUNT_CREDIT_NUM = new PaymentInfoAdditionalFieldType("ACCOUNT_CREDIT_NUM", "Account Credit Number"); public static final PaymentInfoAdditionalFieldType AUTH_CODE = new PaymentInfoAdditionalFieldType("AUTH_CODE", "Authorization Code"); public static final PaymentInfoAdditionalFieldType REQUEST_ID = new PaymentInfoAdditionalFieldType("REQUEST_ID", "Request Id"); public static final PaymentInfoAdditionalFieldType SUBSCRIPTION_ID = new PaymentInfoAdditionalFieldType("SUBSCRIPTION_ID", "Subscription Id"); public static final PaymentInfoAdditionalFieldType SUBSCRIPTION_TITLE = new PaymentInfoAdditionalFieldType("SUBSCRIPTION_TITLE", "Subscription Title"); public static PaymentInfoAdditionalFieldType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public PaymentInfoAdditionalFieldType() { //do nothing } public PaymentInfoAdditionalFieldType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PaymentInfoAdditionalFieldType other = (PaymentInfoAdditionalFieldType) 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_payment_service_type_PaymentInfoAdditionalFieldType.java
538
public class DeleteMappingAction extends IndicesAction<DeleteMappingRequest, DeleteMappingResponse, DeleteMappingRequestBuilder> { public static final DeleteMappingAction INSTANCE = new DeleteMappingAction(); public static final String NAME = "indices/mapping/delete"; private DeleteMappingAction() { super(NAME); } @Override public DeleteMappingResponse newResponse() { return new DeleteMappingResponse(); } @Override public DeleteMappingRequestBuilder newRequestBuilder(IndicesAdminClient client) { return new DeleteMappingRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_mapping_delete_DeleteMappingAction.java
1,395
public class MetaDataCreateIndexService extends AbstractComponent { private final Environment environment; private final ThreadPool threadPool; private final ClusterService clusterService; private final IndicesService indicesService; private final AllocationService allocationService; private final MetaDataService metaDataService; private final Version version; private final String riverIndexName; @Inject public MetaDataCreateIndexService(Settings settings, Environment environment, ThreadPool threadPool, ClusterService clusterService, IndicesService indicesService, AllocationService allocationService, MetaDataService metaDataService, Version version, @RiverIndexName String riverIndexName) { super(settings); this.environment = environment; this.threadPool = threadPool; this.clusterService = clusterService; this.indicesService = indicesService; this.allocationService = allocationService; this.metaDataService = metaDataService; this.version = version; this.riverIndexName = riverIndexName; } public void createIndex(final CreateIndexClusterStateUpdateRequest request, final ClusterStateUpdateListener listener) { ImmutableSettings.Builder updatedSettingsBuilder = ImmutableSettings.settingsBuilder(); for (Map.Entry<String, String> entry : request.settings().getAsMap().entrySet()) { if (!entry.getKey().startsWith("index.")) { updatedSettingsBuilder.put("index." + entry.getKey(), entry.getValue()); } else { updatedSettingsBuilder.put(entry.getKey(), entry.getValue()); } } request.settings(updatedSettingsBuilder.build()); // we lock here, and not within the cluster service callback since we don't want to // block the whole cluster state handling final Semaphore mdLock = metaDataService.indexMetaDataLock(request.index()); // quick check to see if we can acquire a lock, otherwise spawn to a thread pool if (mdLock.tryAcquire()) { createIndex(request, listener, mdLock); return; } threadPool.executor(ThreadPool.Names.MANAGEMENT).execute(new Runnable() { @Override public void run() { try { if (!mdLock.tryAcquire(request.masterNodeTimeout().nanos(), TimeUnit.NANOSECONDS)) { listener.onFailure(new ProcessClusterEventTimeoutException(request.masterNodeTimeout(), "acquire index lock")); return; } } catch (InterruptedException e) { Thread.interrupted(); listener.onFailure(e); return; } createIndex(request, listener, mdLock); } }); } public void validateIndexName(String index, ClusterState state) throws ElasticsearchException { if (state.routingTable().hasIndex(index)) { throw new IndexAlreadyExistsException(new Index(index)); } if (state.metaData().hasIndex(index)) { throw new IndexAlreadyExistsException(new Index(index)); } if (!Strings.validFileName(index)) { throw new InvalidIndexNameException(new Index(index), index, "must not contain the following characters " + Strings.INVALID_FILENAME_CHARS); } if (index.contains("#")) { throw new InvalidIndexNameException(new Index(index), index, "must not contain '#'"); } if (!index.equals(riverIndexName) && index.charAt(0) == '_') { throw new InvalidIndexNameException(new Index(index), index, "must not start with '_'"); } if (!index.toLowerCase(Locale.ROOT).equals(index)) { throw new InvalidIndexNameException(new Index(index), index, "must be lowercase"); } if (state.metaData().aliases().containsKey(index)) { throw new InvalidIndexNameException(new Index(index), index, "already exists as alias"); } } private void createIndex(final CreateIndexClusterStateUpdateRequest request, final ClusterStateUpdateListener listener, final Semaphore mdLock) { clusterService.submitStateUpdateTask("create-index [" + request.index() + "], cause [" + request.cause() + "]", Priority.URGENT, new AckedClusterStateUpdateTask() { @Override public boolean mustAck(DiscoveryNode discoveryNode) { return true; } @Override public void onAllNodesAcked(@Nullable Throwable t) { mdLock.release(); listener.onResponse(new ClusterStateUpdateResponse(true)); } @Override public void onAckTimeout() { mdLock.release(); 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) { mdLock.release(); listener.onFailure(t); } @Override public ClusterState execute(ClusterState currentState) throws Exception { boolean indexCreated = false; String failureReason = null; try { validate(request, currentState); // we only find a template when its an API call (a new index) // find templates, highest order are better matching List<IndexTemplateMetaData> templates = findTemplates(request, currentState); Map<String, Custom> customs = Maps.newHashMap(); // add the request mapping Map<String, Map<String, Object>> mappings = Maps.newHashMap(); for (Map.Entry<String, String> entry : request.mappings().entrySet()) { mappings.put(entry.getKey(), parseMapping(entry.getValue())); } for (Map.Entry<String, Custom> entry : request.customs().entrySet()) { customs.put(entry.getKey(), entry.getValue()); } // apply templates, merging the mappings into the request mapping if exists for (IndexTemplateMetaData template : templates) { for (ObjectObjectCursor<String, CompressedString> cursor : template.mappings()) { if (mappings.containsKey(cursor.key)) { XContentHelper.mergeDefaults(mappings.get(cursor.key), parseMapping(cursor.value.string())); } else { mappings.put(cursor.key, parseMapping(cursor.value.string())); } } // handle custom for (ObjectObjectCursor<String, Custom> cursor : template.customs()) { String type = cursor.key; IndexMetaData.Custom custom = cursor.value; IndexMetaData.Custom existing = customs.get(type); if (existing == null) { customs.put(type, custom); } else { IndexMetaData.Custom merged = IndexMetaData.lookupFactorySafe(type).merge(existing, custom); customs.put(type, merged); } } } // now add config level mappings File mappingsDir = new File(environment.configFile(), "mappings"); if (mappingsDir.exists() && mappingsDir.isDirectory()) { // first index level File indexMappingsDir = new File(mappingsDir, request.index()); if (indexMappingsDir.exists() && indexMappingsDir.isDirectory()) { addMappings(mappings, indexMappingsDir); } // second is the _default mapping File defaultMappingsDir = new File(mappingsDir, "_default"); if (defaultMappingsDir.exists() && defaultMappingsDir.isDirectory()) { addMappings(mappings, defaultMappingsDir); } } ImmutableSettings.Builder indexSettingsBuilder = settingsBuilder(); // apply templates, here, in reverse order, since first ones are better matching for (int i = templates.size() - 1; i >= 0; i--) { indexSettingsBuilder.put(templates.get(i).settings()); } // now, put the request settings, so they override templates indexSettingsBuilder.put(request.settings()); if (indexSettingsBuilder.get(SETTING_NUMBER_OF_SHARDS) == null) { if (request.index().equals(riverIndexName)) { indexSettingsBuilder.put(SETTING_NUMBER_OF_SHARDS, settings.getAsInt(SETTING_NUMBER_OF_SHARDS, 1)); } else { indexSettingsBuilder.put(SETTING_NUMBER_OF_SHARDS, settings.getAsInt(SETTING_NUMBER_OF_SHARDS, 5)); } } if (indexSettingsBuilder.get(SETTING_NUMBER_OF_REPLICAS) == null) { if (request.index().equals(riverIndexName)) { indexSettingsBuilder.put(SETTING_NUMBER_OF_REPLICAS, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 1)); } else { indexSettingsBuilder.put(SETTING_NUMBER_OF_REPLICAS, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 1)); } } if (settings.get(SETTING_AUTO_EXPAND_REPLICAS) != null && indexSettingsBuilder.get(SETTING_AUTO_EXPAND_REPLICAS) == null) { indexSettingsBuilder.put(SETTING_AUTO_EXPAND_REPLICAS, settings.get(SETTING_AUTO_EXPAND_REPLICAS)); } if (indexSettingsBuilder.get(SETTING_VERSION_CREATED) == null) { indexSettingsBuilder.put(SETTING_VERSION_CREATED, version); } indexSettingsBuilder.put(SETTING_UUID, Strings.randomBase64UUID()); Settings actualIndexSettings = indexSettingsBuilder.build(); // Set up everything, now locally create the index to see that things are ok, and apply // create the index here (on the master) to validate it can be created, as well as adding the mapping indicesService.createIndex(request.index(), actualIndexSettings, clusterService.localNode().id()); indexCreated = true; // now add the mappings IndexService indexService = indicesService.indexServiceSafe(request.index()); MapperService mapperService = indexService.mapperService(); // first, add the default mapping if (mappings.containsKey(MapperService.DEFAULT_MAPPING)) { try { mapperService.merge(MapperService.DEFAULT_MAPPING, new CompressedString(XContentFactory.jsonBuilder().map(mappings.get(MapperService.DEFAULT_MAPPING)).string()), false); } catch (Exception e) { failureReason = "failed on parsing default mapping on index creation"; throw new MapperParsingException("mapping [" + MapperService.DEFAULT_MAPPING + "]", e); } } for (Map.Entry<String, Map<String, Object>> entry : mappings.entrySet()) { if (entry.getKey().equals(MapperService.DEFAULT_MAPPING)) { continue; } try { // apply the default here, its the first time we parse it mapperService.merge(entry.getKey(), new CompressedString(XContentFactory.jsonBuilder().map(entry.getValue()).string()), true); } catch (Exception e) { failureReason = "failed on parsing mappings on index creation"; throw new MapperParsingException("mapping [" + entry.getKey() + "]", e); } } // now, update the mappings with the actual source Map<String, MappingMetaData> mappingsMetaData = Maps.newHashMap(); for (DocumentMapper mapper : mapperService) { MappingMetaData mappingMd = new MappingMetaData(mapper); mappingsMetaData.put(mapper.type(), mappingMd); } final IndexMetaData.Builder indexMetaDataBuilder = IndexMetaData.builder(request.index()).settings(actualIndexSettings); for (MappingMetaData mappingMd : mappingsMetaData.values()) { indexMetaDataBuilder.putMapping(mappingMd); } for (Map.Entry<String, Custom> customEntry : customs.entrySet()) { indexMetaDataBuilder.putCustom(customEntry.getKey(), customEntry.getValue()); } indexMetaDataBuilder.state(request.state()); final IndexMetaData indexMetaData; try { indexMetaData = indexMetaDataBuilder.build(); } catch (Exception e) { failureReason = "failed to build index metadata"; throw e; } MetaData newMetaData = MetaData.builder(currentState.metaData()) .put(indexMetaData, false) .build(); logger.info("[{}] creating index, cause [{}], shards [{}]/[{}], mappings {}", request.index(), request.cause(), indexMetaData.numberOfShards(), indexMetaData.numberOfReplicas(), mappings.keySet()); ClusterBlocks.Builder blocks = ClusterBlocks.builder().blocks(currentState.blocks()); if (!request.blocks().isEmpty()) { for (ClusterBlock block : request.blocks()) { blocks.addIndexBlock(request.index(), block); } } if (request.state() == State.CLOSE) { blocks.addIndexBlock(request.index(), MetaDataIndexStateService.INDEX_CLOSED_BLOCK); } ClusterState updatedState = ClusterState.builder(currentState).blocks(blocks).metaData(newMetaData).build(); if (request.state() == State.OPEN) { RoutingTable.Builder routingTableBuilder = RoutingTable.builder(updatedState.routingTable()) .addAsNew(updatedState.metaData().index(request.index())); RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder(updatedState).routingTable(routingTableBuilder).build()); updatedState = ClusterState.builder(updatedState).routingResult(routingResult).build(); } return updatedState; } finally { if (indexCreated) { // Index was already partially created - need to clean up indicesService.removeIndex(request.index(), failureReason != null ? failureReason : "failed to create index"); } } } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { } }); } private Map<String, Object> parseMapping(String mappingSource) throws Exception { return XContentFactory.xContent(mappingSource).createParser(mappingSource).mapAndClose(); } private void addMappings(Map<String, Map<String, Object>> mappings, File mappingsDir) { File[] mappingsFiles = mappingsDir.listFiles(); for (File mappingFile : mappingsFiles) { if (mappingFile.isHidden()) { continue; } int lastDotIndex = mappingFile.getName().lastIndexOf('.'); String mappingType = lastDotIndex != -1 ? mappingFile.getName().substring(0, lastDotIndex) : mappingFile.getName(); try { String mappingSource = Streams.copyToString(new InputStreamReader(new FileInputStream(mappingFile), Charsets.UTF_8)); if (mappings.containsKey(mappingType)) { XContentHelper.mergeDefaults(mappings.get(mappingType), parseMapping(mappingSource)); } else { mappings.put(mappingType, parseMapping(mappingSource)); } } catch (Exception e) { logger.warn("failed to read / parse mapping [" + mappingType + "] from location [" + mappingFile + "], ignoring...", e); } } } private List<IndexTemplateMetaData> findTemplates(CreateIndexClusterStateUpdateRequest request, ClusterState state) { List<IndexTemplateMetaData> templates = Lists.newArrayList(); for (ObjectCursor<IndexTemplateMetaData> cursor : state.metaData().templates().values()) { IndexTemplateMetaData template = cursor.value; if (Regex.simpleMatch(template.template(), request.index())) { templates.add(template); } } // see if we have templates defined under config File templatesDir = new File(environment.configFile(), "templates"); if (templatesDir.exists() && templatesDir.isDirectory()) { File[] templatesFiles = templatesDir.listFiles(); if (templatesFiles != null) { for (File templatesFile : templatesFiles) { XContentParser parser = null; try { byte[] templatesData = Streams.copyToByteArray(templatesFile); parser = XContentHelper.createParser(templatesData, 0, templatesData.length); IndexTemplateMetaData template = IndexTemplateMetaData.Builder.fromXContent(parser); if (Regex.simpleMatch(template.template(), request.index())) { templates.add(template); } } catch (Exception e) { logger.warn("[{}] failed to read template [{}] from config", e, request.index(), templatesFile.getAbsolutePath()); } finally { IOUtils.closeWhileHandlingException(parser); } } } } CollectionUtil.timSort(templates, new Comparator<IndexTemplateMetaData>() { @Override public int compare(IndexTemplateMetaData o1, IndexTemplateMetaData o2) { return o2.order() - o1.order(); } }); return templates; } private void validate(CreateIndexClusterStateUpdateRequest request, ClusterState state) throws ElasticsearchException { validateIndexName(request.index(), state); } }
1no label
src_main_java_org_elasticsearch_cluster_metadata_MetaDataCreateIndexService.java
635
public class OIndexUnique extends OIndexOneValue { public OIndexUnique(String typeId, String algorithm, OIndexEngine<OIdentifiable> engine, String valueContainerAlgorithm) { super(typeId, algorithm, engine, valueContainerAlgorithm); } @Override public OIndexOneValue put(Object key, final OIdentifiable iSingleValue) { checkForRebuild(); key = getCollatingValue(key); modificationLock.requestModificationLock(); try { acquireExclusiveLock(); try { checkForKeyType(key); final OIdentifiable value = indexEngine.get(key); if (value != null) { // CHECK IF THE ID IS THE SAME OF CURRENT: THIS IS THE UPDATE CASE if (!value.equals(iSingleValue)) throw new ORecordDuplicatedException(String.format( "Cannot index record %s: found duplicated key '%s' in index '%s' previously assigned to the record %s", iSingleValue.getIdentity(), key, getName(), value.getIdentity()), value.getIdentity()); else return this; } if (!iSingleValue.getIdentity().isPersistent()) ((ORecord<?>) iSingleValue.getRecord()).save(); indexEngine.put(key, iSingleValue.getIdentity()); return this; } finally { releaseExclusiveLock(); } } finally { modificationLock.releaseModificationLock(); } } @Override protected void putInSnapshot(Object key, OIdentifiable value, Map<Object, Object> snapshot) { key = getCollatingValue(key); Object snapshotValue = snapshot.get(key); if (snapshotValue == null) { final OIdentifiable storedValue = indexEngine.get(key); final Set<OIdentifiable> values = new LinkedHashSet<OIdentifiable>(); if (storedValue != null) values.add(storedValue.getIdentity()); values.add(value.getIdentity()); snapshot.put(key, values); } else if (snapshotValue instanceof Set) { final Set<OIdentifiable> values = (Set<OIdentifiable>) snapshotValue; values.add(value.getIdentity()); } else { final Set<OIdentifiable> values = new LinkedHashSet<OIdentifiable>(); values.add(value); snapshot.put(key, values); } } @Override protected void removeFromSnapshot(Object key, OIdentifiable value, Map<Object, Object> snapshot) { key = getCollatingValue(key); Object snapshotValue = snapshot.get(key); if (snapshotValue instanceof Set) { final Set<OIdentifiable> values = (Set<OIdentifiable>) snapshotValue; if (values.isEmpty()) snapshot.put(key, RemovedValue.INSTANCE); else values.remove(value); } else snapshot.put(key, RemovedValue.INSTANCE); } @Override protected void commitSnapshot(Map<Object, Object> snapshot) { for (Map.Entry<Object, Object> snapshotEntry : snapshot.entrySet()) { Object key = snapshotEntry.getKey(); checkForKeyType(key); Object snapshotValue = snapshotEntry.getValue(); if (snapshotValue instanceof Set) { Set<OIdentifiable> values = (Set<OIdentifiable>) snapshotValue; if (values.isEmpty()) continue; final Iterator<OIdentifiable> valuesIterator = values.iterator(); if (values.size() > 1) { final OIdentifiable valueOne = valuesIterator.next(); final OIdentifiable valueTwo = valuesIterator.next(); throw new ORecordDuplicatedException(String.format( "Cannot index record %s: found duplicated key '%s' in index '%s' previously assigned to the record %s", valueTwo.getIdentity(), key, getName(), valueOne.getIdentity()), valueOne.getIdentity()); } final OIdentifiable value = valuesIterator.next(); indexEngine.put(key, value.getIdentity()); } else if (snapshotValue.equals(RemovedValue.INSTANCE)) indexEngine.remove(key); else assert false : "Provided value can not be committed"; } } @Override public boolean canBeUsedInEqualityOperators() { return true; } @Override public boolean supportsOrderedIterations() { return indexEngine.hasRangeQuerySupport(); } }
1no label
core_src_main_java_com_orientechnologies_orient_core_index_OIndexUnique.java
1,446
public class SnapshotMetaData implements MetaData.Custom { public static final String TYPE = "snapshots"; public static final Factory FACTORY = new Factory(); @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SnapshotMetaData that = (SnapshotMetaData) o; if (!entries.equals(that.entries)) return false; return true; } @Override public int hashCode() { return entries.hashCode(); } public static class Entry { private final State state; private final SnapshotId snapshotId; private final boolean includeGlobalState; private final ImmutableMap<ShardId, ShardSnapshotStatus> shards; private final ImmutableList<String> indices; public Entry(SnapshotId snapshotId, boolean includeGlobalState, State state, ImmutableList<String> indices, ImmutableMap<ShardId, ShardSnapshotStatus> shards) { this.state = state; this.snapshotId = snapshotId; this.includeGlobalState = includeGlobalState; this.indices = indices; if (shards == null) { this.shards = ImmutableMap.of(); } else { this.shards = shards; } } public SnapshotId snapshotId() { return this.snapshotId; } public ImmutableMap<ShardId, ShardSnapshotStatus> shards() { return this.shards; } public State state() { return state; } public ImmutableList<String> indices() { return indices; } public boolean includeGlobalState() { return includeGlobalState; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Entry entry = (Entry) o; if (includeGlobalState != entry.includeGlobalState) return false; if (!indices.equals(entry.indices)) return false; if (!shards.equals(entry.shards)) return false; if (!snapshotId.equals(entry.snapshotId)) return false; if (state != entry.state) return false; return true; } @Override public int hashCode() { int result = state.hashCode(); result = 31 * result + snapshotId.hashCode(); result = 31 * result + (includeGlobalState ? 1 : 0); result = 31 * result + shards.hashCode(); result = 31 * result + indices.hashCode(); return result; } } public static class ShardSnapshotStatus { private State state; private String nodeId; private String reason; private ShardSnapshotStatus() { } public ShardSnapshotStatus(String nodeId) { this(nodeId, State.INIT); } public ShardSnapshotStatus(String nodeId, State state) { this(nodeId, state, null); } public ShardSnapshotStatus(String nodeId, State state, String reason) { this.nodeId = nodeId; this.state = state; this.reason = reason; } public State state() { return state; } public String nodeId() { return nodeId; } public String reason() { return reason; } public static ShardSnapshotStatus readShardSnapshotStatus(StreamInput in) throws IOException { ShardSnapshotStatus shardSnapshotStatus = new ShardSnapshotStatus(); shardSnapshotStatus.readFrom(in); return shardSnapshotStatus; } public void readFrom(StreamInput in) throws IOException { nodeId = in.readOptionalString(); state = State.fromValue(in.readByte()); reason = in.readOptionalString(); } public void writeTo(StreamOutput out) throws IOException { out.writeOptionalString(nodeId); out.writeByte(state.value); out.writeOptionalString(reason); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ShardSnapshotStatus status = (ShardSnapshotStatus) o; if (nodeId != null ? !nodeId.equals(status.nodeId) : status.nodeId != null) return false; if (reason != null ? !reason.equals(status.reason) : status.reason != null) return false; if (state != status.state) return false; return true; } @Override public int hashCode() { int result = state != null ? state.hashCode() : 0; result = 31 * result + (nodeId != null ? nodeId.hashCode() : 0); result = 31 * result + (reason != null ? reason.hashCode() : 0); return result; } } public static enum State { INIT((byte) 0), STARTED((byte) 1), SUCCESS((byte) 2), FAILED((byte) 3), ABORTED((byte) 4), MISSING((byte) 5); private byte value; State(byte value) { this.value = value; } public byte value() { return value; } public boolean completed() { switch (this) { case INIT: return false; case STARTED: return false; case SUCCESS: return true; case FAILED: return true; case ABORTED: return false; case MISSING: return true; default: assert false; return true; } } public boolean failed() { switch (this) { case INIT: return false; case STARTED: return false; case SUCCESS: return false; case FAILED: return true; case ABORTED: return true; case MISSING: return true; default: assert false; return false; } } public static State fromValue(byte value) { switch (value) { case 0: return INIT; case 1: return STARTED; case 2: return SUCCESS; case 3: return FAILED; case 4: return ABORTED; case 5: return MISSING; default: throw new ElasticsearchIllegalArgumentException("No snapshot state for value [" + value + "]"); } } } private final ImmutableList<Entry> entries; public SnapshotMetaData(ImmutableList<Entry> entries) { this.entries = entries; } public SnapshotMetaData(Entry... entries) { this.entries = ImmutableList.copyOf(entries); } public ImmutableList<Entry> entries() { return this.entries; } public Entry snapshot(SnapshotId snapshotId) { for (Entry entry : entries) { if (snapshotId.equals(entry.snapshotId())) { return entry; } } return null; } public static class Factory implements MetaData.Custom.Factory<SnapshotMetaData> { @Override public String type() { return TYPE; //To change body of implemented methods use File | Settings | File Templates. } @Override public SnapshotMetaData readFrom(StreamInput in) throws IOException { Entry[] entries = new Entry[in.readVInt()]; for (int i = 0; i < entries.length; i++) { SnapshotId snapshotId = SnapshotId.readSnapshotId(in); boolean includeGlobalState = in.readBoolean(); State state = State.fromValue(in.readByte()); int indices = in.readVInt(); ImmutableList.Builder<String> indexBuilder = ImmutableList.builder(); for (int j = 0; j < indices; j++) { indexBuilder.add(in.readString()); } ImmutableMap.Builder<ShardId, ShardSnapshotStatus> builder = ImmutableMap.<ShardId, ShardSnapshotStatus>builder(); int shards = in.readVInt(); for (int j = 0; j < shards; j++) { ShardId shardId = ShardId.readShardId(in); String nodeId = in.readOptionalString(); State shardState = State.fromValue(in.readByte()); builder.put(shardId, new ShardSnapshotStatus(nodeId, shardState)); } entries[i] = new Entry(snapshotId, includeGlobalState, state, indexBuilder.build(), builder.build()); } return new SnapshotMetaData(entries); } @Override public void writeTo(SnapshotMetaData repositories, StreamOutput out) throws IOException { out.writeVInt(repositories.entries().size()); for (Entry entry : repositories.entries()) { entry.snapshotId().writeTo(out); out.writeBoolean(entry.includeGlobalState()); out.writeByte(entry.state().value()); out.writeVInt(entry.indices().size()); for (String index : entry.indices()) { out.writeString(index); } out.writeVInt(entry.shards().size()); for (Map.Entry<ShardId, ShardSnapshotStatus> shardEntry : entry.shards().entrySet()) { shardEntry.getKey().writeTo(out); out.writeOptionalString(shardEntry.getValue().nodeId()); out.writeByte(shardEntry.getValue().state().value()); } } } @Override public SnapshotMetaData fromXContent(XContentParser parser) throws IOException { throw new UnsupportedOperationException(); } @Override public void toXContent(SnapshotMetaData customIndexMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startArray("snapshots"); for (Entry entry : customIndexMetaData.entries()) { toXContent(entry, builder, params); } builder.endArray(); } public void toXContent(Entry entry, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(); builder.field("repository", entry.snapshotId().getRepository()); builder.field("snapshot", entry.snapshotId().getSnapshot()); builder.field("include_global_state", entry.includeGlobalState()); builder.field("state", entry.state()); builder.startArray("indices"); { for (String index : entry.indices()) { builder.value(index); } } builder.endArray(); builder.startArray("shards"); { for (Map.Entry<ShardId, ShardSnapshotStatus> shardEntry : entry.shards.entrySet()) { ShardId shardId = shardEntry.getKey(); ShardSnapshotStatus status = shardEntry.getValue(); builder.startObject(); { builder.field("index", shardId.getIndex()); builder.field("shard", shardId.getId()); builder.field("state", status.state()); builder.field("node", status.nodeId()); } builder.endObject(); } } builder.endArray(); builder.endObject(); } public boolean isPersistent() { return false; } } }
1no label
src_main_java_org_elasticsearch_cluster_metadata_SnapshotMetaData.java
485
executor.execute(new Runnable() { public void run() { try { callback.onResponse(serializationService.toObject(resolveResponse())); } catch (Throwable t) { callback.onFailure(t); } } });
1no label
hazelcast-client_src_main_java_com_hazelcast_client_spi_impl_ClientCallFuture.java
442
new Thread() { public void run() { while (true) { try { int size = q.size(); if (size > 50000) { System.err.println("cleaning a little"); for (int i = 0; i < 20000; i++) { q.poll(); totalPoll.incrementAndGet(); } Thread.sleep(2 * 1000); } else { Thread.sleep(10 * 1000); } } catch (InterruptedException e) { e.printStackTrace(); } } } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_queue_ClientQueuePerformanceTest.java
18
public static class TransactionCountPruneStrategy extends AbstractPruneStrategy { private final int maxTransactionCount; public TransactionCountPruneStrategy( FileSystemAbstraction fileSystem, int maxTransactionCount ) { super( fileSystem ); this.maxTransactionCount = maxTransactionCount; } @Override protected Threshold newThreshold() { return new Threshold() { private Long highest; @Override public boolean reached( File file, long version, LogLoader source ) { // Here we know that the log version exists (checked in AbstractPruneStrategy#prune) long tx = source.getFirstCommittedTxId( version ); if ( highest == null ) { highest = source.getLastCommittedTxId(); return false; } return highest-tx >= maxTransactionCount; } }; } }
1no label
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogPruneStrategies.java
609
public class BroadleafResourceHttpRequestBeanFactoryPostProcessor implements BeanFactoryPostProcessor { public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException { String[] names = factory.getBeanNamesForType(ResourceHttpRequestHandler.class); for (String name : names) { BeanDefinition bd = factory.getBeanDefinition(name); bd.setBeanClassName(BroadleafGWTModuleURLMappingResourceHttpRequestHandler.class.getName()); } } }
0true
common_src_main_java_org_broadleafcommerce_common_web_BroadleafResourceHttpRequestBeanFactoryPostProcessor.java
183
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class ClientListTest { static final String name = "test"; static HazelcastInstance hz; static IList list; @BeforeClass public static void init(){ Config config = new Config(); Hazelcast.newHazelcastInstance(config); hz = HazelcastClient.newHazelcastClient(); list = hz.getList(name); } @AfterClass public static void destroy() { hz.shutdown(); Hazelcast.shutdownAll(); } @Before @After public void clear() throws IOException { list.clear(); } @Test public void testAddAll() { List l = new ArrayList(); l.add("item1"); l.add("item2"); assertTrue(list.addAll(l)); assertEquals(2, list.size()); assertTrue(list.addAll(1, l)); assertEquals(4, list.size()); assertEquals("item1", list.get(0)); assertEquals("item1", list.get(1)); assertEquals("item2", list.get(2)); assertEquals("item2", list.get(3)); } @Test public void testAddSetRemove() { assertTrue(list.add("item1")); assertTrue(list.add("item2")); list.add(0,"item3"); assertEquals(3, list.size()); Object o = list.set(2, "item4"); assertEquals("item2", o); assertEquals(3, list.size()); assertEquals("item3", list.get(0)); assertEquals("item1", list.get(1)); assertEquals("item4", list.get(2)); assertFalse(list.remove("item2")); assertTrue(list.remove("item3")); o = list.remove(1); assertEquals("item4", o); assertEquals(1, list.size()); assertEquals("item1", list.get(0)); } @Test public void testIndexOf(){ assertTrue(list.add("item1")); assertTrue(list.add("item2")); assertTrue(list.add("item1")); assertTrue(list.add("item4")); assertEquals(-1, list.indexOf("item5")); assertEquals(0, list.indexOf("item1")); assertEquals(-1, list.lastIndexOf("item6")); assertEquals(2, list.lastIndexOf("item1")); } @Test public void testIterator(){ assertTrue(list.add("item1")); assertTrue(list.add("item2")); assertTrue(list.add("item1")); assertTrue(list.add("item4")); Iterator iter = list.iterator(); assertEquals("item1",iter.next()); assertEquals("item2",iter.next()); assertEquals("item1",iter.next()); assertEquals("item4",iter.next()); assertFalse(iter.hasNext()); ListIterator listIterator = list.listIterator(2); assertEquals("item1",listIterator.next()); assertEquals("item4",listIterator.next()); assertFalse(listIterator.hasNext()); List l = list.subList(1, 3); assertEquals(2, l.size()); assertEquals("item2", l.get(0)); assertEquals("item1", l.get(1)); } @Test public void testContains(){ assertTrue(list.add("item1")); assertTrue(list.add("item2")); assertTrue(list.add("item1")); assertTrue(list.add("item4")); assertFalse(list.contains("item3")); assertTrue(list.contains("item2")); List l = new ArrayList(); l.add("item4"); l.add("item3"); assertFalse(list.containsAll(l)); assertTrue(list.add("item3")); assertTrue(list.containsAll(l)); } @Test public void removeRetainAll(){ assertTrue(list.add("item1")); assertTrue(list.add("item2")); assertTrue(list.add("item1")); assertTrue(list.add("item4")); List l = new ArrayList(); l.add("item4"); l.add("item3"); assertTrue(list.removeAll(l)); assertEquals(3, list.size()); assertFalse(list.removeAll(l)); assertEquals(3, list.size()); l.clear(); l.add("item1"); l.add("item2"); assertFalse(list.retainAll(l)); assertEquals(3, list.size()); l.clear(); assertTrue(list.retainAll(l)); assertEquals(0, list.size()); } @Test public void testListener() throws Exception { // final ISet tempSet = server.getSet(name); final IList tempList = list; final CountDownLatch latch = new CountDownLatch(6); ItemListener listener = new ItemListener() { public void itemAdded(ItemEvent itemEvent) { latch.countDown(); } public void itemRemoved(ItemEvent item) { } }; String registrationId = tempList.addItemListener(listener, true); new Thread(){ public void run() { for (int i=0; i<5; i++){ tempList.add("item" + i); } tempList.add("done"); } }.start(); assertTrue(latch.await(20, TimeUnit.SECONDS)); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_collections_ClientListTest.java
510
public class FixedTimeSource implements TimeSource { private final long timeInMillis; public FixedTimeSource(long timeInMillis) { this.timeInMillis = timeInMillis; } public long timeInMillis() { return timeInMillis; } }
0true
common_src_main_java_org_broadleafcommerce_common_time_FixedTimeSource.java
1,524
private class ProductOptionDTO { private Long id; private String type; private Map<Long, String> values; private String selectedValue; @SuppressWarnings("unused") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @SuppressWarnings("unused") public String getType() { return type; } public void setType(String type) { this.type = type; } @SuppressWarnings("unused") public Map<Long, String> getValues() { return values; } public void setValues(Map<Long, String> values) { this.values = values; } @SuppressWarnings("unused") public String getSelectedValue() { return selectedValue; } @SuppressWarnings("unused") public void setSelectedValue(String selectedValue) { this.selectedValue = selectedValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ProductOptionDTO)) return false; ProductOptionDTO that = (ProductOptionDTO) o; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (selectedValue != null ? !selectedValue.equals(that.selectedValue) : that.selectedValue != null) return false; if (type != null ? !type.equals(that.type) : that.type != null) return false; if (values != null ? !values.equals(that.values) : that.values != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (values != null ? values.hashCode() : 0); result = 31 * result + (selectedValue != null ? selectedValue.hashCode() : 0); return result; } }
1no label
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_processor_ProductOptionsProcessor.java
736
public class IndexDeleteByQueryResponse extends ActionResponse { private String index; private int successfulShards; private int failedShards; private ShardOperationFailedException[] failures; IndexDeleteByQueryResponse(String index, int successfulShards, int failedShards, List<ShardOperationFailedException> failures) { this.index = index; this.successfulShards = successfulShards; this.failedShards = failedShards; if (failures == null || failures.isEmpty()) { this.failures = new DefaultShardOperationFailedException[0]; } else { this.failures = failures.toArray(new ShardOperationFailedException[failures.size()]); } } IndexDeleteByQueryResponse() { } /** * The index the delete by query operation was executed against. */ public String getIndex() { return this.index; } /** * The total number of shards the delete by query was executed on. */ public int getTotalShards() { return failedShards + successfulShards; } /** * The successful number of shards the delete by query was executed on. */ public int getSuccessfulShards() { return successfulShards; } /** * The failed number of shards the delete by query was executed on. */ public int getFailedShards() { return failedShards; } public ShardOperationFailedException[] getFailures() { return failures; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); index = in.readString(); successfulShards = in.readVInt(); failedShards = in.readVInt(); int size = in.readVInt(); failures = new ShardOperationFailedException[size]; for (int i = 0; i < size; i++) { failures[i] = DefaultShardOperationFailedException.readShardOperationFailed(in); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(index); out.writeVInt(successfulShards); out.writeVInt(failedShards); out.writeVInt(failures.length); for (ShardOperationFailedException failure : failures) { failure.writeTo(out); } } }
0true
src_main_java_org_elasticsearch_action_deletebyquery_IndexDeleteByQueryResponse.java
1,420
public static class RemoveRequest { final String name; TimeValue masterTimeout = MasterNodeOperationRequest.DEFAULT_MASTER_NODE_TIMEOUT; public RemoveRequest(String name) { this.name = name; } public RemoveRequest masterTimeout(TimeValue masterTimeout) { this.masterTimeout = masterTimeout; return this; } }
0true
src_main_java_org_elasticsearch_cluster_metadata_MetaDataIndexTemplateService.java
140
@Test public class DateTimeSerializerTest { private final static int FIELD_SIZE = 8; private static final Date OBJECT = new Date(); private ODateTimeSerializer dateTimeSerializer; private static final byte[] stream = new byte[FIELD_SIZE]; @BeforeClass public void beforeClass() { dateTimeSerializer = new ODateTimeSerializer(); } public void testFieldSize() { Assert.assertEquals(dateTimeSerializer.getObjectSize(OBJECT), FIELD_SIZE); } public void testSerialize() { dateTimeSerializer.serialize(OBJECT, stream, 0); Assert.assertEquals(dateTimeSerializer.deserialize(stream, 0), OBJECT); } public void testSerializeNative() { dateTimeSerializer.serializeNative(OBJECT, stream, 0); Assert.assertEquals(dateTimeSerializer.deserializeNative(stream, 0), OBJECT); } public void testNativeDirectMemoryCompatibility() { dateTimeSerializer.serializeNative(OBJECT, stream, 0); ODirectMemoryPointer pointer = new ODirectMemoryPointer(stream); try { Assert.assertEquals(dateTimeSerializer.deserializeFromDirectMemory(pointer, 0), OBJECT); } finally { pointer.free(); } } }
0true
commons_src_test_java_com_orientechnologies_common_serialization_types_DateTimeSerializerTest.java
362
public class DeleteRepositoryAction extends ClusterAction<DeleteRepositoryRequest, DeleteRepositoryResponse, DeleteRepositoryRequestBuilder> { public static final DeleteRepositoryAction INSTANCE = new DeleteRepositoryAction(); public static final String NAME = "cluster/repository/delete"; private DeleteRepositoryAction() { super(NAME); } @Override public DeleteRepositoryResponse newResponse() { return new DeleteRepositoryResponse(); } @Override public DeleteRepositoryRequestBuilder newRequestBuilder(ClusterAdminClient client) { return new DeleteRepositoryRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_repositories_delete_DeleteRepositoryAction.java
1,447
static private class EvictionEntry implements Comparable<EvictionEntry> { final Object key; final Value value; private EvictionEntry(final Object key, final Value value) { this.key = key; this.value = value; } public int compareTo(final EvictionEntry o) { final long thisVal = this.value.getCreationTime(); final long anotherVal = o.value.getCreationTime(); return (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EvictionEntry that = (EvictionEntry) o; if (key != null ? !key.equals(that.key) : that.key != null) return false; if (value != null ? !value.equals(that.value) : that.value != null) return false; return true; } @Override public int hashCode() { return key != null ? key.hashCode() : 0; } }
1no label
hazelcast-hibernate_hazelcast-hibernate3_src_main_java_com_hazelcast_hibernate_local_LocalRegionCache.java
197
public class UniqueTokenFilterTests extends ElasticsearchTestCase { @Test public void simpleTest() throws IOException { Analyzer analyzer = new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName, Reader reader) { Tokenizer t = new WhitespaceTokenizer(Lucene.VERSION, reader); return new TokenStreamComponents(t, new UniqueTokenFilter(t)); } }; TokenStream test = analyzer.tokenStream("test", "this test with test"); test.reset(); CharTermAttribute termAttribute = test.addAttribute(CharTermAttribute.class); assertThat(test.incrementToken(), equalTo(true)); assertThat(termAttribute.toString(), equalTo("this")); assertThat(test.incrementToken(), equalTo(true)); assertThat(termAttribute.toString(), equalTo("test")); assertThat(test.incrementToken(), equalTo(true)); assertThat(termAttribute.toString(), equalTo("with")); assertThat(test.incrementToken(), equalTo(false)); } }
0true
src_test_java_org_apache_lucene_analysis_miscellaneous_UniqueTokenFilterTests.java
303
static class DumPredicate implements Predicate { public boolean apply(Map.Entry mapEntry) { return false; } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapBasicTest.java
368
public interface OLazyObjectListInterface<TYPE> extends List<TYPE> { public void setConvertToRecord(boolean convertToRecord); public boolean isConverted(); }
0true
core_src_main_java_com_orientechnologies_orient_core_db_object_OLazyObjectListInterface.java
921
@Service("blItemOfferProcessor") public class ItemOfferProcessorImpl extends OrderOfferProcessorImpl implements ItemOfferProcessor { protected static final Log LOG = LogFactory.getLog(ItemOfferProcessorImpl.class); /* (non-Javadoc) * @see org.broadleafcommerce.core.offer.service.processor.ItemOfferProcessor#filterItemLevelOffer(org.broadleafcommerce.core.order.domain.Order, java.util.List, java.util.List, org.broadleafcommerce.core.offer.domain.Offer) */ @Override public void filterItemLevelOffer(PromotableOrder order, List<PromotableCandidateItemOffer> qualifiedItemOffers, Offer offer) { boolean isNewFormat = !CollectionUtils.isEmpty(offer.getQualifyingItemCriteria()) || !CollectionUtils.isEmpty(offer.getTargetItemCriteria()); boolean itemLevelQualification = false; boolean offerCreated = false; for (PromotableOrderItem promotableOrderItem : order.getDiscountableOrderItems()) { if(couldOfferApplyToOrder(offer, order, promotableOrderItem)) { if (!isNewFormat) { //support legacy offers PromotableCandidateItemOffer candidate = createCandidateItemOffer(qualifiedItemOffers, offer, order); if (!candidate.getLegacyCandidateTargets().contains(promotableOrderItem)) { candidate.getLegacyCandidateTargets().add(promotableOrderItem); } offerCreated = true; continue; } itemLevelQualification = true; break; } for (PromotableFulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) { if(couldOfferApplyToOrder(offer, order, promotableOrderItem, fulfillmentGroup)) { if (!isNewFormat) { //support legacy offers PromotableCandidateItemOffer candidate = createCandidateItemOffer(qualifiedItemOffers, offer, order); if (!candidate.getLegacyCandidateTargets().contains(promotableOrderItem)) { candidate.getLegacyCandidateTargets().add(promotableOrderItem); } offerCreated = true; continue; } itemLevelQualification = true; break; } } } //Item Qualification - new for 1.5! if (itemLevelQualification && !offerCreated) { CandidatePromotionItems candidates = couldOfferApplyToOrderItems(offer, order.getDiscountableOrderItems(offer.getApplyDiscountToSalePrice())); PromotableCandidateItemOffer candidateOffer = null; if (candidates.isMatchedQualifier()) { //we don't know the final target yet, so put null for the order item for now candidateOffer = createCandidateItemOffer(qualifiedItemOffers, offer, order); candidateOffer.getCandidateQualifiersMap().putAll(candidates.getCandidateQualifiersMap()); } if (candidates.isMatchedTarget() && candidates.isMatchedQualifier()) { if (candidateOffer == null) { //we don't know the final target yet, so put null for the order item for now candidateOffer = createCandidateItemOffer(qualifiedItemOffers, offer, order); } candidateOffer.getCandidateTargetsMap().putAll(candidates.getCandidateTargetsMap()); } } } /** * Create a candidate item offer based on the offer in question and a specific order item * * @param qualifiedItemOffers the container list for candidate item offers * @param offer the offer in question * @return the candidate item offer */ protected PromotableCandidateItemOffer createCandidateItemOffer(List<PromotableCandidateItemOffer> qualifiedItemOffers, Offer offer, PromotableOrder promotableOrder) { PromotableCandidateItemOffer promotableCandidateItemOffer = promotableItemFactory.createPromotableCandidateItemOffer(promotableOrder, offer); qualifiedItemOffers.add(promotableCandidateItemOffer); return promotableCandidateItemOffer; } /* (non-Javadoc) * @see org.broadleafcommerce.core.offer.service.processor.ItemOfferProcessor#applyAllItemOffers(java.util.List, java.util.List) */ @Override public void applyAllItemOffers(List<PromotableCandidateItemOffer> itemOffers, PromotableOrder order) { // Iterate through the collection of CandidateItemOffers. Remember that each one is an offer that may apply to a // particular OrderItem. Multiple CandidateItemOffers may contain a reference to the same OrderItem object. // The same offer may be applied to different Order Items for (PromotableCandidateItemOffer itemOffer : itemOffers) { if (offerMeetsSubtotalRequirements(order, itemOffer)) { applyItemOffer(order, itemOffer); } } } protected boolean offerMeetsSubtotalRequirements(PromotableOrder order, PromotableCandidateItemOffer itemOffer) { if (itemOffer.getOffer().getQualifyingItemSubTotal() == null || itemOffer.getOffer().getQualifyingItemSubTotal().lessThanOrEqual(Money.ZERO)) { return true; } //TODO: Check subtotal requirement before continuing return false; } protected boolean isTotalitarianOfferAppliedToAnyItem(PromotableOrder order) { List<PromotableOrderItemPriceDetail> allPriceDetails = order.getAllPromotableOrderItemPriceDetails(); for (PromotableOrderItemPriceDetail targetItem : allPriceDetails) { if (targetItem.isTotalitarianOfferApplied()) { return true; } } return false; } /** * Private method used by applyAdjustments to create an OrderItemAdjustment from a CandidateOrderOffer * and associates the OrderItemAdjustment to the OrderItem. * * @param orderOffer a CandidateOrderOffer to apply to an Order */ protected void applyOrderItemAdjustment(PromotableCandidateItemOffer itemOffer, PromotableOrderItemPriceDetail itemPriceDetail) { PromotableOrderItemPriceDetailAdjustment promotableOrderItemPriceDetailAdjustment = promotableItemFactory.createPromotableOrderItemPriceDetailAdjustment(itemOffer, itemPriceDetail); itemPriceDetail.addCandidateItemPriceDetailAdjustment(promotableOrderItemPriceDetailAdjustment); } /** * The itemOffer has been qualified and prior methods added PromotionDiscount objects onto the ItemPriceDetail. * This code will convert the PromotionDiscounts into Adjustments * @param order * @param itemOffer */ protected void applyAdjustments(PromotableOrder order, PromotableCandidateItemOffer itemOffer) { List<PromotableOrderItemPriceDetail> itemPriceDetails = order.getAllPromotableOrderItemPriceDetails(); for (PromotableOrderItemPriceDetail itemPriceDetail : itemPriceDetails) { for (PromotionDiscount discount : itemPriceDetail.getPromotionDiscounts()) { if (discount.getPromotion().equals(itemOffer.getOffer())) { if (itemOffer.getOffer().isTotalitarianOffer() || !itemOffer.getOffer().isCombinableWithOtherOffers()) { // We've decided to apply this adjustment but if it doesn't actually reduce // the value of the item if (adjustmentIsNotGoodEnoughToBeApplied(itemOffer, itemPriceDetail)) { break; } } applyOrderItemAdjustment(itemOffer, itemPriceDetail); break; } } } } /** * Legacy adjustments use the stackable flag instead of item qualifiers and targets * @param order * @param itemOffer */ protected void applyLegacyAdjustments(PromotableOrder order, PromotableCandidateItemOffer itemOffer) { for (PromotableOrderItem item : itemOffer.getLegacyCandidateTargets()) { for (PromotableOrderItemPriceDetail itemPriceDetail : item.getPromotableOrderItemPriceDetails()) { if (!itemOffer.getOffer().isStackable() || !itemOffer.getOffer().isCombinableWithOtherOffers()) { if (itemPriceDetail.getCandidateItemAdjustments().size() != 0) { continue; } } else { if (itemPriceDetail.hasNonCombinableAdjustments()) { continue; } } applyOrderItemAdjustment(itemOffer, itemPriceDetail); } } } /** * The adjustment might not be better than the sale price. * @param itemOffer * @param detail * @return */ protected boolean adjustmentIsNotGoodEnoughToBeApplied(PromotableCandidateItemOffer itemOffer, PromotableOrderItemPriceDetail detail) { if (!itemOffer.getOffer().getApplyDiscountToSalePrice()) { Money salePrice = detail.getPromotableOrderItem().getSalePriceBeforeAdjustments(); Money retailPrice = detail.getPromotableOrderItem().getRetailPriceBeforeAdjustments(); Money savings = itemOffer.calculateSavingsForOrderItem(detail.getPromotableOrderItem(), 1); if (salePrice != null) { if (salePrice.lessThan(retailPrice.subtract(savings))) { // Not good enough return true; } } } return false; } /** * Return false if a totalitarian offer has already been applied and this order already has * item adjustments. * * @param order * @param itemOffer * @return */ protected boolean itemOfferCanBeApplied(PromotableOrder order, PromotableCandidateItemOffer itemOffer) { for (PromotableOrderItemPriceDetail detail : order.getAllPromotableOrderItemPriceDetails()) { for (PromotableOrderItemPriceDetailAdjustment adjustment : detail.getCandidateItemAdjustments()) { if (adjustment.isTotalitarian() || itemOffer.getOffer().isTotalitarianOffer()) { // A totalitarian offer has already been applied or this offer is totalitarian // and another offer was already applied. return false; } else if (itemOffer.isLegacyOffer()) { continue; } else if (!adjustment.isCombinable() || !itemOffer.getOffer().isCombinableWithOtherOffers()) { // A nonCombinable offer has been applied or this is a non-combinable offer // and adjustments have already been applied. return false; } } } return true; } protected void applyItemOffer(PromotableOrder order, PromotableCandidateItemOffer itemOffer) { if (itemOfferCanBeApplied(order, itemOffer)) { applyItemQualifiersAndTargets(itemOffer, order); if (itemOffer.isLegacyOffer()) { applyLegacyAdjustments(order, itemOffer); } else { applyAdjustments(order, itemOffer); } } } /** * Some promotions can only apply to the retail price. This method determines whether * retailPrice only promotions should be used instead of those that can apply to the sale * price as well. * * @param order * @return */ protected void chooseSaleOrRetailAdjustments(PromotableOrder order) { List<PromotableOrderItemPriceDetail> itemPriceDetails = order.getAllPromotableOrderItemPriceDetails(); for (PromotableOrderItemPriceDetail itemDetail : itemPriceDetails) { itemDetail.chooseSaleOrRetailAdjustments(); } mergePriceDetails(order); } /** * Checks to see if any priceDetails need to be combined and if so, combines them. * * @param order * @return */ protected void mergePriceDetails(PromotableOrder order) { List<PromotableOrderItem> items = order.getAllOrderItems(); for (PromotableOrderItem item : items) { item.mergeLikeDetails(); } } protected void applyItemQualifiersAndTargets(PromotableCandidateItemOffer itemOffer, PromotableOrder order) { if (itemOffer.isLegacyOffer()) { LOG.warn("The item offer with id " + itemOffer.getOffer().getId() + " is a legacy offer which means that it" + " does not have any item qualifier criteria AND does not have any target item criteria. As a result," + " we are skipping the marking of qualifiers and targets which will cause issues if you are relying on" + " 'maxUsesPerOrder' behavior. To resolve this, qualifier criteria is not required but you must at least" + " create some target item criteria for this offer."); return; } else { markQualifiersAndTargets(order, itemOffer); splitDetailsIfNecessary(order.getAllPromotableOrderItemPriceDetails()); } } protected List<PromotableOrderItemPriceDetail> buildPriceDetailListFromOrderItems(List<PromotableOrderItem> items) { List<PromotableOrderItemPriceDetail> itemPriceDetails = new ArrayList<PromotableOrderItemPriceDetail>(); for (PromotableOrderItem item : items) { for (PromotableOrderItemPriceDetail detail : item.getPromotableOrderItemPriceDetails()) { itemPriceDetails.add(detail); } } return itemPriceDetails; } /** * Loop through ItemCriteria and mark qualifiers required to give the promotion to 1 or more targets. * @param itemOffer * @param order * @return */ protected boolean markQualifiers(PromotableCandidateItemOffer itemOffer, PromotableOrder order) { for (OfferItemCriteria itemCriteria : itemOffer.getCandidateQualifiersMap().keySet()) { List<PromotableOrderItem> promotableItems = itemOffer.getCandidateQualifiersMap().get(itemCriteria); List<PromotableOrderItemPriceDetail> priceDetails = buildPriceDetailListFromOrderItems(promotableItems); Collections.sort(priceDetails, getQualifierItemComparator(itemOffer.getOffer().getApplyDiscountToSalePrice())); // Calculate the number of qualifiers needed that will not receive the promotion. // These will be reserved first before the target is assigned. int qualifierQtyNeeded = itemCriteria.getQuantity(); for (PromotableOrderItemPriceDetail detail : priceDetails) { // Mark Qualifiers if (qualifierQtyNeeded > 0) { int itemQtyAvailableToBeUsedAsQualifier = detail.getQuantityAvailableToBeUsedAsQualifier(itemOffer); if (itemQtyAvailableToBeUsedAsQualifier > 0) { int qtyToMarkAsQualifier = Math.min(qualifierQtyNeeded, itemQtyAvailableToBeUsedAsQualifier); qualifierQtyNeeded -= qtyToMarkAsQualifier; detail.addPromotionQualifier(itemOffer, itemCriteria, qtyToMarkAsQualifier); } } if (qualifierQtyNeeded == 0) { break; } } if (qualifierQtyNeeded != 0) { return false; } } return true; } /** * Loop through ItemCriteria and mark targets that can get this promotion to give the promotion to 1 or more targets. * @param itemOffer * @param order * @return */ protected boolean markTargets(PromotableCandidateItemOffer itemOffer, PromotableOrder order) { Offer promotion = itemOffer.getOffer(); if (itemOffer.getCandidateTargetsMap().keySet().isEmpty()) { return false; } for (OfferItemCriteria itemCriteria : itemOffer.getCandidateTargetsMap().keySet()) { List<PromotableOrderItem> promotableItems = itemOffer.getCandidateTargetsMap().get(itemCriteria); List<PromotableOrderItemPriceDetail> priceDetails = buildPriceDetailListFromOrderItems(promotableItems); Collections.sort(priceDetails, getTargetItemComparator(itemOffer.getOffer().getApplyDiscountToSalePrice())); int targetQtyNeeded = itemCriteria.getQuantity(); for (PromotableOrderItemPriceDetail detail : priceDetails) { int itemQtyAvailableToBeUsedAsTarget = detail.getQuantityAvailableToBeUsedAsTarget(itemOffer); if (itemQtyAvailableToBeUsedAsTarget > 0) { if (promotion.isUnlimitedUsePerOrder() || (itemOffer.getUses() < promotion.getMaxUsesPerOrder())) { int qtyToMarkAsTarget = Math.min(targetQtyNeeded, itemQtyAvailableToBeUsedAsTarget); targetQtyNeeded -= qtyToMarkAsTarget; detail.addPromotionDiscount(itemOffer, itemCriteria, qtyToMarkAsTarget); } } if (targetQtyNeeded == 0) { break; } } if (targetQtyNeeded != 0) { return false; } } itemOffer.addUse(); return true; } /** * Used in {@link #applyItemQualifiersAndTargets(PromotableCandidateItemOffer, PromotableOrder)} allow for customized * sorting for which qualifier items should be attempted to be used first for a promotion. Default behavior * is to sort descending, so higher-value items are attempted to be qualified first. * * @param applyToSalePrice - whether or not the Comparator should use the sale price for comparison * @return */ protected Comparator<PromotableOrderItemPriceDetail> getQualifierItemComparator(final boolean applyToSalePrice) { return new Comparator<PromotableOrderItemPriceDetail>() { @Override public int compare(PromotableOrderItemPriceDetail o1, PromotableOrderItemPriceDetail o2) { Money price = o1.getPromotableOrderItem().getPriceBeforeAdjustments(applyToSalePrice); Money price2 = o2.getPromotableOrderItem().getPriceBeforeAdjustments(applyToSalePrice); // highest amount first return price2.compareTo(price); } }; } /** * <p> * Used in {@link #applyItemQualifiersAndTargets(PromotableCandidateItemOffer, PromotableOrder)} allow for customized * sorting for which target items the promotion should be attempted to be applied to first. Default behavior is to * sort descending, so higher-value items get the promotion over lesser-valued items. * </p> * <p> * Note: By default, both the {@link #getQualifierItemComparator(boolean)} and this target comparator are sorted * in descending order. This means that higher-valued items can be paired with higher-valued items and lower-valued * items can be paired with lower-valued items. This also ensures that you will <b>not</b> have the scenario where 2 * lower-valued items can be used to qualify a higher-valued target. * </p> * * @param applyToSalePrice - whether or not the Comparator should use the sale price for comparison * @return */ protected Comparator<PromotableOrderItemPriceDetail> getTargetItemComparator(final boolean applyToSalePrice) { return new Comparator<PromotableOrderItemPriceDetail>() { @Override public int compare(PromotableOrderItemPriceDetail o1, PromotableOrderItemPriceDetail o2) { Money price = o1.getPromotableOrderItem().getPriceBeforeAdjustments(applyToSalePrice); Money price2 = o2.getPromotableOrderItem().getPriceBeforeAdjustments(applyToSalePrice); // highest amount first return price2.compareTo(price); } }; } @Override public void filterOffers(PromotableOrder order, List<Offer> filteredOffers, List<PromotableCandidateOrderOffer> qualifiedOrderOffers, List<PromotableCandidateItemOffer> qualifiedItemOffers) { // set order subTotal price to total item price without adjustments order.setOrderSubTotalToPriceWithoutAdjustments(); for (Offer offer : filteredOffers) { if(offer.getType().equals(OfferType.ORDER)){ filterOrderLevelOffer(order, qualifiedOrderOffers, offer); } else if(offer.getType().equals(OfferType.ORDER_ITEM)){ filterItemLevelOffer(order, qualifiedItemOffers, offer); } } } /** * This method determines the potential savings for each item offer as if it was the only item offer being applied. * @param itemOffers * @param order */ protected void calculatePotentialSavings(List<PromotableCandidateItemOffer> itemOffers, PromotableOrder order) { if (itemOffers.size() > 1) { for (PromotableCandidateItemOffer itemOffer : itemOffers) { Money potentialSavings = new Money(order.getOrderCurrency()); if (itemOffer.isLegacyOffer()) { for (PromotableOrderItem item : itemOffer.getLegacyCandidateTargets()) { potentialSavings = potentialSavings.add( itemOffer.calculateSavingsForOrderItem(item, item.getQuantity())); } } else { markQualifiersAndTargets(order, itemOffer); for (PromotableOrderItemPriceDetail detail : order.getAllPromotableOrderItemPriceDetails()) { PromotableOrderItem item = detail.getPromotableOrderItem(); for (PromotionDiscount discount : detail.getPromotionDiscounts()) { potentialSavings = potentialSavings.add( itemOffer.calculateSavingsForOrderItem(item, discount.getQuantity())); } // Reset state back for next offer detail.getPromotionDiscounts().clear(); detail.getPromotionQualifiers().clear(); } } itemOffer.setPotentialSavings(potentialSavings); } } } protected void markQualifiersAndTargets(PromotableOrder order, PromotableCandidateItemOffer itemOffer) { boolean matchFound = true; if (itemOffer.isLegacyOffer()) { return; } int count = 1; do { boolean qualifiersFound = markQualifiers(itemOffer, order); boolean targetsFound = markTargets(itemOffer, order); if (qualifiersFound && targetsFound) { finalizeQuantities(order.getAllPromotableOrderItemPriceDetails()); } else { clearAllNonFinalizedQuantities(order.getAllPromotableOrderItemPriceDetails()); matchFound = false; break; } // If we found a match, try again to see if the promotion can be applied again. } while (matchFound); } protected boolean offerListStartsWithNonCombinable(List<PromotableCandidateItemOffer> offerList) { if (offerList.size() > 1) { PromotableCandidateItemOffer offer = offerList.get(0); if (offer.getOffer().isTotalitarianOffer() || !offer.getOffer().isCombinableWithOtherOffers()) { return true; } } return false; } /** * This method could be overridden to potentially run all permutations of offers. * A reasonable alternative is to have a permutation with nonCombinable offers * and another with combinable offers. * * @param offers * @return */ protected List<List<PromotableCandidateItemOffer>> buildItemOfferPermutations( List<PromotableCandidateItemOffer> offers) { List<List<PromotableCandidateItemOffer>> listOfOfferLists = new ArrayList<List<PromotableCandidateItemOffer>>(); // add the default list listOfOfferLists.add(offers); if (offerListStartsWithNonCombinable(offers)) { List<PromotableCandidateItemOffer> listWithoutTotalitarianOrNonCombinables = new ArrayList<PromotableCandidateItemOffer>(offers); Iterator<PromotableCandidateItemOffer> offerIterator = listWithoutTotalitarianOrNonCombinables.iterator(); while (offerIterator.hasNext()) { PromotableCandidateItemOffer offer = offerIterator.next(); if (offer.getOffer().isTotalitarianOffer() || !offer.getOffer().isCombinableWithOtherOffers()) { offerIterator.remove(); } } if (listWithoutTotalitarianOrNonCombinables.size() > 0) { listOfOfferLists.add(listWithoutTotalitarianOrNonCombinables); } } return listOfOfferLists; } protected void determineBestPermutation(List<PromotableCandidateItemOffer> itemOffers, PromotableOrder order) { List<List<PromotableCandidateItemOffer>> permutations = buildItemOfferPermutations(itemOffers); List<PromotableCandidateItemOffer> bestOfferList = null; Money lowestSubtotal = null; if (permutations.size() > 1) { for (List<PromotableCandidateItemOffer> offerList : permutations) { applyAllItemOffers(offerList, order); chooseSaleOrRetailAdjustments(order); Money testSubtotal = order.calculateSubtotalWithAdjustments(); if (lowestSubtotal == null || testSubtotal.lessThan(lowestSubtotal)) { lowestSubtotal = testSubtotal; bestOfferList = offerList; } // clear price details for (PromotableOrderItem item : order.getDiscountableOrderItems()) { item.resetPriceDetails(); } } } else { bestOfferList = permutations.get(0); } applyAllItemOffers(bestOfferList, order); } @Override @SuppressWarnings("unchecked") public void applyAndCompareOrderAndItemOffers(PromotableOrder order, List<PromotableCandidateOrderOffer> qualifiedOrderOffers, List<PromotableCandidateItemOffer> qualifiedItemOffers) { if (!qualifiedItemOffers.isEmpty()) { calculatePotentialSavings(qualifiedItemOffers, order); //after savings have been calculated, uses will have been marked on offers which can effect //the actual application of those offers. Thus the uses for each item offer needs to be reset for (PromotableCandidateItemOffer itemOffer : qualifiedItemOffers) { itemOffer.resetUses(); } // Sort order item offers by priority and potential total discount Collections.sort(qualifiedItemOffers, ItemOfferComparator.INSTANCE); if (qualifiedItemOffers.size() > 1) { determineBestPermutation(qualifiedItemOffers, order); } else { applyAllItemOffers(qualifiedItemOffers, order); } } chooseSaleOrRetailAdjustments(order); order.setOrderSubTotalToPriceWithAdjustments(); if (!qualifiedOrderOffers.isEmpty()) { // Sort order offers by priority and discount Collections.sort(qualifiedOrderOffers, OrderOfferComparator.INSTANCE); //qualifiedOrderOffers = removeTrailingNotCombinableOrderOffers(qualifiedOrderOffers); applyAllOrderOffers(qualifiedOrderOffers, order); } order.setOrderSubTotalToPriceWithAdjustments(); // TODO: only do this if absolutely required. If you find one that no longer qualifies, then // pull it out and reapply. if (!qualifiedOrderOffers.isEmpty() && !qualifiedItemOffers.isEmpty()) { List<PromotableCandidateOrderOffer> finalQualifiedOrderOffers = new ArrayList<PromotableCandidateOrderOffer>(); order.removeAllCandidateOrderOfferAdjustments(); for (PromotableCandidateOrderOffer candidateOrderOffer : qualifiedOrderOffers) { // recheck the list of order offers and verify if they still apply with the new subtotal /* * Note - there is an edge case possibility where this logic would miss an order promotion * that had a subtotal requirement that was missed because of item deductions, but without * the item deductions, the order promotion would have been included and ended up giving the * customer a better deal than the item deductions. */ if (couldOfferApplyToOrder(candidateOrderOffer.getOffer(), order)) { finalQualifiedOrderOffers.add(candidateOrderOffer); } } // Sort order offers by priority and discount Collections.sort(finalQualifiedOrderOffers, OrderOfferComparator.INSTANCE); if (!finalQualifiedOrderOffers.isEmpty()) { applyAllOrderOffers(finalQualifiedOrderOffers, order); order.setOrderSubTotalToPriceWithAdjustments(); } } } /** * Gets rid of totalitarian and nonCombinable item offers that can't possibly be applied. * @param qualifiedItemOffers */ private void removeTrailingNonCombinableOrTotalitarianOffers(List<PromotableCandidateItemOffer> qualifiedItemOffers) { boolean first = true; Iterator<PromotableCandidateItemOffer> offerIterator = qualifiedItemOffers.iterator(); if (offerIterator.hasNext()) { // ignore the first one. offerIterator.next(); } while (offerIterator.hasNext()) { PromotableCandidateItemOffer itemOffer = offerIterator.next(); if (itemOffer.getOffer().isTotalitarianOffer()) { // Remove Totalitarian offers that aren't the first offer. offerIterator.remove(); } else { if (!itemOffer.isLegacyOffer() && !itemOffer.getOffer().isCombinableWithOtherOffers()) { // Remove nonCombinable offers that aren't the first offer offerIterator.remove(); } } } } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_processor_ItemOfferProcessorImpl.java
1,355
ShardFailedTransportHandler.ACTION, shardRoutingEntry, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleException(TransportException exp) { logger.warn("failed to send failed shard to [{}]", exp, clusterService.state().nodes().masterNode()); } });
0true
src_main_java_org_elasticsearch_cluster_action_shard_ShardStateAction.java
347
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class ClientSortLimitTest extends HazelcastTestSupport { static HazelcastInstance client; static IMap map; static int pageSize = 5; static int size = 50; @BeforeClass public static void createInstances(){ Hazelcast.newHazelcastInstance(); Hazelcast.newHazelcastInstance(); client = HazelcastClient.newHazelcastClient(); } @AfterClass public static void shutdownInstances(){ HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } @Before public void init(){ map = client.getMap(randomString()); for (int i = 0; i < size; i++) { map.put(i, i); } } @After public void reset(){ map.destroy(); } @Test public void testWithoutAnchor() { final PagingPredicate predicate = new PagingPredicate(pageSize); predicate.nextPage(); predicate.nextPage(); Collection<Integer> values = map.values(predicate); assertIterableEquals(values, 10, 11, 12, 13, 14); predicate.previousPage(); values = map.values(predicate); assertIterableEquals(values, 5, 6, 7, 8, 9); predicate.previousPage(); values = map.values(predicate); assertIterableEquals(values, 0, 1, 2, 3, 4); } @Test public void testGoTo_previousPage_BeforeTheStart() { final PagingPredicate predicate = new PagingPredicate(pageSize); predicate.previousPage(); Collection<Integer> values = map.values(predicate); values = map.values(predicate); assertIterableEquals(values, 0, 1, 2, 3, 4); } @Test public void testGoTo_NextPage_AfterTheEnd() { final PagingPredicate predicate = new PagingPredicate(pageSize); for ( int i=0; i < size/pageSize; i++ ) { predicate.nextPage(); } Collection<Integer> values = map.values(predicate); values = map.values(predicate); assertEquals( size/pageSize - 1, predicate.getPage()); assertIterableEquals(values, 45, 46, 47, 48, 49); } @Test public void testPagingWithoutFilteringAndComparator() { Set<Integer> set = new HashSet<Integer>(); final PagingPredicate predicate = new PagingPredicate(pageSize); Collection<Integer> values = map.values(predicate); while (values.size() > 0) { assertEquals(pageSize, values.size()); set.addAll(values); predicate.nextPage(); values = map.values(predicate); } assertEquals(size, set.size()); } @Test public void testPagingWithFilteringAndComparator() { final Predicate lessEqual = Predicates.lessEqual("this", 8); final TestComparator comparator = new TestComparator(false, IterationType.VALUE); final PagingPredicate predicate = new PagingPredicate(lessEqual, comparator, pageSize); Collection<Integer> values = map.values(predicate); assertIterableEquals(values, 8, 7, 6, 5, 4); predicate.nextPage(); assertEquals(4, predicate.getAnchor().getValue()); values = map.values(predicate); assertIterableEquals(values, 3, 2, 1, 0); predicate.nextPage(); assertEquals(0, predicate.getAnchor().getValue()); values = map.values(predicate); assertEquals(0, values.size()); } @Test public void testKeyPaging() { map.clear(); for (int i = 0; i < size; i++) { // keys [50-1] values [0-49] map.put(size - i, i); } final Predicate lessEqual = Predicates.lessEqual("this", 8); // less than 8 final TestComparator comparator = new TestComparator(true, IterationType.KEY); //ascending keys final PagingPredicate predicate = new PagingPredicate(lessEqual, comparator, pageSize); Set<Integer> keySet = map.keySet(predicate); assertIterableEquals(keySet, 42, 43, 44, 45, 46); predicate.nextPage(); assertEquals(46, predicate.getAnchor().getKey()); keySet = map.keySet(predicate); assertIterableEquals(keySet, 47, 48, 49, 50); predicate.nextPage(); assertEquals(50, predicate.getAnchor().getKey()); keySet = map.keySet(predicate); assertEquals(0, keySet.size()); } @Test public void testEqualValuesPaging() { for (int i = size; i < 2 * size; i++) { //keys[50-99] values[0-49] map.put(i, i - size); } final Predicate lessEqual = Predicates.lessEqual("this", 8); // entries which has value less than 8 final TestComparator comparator = new TestComparator(true, IterationType.VALUE); //ascending values final PagingPredicate predicate = new PagingPredicate(lessEqual, comparator, pageSize); //pageSize = 5 Collection<Integer> values = map.values(predicate); assertIterableEquals(values, 0, 0, 1, 1, 2); predicate.nextPage(); values = map.values(predicate); assertIterableEquals(values, 2, 3, 3, 4, 4); predicate.nextPage(); values = map.values(predicate); assertIterableEquals(values, 5, 5, 6, 6, 7); predicate.nextPage(); values = map.values(predicate); assertIterableEquals(values, 7, 8, 8); } @Test public void testNextPageAfterResultSetEmpty(){ final Predicate lessEqual = Predicates.lessEqual("this", 3); // entries which has value less than 3 final TestComparator comparator = new TestComparator(true, IterationType.VALUE); //ascending values final PagingPredicate predicate = new PagingPredicate(lessEqual, comparator, pageSize); //pageSize = 5 Collection<Integer> values = map.values(predicate); assertIterableEquals(values, 0, 1, 2, 3); predicate.nextPage(); values = map.values(predicate); assertEquals(0, values.size()); predicate.nextPage(); values = map.values(predicate); assertEquals(0, values.size()); } 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
4,569
public class GcNames { public static String YOUNG = "young"; public static String OLD = "old"; public static String SURVIVOR = "survivor"; /** * Resolves the GC type by its memory pool name ({@link java.lang.management.MemoryPoolMXBean#getName()}. */ public static String getByMemoryPoolName(String poolName, String defaultName) { if ("Eden Space".equals(poolName) || "PS Eden Space".equals(poolName) || "Par Eden Space".equals(poolName) || "G1 Eden Space".equals(poolName)) { return YOUNG; } if ("Survivor Space".equals(poolName) || "PS Survivor Space".equals(poolName) || "Par Survivor Space".equals(poolName) || "G1 Survivor Space".equals(poolName)) { return SURVIVOR; } if ("Tenured Gen".equals(poolName) || "PS Old Gen".equals(poolName) || "CMS Old Gen".equals(poolName) || "G1 Old Gen".equals(poolName)) { return OLD; } return defaultName; } public static String getByGcName(String gcName, String defaultName) { if ("Copy".equals(gcName) || "PS Scavenge".equals(gcName) || "ParNew".equals(gcName) || "G1 Young Generation".equals(gcName)) { return YOUNG; } if ("MarkSweepCompact".equals(gcName) || "PS MarkSweep".equals(gcName) || "ConcurrentMarkSweep".equals(gcName) || "G1 Old Generation".equals(gcName)) { return OLD; } return defaultName; } }
1no label
src_main_java_org_elasticsearch_monitor_jvm_GcNames.java
1,515
public class PreferPrimaryAllocationTests extends ElasticsearchAllocationTestCase { private final ESLogger logger = Loggers.getLogger(PreferPrimaryAllocationTests.class); @Test public void testPreferPrimaryAllocationOverReplicas() { logger.info("create an allocation with 1 initial recoveries"); AllocationService strategy = createAllocationService(settingsBuilder() .put("cluster.routing.allocation.node_concurrent_recoveries", 1) .put("cluster.routing.allocation.node_initial_primaries_recoveries", 1) .build()); logger.info("create several indices with no replicas, and wait till all are allocated"); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test1").numberOfShards(10).numberOfReplicas(0)) .put(IndexMetaData.builder("test2").numberOfShards(10).numberOfReplicas(0)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test1")) .addAsNew(metaData.index("test2")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("adding two nodes and performing rerouting till all are allocated"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2"))).build(); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); while (!clusterState.routingNodes().shardsWithState(INITIALIZING).isEmpty()) { routingTable = strategy.applyStartedShards(clusterState, clusterState.routingNodes().shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); } logger.info("increasing the number of replicas to 1, and perform a reroute (to get the replicas allocation going)"); routingTable = RoutingTable.builder(routingTable).updateNumberOfReplicas(1).build(); metaData = MetaData.builder(clusterState.metaData()).updateNumberOfReplicas(1).build(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).metaData(metaData).build(); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); logger.info("2 replicas should be initializing now for the existing indices (we throttle to 1)"); assertThat(clusterState.routingNodes().shardsWithState(INITIALIZING).size(), equalTo(2)); logger.info("create a new index"); metaData = MetaData.builder(clusterState.metaData()) .put(IndexMetaData.builder("new_index").numberOfShards(4).numberOfReplicas(0)) .build(); routingTable = RoutingTable.builder(clusterState.routingTable()) .addAsNew(metaData.index("new_index")) .build(); clusterState = ClusterState.builder(clusterState).metaData(metaData).routingTable(routingTable).build(); logger.info("reroute, verify that primaries for the new index primary shards are allocated"); routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(clusterState.routingTable().index("new_index").shardsWithState(INITIALIZING).size(), equalTo(2)); } }
0true
src_test_java_org_elasticsearch_cluster_routing_allocation_PreferPrimaryAllocationTests.java
450
executor.execute(new Runnable() { @Override public void run() { for (int i = 0; i < operations; i++) { map1.put("foo-" + i, "bar"); } } }, 60, EntryEventType.ADDED, operations, 0.75, map1, map2);
0true
hazelcast-client_src_test_java_com_hazelcast_client_replicatedmap_ClientReplicatedMapTest.java
5,301
return new Comparator<Terms.Bucket>() { @Override public int compare(Terms.Bucket o1, Terms.Bucket o2) { double v1 = ((MetricsAggregator.MultiValue) aggregator).metric(valueName, ((InternalTerms.Bucket) o1).bucketOrd); double v2 = ((MetricsAggregator.MultiValue) aggregator).metric(valueName, ((InternalTerms.Bucket) o2).bucketOrd); // some metrics may return NaN (eg. avg, variance, etc...) in which case we'd like to push all of those to // the bottom if (v1 == Double.NaN) { return asc ? 1 : -1; } return asc ? Double.compare(v1, v2) : Double.compare(v2, v1); } };
1no label
src_main_java_org_elasticsearch_search_aggregations_bucket_terms_InternalOrder.java
207
Callable<Object> response = new Callable<Object>() { public Object call() throws Exception { Boolean result; try { OStorageRemoteThreadLocal.INSTANCE.get().sessionId = sessionId; beginResponse(network); result = network.readByte() == 1; } finally { endResponse(network); OStorageRemoteThreadLocal.INSTANCE.get().sessionId = -1; } iCallback.call(iRid, result); return null; } };
0true
client_src_main_java_com_orientechnologies_orient_client_remote_OStorageRemote.java
766
public class SetContainer extends CollectionContainer { private static final int INITIAL_CAPACITY = 1000; private Set<CollectionItem> itemSet; private SetConfig config; public SetContainer() { } public SetContainer(String name, NodeEngine nodeEngine) { super(name, nodeEngine); } @Override protected SetConfig getConfig() { if (config == null) { config = nodeEngine.getConfig().findSetConfig(name); } return config; } @Override protected Map<Long, Data> addAll(List<Data> valueList) { final int size = valueList.size(); final Map<Long, Data> map = new HashMap<Long, Data>(size); List<CollectionItem> list = new ArrayList<CollectionItem>(size); for (Data value : valueList) { final long itemId = nextId(); final CollectionItem item = new CollectionItem(itemId, value); if (!getCollection().contains(item)) { list.add(item); map.put(itemId, value); } } getCollection().addAll(list); return map; } @Override public Set<CollectionItem> getCollection() { if (itemSet == null) { if (itemMap != null && !itemMap.isEmpty()) { itemSet = new HashSet<CollectionItem>(itemMap.values()); itemMap.clear(); } else { itemSet = new HashSet<CollectionItem>(INITIAL_CAPACITY); } itemMap = null; } return itemSet; } @Override protected Map<Long, CollectionItem> getMap() { if (itemMap == null) { if (itemSet != null && !itemSet.isEmpty()) { itemMap = new HashMap<Long, CollectionItem>(itemSet.size()); for (CollectionItem item : itemSet) { itemMap.put(item.getItemId(), item); } itemSet.clear(); } else { itemMap = new HashMap<Long, CollectionItem>(INITIAL_CAPACITY); } itemSet = null; } return itemMap; } @Override protected void onDestroy() { if (itemSet != null) { itemSet.clear(); } } }
0true
hazelcast_src_main_java_com_hazelcast_collection_set_SetContainer.java
163
@SuppressWarnings("unchecked") public class OSynchEventAdapter<RESOURCE_TYPE, RESPONSE_TYPE> { protected final LinkedHashMap<RESOURCE_TYPE, Object[]> queue = new LinkedHashMap<RESOURCE_TYPE, Object[]>(); public OSynchEventAdapter() { } public void registerCallbackCurrentThread(final RESOURCE_TYPE iResource) { queue.put(iResource, new Object[] { iResource, null }); } /** * Wait forever until the requested resource is unlocked. */ public RESPONSE_TYPE waitForResource(final RESOURCE_TYPE iResource) { return getValue(iResource, 0); } /** * Wait until the requested resource is unlocked. Put the current thread in sleep until timeout or is waked up by an unlock. */ public synchronized RESPONSE_TYPE getValue(final RESOURCE_TYPE iResource, final long iTimeout) { if (OLogManager.instance().isDebugEnabled()) OLogManager.instance().debug( this, "Thread [" + Thread.currentThread().getId() + "] is waiting for the resource " + iResource + (iTimeout <= 0 ? " forever" : " until " + iTimeout + "ms")); synchronized (iResource) { try { iResource.wait(iTimeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new OLockException("Thread interrupted while waiting for resource '" + iResource + "'"); } } Object[] value = queue.remove(iResource); return (RESPONSE_TYPE) (value != null ? value[1] : null); } public void setValue(final RESOURCE_TYPE iResource, final Object iValue) { final Object[] waiter = queue.get(iResource); if (waiter == null) return; synchronized (waiter[0]) { waiter[1] = iValue; waiter[0].notifyAll(); } } }
0true
commons_src_main_java_com_orientechnologies_common_synch_OSynchEventAdapter.java
49
@edu.umd.cs.findbugs.annotations.SuppressWarnings({ "EI_EXPOSE_REP", "MS_MUTABLE_ARRAY", "MS_PKGPROTECT" }) public abstract class HttpCommand extends AbstractTextCommand { public static final String HEADER_CONTENT_TYPE = "content-type: "; public static final String HEADER_CONTENT_LENGTH = "content-length: "; public static final String HEADER_CHUNKED = "transfer-encoding: chunked"; public static final String HEADER_EXPECT_100 = "expect: 100"; public static final byte[] RES_200 = stringToBytes("HTTP/1.1 200 OK\r\n"); public static final byte[] RES_400 = stringToBytes("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n"); public static final byte[] RES_403 = stringToBytes("HTTP/1.1 403 Forbidden\r\n\r\n"); public static final byte[] RES_404 = stringToBytes("HTTP/1.1 404 Not Found\r\n\r\n"); public static final byte[] RES_100 = stringToBytes("HTTP/1.1 100 Continue\r\n\r\n"); public static final byte[] RES_204 = stringToBytes("HTTP/1.1 204 No Content\r\nContent-Length: 0\r\n\r\n"); public static final byte[] RES_503 = stringToBytes("HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n"); public static final byte[] RES_500 = stringToBytes("HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n"); public static final byte[] CONTENT_TYPE = stringToBytes("Content-Type: "); public static final byte[] CONTENT_LENGTH = stringToBytes("Content-Length: "); public static final byte[] CONTENT_TYPE_PLAIN_TEXT = stringToBytes("text/plain"); public static final byte[] CONTENT_TYPE_BINARY = stringToBytes("application/binary"); protected final String uri; protected ByteBuffer response; public HttpCommand(TextCommandType type, String uri) { super(type); this.uri = uri; } public boolean shouldReply() { return true; } public String getURI() { return uri; } public void send204() { this.response = ByteBuffer.wrap(RES_204); } public void send400() { this.response = ByteBuffer.wrap(RES_400); } public void setResponse(byte[] value) { this.response = ByteBuffer.wrap(value); } public void send200() { setResponse(null, null); } /** * HTTP/1.0 200 OK * Date: Fri, 31 Dec 1999 23:59:59 GMT * Content-TextCommandType: text/html * Content-Length: 1354 * * @param contentType * @param value */ public void setResponse(byte[] contentType, byte[] value) { int valueSize = (value == null) ? 0 : value.length; byte[] len = stringToBytes(String.valueOf(valueSize)); int size = RES_200.length; if (contentType != null) { size += CONTENT_TYPE.length; size += contentType.length; size += RETURN.length; } size += CONTENT_LENGTH.length; size += len.length; size += RETURN.length; size += RETURN.length; size += valueSize; size += RETURN.length; this.response = ByteBuffer.allocate(size); response.put(RES_200); if (contentType != null) { response.put(CONTENT_TYPE); response.put(contentType); response.put(RETURN); } response.put(CONTENT_LENGTH); response.put(len); response.put(RETURN); response.put(RETURN); if (value != null) { response.put(value); } response.put(RETURN); response.flip(); } public boolean writeTo(ByteBuffer bb) { IOUtil.copyToHeapBuffer(response, bb); return !response.hasRemaining(); } @Override public String toString() { return "HttpCommand [" + type + "]{" + "uri='" + uri + '\'' + '}' + super.toString(); } }
0true
hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpCommand.java
76
class FindExtendedTypeExpressionVisitor extends Visitor { Tree.InvocationExpression invocationExpression; @Override public void visit(Tree.ExtendedType that) { super.visit(that); if (that.getType()==node) { invocationExpression = that.getInvocationExpression(); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_CeylonCorrectionProcessor.java
219
public abstract class OrientConsole extends OConsoleApplication { public OrientConsole(String[] args) { super(args); } @Override protected void onException(Throwable e) { Throwable current = e; while (current != null) { err.print("\nError: " + current.toString()); current = current.getCause(); } } @Override protected void onBefore() { printApplicationInfo(); } protected void printApplicationInfo() { } @Override protected void onAfter() { out.println(); } @Override public void help() { super.help(); } protected String format(final String iValue, final int iMaxSize) { if (iValue == null) return null; if (iValue.length() > iMaxSize) return iValue.substring(0, iMaxSize - 3) + "..."; return iValue; } }
0true
tools_src_main_java_com_orientechnologies_orient_console_OrientConsole.java
103
final Thread thread = new Thread() { @Override public void run() { while (!isInterrupted()) { m.put("key2", "value2"); try { Thread.sleep(100); } catch (InterruptedException ignored) { } } } };
0true
hazelcast-client_src_test_java_com_hazelcast_client_ClientIssueTest.java
850
public class GetAndAlterRequest extends AbstractAlterRequest { public GetAndAlterRequest() { } public GetAndAlterRequest(String name, Data function) { super(name, function); } @Override protected Operation prepareOperation() { return new GetAndAlterOperation(name, function); } @Override public int getClassId() { return AtomicReferencePortableHook.GET_AND_ALTER; } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_GetAndAlterRequest.java
1,502
public static class Reduce extends Reducer<LongWritable, Holder, NullWritable, FaunusVertex> { private boolean trackState; @Override public void setup(final Reducer.Context context) { this.trackState = context.getConfiguration().getBoolean(Tokens.TITAN_HADOOP_PIPELINE_TRACK_STATE, false); } @Override public void reduce(final LongWritable key, final Iterable<Holder> values, final Reducer<LongWritable, Holder, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { FaunusVertex vertex = null; final Set<Long> ids = new HashSet<Long>(); for (final Holder holder : values) { final char tag = holder.getTag(); if (tag == 'k') { ids.add(holder.get().getLongId()); // todo: once vertex is found, do individual removes to save memory } else if (tag == 'v') { vertex = (FaunusVertex) holder.get(); } else { vertex = (FaunusVertex) holder.get(); Iterator<Edge> itty = vertex.getEdges(Direction.BOTH).iterator(); while (itty.hasNext()) { itty.next(); itty.remove(); } vertex.updateLifeCycle(ElementLifeCycle.Event.REMOVED); } } if (null != vertex) { if (ids.size() > 0) vertex.removeEdgesToFrom(ids); if (this.trackState) context.write(NullWritable.get(), vertex); else if (!vertex.isRemoved()) context.write(NullWritable.get(), vertex); DEFAULT_COMPAT.incrementContextCounter(context, Counters.OUT_EDGES_KEPT, Iterables.size(vertex.getEdges(OUT))); DEFAULT_COMPAT.incrementContextCounter(context, Counters.IN_EDGES_KEPT, Iterables.size(vertex.getEdges(IN))); } } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_sideeffect_CommitVerticesMapReduce.java
1,695
public class ByteBufferBytesReference implements BytesReference { private final ByteBuffer buffer; public ByteBufferBytesReference(ByteBuffer buffer) { this.buffer = buffer; } @Override public byte get(int index) { return buffer.get(buffer.position() + index); } @Override public int length() { return buffer.remaining(); } @Override public BytesReference slice(int from, int length) { ByteBuffer dup = buffer.duplicate(); dup.position(buffer.position() + from); dup.limit(buffer.position() + from + length); return new ByteBufferBytesReference(dup); } @Override public StreamInput streamInput() { return new ByteBufferStreamInput(buffer); } @Override public void writeTo(OutputStream os) throws IOException { if (buffer.hasArray()) { os.write(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); } else { byte[] tmp = new byte[8192]; ByteBuffer buf = buffer.duplicate(); while (buf.hasRemaining()) { buf.get(tmp, 0, Math.min(tmp.length, buf.remaining())); os.write(tmp); } } } @Override public byte[] toBytes() { if (!buffer.hasRemaining()) { return BytesRef.EMPTY_BYTES; } byte[] tmp = new byte[buffer.remaining()]; buffer.duplicate().get(tmp); return tmp; } @Override public BytesArray toBytesArray() { if (buffer.hasArray()) { return new BytesArray(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); } return new BytesArray(toBytes()); } @Override public BytesArray copyBytesArray() { return new BytesArray(toBytes()); } @Override public ChannelBuffer toChannelBuffer() { return ChannelBuffers.wrappedBuffer(buffer); } @Override public boolean hasArray() { return buffer.hasArray(); } @Override public byte[] array() { return buffer.array(); } @Override public int arrayOffset() { return buffer.arrayOffset() + buffer.position(); } @Override public int hashCode() { return Helper.bytesHashCode(this); } @Override public boolean equals(Object obj) { return Helper.bytesEqual(this, (BytesReference) obj); } @Override public String toUtf8() { if (!buffer.hasRemaining()) { return ""; } final CharsetDecoder decoder = CharsetUtil.getDecoder(Charsets.UTF_8); final CharBuffer dst = CharBuffer.allocate( (int) ((double) buffer.remaining() * decoder.maxCharsPerByte())); try { CoderResult cr = decoder.decode(buffer, dst, true); if (!cr.isUnderflow()) { cr.throwException(); } cr = decoder.flush(dst); if (!cr.isUnderflow()) { cr.throwException(); } } catch (CharacterCodingException x) { throw new IllegalStateException(x); } return dst.flip().toString(); } @Override public BytesRef toBytesRef() { if (buffer.hasArray()) { return new BytesRef(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); } return new BytesRef(toBytes()); } @Override public BytesRef copyBytesRef() { return new BytesRef(toBytes()); } }
1no label
src_main_java_org_elasticsearch_common_bytes_ByteBufferBytesReference.java
1,058
public class TermVectorRequestBuilder extends ActionRequestBuilder<TermVectorRequest, TermVectorResponse, TermVectorRequestBuilder> { public TermVectorRequestBuilder(Client client) { super((InternalClient) client, new TermVectorRequest()); } public TermVectorRequestBuilder(Client client, String index, String type, String id) { super((InternalClient) client, new TermVectorRequest(index, type, id)); } /** * Sets the routing. Required if routing isn't id based. */ public TermVectorRequestBuilder setRouting(String routing) { request.routing(routing); return this; } /** * Sets the parent id of this document. Will simply set the routing to this value, as it is only * used for routing with delete requests. */ public TermVectorRequestBuilder setParent(String parent) { request.parent(parent); return this; } /** * Sets the preference to execute the search. Defaults to randomize across shards. Can be set to * <tt>_local</tt> to prefer local shards, <tt>_primary</tt> to execute only on primary shards, or * a custom value, which guarantees that the same order will be used across different requests. */ public TermVectorRequestBuilder setPreference(String preference) { request.preference(preference); return this; } public TermVectorRequestBuilder setOffsets(boolean offsets) { request.offsets(offsets); return this; } public TermVectorRequestBuilder setPositions(boolean positions) { request.positions(positions); return this; } public TermVectorRequestBuilder setPayloads(boolean payloads) { request.payloads(payloads); return this; } public TermVectorRequestBuilder setTermStatistics(boolean termStatistics) { request.termStatistics(termStatistics); return this; } public TermVectorRequestBuilder setFieldStatistics(boolean fieldStatistics) { request.fieldStatistics(fieldStatistics); return this; } public TermVectorRequestBuilder setSelectedFields(String... fields) { request.selectedFields(fields); return this; } @Override protected void doExecute(ActionListener<TermVectorResponse> listener) { ((Client) client).termVector(request, listener); } }
0true
src_main_java_org_elasticsearch_action_termvector_TermVectorRequestBuilder.java
570
@PreInitializeConfigOptions public class KCVSLogManager implements LogManager { private static final Logger log = LoggerFactory.getLogger(KCVSLogManager.class); public static final ConfigOption<Boolean> LOG_FIXED_PARTITION = new ConfigOption<Boolean>(LOG_NS,"fixed-partition", "Whether all log entries are written to one fixed partition even if the backend store is partitioned." + "This can cause imbalanced loads and should only be used on low volume logs", ConfigOption.Type.GLOBAL_OFFLINE, false); public static final ConfigOption<Integer> LOG_MAX_PARTITIONS = new ConfigOption<Integer>(LOG_NS,"max-partitions", "The maximum number of partitions to use for logging. Setting up this many actual or virtual partitions. Must be bigger than 1" + "and a power of 2.", ConfigOption.Type.FIXED, Integer.class, new Predicate<Integer>() { @Override public boolean apply(@Nullable Integer integer) { return integer!=null && integer>1 && NumberUtil.isPowerOf2(integer); } }); /** * Configuration of this log manager */ private final Configuration configuration; /** * Store Manager against which to open the {@link KeyColumnValueStore}s to wrap the {@link KCVSLog} around. */ final KeyColumnValueStoreManager storeManager; /** * Id which uniquely identifies this instance. Also see {@link GraphDatabaseConfiguration#UNIQUE_INSTANCE_ID}. */ final String senderId; /** * The number of first bits of the key that identifies a partition. If this number is X then there are 2^X different * partition blocks each of which is identified by a partition id. */ final int partitionBitWidth; /** * A collection of partition ids to which the logs write in round-robin fashion. */ final int[] defaultWritePartitionIds; /** * A collection of partition ids from which the readers will read concurrently. */ final int[] readPartitionIds; /** * Serializer used to (de)-serialize the log messages */ final Serializer serializer; /** * Keeps track of all open logs */ private final Map<String,KCVSLog> openLogs; /** * Opens a log manager against the provided KCVS store with the given configuration. * @param storeManager * @param config */ public KCVSLogManager(final KeyColumnValueStoreManager storeManager, final Configuration config) { this(storeManager, config, null); } /** * Opens a log manager against the provided KCVS store with the given configuration. Also provided is a list * of read-partition-ids. These only apply when readers are registered against an opened log. In that case, * the readers only read from the provided list of partition ids. * @param storeManager * @param config * @param readPartitionIds */ public KCVSLogManager(KeyColumnValueStoreManager storeManager, final Configuration config, final int[] readPartitionIds) { Preconditions.checkArgument(storeManager!=null && config!=null); if (config.has(LOG_STORE_TTL)) { if (TTLKVCSManager.supportsStoreTTL(storeManager)) { storeManager = new TTLKVCSManager(storeManager, ConversionHelper.getTTLSeconds(config.get(LOG_STORE_TTL))); } else { log.warn("Log is configured with TTL but underlying storage backend does not support TTL, hence this" + "configuration option is ignored and entries must be manually removed from the backend."); } } this.storeManager = storeManager; this.configuration = config; openLogs = new HashMap<String, KCVSLog>(); this.senderId=config.get(GraphDatabaseConfiguration.UNIQUE_INSTANCE_ID); Preconditions.checkNotNull(senderId); if (config.get(CLUSTER_PARTITION)) { ConfigOption<Integer> maxPartitionConfig = config.has(LOG_MAX_PARTITIONS)? LOG_MAX_PARTITIONS:CLUSTER_MAX_PARTITIONS; int maxPartitions = config.get(maxPartitionConfig); Preconditions.checkArgument(maxPartitions<=config.get(CLUSTER_MAX_PARTITIONS), "Number of log partitions cannot be larger than number of cluster partitions"); this.partitionBitWidth= NumberUtil.getPowerOf2(maxPartitions); } else { this.partitionBitWidth=0; } Preconditions.checkArgument(partitionBitWidth>=0 && partitionBitWidth<32); final int numPartitions = (1<<partitionBitWidth); //Partitioning if (config.get(CLUSTER_PARTITION) && !config.get(LOG_FIXED_PARTITION)) { //Write partitions - default initialization: writing to all partitions int[] writePartitions = new int[numPartitions]; for (int i=0;i<numPartitions;i++) writePartitions[i]=i; if (storeManager.getFeatures().hasLocalKeyPartition()) { //Write only to local partitions List<Integer> localPartitions = new ArrayList<Integer>(); try { List<PartitionIDRange> partitionRanges = PartitionIDRange.getIDRanges(partitionBitWidth, storeManager.getLocalKeyPartition()); for (PartitionIDRange idrange : partitionRanges) { for (int p : idrange.getAllContainedIDs()) localPartitions.add(p); } } catch (Throwable e) { log.error("Could not process local id partitions",e); } if (!localPartitions.isEmpty()) { writePartitions = new int[localPartitions.size()]; for (int i=0;i<localPartitions.size();i++) writePartitions[i]=localPartitions.get(i); } } this.defaultWritePartitionIds = writePartitions; //Read partitions if (readPartitionIds!=null && readPartitionIds.length>0) { for (int readPartitionId : readPartitionIds) { checkValidPartitionId(readPartitionId,partitionBitWidth); } this.readPartitionIds = Arrays.copyOf(readPartitionIds,readPartitionIds.length); } else { this.readPartitionIds=new int[numPartitions]; for (int i=0;i<numPartitions;i++) this.readPartitionIds[i]=i; } } else { this.defaultWritePartitionIds=new int[]{0}; Preconditions.checkArgument(readPartitionIds==null || (readPartitionIds.length==0 && readPartitionIds[0]==0), "Cannot configure read partition ids on unpartitioned backend or with fixed partitions enabled"); this.readPartitionIds=new int[]{0}; } this.serializer = new StandardSerializer(false); } private static void checkValidPartitionId(int partitionId, int partitionBitWidth) { Preconditions.checkArgument(partitionId>=0 && partitionId<(1<<partitionBitWidth)); } @Override public synchronized KCVSLog openLog(final String name) throws BackendException { if (openLogs.containsKey(name)) return openLogs.get(name); KCVSLog log = new KCVSLog(name,this,storeManager.openDatabase(name),configuration); openLogs.put(name,log); return log; } /** * Must be triggered by a particular {@link KCVSLog} when it is closed so that this log can be removed from the list * of open logs. * @param log */ synchronized void closedLog(KCVSLog log) { KCVSLog l = openLogs.remove(log.getName()); assert l==log; } @Override public synchronized void close() throws BackendException { /* Copying the map is necessary to avoid ConcurrentModificationException. * The path to ConcurrentModificationException in the absence of a copy is * log.close() -> manager.closedLog(log) -> openLogs.remove(log.getName()). */ for (KCVSLog log : ImmutableMap.copyOf(openLogs).values()) log.close(); } }
1no label
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_log_kcvs_KCVSLogManager.java
284
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class ClientStaticLBTest { @AfterClass public static void destroy() { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } @Test public void testStaticLB_withMembers() { TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1); HazelcastInstance server = factory.newHazelcastInstance(); Member member = server.getCluster().getLocalMember(); StaticLB lb = new StaticLB(member); Member nextMember = lb.next(); assertEquals(member, nextMember); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_loadBalancer_ClientStaticLBTest.java
604
@Component("blLocaleResolver") public class BroadleafLocaleResolverImpl implements BroadleafLocaleResolver { private final Log LOG = LogFactory.getLog(BroadleafLocaleResolverImpl.class); /** * Parameter/Attribute name for the current language */ public static String LOCALE_VAR = "blLocale"; /** * Parameter/Attribute name for the current language */ public static String LOCALE_CODE_PARAM = "blLocaleCode"; /** * Attribute indicating that the LOCALE was pulled from session. Other filters may want to * behave differently if this is the case. */ public static String LOCALE_PULLED_FROM_SESSION = "blLocalePulledFromSession"; @Resource(name = "blLocaleService") private LocaleService localeService; @Override public Locale resolveLocale(HttpServletRequest request) { return resolveLocale(new ServletWebRequest(request)); } @Override public Locale resolveLocale(WebRequest request) { Locale locale = null; // First check for request attribute locale = (Locale) request.getAttribute(LOCALE_VAR, WebRequest.SCOPE_REQUEST); // Second, check for a request parameter if (locale == null && BLCRequestUtils.getURLorHeaderParameter(request, LOCALE_CODE_PARAM) != null) { String localeCode = BLCRequestUtils.getURLorHeaderParameter(request, LOCALE_CODE_PARAM); locale = localeService.findLocaleByCode(localeCode); if (BLCRequestUtils.isOKtoUseSession(request)) { request.removeAttribute(BroadleafCurrencyResolverImpl.CURRENCY_VAR, WebRequest.SCOPE_GLOBAL_SESSION); } if (LOG.isTraceEnabled()) { LOG.trace("Attempt to find locale by param " + localeCode + " resulted in " + locale); } } // Third, check the session if (locale == null && BLCRequestUtils.isOKtoUseSession(request)) { locale = (Locale) request.getAttribute(LOCALE_VAR, WebRequest.SCOPE_GLOBAL_SESSION); if (LOG.isTraceEnabled()) { LOG.trace("Attempt to find locale from session resulted in " + locale); } if (locale != null) { request.setAttribute(LOCALE_PULLED_FROM_SESSION, Boolean.TRUE, WebRequest.SCOPE_REQUEST); } } // Finally, use the default if (locale == null) { locale = localeService.findDefaultLocale(); if (BLCRequestUtils.isOKtoUseSession(request)) { request.removeAttribute(BroadleafCurrencyResolverImpl.CURRENCY_VAR, WebRequest.SCOPE_GLOBAL_SESSION); } if (LOG.isTraceEnabled()) { LOG.trace("Locale set to default locale " + locale); } } if (BLCRequestUtils.isOKtoUseSession(request)) { request.setAttribute(LOCALE_VAR, locale, WebRequest.SCOPE_GLOBAL_SESSION); } return locale; } }
0true
common_src_main_java_org_broadleafcommerce_common_web_BroadleafLocaleResolverImpl.java
934
class AsyncBroadcastAction { private final Request request; private final ActionListener<Response> listener; private final ClusterState clusterState; private final DiscoveryNodes nodes; private final GroupShardsIterator shardsIts; private final int expectedOps; private final AtomicInteger counterOps = new AtomicInteger(); private final AtomicReferenceArray shardsResponses; AsyncBroadcastAction(Request request, ActionListener<Response> listener) { this.request = request; this.listener = listener; clusterState = clusterService.state(); ClusterBlockException blockException = checkGlobalBlock(clusterState, request); if (blockException != null) { throw blockException; } // update to concrete indices String[] concreteIndices = clusterState.metaData().concreteIndices(request.indices(), request.indicesOptions()); blockException = checkRequestBlock(clusterState, request, concreteIndices); if (blockException != null) { throw blockException; } nodes = clusterState.nodes(); shardsIts = shards(clusterState, request, concreteIndices); expectedOps = shardsIts.size(); shardsResponses = new AtomicReferenceArray<Object>(expectedOps); } public void start() { if (shardsIts.size() == 0) { // no shards try { listener.onResponse(newResponse(request, new AtomicReferenceArray(0), clusterState)); } catch (Throwable e) { listener.onFailure(e); } return; } request.beforeStart(); // count the local operations, and perform the non local ones int localOperations = 0; int shardIndex = -1; for (final ShardIterator shardIt : shardsIts) { shardIndex++; final ShardRouting shard = shardIt.firstOrNull(); if (shard != null) { if (shard.currentNodeId().equals(nodes.localNodeId())) { localOperations++; } else { // do the remote operation here, the localAsync flag is not relevant performOperation(shardIt, shardIndex, true); } } else { // really, no shards active in this group onOperation(null, shardIt, shardIndex, new NoShardAvailableActionException(shardIt.shardId())); } } // we have local operations, perform them now if (localOperations > 0) { if (request.operationThreading() == BroadcastOperationThreading.SINGLE_THREAD) { request.beforeLocalFork(); threadPool.executor(executor).execute(new Runnable() { @Override public void run() { int shardIndex = -1; for (final ShardIterator shardIt : shardsIts) { shardIndex++; final ShardRouting shard = shardIt.firstOrNull(); if (shard != null) { if (shard.currentNodeId().equals(nodes.localNodeId())) { performOperation(shardIt, shardIndex, false); } } } } }); } else { boolean localAsync = request.operationThreading() == BroadcastOperationThreading.THREAD_PER_SHARD; if (localAsync) { request.beforeLocalFork(); } shardIndex = -1; for (final ShardIterator shardIt : shardsIts) { shardIndex++; final ShardRouting shard = shardIt.firstOrNull(); if (shard != null) { if (shard.currentNodeId().equals(nodes.localNodeId())) { performOperation(shardIt, shardIndex, localAsync); } } } } } } void performOperation(final ShardIterator shardIt, int shardIndex, boolean localAsync) { performOperation(shardIt, shardIt.nextOrNull(), shardIndex, localAsync); } void performOperation(final ShardIterator shardIt, final ShardRouting shard, final int shardIndex, boolean localAsync) { if (shard == null) { // no more active shards... (we should not really get here, just safety) onOperation(null, shardIt, shardIndex, new NoShardAvailableActionException(shardIt.shardId())); } else { try { final ShardRequest shardRequest = newShardRequest(shard, request); if (shard.currentNodeId().equals(nodes.localNodeId())) { if (localAsync) { threadPool.executor(executor).execute(new Runnable() { @Override public void run() { try { onOperation(shard, shardIndex, shardOperation(shardRequest)); } catch (Throwable e) { onOperation(shard, shardIt, shardIndex, e); } } }); } else { onOperation(shard, shardIndex, shardOperation(shardRequest)); } } else { DiscoveryNode node = nodes.get(shard.currentNodeId()); if (node == null) { // no node connected, act as failure onOperation(shard, shardIt, shardIndex, new NoShardAvailableActionException(shardIt.shardId())); } else { transportService.sendRequest(node, transportShardAction, shardRequest, new BaseTransportResponseHandler<ShardResponse>() { @Override public ShardResponse newInstance() { return newShardResponse(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void handleResponse(ShardResponse response) { onOperation(shard, shardIndex, response); } @Override public void handleException(TransportException e) { onOperation(shard, shardIt, shardIndex, e); } }); } } } catch (Throwable e) { onOperation(shard, shardIt, shardIndex, e); } } } @SuppressWarnings({"unchecked"}) void onOperation(ShardRouting shard, int shardIndex, ShardResponse response) { shardsResponses.set(shardIndex, response); if (expectedOps == counterOps.incrementAndGet()) { finishHim(); } } @SuppressWarnings({"unchecked"}) void onOperation(@Nullable ShardRouting shard, final ShardIterator shardIt, int shardIndex, Throwable t) { // we set the shard failure always, even if its the first in the replication group, and the next one // will work (it will just override it...) setFailure(shardIt, shardIndex, t); ShardRouting nextShard = shardIt.nextOrNull(); if (nextShard != null) { if (t != null) { if (logger.isTraceEnabled()) { if (!TransportActions.isShardNotAvailableException(t)) { if (shard != null) { logger.trace(shard.shortSummary() + ": Failed to execute [" + request + "]", t); } else { logger.trace(shardIt.shardId() + ": Failed to execute [" + request + "]", t); } } } } // we are not threaded here if we got here from the transport // or we possibly threaded if we got from a local threaded one, // in which case, the next shard in the partition will not be local one // so there is no meaning to this flag performOperation(shardIt, nextShard, shardIndex, true); } else { if (logger.isDebugEnabled()) { if (t != null) { if (!TransportActions.isShardNotAvailableException(t)) { if (shard != null) { logger.debug(shard.shortSummary() + ": Failed to execute [" + request + "]", t); } else { logger.debug(shardIt.shardId() + ": Failed to execute [" + request + "]", t); } } } } if (expectedOps == counterOps.incrementAndGet()) { finishHim(); } } } void finishHim() { try { listener.onResponse(newResponse(request, shardsResponses, clusterState)); } catch (Throwable e) { listener.onFailure(e); } } void setFailure(ShardIterator shardIt, int shardIndex, Throwable t) { // we don't aggregate shard failures on non active shards (but do keep the header counts right) if (TransportActions.isShardNotAvailableException(t)) { return; } if (!(t instanceof BroadcastShardOperationFailedException)) { t = new BroadcastShardOperationFailedException(shardIt.shardId(), t); } Object response = shardsResponses.get(shardIndex); if (response == null) { // just override it and return shardsResponses.set(shardIndex, t); } if (!(response instanceof Throwable)) { // we should never really get here... return; } // the failure is already present, try and not override it with an exception that is less meaningless // for example, getting illegal shard state if (TransportActions.isReadOverrideException(t)) { shardsResponses.set(shardIndex, t); } } }
1no label
src_main_java_org_elasticsearch_action_support_broadcast_TransportBroadcastOperationAction.java
1,400
threadPool.executor(ThreadPool.Names.MANAGEMENT).execute(new Runnable() { @Override public void run() { try { if (!mdLock.tryAcquire(request.masterTimeout.nanos(), TimeUnit.NANOSECONDS)) { userListener.onFailure(new ProcessClusterEventTimeoutException(request.masterTimeout, "acquire index lock")); return; } } catch (InterruptedException e) { userListener.onFailure(e); return; } deleteIndex(request, userListener, mdLock); } });
0true
src_main_java_org_elasticsearch_cluster_metadata_MetaDataDeleteIndexService.java
101
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_PAGE_FLD") @EntityListeners(value = { AdminAuditableListener.class }) public class PageFieldImpl implements PageField { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "PageFieldId") @GenericGenerator( name="PageFieldId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="PageFieldImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.cms.page.domain.PageFieldImpl") } ) @Column(name = "PAGE_FLD_ID") protected Long id; @Embedded @AdminPresentation(excluded = true) protected AdminAuditable auditable = new AdminAuditable(); @Column (name = "FLD_KEY") protected String fieldKey; @ManyToOne(targetEntity = PageImpl.class) @JoinColumn(name="PAGE_ID") protected Page page; @Column (name = "VALUE") protected String stringValue; @Column(name = "LOB_VALUE", length = Integer.MAX_VALUE-1) @Lob @Type(type = "org.hibernate.type.StringClobType") protected String lobValue; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getFieldKey() { return fieldKey; } @Override public void setFieldKey(String fieldKey) { this.fieldKey = fieldKey; } @Override public Page getPage() { return page; } @Override public void setPage(Page page) { this.page = page; } @Override public String getValue() { if (stringValue != null && stringValue.length() > 0) { return stringValue; } else { return lobValue; } } @Override public void setValue(String value) { if (value != null) { if (value.length() <= 256) { stringValue = value; lobValue = null; } else { stringValue = null; lobValue = value; } } else { lobValue = null; stringValue = null; } } @Override public AdminAuditable getAuditable() { return auditable; } @Override public void setAuditable(AdminAuditable auditable) { this.auditable = auditable; } @Override public PageField cloneEntity() { PageFieldImpl newPageField = new PageFieldImpl(); newPageField.fieldKey = fieldKey; newPageField.page = page; newPageField.lobValue = lobValue; newPageField.stringValue = stringValue; return newPageField; } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_domain_PageFieldImpl.java
3,239
public final class BytesRefOrdValComparator extends NestedWrappableComparator<BytesRef> { final IndexFieldData.WithOrdinals<?> indexFieldData; final BytesRef missingValue; /* Ords for each slot, times 4. @lucene.internal */ final long[] ords; final SortMode sortMode; /* Values for each slot. @lucene.internal */ final BytesRef[] values; /* Which reader last copied a value into the slot. When we compare two slots, we just compare-by-ord if the readerGen is the same; else we must compare the values (slower). @lucene.internal */ final int[] readerGen; /* Gen of current reader we are on. @lucene.internal */ int currentReaderGen = -1; /* Current reader's doc ord/values. @lucene.internal */ BytesValues.WithOrdinals termsIndex; long missingOrd; /* Bottom slot, or -1 if queue isn't full yet @lucene.internal */ int bottomSlot = -1; /* Bottom ord (same as ords[bottomSlot] once bottomSlot is set). Cached for faster compares. @lucene.internal */ long bottomOrd; final BytesRef tempBR = new BytesRef(); public BytesRefOrdValComparator(IndexFieldData.WithOrdinals<?> indexFieldData, int numHits, SortMode sortMode, BytesRef missingValue) { this.indexFieldData = indexFieldData; this.sortMode = sortMode; this.missingValue = missingValue; ords = new long[numHits]; values = new BytesRef[numHits]; readerGen = new int[numHits]; } @Override public int compare(int slot1, int slot2) { if (readerGen[slot1] == readerGen[slot2]) { return LongValuesComparator.compare(ords[slot1], ords[slot2]); } final BytesRef val1 = values[slot1]; final BytesRef val2 = values[slot2]; if (val1 == null) { if (val2 == null) { return 0; } return -1; } else if (val2 == null) { return 1; } return val1.compareTo(val2); } @Override public int compareBottom(int doc) { throw new UnsupportedOperationException(); } @Override public int compareBottomMissing() { throw new UnsupportedOperationException(); } @Override public void copy(int slot, int doc) { throw new UnsupportedOperationException(); } @Override public void missing(int slot) { throw new UnsupportedOperationException(); } @Override public int compareDocToValue(int doc, BytesRef value) { throw new UnsupportedOperationException(); } class PerSegmentComparator extends NestedWrappableComparator<BytesRef> { final Ordinals.Docs readerOrds; final BytesValues.WithOrdinals termsIndex; public PerSegmentComparator(BytesValues.WithOrdinals termsIndex) { this.readerOrds = termsIndex.ordinals(); this.termsIndex = termsIndex; if (readerOrds.getNumOrds() > Long.MAX_VALUE / 4) { throw new IllegalStateException("Current terms index pretends it has more than " + (Long.MAX_VALUE / 4) + " ordinals, which is unsupported by this impl"); } } @Override public FieldComparator<BytesRef> setNextReader(AtomicReaderContext context) throws IOException { return BytesRefOrdValComparator.this.setNextReader(context); } @Override public int compare(int slot1, int slot2) { return BytesRefOrdValComparator.this.compare(slot1, slot2); } @Override public void setBottom(final int bottom) { BytesRefOrdValComparator.this.setBottom(bottom); } @Override public BytesRef value(int slot) { return BytesRefOrdValComparator.this.value(slot); } @Override public int compareValues(BytesRef val1, BytesRef val2) { if (val1 == null) { if (val2 == null) { return 0; } return -1; } else if (val2 == null) { return 1; } return val1.compareTo(val2); } @Override public int compareDocToValue(int doc, BytesRef value) { final long ord = getOrd(doc); final BytesRef docValue = ord == Ordinals.MISSING_ORDINAL ? missingValue : termsIndex.getValueByOrd(ord); return compareValues(docValue, value); } protected long getOrd(int doc) { return readerOrds.getOrd(doc); } @Override public int compareBottom(int doc) { assert bottomSlot != -1; final long docOrd = getOrd(doc); final long comparableOrd = docOrd == Ordinals.MISSING_ORDINAL ? missingOrd : docOrd << 2; return LongValuesComparator.compare(bottomOrd, comparableOrd); } @Override public int compareBottomMissing() { assert bottomSlot != -1; return LongValuesComparator.compare(bottomOrd, missingOrd); } @Override public void copy(int slot, int doc) { final long ord = getOrd(doc); if (ord == Ordinals.MISSING_ORDINAL) { ords[slot] = missingOrd; values[slot] = missingValue; } else { assert ord > 0; ords[slot] = ord << 2; if (values[slot] == null || values[slot] == missingValue) { values[slot] = new BytesRef(); } values[slot].copyBytes(termsIndex.getValueByOrd(ord)); } readerGen[slot] = currentReaderGen; } @Override public void missing(int slot) { ords[slot] = missingOrd; values[slot] = missingValue; } } // for assertions private boolean consistentInsertedOrd(BytesValues.WithOrdinals termsIndex, long ord, BytesRef value) { assert ord >= 0 : ord; assert (ord == 0) == (value == null) : "ord=" + ord + ", value=" + value; final long previousOrd = ord >>> 2; final long nextOrd = previousOrd + 1; final BytesRef previous = previousOrd == 0 ? null : termsIndex.getValueByOrd(previousOrd); if ((ord & 3) == 0) { // there was an existing ord with the inserted value assert compareValues(previous, value) == 0; } else { assert compareValues(previous, value) < 0; } if (nextOrd < termsIndex.ordinals().getMaxOrd()) { final BytesRef next = termsIndex.getValueByOrd(nextOrd); assert compareValues(value, next) < 0; } return true; } // find where to insert an ord in the current terms index private long ordInCurrentReader(BytesValues.WithOrdinals termsIndex, BytesRef value) { final long docOrd = binarySearch(termsIndex, value); assert docOrd != -1; // would mean smaller than null final long ord; if (docOrd >= 0) { // value exists in the current segment ord = docOrd << 2; } else { // value doesn't exist, use the ord between the previous and the next term ord = ((-2 - docOrd) << 2) + 2; } assert (ord & 1) == 0; return ord; } @Override public FieldComparator<BytesRef> setNextReader(AtomicReaderContext context) throws IOException { termsIndex = indexFieldData.load(context).getBytesValues(false); assert termsIndex.ordinals() != null && termsIndex.ordinals().ordinals() != null; if (missingValue == null) { missingOrd = Ordinals.MISSING_ORDINAL; } else { missingOrd = ordInCurrentReader(termsIndex, missingValue); assert consistentInsertedOrd(termsIndex, missingOrd, missingValue); } FieldComparator<BytesRef> perSegComp = null; assert termsIndex.ordinals() != null && termsIndex.ordinals().ordinals() != null; if (termsIndex.isMultiValued()) { perSegComp = new PerSegmentComparator(termsIndex) { @Override protected long getOrd(int doc) { return getRelevantOrd(readerOrds, doc, sortMode); } }; } else { perSegComp = new PerSegmentComparator(termsIndex); } currentReaderGen++; if (bottomSlot != -1) { perSegComp.setBottom(bottomSlot); } return perSegComp; } @Override public void setBottom(final int bottom) { bottomSlot = bottom; final BytesRef bottomValue = values[bottomSlot]; if (bottomValue == null) { bottomOrd = Ordinals.MISSING_ORDINAL; } else if (currentReaderGen == readerGen[bottomSlot]) { bottomOrd = ords[bottomSlot]; } else { // insert an ord bottomOrd = ordInCurrentReader(termsIndex, bottomValue); if (bottomOrd == missingOrd) { // bottomValue and missingValue and in-between the same field data values -> tie-break // this is why we multiply ords by 4 assert missingValue != null; final int cmp = bottomValue.compareTo(missingValue); if (cmp < 0) { --bottomOrd; } else if (cmp > 0) { ++bottomOrd; } } assert consistentInsertedOrd(termsIndex, bottomOrd, bottomValue); } readerGen[bottomSlot] = currentReaderGen; } @Override public BytesRef value(int slot) { return values[slot]; } final protected static long binarySearch(BytesValues.WithOrdinals a, BytesRef key) { return binarySearch(a, key, 1, a.ordinals().getNumOrds()); } final protected static long binarySearch(BytesValues.WithOrdinals a, BytesRef key, long low, long high) { assert low != Ordinals.MISSING_ORDINAL; assert high == Ordinals.MISSING_ORDINAL || (a.getValueByOrd(high) == null | a.getValueByOrd(high) != null); // make sure we actually can get these values assert low == high + 1 || a.getValueByOrd(low) == null | a.getValueByOrd(low) != null; while (low <= high) { long mid = (low + high) >>> 1; BytesRef midVal = a.getValueByOrd(mid); int cmp; if (midVal != null) { cmp = midVal.compareTo(key); } else { cmp = -1; } if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; } return -(low + 1); } static long getRelevantOrd(Ordinals.Docs readerOrds, int docId, SortMode sortMode) { int length = readerOrds.setDocument(docId); long relevantVal = sortMode.startLong(); long result = 0; assert sortMode == SortMode.MAX || sortMode == SortMode.MIN; for (int i = 0; i < length; i++) { result = relevantVal = sortMode.apply(readerOrds.nextOrd(), relevantVal); } assert result >= 0; assert result <= readerOrds.getMaxOrd(); return result; // Enable this when the api can tell us that the ords per doc are ordered /*if (reversed) { IntArrayRef ref = readerOrds.getOrds(docId); if (ref.isEmpty()) { return 0; } else { return ref.values[ref.end - 1]; // last element is the highest value. } } else { return readerOrds.getOrd(docId); // returns the lowest value }*/ } }
1no label
src_main_java_org_elasticsearch_index_fielddata_fieldcomparator_BytesRefOrdValComparator.java
390
public enum STATUS { NOT_LOADED, LOADED, MARSHALLING, UNMARSHALLING }
0true
core_src_main_java_com_orientechnologies_orient_core_db_record_ORecordElement.java
1,500
public class GroupProperties { public static final String PROP_HOSTED_MANAGEMENT_ENABLED = "hazelcast.hosted.management.enabled"; public static final String PROP_HOSTED_MANAGEMENT_URL = "hazelcast.hosted.management.url"; public static final String PROP_HEALTH_MONITORING_LEVEL = "hazelcast.health.monitoring.level"; public static final String PROP_HEALTH_MONITORING_DELAY_SECONDS = "hazelcast.health.monitoring.delay.seconds"; public static final String PROP_VERSION_CHECK_ENABLED = "hazelcast.version.check.enabled"; public static final String PROP_PREFER_IPv4_STACK = "hazelcast.prefer.ipv4.stack"; public static final String PROP_IO_THREAD_COUNT = "hazelcast.io.thread.count"; /** * The number of partition threads per Member. If this is less than the number of partitions on a Member, then * partition operations will queue behind other operations of different partitions. The default is 4. */ public static final String PROP_PARTITION_OPERATION_THREAD_COUNT = "hazelcast.operation.thread.count"; public static final String PROP_GENERIC_OPERATION_THREAD_COUNT = "hazelcast.operation.generic.thread.count"; public static final String PROP_EVENT_THREAD_COUNT = "hazelcast.event.thread.count"; public static final String PROP_EVENT_QUEUE_CAPACITY = "hazelcast.event.queue.capacity"; public static final String PROP_EVENT_QUEUE_TIMEOUT_MILLIS = "hazelcast.event.queue.timeout.millis"; public static final String PROP_CONNECT_ALL_WAIT_SECONDS = "hazelcast.connect.all.wait.seconds"; public static final String PROP_MEMCACHE_ENABLED = "hazelcast.memcache.enabled"; public static final String PROP_REST_ENABLED = "hazelcast.rest.enabled"; public static final String PROP_MAP_LOAD_CHUNK_SIZE = "hazelcast.map.load.chunk.size"; public static final String PROP_MERGE_FIRST_RUN_DELAY_SECONDS = "hazelcast.merge.first.run.delay.seconds"; public static final String PROP_MERGE_NEXT_RUN_DELAY_SECONDS = "hazelcast.merge.next.run.delay.seconds"; public static final String PROP_OPERATION_CALL_TIMEOUT_MILLIS = "hazelcast.operation.call.timeout.millis"; public static final String PROP_SOCKET_BIND_ANY = "hazelcast.socket.bind.any"; public static final String PROP_SOCKET_SERVER_BIND_ANY = "hazelcast.socket.server.bind.any"; public static final String PROP_SOCKET_CLIENT_BIND_ANY = "hazelcast.socket.client.bind.any"; public static final String PROP_SOCKET_CLIENT_BIND = "hazelcast.socket.client.bind"; public static final String PROP_SOCKET_RECEIVE_BUFFER_SIZE = "hazelcast.socket.receive.buffer.size"; public static final String PROP_SOCKET_SEND_BUFFER_SIZE = "hazelcast.socket.send.buffer.size"; public static final String PROP_SOCKET_LINGER_SECONDS = "hazelcast.socket.linger.seconds"; public static final String PROP_SOCKET_KEEP_ALIVE = "hazelcast.socket.keep.alive"; public static final String PROP_SOCKET_NO_DELAY = "hazelcast.socket.no.delay"; public static final String PROP_SHUTDOWNHOOK_ENABLED = "hazelcast.shutdownhook.enabled"; public static final String PROP_WAIT_SECONDS_BEFORE_JOIN = "hazelcast.wait.seconds.before.join"; public static final String PROP_MAX_WAIT_SECONDS_BEFORE_JOIN = "hazelcast.max.wait.seconds.before.join"; public static final String PROP_MAX_JOIN_SECONDS = "hazelcast.max.join.seconds"; public static final String PROP_MAX_JOIN_MERGE_TARGET_SECONDS = "hazelcast.max.join.merge.target.seconds"; public static final String PROP_HEARTBEAT_INTERVAL_SECONDS = "hazelcast.heartbeat.interval.seconds"; public static final String PROP_MAX_NO_HEARTBEAT_SECONDS = "hazelcast.max.no.heartbeat.seconds"; public static final String PROP_MAX_NO_MASTER_CONFIRMATION_SECONDS = "hazelcast.max.no.master.confirmation.seconds"; public static final String PROP_MASTER_CONFIRMATION_INTERVAL_SECONDS = "hazelcast.master.confirmation.interval.seconds"; public static final String PROP_MEMBER_LIST_PUBLISH_INTERVAL_SECONDS = "hazelcast.member.list.publish.interval.seconds"; public static final String PROP_ICMP_ENABLED = "hazelcast.icmp.enabled"; public static final String PROP_ICMP_TIMEOUT = "hazelcast.icmp.timeout"; public static final String PROP_ICMP_TTL = "hazelcast.icmp.ttl"; public static final String PROP_INITIAL_MIN_CLUSTER_SIZE = "hazelcast.initial.min.cluster.size"; public static final String PROP_INITIAL_WAIT_SECONDS = "hazelcast.initial.wait.seconds"; public static final String PROP_MAP_REPLICA_WAIT_SECONDS_FOR_SCHEDULED_OPERATIONS = "hazelcast.map.replica.wait.seconds.for.scheduled.tasks"; public static final String PROP_PARTITION_COUNT = "hazelcast.partition.count"; public static final String PROP_LOGGING_TYPE = "hazelcast.logging.type"; public static final String PROP_ENABLE_JMX = "hazelcast.jmx"; public static final String PROP_ENABLE_JMX_DETAILED = "hazelcast.jmx.detailed"; public static final String PROP_MC_MAX_VISIBLE_INSTANCE_COUNT = "hazelcast.mc.max.visible.instance.count"; public static final String PROP_MC_URL_CHANGE_ENABLED = "hazelcast.mc.url.change.enabled"; public static final String PROP_CONNECTION_MONITOR_INTERVAL = "hazelcast.connection.monitor.interval"; public static final String PROP_CONNECTION_MONITOR_MAX_FAULTS = "hazelcast.connection.monitor.max.faults"; public static final String PROP_PARTITION_MIGRATION_INTERVAL = "hazelcast.partition.migration.interval"; public static final String PROP_PARTITION_MIGRATION_TIMEOUT = "hazelcast.partition.migration.timeout"; public static final String PROP_PARTITION_MIGRATION_ZIP_ENABLED = "hazelcast.partition.migration.zip.enabled"; public static final String PROP_PARTITION_TABLE_SEND_INTERVAL = "hazelcast.partition.table.send.interval"; public static final String PROP_PARTITION_BACKUP_SYNC_INTERVAL = "hazelcast.partition.backup.sync.interval"; public static final String PROP_PARTITIONING_STRATEGY_CLASS = "hazelcast.partitioning.strategy.class"; public static final String PROP_GRACEFUL_SHUTDOWN_MAX_WAIT = "hazelcast.graceful.shutdown.max.wait"; public static final String PROP_SYSTEM_LOG_ENABLED = "hazelcast.system.log.enabled"; public static final String PROP_ELASTIC_MEMORY_ENABLED = "hazelcast.elastic.memory.enabled"; public static final String PROP_ELASTIC_MEMORY_TOTAL_SIZE = "hazelcast.elastic.memory.total.size"; public static final String PROP_ELASTIC_MEMORY_CHUNK_SIZE = "hazelcast.elastic.memory.chunk.size"; public static final String PROP_ELASTIC_MEMORY_SHARED_STORAGE = "hazelcast.elastic.memory.shared.storage"; public static final String PROP_ELASTIC_MEMORY_UNSAFE_ENABLED = "hazelcast.elastic.memory.unsafe.enabled"; public static final String PROP_ENTERPRISE_LICENSE_KEY = "hazelcast.enterprise.license.key"; /** * This property will only be used temporary until we have exposed the hosted management center to the public. * So it will be disabled by default. */ public final GroupProperty HOSTED_MANAGEMENT_ENABLED; public final GroupProperty HOSTED_MANAGEMENT_URL; public final GroupProperty PARTITION_OPERATION_THREAD_COUNT; public final GroupProperty GENERIC_OPERATION_THREAD_COUNT; public final GroupProperty EVENT_THREAD_COUNT; public final GroupProperty HEALTH_MONITORING_LEVEL; public final GroupProperty HEALTH_MONITORING_DELAY_SECONDS; public final GroupProperty IO_THREAD_COUNT; public final GroupProperty EVENT_QUEUE_CAPACITY; public final GroupProperty EVENT_QUEUE_TIMEOUT_MILLIS; public final GroupProperty PREFER_IPv4_STACK; public final GroupProperty CONNECT_ALL_WAIT_SECONDS; public final GroupProperty VERSION_CHECK_ENABLED; public final GroupProperty MEMCACHE_ENABLED; public final GroupProperty REST_ENABLED; public final GroupProperty MAP_LOAD_CHUNK_SIZE; public final GroupProperty MERGE_FIRST_RUN_DELAY_SECONDS; public final GroupProperty MERGE_NEXT_RUN_DELAY_SECONDS; public final GroupProperty OPERATION_CALL_TIMEOUT_MILLIS; public final GroupProperty SOCKET_SERVER_BIND_ANY; public final GroupProperty SOCKET_CLIENT_BIND_ANY; public final GroupProperty SOCKET_CLIENT_BIND; // number of kilobytes public final GroupProperty SOCKET_RECEIVE_BUFFER_SIZE; // number of kilobytes public final GroupProperty SOCKET_SEND_BUFFER_SIZE; public final GroupProperty SOCKET_LINGER_SECONDS; public final GroupProperty SOCKET_KEEP_ALIVE; public final GroupProperty SOCKET_NO_DELAY; public final GroupProperty SHUTDOWNHOOK_ENABLED; public final GroupProperty WAIT_SECONDS_BEFORE_JOIN; public final GroupProperty MAX_WAIT_SECONDS_BEFORE_JOIN; public final GroupProperty MAX_JOIN_SECONDS; public final GroupProperty MAX_JOIN_MERGE_TARGET_SECONDS; public final GroupProperty MAX_NO_HEARTBEAT_SECONDS; public final GroupProperty HEARTBEAT_INTERVAL_SECONDS; public final GroupProperty MASTER_CONFIRMATION_INTERVAL_SECONDS; public final GroupProperty MAX_NO_MASTER_CONFIRMATION_SECONDS; public final GroupProperty MEMBER_LIST_PUBLISH_INTERVAL_SECONDS; public final GroupProperty ICMP_ENABLED; public final GroupProperty ICMP_TIMEOUT; public final GroupProperty ICMP_TTL; public final GroupProperty INITIAL_WAIT_SECONDS; public final GroupProperty INITIAL_MIN_CLUSTER_SIZE; public final GroupProperty MAP_REPLICA_WAIT_SECONDS_FOR_SCHEDULED_TASKS; public final GroupProperty PARTITION_COUNT; public final GroupProperty LOGGING_TYPE; public final GroupProperty ENABLE_JMX; public final GroupProperty ENABLE_JMX_DETAILED; public final GroupProperty MC_MAX_INSTANCE_COUNT; public final GroupProperty MC_URL_CHANGE_ENABLED; public final GroupProperty CONNECTION_MONITOR_INTERVAL; public final GroupProperty CONNECTION_MONITOR_MAX_FAULTS; public final GroupProperty PARTITION_MIGRATION_INTERVAL; public final GroupProperty PARTITION_MIGRATION_TIMEOUT; public final GroupProperty PARTITION_MIGRATION_ZIP_ENABLED; public final GroupProperty PARTITION_TABLE_SEND_INTERVAL; public final GroupProperty PARTITION_BACKUP_SYNC_INTERVAL; public final GroupProperty PARTITIONING_STRATEGY_CLASS; public final GroupProperty GRACEFUL_SHUTDOWN_MAX_WAIT; public final GroupProperty SYSTEM_LOG_ENABLED; public final GroupProperty ELASTIC_MEMORY_ENABLED; public final GroupProperty ELASTIC_MEMORY_TOTAL_SIZE; public final GroupProperty ELASTIC_MEMORY_CHUNK_SIZE; public final GroupProperty ELASTIC_MEMORY_SHARED_STORAGE; public final GroupProperty ELASTIC_MEMORY_UNSAFE_ENABLED; public final GroupProperty ENTERPRISE_LICENSE_KEY; /** * * @param config */ public GroupProperties(Config config) { HOSTED_MANAGEMENT_ENABLED = new GroupProperty(config, PROP_HOSTED_MANAGEMENT_ENABLED, "false"); //todo: we need to pull out the version. HOSTED_MANAGEMENT_URL = new GroupProperty(config, PROP_HOSTED_MANAGEMENT_URL, "http://manage.hazelcast.com/3.2"); HEALTH_MONITORING_LEVEL = new GroupProperty(config, PROP_HEALTH_MONITORING_LEVEL, HealthMonitorLevel.SILENT.toString()); HEALTH_MONITORING_DELAY_SECONDS = new GroupProperty(config, PROP_HEALTH_MONITORING_DELAY_SECONDS, "30"); VERSION_CHECK_ENABLED = new GroupProperty(config, PROP_VERSION_CHECK_ENABLED, "true"); PREFER_IPv4_STACK = new GroupProperty(config, PROP_PREFER_IPv4_STACK, "true"); IO_THREAD_COUNT = new GroupProperty(config, PROP_IO_THREAD_COUNT, "3"); //-1 means that the value is worked out dynamically. PARTITION_OPERATION_THREAD_COUNT = new GroupProperty(config, PROP_PARTITION_OPERATION_THREAD_COUNT, "-1"); GENERIC_OPERATION_THREAD_COUNT = new GroupProperty(config, PROP_GENERIC_OPERATION_THREAD_COUNT, "-1"); EVENT_THREAD_COUNT = new GroupProperty(config, PROP_EVENT_THREAD_COUNT, "5"); EVENT_QUEUE_CAPACITY = new GroupProperty(config, PROP_EVENT_QUEUE_CAPACITY, "1000000"); EVENT_QUEUE_TIMEOUT_MILLIS = new GroupProperty(config, PROP_EVENT_QUEUE_TIMEOUT_MILLIS, "250"); CONNECT_ALL_WAIT_SECONDS = new GroupProperty(config, PROP_CONNECT_ALL_WAIT_SECONDS, "120"); MEMCACHE_ENABLED = new GroupProperty(config, PROP_MEMCACHE_ENABLED, "true"); REST_ENABLED = new GroupProperty(config, PROP_REST_ENABLED, "true"); MAP_LOAD_CHUNK_SIZE = new GroupProperty(config, PROP_MAP_LOAD_CHUNK_SIZE, "1000"); MERGE_FIRST_RUN_DELAY_SECONDS = new GroupProperty(config, PROP_MERGE_FIRST_RUN_DELAY_SECONDS, "300"); MERGE_NEXT_RUN_DELAY_SECONDS = new GroupProperty(config, PROP_MERGE_NEXT_RUN_DELAY_SECONDS, "120"); OPERATION_CALL_TIMEOUT_MILLIS = new GroupProperty(config, PROP_OPERATION_CALL_TIMEOUT_MILLIS, "60000"); final GroupProperty SOCKET_BIND_ANY = new GroupProperty(config, PROP_SOCKET_BIND_ANY, "true"); SOCKET_SERVER_BIND_ANY = new GroupProperty(config, PROP_SOCKET_SERVER_BIND_ANY, SOCKET_BIND_ANY); SOCKET_CLIENT_BIND_ANY = new GroupProperty(config, PROP_SOCKET_CLIENT_BIND_ANY, SOCKET_BIND_ANY); SOCKET_CLIENT_BIND = new GroupProperty(config, PROP_SOCKET_CLIENT_BIND, "true"); SOCKET_RECEIVE_BUFFER_SIZE = new GroupProperty(config, PROP_SOCKET_RECEIVE_BUFFER_SIZE, "32"); SOCKET_SEND_BUFFER_SIZE = new GroupProperty(config, PROP_SOCKET_SEND_BUFFER_SIZE, "32"); SOCKET_LINGER_SECONDS = new GroupProperty(config, PROP_SOCKET_LINGER_SECONDS, "0"); SOCKET_KEEP_ALIVE = new GroupProperty(config, PROP_SOCKET_KEEP_ALIVE, "true"); SOCKET_NO_DELAY = new GroupProperty(config, PROP_SOCKET_NO_DELAY, "true"); SHUTDOWNHOOK_ENABLED = new GroupProperty(config, PROP_SHUTDOWNHOOK_ENABLED, "true"); WAIT_SECONDS_BEFORE_JOIN = new GroupProperty(config, PROP_WAIT_SECONDS_BEFORE_JOIN, "5"); MAX_WAIT_SECONDS_BEFORE_JOIN = new GroupProperty(config, PROP_MAX_WAIT_SECONDS_BEFORE_JOIN, "20"); MAX_JOIN_SECONDS = new GroupProperty(config, PROP_MAX_JOIN_SECONDS, "300"); MAX_JOIN_MERGE_TARGET_SECONDS = new GroupProperty(config, PROP_MAX_JOIN_MERGE_TARGET_SECONDS, "20"); HEARTBEAT_INTERVAL_SECONDS = new GroupProperty(config, PROP_HEARTBEAT_INTERVAL_SECONDS, "1"); MAX_NO_HEARTBEAT_SECONDS = new GroupProperty(config, PROP_MAX_NO_HEARTBEAT_SECONDS, "300"); MASTER_CONFIRMATION_INTERVAL_SECONDS = new GroupProperty(config, PROP_MASTER_CONFIRMATION_INTERVAL_SECONDS, "30"); MAX_NO_MASTER_CONFIRMATION_SECONDS = new GroupProperty(config, PROP_MAX_NO_MASTER_CONFIRMATION_SECONDS, "300"); MEMBER_LIST_PUBLISH_INTERVAL_SECONDS = new GroupProperty(config, PROP_MEMBER_LIST_PUBLISH_INTERVAL_SECONDS, "300"); ICMP_ENABLED = new GroupProperty(config, PROP_ICMP_ENABLED, "false"); ICMP_TIMEOUT = new GroupProperty(config, PROP_ICMP_TIMEOUT, "1000"); ICMP_TTL = new GroupProperty(config, PROP_ICMP_TTL, "0"); INITIAL_MIN_CLUSTER_SIZE = new GroupProperty(config, PROP_INITIAL_MIN_CLUSTER_SIZE, "0"); INITIAL_WAIT_SECONDS = new GroupProperty(config, PROP_INITIAL_WAIT_SECONDS, "0"); MAP_REPLICA_WAIT_SECONDS_FOR_SCHEDULED_TASKS = new GroupProperty(config, PROP_MAP_REPLICA_WAIT_SECONDS_FOR_SCHEDULED_OPERATIONS, "10"); PARTITION_COUNT = new GroupProperty(config, PROP_PARTITION_COUNT, "271"); LOGGING_TYPE = new GroupProperty(config, PROP_LOGGING_TYPE, "jdk"); ENABLE_JMX = new GroupProperty(config, PROP_ENABLE_JMX, "false"); ENABLE_JMX_DETAILED = new GroupProperty(config, PROP_ENABLE_JMX_DETAILED, "false"); MC_MAX_INSTANCE_COUNT = new GroupProperty(config, PROP_MC_MAX_VISIBLE_INSTANCE_COUNT, "100"); MC_URL_CHANGE_ENABLED = new GroupProperty(config, PROP_MC_URL_CHANGE_ENABLED, "true"); CONNECTION_MONITOR_INTERVAL = new GroupProperty(config, PROP_CONNECTION_MONITOR_INTERVAL, "100"); CONNECTION_MONITOR_MAX_FAULTS = new GroupProperty(config, PROP_CONNECTION_MONITOR_MAX_FAULTS, "3"); PARTITION_MIGRATION_INTERVAL = new GroupProperty(config, PROP_PARTITION_MIGRATION_INTERVAL, "0"); PARTITION_MIGRATION_TIMEOUT = new GroupProperty(config, PROP_PARTITION_MIGRATION_TIMEOUT, "300"); PARTITION_MIGRATION_ZIP_ENABLED = new GroupProperty(config, PROP_PARTITION_MIGRATION_ZIP_ENABLED, "true"); PARTITION_TABLE_SEND_INTERVAL = new GroupProperty(config, PROP_PARTITION_TABLE_SEND_INTERVAL, "15"); PARTITION_BACKUP_SYNC_INTERVAL = new GroupProperty(config, PROP_PARTITION_BACKUP_SYNC_INTERVAL, "30"); PARTITIONING_STRATEGY_CLASS = new GroupProperty(config, PROP_PARTITIONING_STRATEGY_CLASS, ""); GRACEFUL_SHUTDOWN_MAX_WAIT = new GroupProperty(config, PROP_GRACEFUL_SHUTDOWN_MAX_WAIT, "600"); SYSTEM_LOG_ENABLED = new GroupProperty(config, PROP_SYSTEM_LOG_ENABLED, "true"); ELASTIC_MEMORY_ENABLED = new GroupProperty(config, PROP_ELASTIC_MEMORY_ENABLED, "false"); ELASTIC_MEMORY_TOTAL_SIZE = new GroupProperty(config, PROP_ELASTIC_MEMORY_TOTAL_SIZE, "128M"); ELASTIC_MEMORY_CHUNK_SIZE = new GroupProperty(config, PROP_ELASTIC_MEMORY_CHUNK_SIZE, "1K"); ELASTIC_MEMORY_SHARED_STORAGE = new GroupProperty(config, PROP_ELASTIC_MEMORY_SHARED_STORAGE, "false"); ELASTIC_MEMORY_UNSAFE_ENABLED = new GroupProperty(config, PROP_ELASTIC_MEMORY_UNSAFE_ENABLED, "false"); ENTERPRISE_LICENSE_KEY = new GroupProperty(config, PROP_ENTERPRISE_LICENSE_KEY); } public static class GroupProperty { private final String name; private final String value; GroupProperty(Config config, String name) { this(config, name, (String) null); } GroupProperty(Config config, String name, GroupProperty defaultValue) { this(config, name, defaultValue != null ? defaultValue.getString() : null); } GroupProperty(Config config, String name, String defaultValue) { this.name = name; String configValue = (config != null) ? config.getProperty(name) : null; if (configValue != null) { value = configValue; } else if (System.getProperty(name) != null) { value = System.getProperty(name); } else { value = defaultValue; } } public String getName() { return this.name; } public String getValue() { return value; } public int getInteger() { return Integer.parseInt(this.value); } public byte getByte() { return Byte.parseByte(this.value); } public boolean getBoolean() { return Boolean.valueOf(this.value); } public String getString() { return value; } public long getLong() { return Long.parseLong(this.value); } @Override public String toString() { return "GroupProperty [name=" + this.name + ", value=" + this.value + "]"; } } }
1no label
hazelcast_src_main_java_com_hazelcast_instance_GroupProperties.java
834
public class AtomicReferenceService implements ManagedService, RemoteService, MigrationAwareService { /** * The name of the AtomicReferenceService. */ public static final String SERVICE_NAME = "hz:impl:atomicReferenceService"; private NodeEngine nodeEngine; private final ConcurrentMap<String, ReferenceWrapper> references = new ConcurrentHashMap<String, ReferenceWrapper>(); private final ConstructorFunction<String, ReferenceWrapper> atomicReferenceConstructorFunction = new ConstructorFunction<String, ReferenceWrapper>() { public ReferenceWrapper createNew(String key) { return new ReferenceWrapper(); } }; public AtomicReferenceService() { } public ReferenceWrapper getReference(String name) { return getOrPutIfAbsent(references, name, atomicReferenceConstructorFunction); } // need for testing.. public boolean containsAtomicReference(String name) { return references.containsKey(name); } @Override public void init(NodeEngine nodeEngine, Properties properties) { this.nodeEngine = nodeEngine; } @Override public void reset() { references.clear(); } @Override public void shutdown(boolean terminate) { reset(); } @Override public AtomicReferenceProxy createDistributedObject(String name) { return new AtomicReferenceProxy(name, nodeEngine, this); } @Override public void destroyDistributedObject(String name) { references.remove(name); } @Override public void beforeMigration(PartitionMigrationEvent partitionMigrationEvent) { } @Override public Operation prepareReplicationOperation(PartitionReplicationEvent event) { if (event.getReplicaIndex() > 1) { return null; } Map<String, Data> data = new HashMap<String, Data>(); int partitionId = event.getPartitionId(); for (String name : references.keySet()) { if (partitionId == getPartitionId(name)) { ReferenceWrapper referenceWrapper = references.get(name); Data value = referenceWrapper.get(); data.put(name, value); } } return data.isEmpty() ? null : new AtomicReferenceReplicationOperation(data); } @Override public void commitMigration(PartitionMigrationEvent partitionMigrationEvent) { if (partitionMigrationEvent.getMigrationEndpoint() == MigrationEndpoint.SOURCE) { int partitionId = partitionMigrationEvent.getPartitionId(); removeReference(partitionId); } } @Override public void rollbackMigration(PartitionMigrationEvent partitionMigrationEvent) { if (partitionMigrationEvent.getMigrationEndpoint() == MigrationEndpoint.DESTINATION) { int partitionId = partitionMigrationEvent.getPartitionId(); removeReference(partitionId); } } @Override public void clearPartitionReplica(int partitionId) { removeReference(partitionId); } public void removeReference(int partitionId) { final Iterator<String> iterator = references.keySet().iterator(); while (iterator.hasNext()) { String name = iterator.next(); if (getPartitionId(name) == partitionId) { iterator.remove(); } } } private int getPartitionId(String name) { InternalPartitionService partitionService = nodeEngine.getPartitionService(); String partitionKey = StringPartitioningStrategy.getPartitionKey(name); return partitionService.getPartitionId(partitionKey); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_AtomicReferenceService.java
3,615
@Beta public class XAResourceImpl implements XAResource { private final TransactionManagerServiceImpl transactionManager; private final TransactionContextImpl transactionContext; private final ILogger logger; private int transactionTimeoutSeconds; public XAResourceImpl(TransactionManagerServiceImpl transactionManager, TransactionContextImpl transactionContext, NodeEngineImpl nodeEngine) { this.transactionManager = transactionManager; this.transactionContext = transactionContext; this.logger = nodeEngine.getLogger(XAResourceImpl.class); } //XAResource --START @Override public synchronized void start(Xid xid, int flags) throws XAException { nullCheck(xid); switch (flags) { case TMNOFLAGS: if (getTransaction(xid) != null) { final XAException xaException = new XAException(XAException.XAER_DUPID); logger.severe("Duplicate xid: " + xid, xaException); throw xaException; } try { final Transaction transaction = getTransaction(); transactionManager.addManagedTransaction(xid, transaction); transaction.begin(); } catch (IllegalStateException e) { logger.severe(e); throw new XAException(XAException.XAER_INVAL); } break; case TMRESUME: case TMJOIN: break; default: throw new XAException(XAException.XAER_INVAL); } } @Override public synchronized void end(Xid xid, int flags) throws XAException { nullCheck(xid); final TransactionImpl transaction = (TransactionImpl) getTransaction(); final SerializableXID sXid = transaction.getXid(); if (sXid == null || !sXid.equals(xid)) { logger.severe("started xid: " + sXid + " and given xid : " + xid + " not equal!!!"); } validateTx(transaction, State.ACTIVE); switch (flags) { case XAResource.TMSUCCESS: //successfully end. break; case XAResource.TMFAIL: transaction.setRollbackOnly(); throw new XAException(XAException.XA_RBROLLBACK); // break; case XAResource.TMSUSPEND: break; default: throw new XAException(XAException.XAER_INVAL); } } @Override public synchronized int prepare(Xid xid) throws XAException { nullCheck(xid); final TransactionImpl transaction = (TransactionImpl) getTransaction(); final SerializableXID sXid = transaction.getXid(); if (sXid == null || !sXid.equals(xid)) { logger.severe("started xid: " + sXid + " and given xid : " + xid + " not equal!!!"); } validateTx(transaction, State.ACTIVE); try { transaction.prepare(); } catch (TransactionException e) { throw new XAException(XAException.XAER_RMERR); } return XAResource.XA_OK; } @Override public synchronized void commit(Xid xid, boolean onePhase) throws XAException { nullCheck(xid); final Transaction transaction = getTransaction(xid); if (onePhase) { validateTx(transaction, State.ACTIVE); transaction.prepare(); } validateTx(transaction, State.PREPARED); try { transaction.commit(); transactionManager.removeManagedTransaction(xid); } catch (TransactionException e) { throw new XAException(XAException.XAER_RMERR); } } @Override public synchronized void rollback(Xid xid) throws XAException { nullCheck(xid); final Transaction transaction = getTransaction(xid); //NO_TXN means do not validate state validateTx(transaction, State.NO_TXN); try { transaction.rollback(); transactionManager.removeManagedTransaction(xid); } catch (TransactionException e) { throw new XAException(XAException.XAER_RMERR); } } @Override public synchronized void forget(Xid xid) throws XAException { throw new XAException(XAException.XAER_PROTO); } @Override public synchronized boolean isSameRM(XAResource xaResource) throws XAException { if (xaResource instanceof XAResourceImpl) { XAResourceImpl other = (XAResourceImpl) xaResource; return transactionManager.equals(other.transactionManager); } return false; } @Override public synchronized Xid[] recover(int flag) throws XAException { return transactionManager.recover(); } @Override public synchronized int getTransactionTimeout() throws XAException { return transactionTimeoutSeconds; } @Override public synchronized boolean setTransactionTimeout(int seconds) throws XAException { this.transactionTimeoutSeconds = seconds; return false; } //XAResource --END private void nullCheck(Xid xid) throws XAException { if (xid == null) { final XAException xaException = new XAException(XAException.XAER_INVAL); logger.severe("Xid cannot be null!!!", xaException); throw xaException; } } private void validateTx(Transaction tx, State state) throws XAException { if (tx == null) { final XAException xaException = new XAException(XAException.XAER_NOTA); logger.severe("Transaction is not available!!!", xaException); throw xaException; } final State txState = tx.getState(); switch (state) { case ACTIVE: if (txState != State.ACTIVE) { final XAException xaException = new XAException(XAException.XAER_NOTA); logger.severe("Transaction is not active!!! state: " + txState, xaException); throw xaException; } break; case PREPARED: if (txState != State.PREPARED) { final XAException xaException = new XAException(XAException.XAER_INVAL); logger.severe("Transaction is not prepared!!! state: " + txState, xaException); throw xaException; } break; default: break; } } private Transaction getTransaction(Xid xid) { return transactionManager.getManagedTransaction(xid); } private Transaction getTransaction() { return transactionContext.getTransaction(); } @Override public String toString() { final String txnId = transactionContext.getTxnId(); final StringBuilder sb = new StringBuilder("XAResourceImpl{"); sb.append("txdId=").append(txnId); sb.append(", transactionTimeoutSeconds=").append(transactionTimeoutSeconds); sb.append('}'); return sb.toString(); } }
1no label
hazelcast_src_main_java_com_hazelcast_transaction_impl_XAResourceImpl.java
2
public class AbbreviationServiceImpl implements AbbreviationService { private static final Logger logger = LoggerFactory.getLogger(AbbreviationServiceImpl.class); private static final String ABBREVIATIONS_FILE_PROPERTY = "abbreviations-file"; private AbbreviationsManager manager; /** * Activates the service implementation. A map of properties is * used to configure the service. * * @param context the component context for this service */ public void activate(ComponentContext context) { @SuppressWarnings("unchecked") Dictionary<String,String> properties = context.getProperties(); // This property will always be present, according to OSGi 4.1 Compendium // Specification section 112.6. String componentName = properties.get("component.name"); String abbreviationsFilePath = properties.get(ABBREVIATIONS_FILE_PROPERTY); Properties abbreviationsProperties = null; if (abbreviationsFilePath == null) { logger.warn("{}: no configuration value for {} - no abbreviations will be available.", componentName, ABBREVIATIONS_FILE_PROPERTY); } else { InputStream in = findFile(abbreviationsFilePath); if (in == null) { logger.warn("{}: abbreviations file <{}> not found - no abbreviations will be available.", componentName, abbreviationsFilePath); } else { try { abbreviationsProperties = new Properties(); abbreviationsProperties.load(in); } catch (IOException ex) { logger.warn("{}: error loading abbreviations file <{}> - no abbreviations will be available.", componentName, abbreviationsFilePath); abbreviationsProperties = null; } } } if (abbreviationsProperties == null) { abbreviationsProperties = new Properties(); } manager = new AbbreviationsManager(abbreviationsProperties); } /** * Looks up a file given a path. The file is looked up first relative to the * current directory. If not found, a matching resource within the bundle is * tried. If neither method works, null is returned to indicate that the file * could not be found. * * @param path a relative or absolute pathname, or a resource name from within the bundle * @return an input stream for reading from the file, or null if the file could not be found */ InputStream findFile(String path) { // 1. Try to find using the file path, which may be absolute or // relative to the current directory. File f = new File(path); if (f.isFile() && f.canRead()) { try { return new FileInputStream(f); } catch (Exception ex) { // ignore, for now } } // 2. Try to find a resource in the bundle. This return value may be null, // if no resource is found matching the path. return getClass().getResourceAsStream(path); } @Override public Abbreviations getAbbreviations(String s) { return manager.getAbbreviations(s); } }
0true
tableViews_src_main_java_gov_nasa_arc_mct_abbreviation_impl_AbbreviationServiceImpl.java
1,051
@SuppressWarnings("unchecked") public class OCommandExecutorSQLSelect extends OCommandExecutorSQLResultsetAbstract { private static final String KEYWORD_AS = " AS "; public static final String KEYWORD_SELECT = "SELECT"; public static final String KEYWORD_ASC = "ASC"; public static final String KEYWORD_DESC = "DESC"; public static final String KEYWORD_ORDER = "ORDER"; public static final String KEYWORD_BY = "BY"; public static final String KEYWORD_GROUP = "GROUP"; public static final String KEYWORD_FETCHPLAN = "FETCHPLAN"; private static final int MIN_THRESHOLD_USE_INDEX_AS_TARGET = 100; private Map<String, String> projectionDefinition = null; private Map<String, Object> projections = null; // THIS HAS BEEN KEPT FOR COMPATIBILITY; BUT // IT'S // USED THE // PROJECTIONS IN GROUPED-RESULTS private List<OPair<String, String>> orderedFields; private List<String> groupByFields; private Map<Object, ORuntimeResult> groupedResult; private Object expandTarget; private int fetchLimit = -1; private OIdentifiable lastRecord; private Iterator<OIdentifiable> subIterator; private String fetchPlan; /** * Compile the filter conditions only the first time. */ public OCommandExecutorSQLSelect parse(final OCommandRequest iRequest) { super.parse(iRequest); if (context == null) context = new OBasicCommandContext(); final int pos = parseProjections(); if (pos == -1) return this; final int endPosition = parserText.length(); parserNextWord(true); if (parserGetLastWord().equalsIgnoreCase(KEYWORD_FROM)) { // FROM parsedTarget = OSQLEngine.getInstance().parseTarget(parserText.substring(parserGetCurrentPosition(), endPosition), getContext(), KEYWORD_WHERE); parserSetCurrentPosition(parsedTarget.parserIsEnded() ? endPosition : parsedTarget.parserGetCurrentPosition() + parserGetCurrentPosition()); } else parserGoBack(); if (!parserIsEnded()) { parserSkipWhiteSpaces(); while (!parserIsEnded()) { parserNextWord(true); if (!parserIsEnded()) { final String w = parserGetLastWord(); if (w.equals(KEYWORD_WHERE)) { compiledFilter = OSQLEngine.getInstance().parseCondition(parserText.substring(parserGetCurrentPosition(), endPosition), getContext(), KEYWORD_WHERE); optimize(); parserSetCurrentPosition(compiledFilter.parserIsEnded() ? endPosition : compiledFilter.parserGetCurrentPosition() + parserGetCurrentPosition()); } else if (w.equals(KEYWORD_LET)) parseLet(); else if (w.equals(KEYWORD_GROUP)) parseGroupBy(w); else if (w.equals(KEYWORD_ORDER)) parseOrderBy(w); else if (w.equals(KEYWORD_LIMIT)) parseLimit(w); else if (w.equals(KEYWORD_SKIP)) parseSkip(w); else if (w.equals(KEYWORD_FETCHPLAN)) parseFetchplan(w); else if (w.equals(KEYWORD_TIMEOUT)) parseTimeout(w); else throwParsingException("Invalid keyword '" + w + "'"); } } } if (limit == 0 || limit < -1) { throw new IllegalArgumentException("Limit must be > 0 or = -1 (no limit)"); } return this; } /** * Determine clusters that are used in select operation * * @return set of involved clusters */ public Set<Integer> getInvolvedClusters() { final Set<Integer> clusters = new HashSet<Integer>(); if (parsedTarget.getTargetRecords() != null) { for (OIdentifiable identifiable : parsedTarget.getTargetRecords()) { clusters.add(identifiable.getIdentity().getClusterId()); } } if (parsedTarget.getTargetClasses() != null) { final OStorage storage = getDatabase().getStorage(); for (String clazz : parsedTarget.getTargetClasses().values()) { clusters.add(storage.getClusterIdByName(clazz)); } } if (parsedTarget.getTargetClusters() != null) { final OStorage storage = getDatabase().getStorage(); for (String clazz : parsedTarget.getTargetClusters().values()) { clusters.add(storage.getClusterIdByName(clazz)); } } if (parsedTarget.getTargetIndex() != null) { // TODO indexes?? } return clusters; } /** * Add condition so that query will be executed only on the given id range. That is used to verify that query will be executed on * the single node * * @param fromId * @param toId * @return this */ public OCommandExecutorSQLSelect boundToLocalNode(long fromId, long toId) { if (fromId == toId) { // single node in dht return this; } final OSQLFilterCondition nodeCondition; if (fromId < toId) { nodeCondition = getConditionForRidPosRange(fromId, toId); } else { nodeCondition = new OSQLFilterCondition(getConditionForRidPosRange(fromId, Long.MAX_VALUE), new OQueryOperatorOr(), getConditionForRidPosRange(-1L, toId)); } if (compiledFilter == null) { compiledFilter = OSQLEngine.getInstance().parseCondition("", getContext(), KEYWORD_WHERE); } final OSQLFilterCondition rootCondition = compiledFilter.getRootCondition(); if (rootCondition != null) { compiledFilter.setRootCondition(new OSQLFilterCondition(nodeCondition, new OQueryOperatorAnd(), rootCondition)); } else { compiledFilter.setRootCondition(nodeCondition); } return this; } protected static OSQLFilterCondition getConditionForRidPosRange(long fromId, long toId) { final OSQLFilterCondition fromCondition = new OSQLFilterCondition(new OSQLFilterItemField(null, ODocumentHelper.ATTRIBUTE_RID_POS), new OQueryOperatorMajor(), fromId); final OSQLFilterCondition toCondition = new OSQLFilterCondition( new OSQLFilterItemField(null, ODocumentHelper.ATTRIBUTE_RID_POS), new OQueryOperatorMinorEquals(), toId); return new OSQLFilterCondition(fromCondition, new OQueryOperatorAnd(), toCondition); } /** * @return {@code ture} if any of the sql functions perform aggregation, {@code false} otherwise */ public boolean isAnyFunctionAggregates() { if (projections != null) { for (Entry<String, Object> p : projections.entrySet()) { if (p.getValue() instanceof OSQLFunctionRuntime && ((OSQLFunctionRuntime) p.getValue()).aggregateResults()) return true; } } return false; } public boolean hasNext() { if (lastRecord == null) // GET THE NEXT lastRecord = next(); // BROWSE ALL THE RECORDS return lastRecord != null; } public OIdentifiable next() { if (lastRecord != null) { // RETURN LATEST AND RESET IT final OIdentifiable result = lastRecord; lastRecord = null; return result; } if (subIterator == null) { if (target == null) { // GET THE RESULT executeSearch(null); applyExpand(); handleNoTarget(); handleGroupBy(); applyOrderBy(); subIterator = new ArrayList<OIdentifiable>((List<OIdentifiable>) getResult()).iterator(); lastRecord = null; tempResult = null; groupedResult = null; } else subIterator = (Iterator<OIdentifiable>) target; } // RESUME THE LAST POSITION if (lastRecord == null && subIterator != null) while (subIterator.hasNext()) { lastRecord = subIterator.next(); if (lastRecord != null) return lastRecord; } return lastRecord; } public void remove() { throw new UnsupportedOperationException("remove()"); } public Iterator<OIdentifiable> iterator() { return this; } public Object execute(final Map<Object, Object> iArgs) { if (iArgs != null) // BIND ARGUMENTS INTO CONTEXT TO ACCESS FROM ANY POINT (EVEN FUNCTIONS) for (Entry<Object, Object> arg : iArgs.entrySet()) context.setVariable(arg.getKey().toString(), arg.getValue()); if (timeoutMs > 0) getContext().beginExecution(timeoutMs, timeoutStrategy); if (!optimizeExecution()) { fetchLimit = getQueryFetchLimit(); executeSearch(iArgs); applyExpand(); handleNoTarget(); handleGroupBy(); applyOrderBy(); applyLimitAndSkip(); } return getResult(); } protected void executeSearch(final Map<Object, Object> iArgs) { assignTarget(iArgs); if (target == null) { if (let != null) // EXECUTE ONCE TO ASSIGN THE LET assignLetClauses(lastRecord != null ? lastRecord.getRecord() : null); // SEARCH WITHOUT USING TARGET (USUALLY WHEN LET/INDEXES ARE INVOLVED) return; } final long startFetching = System.currentTimeMillis(); try { // BROWSE ALL THE RECORDS while (target.hasNext()) if (!executeSearchRecord(target.next())) break; } finally { context.setVariable("fetchingFromTargetElapsed", (System.currentTimeMillis() - startFetching)); } if (request.getResultListener() != null) request.getResultListener().end(); } @Override protected boolean assignTarget(Map<Object, Object> iArgs) { if (!super.assignTarget(iArgs)) { if (parsedTarget.getTargetIndex() != null) searchInIndex(); else throw new OQueryParsingException("No source found in query: specify class, cluster(s), index or single record(s). Use " + getSyntax()); } return true; } protected boolean executeSearchRecord(final OIdentifiable id) { if (Thread.interrupted()) throw new OCommandExecutionException("The select execution has been interrupted"); if (!context.checkTimeout()) return false; final ORecordInternal<?> record = id.getRecord(); context.updateMetric("recordReads", +1); if (record == null || record.getRecordType() != ODocument.RECORD_TYPE) // SKIP IT return true; context.updateMetric("documentReads", +1); if (filter(record)) if (!handleResult(record, true)) // END OF EXECUTION return false; return true; } protected boolean handleResult(final OIdentifiable iRecord, final boolean iCloneIt) { lastRecord = null; if (orderedFields == null && skip > 0) { skip--; return true; } if (iCloneIt) lastRecord = iRecord instanceof ORecord<?> ? ((ORecord<?>) iRecord).copy() : iRecord.getIdentity().copy(); else lastRecord = iRecord; resultCount++; addResult(lastRecord); if (orderedFields == null && !isAnyFunctionAggregates() && fetchLimit > -1 && resultCount >= fetchLimit) // BREAK THE EXECUTION return false; return true; } protected void addResult(OIdentifiable iRecord) { if (iRecord == null) return; if (projections != null || groupByFields != null && !groupByFields.isEmpty()) { if (groupedResult == null) { // APPLY PROJECTIONS IN LINE iRecord = ORuntimeResult.getProjectionResult(resultCount, projections, context, iRecord); if (iRecord == null) return; } else { // AGGREGATION/GROUP BY final ODocument doc = (ODocument) iRecord.getRecord(); Object fieldValue = null; if (groupByFields != null && !groupByFields.isEmpty()) { if (groupByFields.size() > 1) { // MULTI-FIELD FROUP BY final Object[] fields = new Object[groupByFields.size()]; for (int i = 0; i < groupByFields.size(); ++i) { final String field = groupByFields.get(i); if (field.startsWith("$")) fields[i] = context.getVariable(field); else fields[i] = doc.field(field); } fieldValue = fields; } else { final String field = groupByFields.get(0); if (field != null) { if (field.startsWith("$")) fieldValue = context.getVariable(field); else fieldValue = doc.field(field); } } } getProjectionGroup(fieldValue).applyRecord(iRecord); return; } } if (orderedFields == null && expandTarget == null) { // SEND THE RESULT INLINE if (request.getResultListener() != null) request.getResultListener().result(iRecord); } else { // COLLECT ALL THE RECORDS AND ORDER THEM AT THE END if (tempResult == null) tempResult = new ArrayList<OIdentifiable>(); ((Collection<OIdentifiable>) tempResult).add(iRecord); } } protected ORuntimeResult getProjectionGroup(final Object fieldValue) { ORuntimeResult group = null; final long projectionElapsed = (Long) context.getVariable("projectionElapsed", 0l); final long begin = System.currentTimeMillis(); try { Object key = null; if (groupedResult == null) groupedResult = new LinkedHashMap<Object, ORuntimeResult>(); if (fieldValue != null) { if (fieldValue.getClass().isArray()) { // LOOK IT BY HASH (FASTER THAN COMPARE EACH SINGLE VALUE) final Object[] array = (Object[]) fieldValue; final StringBuilder keyArray = new StringBuilder(); for (Object o : array) { if (keyArray.length() > 0) keyArray.append(","); if (o != null) keyArray.append(o instanceof OIdentifiable ? ((OIdentifiable) o).getIdentity().toString() : o.toString()); else keyArray.append("null"); } key = keyArray.toString(); } else // LOKUP FOR THE FIELD key = fieldValue; } group = groupedResult.get(key); if (group == null) { group = new ORuntimeResult(fieldValue, createProjectionFromDefinition(), resultCount, context); groupedResult.put(key, group); } return group; } finally { context.setVariable("projectionElapsed", projectionElapsed + (System.currentTimeMillis() - begin)); } } private int getQueryFetchLimit() { if (orderedFields != null) { return -1; } final int sqlLimit; final int requestLimit; if (limit > -1) sqlLimit = limit; else sqlLimit = -1; if (request.getLimit() > -1) requestLimit = request.getLimit(); else requestLimit = -1; if (sqlLimit == -1) return requestLimit; if (requestLimit == -1) return sqlLimit; return Math.min(sqlLimit, requestLimit); } public Map<String, Object> getProjections() { return projections; } public List<OPair<String, String>> getOrderedFields() { return orderedFields; } protected void parseGroupBy(final String w) { parserRequiredKeyword(KEYWORD_BY); groupByFields = new ArrayList<String>(); while (!parserIsEnded() && (groupByFields.size() == 0 || parserGetLastSeparator() == ',' || parserGetCurrentChar() == ',')) { final String fieldName = parserRequiredWord(false, "Field name expected"); groupByFields.add(fieldName); parserSkipWhiteSpaces(); } if (groupByFields.size() == 0) throwParsingException("Group by field set was missed. Example: GROUP BY name, salary"); // AGGREGATE IT getProjectionGroup(null); } protected void parseOrderBy(final String w) { parserRequiredKeyword(KEYWORD_BY); String fieldOrdering = null; orderedFields = new ArrayList<OPair<String, String>>(); while (!parserIsEnded() && (orderedFields.size() == 0 || parserGetLastSeparator() == ',' || parserGetCurrentChar() == ',')) { final String fieldName = parserRequiredWord(false, "Field name expected"); parserOptionalWord(true); final String word = parserGetLastWord(); if (word.length() == 0) // END CLAUSE: SET AS ASC BY DEFAULT fieldOrdering = KEYWORD_ASC; else if (word.equals(KEYWORD_LIMIT) || word.equals(KEYWORD_SKIP)) { // NEXT CLAUSE: SET AS ASC BY DEFAULT fieldOrdering = KEYWORD_ASC; parserGoBack(); } else { if (word.equals(KEYWORD_ASC)) fieldOrdering = KEYWORD_ASC; else if (word.equals(KEYWORD_DESC)) fieldOrdering = KEYWORD_DESC; else throwParsingException("Ordering mode '" + word + "' not supported. Valid is 'ASC', 'DESC' or nothing ('ASC' by default)"); } orderedFields.add(new OPair<String, String>(fieldName, fieldOrdering)); parserSkipWhiteSpaces(); } if (orderedFields.size() == 0) throwParsingException("Order by field set was missed. Example: ORDER BY name ASC, salary DESC"); } @Override protected void searchInClasses() { final OClass cls = parsedTarget.getTargetClasses().keySet().iterator().next(); if (searchForIndexes(cls)) { } else super.searchInClasses(); } @SuppressWarnings("rawtypes") private boolean searchForIndexes(final OClass iSchemaClass) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.CLASS, ORole.PERMISSION_READ, iSchemaClass.getName().toLowerCase()); // Create set that is sorted by amount of fields in OIndexSearchResult items // so the most specific restrictions will be processed first. final List<OIndexSearchResult> indexSearchResults = new ArrayList<OIndexSearchResult>(); // fetch all possible variants of subqueries that can be used in indexes. if (compiledFilter == null) return false; analyzeQueryBranch(iSchemaClass, compiledFilter.getRootCondition(), indexSearchResults); // most specific will be processed first Collections.sort(indexSearchResults, new Comparator<OIndexSearchResult>() { public int compare(final OIndexSearchResult searchResultOne, final OIndexSearchResult searchResultTwo) { return searchResultTwo.getFieldCount() - searchResultOne.getFieldCount(); } }); // go through all variants to choose which one can be used for index search. for (final OIndexSearchResult searchResult : indexSearchResults) { final List<OIndex<?>> involvedIndexes = getInvolvedIndexes(iSchemaClass, searchResult); Collections.sort(involvedIndexes, IndexComparator.INSTANCE); // go through all possible index for given set of fields. for (final OIndex index : involvedIndexes) { if (index.isRebuiding()) continue; final OIndexDefinition indexDefinition = index.getDefinition(); final OQueryOperator operator = searchResult.lastOperator; // we need to test that last field in query subset and field in index that has the same position // are equals. if (!OIndexSearchResult.isIndexEqualityOperator(operator)) { final String lastFiled = searchResult.lastField.getItemName(searchResult.lastField.getItemCount() - 1); final String relatedIndexField = indexDefinition.getFields().get(searchResult.fieldValuePairs.size()); if (!lastFiled.equals(relatedIndexField)) continue; } final int searchResultFieldsCount = searchResult.fields().size(); final List<Object> keyParams = new ArrayList<Object>(searchResultFieldsCount); // We get only subset contained in processed sub query. for (final String fieldName : indexDefinition.getFields().subList(0, searchResultFieldsCount)) { final Object fieldValue = searchResult.fieldValuePairs.get(fieldName); if (fieldValue instanceof OSQLQuery<?>) return false; if (fieldValue != null) keyParams.add(fieldValue); else { if (searchResult.lastValue instanceof OSQLQuery<?>) return false; keyParams.add(searchResult.lastValue); } } INDEX_OPERATION_TYPE opType = null; if (context.isRecordingMetrics()) { Set<String> idxNames = (Set<String>) context.getVariable("involvedIndexes"); if (idxNames == null) { idxNames = new HashSet<String>(); context.setVariable("involvedIndexes", idxNames); } if (index instanceof OChainedIndexProxy) { idxNames.addAll(((OChainedIndexProxy) index).getIndexNames()); } else idxNames.add(index.getName()); } if (projections != null && projections.size() == 1) { final Object v = projections.values().iterator().next(); if (v instanceof OSQLFunctionRuntime && ((OSQLFunctionRuntime) v).getFunction() instanceof OSQLFunctionCount) { if (!(compiledFilter.getRootCondition().getLeft() instanceof OSQLFilterCondition || compiledFilter.getRootCondition() .getRight() instanceof OSQLFilterCondition)) // OPTIMIZATION: JUST COUNT IT opType = INDEX_OPERATION_TYPE.COUNT; } } if (opType == null) opType = INDEX_OPERATION_TYPE.GET; OQueryOperator.IndexResultListener resultListener; if (fetchLimit < 0 || opType == INDEX_OPERATION_TYPE.COUNT) resultListener = null; else resultListener = new IndexResultListener(); Object result; try { result = operator.executeIndexQuery(context, index, opType, keyParams, resultListener, fetchLimit); } catch (Exception e) { OLogManager .instance() .error( this, "Error on using index %s in query '%s'. Probably you need to rebuild indexes. Now executing query using cluster scan", e, index.getName(), request != null && request.getText() != null ? request.getText() : ""); return false; } if (result == null) continue; if (opType == INDEX_OPERATION_TYPE.COUNT) { // OPTIMIZATION: EMBED THE RESULT IN A DOCUMENT AND AVOID THE CLASSIC PATH final String projName = projectionDefinition.keySet().iterator().next(); projectionDefinition.clear(); getProjectionGroup(null).applyValue(projName, result); } else fillSearchIndexResultSet(result); return true; } } return false; } private static List<OIndex<?>> getInvolvedIndexes(OClass iSchemaClass, OIndexSearchResult searchResultFields) { final Set<OIndex<?>> involvedIndexes = iSchemaClass.getInvolvedIndexes(searchResultFields.fields()); final List<OIndex<?>> result = new ArrayList<OIndex<?>>(involvedIndexes.size()); for (OIndex<?> involvedIndex : involvedIndexes) { if (searchResultFields.lastField.isLong()) { result.addAll(OChainedIndexProxy.createdProxy(involvedIndex, searchResultFields.lastField, getDatabase())); } else { result.add(involvedIndex); } } return result; } private static OIndexSearchResult analyzeQueryBranch(final OClass iSchemaClass, OSQLFilterCondition iCondition, final List<OIndexSearchResult> iIndexSearchResults) { if (iCondition == null) return null; OQueryOperator operator = iCondition.getOperator(); while (operator == null) { if (iCondition.getRight() == null && iCondition.getLeft() instanceof OSQLFilterCondition) { iCondition = (OSQLFilterCondition) iCondition.getLeft(); operator = iCondition.getOperator(); } else { return null; } } final OIndexReuseType indexReuseType = operator.getIndexReuseType(iCondition.getLeft(), iCondition.getRight()); if (indexReuseType.equals(OIndexReuseType.INDEX_INTERSECTION)) { final OIndexSearchResult leftResult = analyzeQueryBranch(iSchemaClass, (OSQLFilterCondition) iCondition.getLeft(), iIndexSearchResults); final OIndexSearchResult rightResult = analyzeQueryBranch(iSchemaClass, (OSQLFilterCondition) iCondition.getRight(), iIndexSearchResults); if (leftResult != null && rightResult != null) { if (leftResult.canBeMerged(rightResult)) { final OIndexSearchResult mergeResult = leftResult.merge(rightResult); if (iSchemaClass.areIndexed(mergeResult.fields())) iIndexSearchResults.add(mergeResult); return leftResult.merge(rightResult); } } return null; } else if (indexReuseType.equals(OIndexReuseType.INDEX_METHOD)) { OIndexSearchResult result = createIndexedProperty(iCondition, iCondition.getLeft()); if (result == null) result = createIndexedProperty(iCondition, iCondition.getRight()); if (result == null) return null; if (checkIndexExistence(iSchemaClass, result)) iIndexSearchResults.add(result); return result; } return null; } /** * Add SQL filter field to the search candidate list. * * @param iCondition Condition item * @param iItem Value to search * @return true if the property was indexed and found, otherwise false */ private static OIndexSearchResult createIndexedProperty(final OSQLFilterCondition iCondition, final Object iItem) { if (iItem == null || !(iItem instanceof OSQLFilterItemField)) return null; if (iCondition.getLeft() instanceof OSQLFilterItemField && iCondition.getRight() instanceof OSQLFilterItemField) return null; final OSQLFilterItemField item = (OSQLFilterItemField) iItem; if (item.hasChainOperators() && !item.isFieldChain()) return null; final Object origValue = iCondition.getLeft() == iItem ? iCondition.getRight() : iCondition.getLeft(); if (iCondition.getOperator() instanceof OQueryOperatorBetween || iCondition.getOperator() instanceof OQueryOperatorIn) { return new OIndexSearchResult(iCondition.getOperator(), item.getFieldChain(), origValue); } final Object value = OSQLHelper.getValue(origValue); if (value == null) return null; return new OIndexSearchResult(iCondition.getOperator(), item.getFieldChain(), value); } private void fillSearchIndexResultSet(final Object indexResult) { if (indexResult != null) { if (indexResult instanceof Collection<?>) { Collection<OIdentifiable> indexResultSet = (Collection<OIdentifiable>) indexResult; context.updateMetric("indexReads", indexResultSet.size()); for (OIdentifiable identifiable : indexResultSet) { ORecord<?> record = identifiable.getRecord(); // Don't throw exceptions is record is null, as indexed queries may fail when using record level security if ((record != null) && filter((ORecordInternal<?>) record)) { final boolean continueResultParsing = handleResult(record, false); if (!continueResultParsing) break; } } } else { final ORecord<?> record = ((OIdentifiable) indexResult).getRecord(); if (filter((ORecordInternal<?>) record)) handleResult(record, true); } } } protected int parseProjections() { if (!parserOptionalKeyword(KEYWORD_SELECT)) return -1; int upperBound = OStringSerializerHelper.getLowerIndexOf(parserTextUpperCase, parserGetCurrentPosition(), KEYWORD_FROM_2FIND, KEYWORD_LET_2FIND); if (upperBound == -1) // UP TO THE END upperBound = parserText.length(); final String projectionString = parserText.substring(parserGetCurrentPosition(), upperBound).trim(); if (projectionString.length() > 0) { // EXTRACT PROJECTIONS projections = new LinkedHashMap<String, Object>(); projectionDefinition = new LinkedHashMap<String, String>(); final List<String> items = OStringSerializerHelper.smartSplit(projectionString, ','); String fieldName; int beginPos; int endPos; for (String projection : items) { projection = projection.trim(); if (projectionDefinition == null) throw new OCommandSQLParsingException("Projection not allowed with FLATTEN() and EXPAND() operators"); fieldName = null; endPos = projection.toUpperCase(Locale.ENGLISH).indexOf(KEYWORD_AS); if (endPos > -1) { // EXTRACT ALIAS fieldName = projection.substring(endPos + KEYWORD_AS.length()).trim(); projection = projection.substring(0, endPos).trim(); if (projectionDefinition.containsKey(fieldName)) throw new OCommandSQLParsingException("Field '" + fieldName + "' is duplicated in current SELECT, choose a different name"); } else { // EXTRACT THE FIELD NAME WITHOUT FUNCTIONS AND/OR LINKS beginPos = projection.charAt(0) == '@' ? 1 : 0; endPos = extractProjectionNameSubstringEndPosition(projection); fieldName = endPos > -1 ? projection.substring(beginPos, endPos) : projection.substring(beginPos); fieldName = OStringSerializerHelper.getStringContent(fieldName); // FIND A UNIQUE NAME BY ADDING A COUNTER for (int fieldIndex = 2; projectionDefinition.containsKey(fieldName); ++fieldIndex) fieldName += fieldIndex; } String p = projection.toUpperCase(Locale.ENGLISH); if (p.startsWith("FLATTEN(") || p.startsWith("EXPAND(")) { if (p.startsWith("FLATTEN(")) OLogManager.instance().debug(this, "FLATTEN() operator has been replaced by EXPAND()"); List<String> pars = OStringSerializerHelper.getParameters(projection); if (pars.size() != 1) { throw new OCommandSQLParsingException( "EXPAND/FLATTEN operators expects the field name as parameter. Example EXPAND( out )"); } expandTarget = OSQLHelper.parseValue(this, pars.get(0).trim(), context); // BY PASS THIS AS PROJECTION BUT TREAT IT AS SPECIAL projectionDefinition = null; projections = null; if (groupedResult == null && expandTarget instanceof OSQLFunctionRuntime && ((OSQLFunctionRuntime) expandTarget).aggregateResults()) getProjectionGroup(null); continue; } projectionDefinition.put(fieldName, projection); } if (projectionDefinition != null && (projectionDefinition.size() > 1 || !projectionDefinition.values().iterator().next().equals("*"))) { projections = createProjectionFromDefinition(); for (Object p : projections.values()) { if (groupedResult == null && p instanceof OSQLFunctionRuntime && ((OSQLFunctionRuntime) p).aggregateResults()) { // AGGREGATE IT getProjectionGroup(null); break; } } } else { // TREATS SELECT * AS NO PROJECTION projectionDefinition = null; projections = null; } } if (upperBound < parserText.length() - 1) parserSetCurrentPosition(upperBound); else parserSetEndOfText(); return parserGetCurrentPosition(); } protected Map<String, Object> createProjectionFromDefinition() { if (projectionDefinition == null) return new LinkedHashMap<String, Object>(); final Map<String, Object> projections = new LinkedHashMap<String, Object>(projectionDefinition.size()); for (Entry<String, String> p : projectionDefinition.entrySet()) { final Object projectionValue = OSQLHelper.parseValue(this, p.getValue(), context); projections.put(p.getKey(), projectionValue); } return projections; } protected int extractProjectionNameSubstringEndPosition(final String projection) { int endPos; final int pos1 = projection.indexOf('.'); final int pos2 = projection.indexOf('('); final int pos3 = projection.indexOf('['); if (pos1 > -1 && pos2 == -1 && pos3 == -1) endPos = pos1; else if (pos2 > -1 && pos1 == -1 && pos3 == -1) endPos = pos2; else if (pos3 > -1 && pos1 == -1 && pos2 == -1) endPos = pos3; else if (pos1 > -1 && pos2 > -1 && pos3 == -1) endPos = Math.min(pos1, pos2); else if (pos2 > -1 && pos3 > -1 && pos1 == -1) endPos = Math.min(pos2, pos3); else if (pos1 > -1 && pos3 > -1 && pos2 == -1) endPos = Math.min(pos1, pos3); else if (pos1 > -1 && pos2 > -1 && pos3 > -1) { endPos = Math.min(pos1, pos2); endPos = Math.min(endPos, pos3); } else endPos = -1; return endPos; } private void applyOrderBy() { if (orderedFields == null) return; final long startOrderBy = System.currentTimeMillis(); try { if (tempResult instanceof OMultiCollectionIterator) { final List<OIdentifiable> list = new ArrayList<OIdentifiable>(); for (OIdentifiable o : tempResult) list.add(o); tempResult = list; } ODocumentHelper.sort((List<? extends OIdentifiable>) tempResult, orderedFields); orderedFields.clear(); } finally { context.setVariable("orderByElapsed", (System.currentTimeMillis() - startOrderBy)); } } /** * Extract the content of collections and/or links and put it as result */ private void applyExpand() { if (expandTarget == null) return; Object fieldValue; final long startExpand = System.currentTimeMillis(); try { if (tempResult == null) { tempResult = new ArrayList<OIdentifiable>(); if (expandTarget instanceof OSQLFilterItemVariable) { Object r = ((OSQLFilterItemVariable) expandTarget).getValue(null, context); if (r != null) { if (r instanceof OIdentifiable) ((Collection<OIdentifiable>) tempResult).add((OIdentifiable) r); else if (OMultiValue.isMultiValue(r)) { for (Object o : OMultiValue.getMultiValueIterable(r)) ((Collection<OIdentifiable>) tempResult).add((OIdentifiable) o); } } } } else { final OMultiCollectionIterator<OIdentifiable> finalResult = new OMultiCollectionIterator<OIdentifiable>(); finalResult.setLimit(limit); for (OIdentifiable id : tempResult) { if (expandTarget instanceof OSQLFilterItem) fieldValue = ((OSQLFilterItem) expandTarget).getValue(id.getRecord(), context); else if (expandTarget instanceof OSQLFunctionRuntime) fieldValue = ((OSQLFunctionRuntime) expandTarget).getResult(); else fieldValue = expandTarget.toString(); if (fieldValue != null) if (fieldValue instanceof Collection<?>) { finalResult.add((Collection<OIdentifiable>) fieldValue); } else if (fieldValue instanceof Map<?, ?>) { finalResult.add(((Map<?, OIdentifiable>) fieldValue).values()); } else if (fieldValue instanceof OMultiCollectionIterator) { finalResult.add((OMultiCollectionIterator<OIdentifiable>) fieldValue); } else if (fieldValue instanceof OIdentifiable) finalResult.add((OIdentifiable) fieldValue); } tempResult = finalResult; } } finally { context.setVariable("expandElapsed", (System.currentTimeMillis() - startExpand)); } } private void searchInIndex() { final OIndex<Object> index = (OIndex<Object>) getDatabase().getMetadata().getIndexManager() .getIndex(parsedTarget.getTargetIndex()); if (index == null) throw new OCommandExecutionException("Target index '" + parsedTarget.getTargetIndex() + "' not found"); // nothing was added yet, so index definition for manual index was not calculated if (index.getDefinition() == null) return; if (compiledFilter != null && compiledFilter.getRootCondition() != null) { if (!"KEY".equalsIgnoreCase(compiledFilter.getRootCondition().getLeft().toString())) throw new OCommandExecutionException("'Key' field is required for queries against indexes"); final OQueryOperator indexOperator = compiledFilter.getRootCondition().getOperator(); if (indexOperator instanceof OQueryOperatorBetween) { final Object[] values = (Object[]) compiledFilter.getRootCondition().getRight(); final Collection<ODocument> entries = index.getEntriesBetween(getIndexKey(index.getDefinition(), values[0]), getIndexKey(index.getDefinition(), values[2])); for (final OIdentifiable r : entries) { final boolean continueResultParsing = handleResult(r, false); if (!continueResultParsing) break; } } else if (indexOperator instanceof OQueryOperatorMajor) { final Object value = compiledFilter.getRootCondition().getRight(); final Collection<ODocument> entries = index.getEntriesMajor(getIndexKey(index.getDefinition(), value), false); parseIndexSearchResult(entries); } else if (indexOperator instanceof OQueryOperatorMajorEquals) { final Object value = compiledFilter.getRootCondition().getRight(); final Collection<ODocument> entries = index.getEntriesMajor(getIndexKey(index.getDefinition(), value), true); parseIndexSearchResult(entries); } else if (indexOperator instanceof OQueryOperatorMinor) { final Object value = compiledFilter.getRootCondition().getRight(); final Collection<ODocument> entries = index.getEntriesMinor(getIndexKey(index.getDefinition(), value), false); parseIndexSearchResult(entries); } else if (indexOperator instanceof OQueryOperatorMinorEquals) { final Object value = compiledFilter.getRootCondition().getRight(); final Collection<ODocument> entries = index.getEntriesMinor(getIndexKey(index.getDefinition(), value), true); parseIndexSearchResult(entries); } else if (indexOperator instanceof OQueryOperatorIn) { final List<Object> origValues = (List<Object>) compiledFilter.getRootCondition().getRight(); final List<Object> values = new ArrayList<Object>(origValues.size()); for (Object val : origValues) { if (index.getDefinition() instanceof OCompositeIndexDefinition) { throw new OCommandExecutionException("Operator IN not supported yet."); } val = getIndexKey(index.getDefinition(), val); values.add(val); } final Collection<ODocument> entries = index.getEntries(values); parseIndexSearchResult(entries); } else { final Object right = compiledFilter.getRootCondition().getRight(); Object keyValue = getIndexKey(index.getDefinition(), right); final Object res; if (index.getDefinition().getParamCount() == 1) { // CONVERT BEFORE SEARCH IF NEEDED final OType type = index.getDefinition().getTypes()[0]; keyValue = OType.convert(keyValue, type.getDefaultJavaType()); res = index.get(keyValue); } else { final Object secondKey = getIndexKey(index.getDefinition(), right); if (keyValue instanceof OCompositeKey && secondKey instanceof OCompositeKey && ((OCompositeKey) keyValue).getKeys().size() == index.getDefinition().getParamCount() && ((OCompositeKey) secondKey).getKeys().size() == index.getDefinition().getParamCount()) res = index.get(keyValue); else res = index.getValuesBetween(keyValue, secondKey); } if (res != null) if (res instanceof Collection<?>) // MULTI VALUES INDEX for (final OIdentifiable r : (Collection<OIdentifiable>) res) handleResult(createIndexEntryAsDocument(keyValue, r.getIdentity()), true); else // SINGLE VALUE INDEX handleResult(createIndexEntryAsDocument(keyValue, ((OIdentifiable) res).getIdentity()), true); } } else { if (isIndexSizeQuery()) { getProjectionGroup(null).applyValue(projections.keySet().iterator().next(), index.getSize()); return; } if (isIndexKeySizeQuery()) { getProjectionGroup(null).applyValue(projections.keySet().iterator().next(), index.getKeySize()); return; } final OIndexInternal<?> indexInternal = index.getInternal(); if (indexInternal instanceof OSharedResource) ((OSharedResource) indexInternal).acquireExclusiveLock(); try { // ADD ALL THE ITEMS AS RESULT for (Iterator<Entry<Object, Object>> it = index.iterator(); it.hasNext(); ) { final Entry<Object, Object> current = it.next(); if (current.getValue() instanceof Collection<?>) { for (OIdentifiable identifiable : ((Set<OIdentifiable>) current.getValue())) if (!handleResult(createIndexEntryAsDocument(current.getKey(), identifiable.getIdentity()), true)) break; } else if (!handleResult(createIndexEntryAsDocument(current.getKey(), (OIdentifiable) current.getValue()), true)) break; } } finally { if (indexInternal instanceof OSharedResource) ((OSharedResource) indexInternal).releaseExclusiveLock(); } } } private boolean isIndexSizeQuery() { if (!(groupedResult != null && projections.entrySet().size() == 1)) return false; final Object projection = projections.values().iterator().next(); if (!(projection instanceof OSQLFunctionRuntime)) return false; final OSQLFunctionRuntime f = (OSQLFunctionRuntime) projection; if (!f.getRoot().equals(OSQLFunctionCount.NAME)) return false; if (!((f.configuredParameters == null || f.configuredParameters.length == 0) || (f.configuredParameters != null && f.configuredParameters.length == 1 && f.configuredParameters[0].equals("*")))) return false; return true; } private boolean isIndexKeySizeQuery() { if (!(groupedResult != null && projections.entrySet().size() == 1)) return false; final Object projection = projections.values().iterator().next(); if (!(projection instanceof OSQLFunctionRuntime)) return false; final OSQLFunctionRuntime f = (OSQLFunctionRuntime) projection; if (!f.getRoot().equals(OSQLFunctionCount.NAME)) return false; if (!(f.configuredParameters != null && f.configuredParameters.length == 1 && f.configuredParameters[0] instanceof OSQLFunctionRuntime)) return false; final OSQLFunctionRuntime fConfigured = (OSQLFunctionRuntime) f.configuredParameters[0]; if (!fConfigured.getRoot().equals(OSQLFunctionDistinct.NAME)) return false; if (!(fConfigured.configuredParameters != null && fConfigured.configuredParameters.length == 1 && fConfigured.configuredParameters[0] instanceof OSQLFilterItemField)) return false; final OSQLFilterItemField field = (OSQLFilterItemField) fConfigured.configuredParameters[0]; if (!field.getRoot().equals("key")) return false; return true; } private static Object getIndexKey(final OIndexDefinition indexDefinition, Object value) { if (indexDefinition instanceof OCompositeIndexDefinition) { if (value instanceof List) { final List<?> values = (List<?>) value; List<Object> keyParams = new ArrayList<Object>(values.size()); for (Object o : values) { keyParams.add(OSQLHelper.getValue(o)); } return indexDefinition.createValue(keyParams); } else { value = OSQLHelper.getValue(value); if (value instanceof OCompositeKey) { return value; } else { return indexDefinition.createValue(value); } } } else { return OSQLHelper.getValue(value); } } protected void parseIndexSearchResult(final Collection<ODocument> entries) { for (final ODocument document : entries) { final boolean continueResultParsing = handleResult(document, false); if (!continueResultParsing) break; } } private static ODocument createIndexEntryAsDocument(final Object iKey, final OIdentifiable iValue) { final ODocument doc = new ODocument().setOrdered(true); doc.field("key", iKey); doc.field("rid", iValue); doc.unsetDirty(); return doc; } private void handleNoTarget() { if (parsedTarget == null) // ONLY LET, APPLY TO THEM addResult(ORuntimeResult.createProjectionDocument(resultCount)); } private void handleGroupBy() { if (groupedResult != null && tempResult == null) { final long startGroupBy = System.currentTimeMillis(); try { tempResult = new ArrayList<OIdentifiable>(); for (Entry<Object, ORuntimeResult> g : groupedResult.entrySet()) { if (g.getKey() != null || (groupedResult.size() == 1 && groupByFields == null)) { final ODocument doc = g.getValue().getResult(); if (doc != null && !doc.isEmpty()) ((List<OIdentifiable>) tempResult).add(doc); } } } finally { context.setVariable("groupByElapsed", (System.currentTimeMillis() - startGroupBy)); } } } private static boolean checkIndexExistence(final OClass iSchemaClass, final OIndexSearchResult result) { if (!iSchemaClass.areIndexed(result.fields())) return false; if (result.lastField.isLong()) { final int fieldCount = result.lastField.getItemCount(); OClass cls = iSchemaClass.getProperty(result.lastField.getItemName(0)).getLinkedClass(); for (int i = 1; i < fieldCount; i++) { if (cls == null || !cls.areIndexed(result.lastField.getItemName(i))) { return false; } cls = cls.getProperty(result.lastField.getItemName(i)).getLinkedClass(); } } return true; } @Override public String getSyntax() { return "SELECT [<Projections>] FROM <Target> [LET <Assignment>*] [WHERE <Condition>*] [ORDER BY <Fields>* [ASC|DESC]*] [LIMIT <MaxRecords>] TIMEOUT <TimeoutInMs>"; } /** * Parses the fetchplan keyword if found. */ protected boolean parseFetchplan(final String w) throws OCommandSQLParsingException { if (!w.equals(KEYWORD_FETCHPLAN)) return false; parserSkipWhiteSpaces(); int start = parserGetCurrentPosition(); parserNextWord(true); int end = parserGetCurrentPosition(); parserSkipWhiteSpaces(); int position = parserGetCurrentPosition(); while (!parserIsEnded()) { parserNextWord(true); final String word = OStringSerializerHelper.getStringContent(parserGetLastWord()); if (!word.matches(".*:-?\\d+")) break; end = parserGetCurrentPosition(); parserSkipWhiteSpaces(); position = parserGetCurrentPosition(); } parserSetCurrentPosition(position); fetchPlan = OStringSerializerHelper.getStringContent(parserText.substring(start, end)); request.setFetchPlan(fetchPlan); return true; } public String getFetchPlan() { return fetchPlan != null ? fetchPlan : request.getFetchPlan(); } protected boolean optimizeExecution() { if ((compiledFilter == null || (compiledFilter != null && compiledFilter.getRootCondition() == null)) && groupByFields == null && projections != null && projections.size() == 1) { final long startOptimization = System.currentTimeMillis(); try { final Map.Entry<String, Object> entry = projections.entrySet().iterator().next(); if (entry.getValue() instanceof OSQLFunctionRuntime) { final OSQLFunctionRuntime rf = (OSQLFunctionRuntime) entry.getValue(); if (rf.function instanceof OSQLFunctionCount && rf.configuredParameters.length == 1 && "*".equals(rf.configuredParameters[0])) { long count = 0; if (parsedTarget.getTargetClasses() != null) { final OClass cls = parsedTarget.getTargetClasses().keySet().iterator().next(); count = cls.count(); } else if (parsedTarget.getTargetClusters() != null) { for (String cluster : parsedTarget.getTargetClusters().keySet()) { count += getDatabase().countClusterElements(cluster); } } else if (parsedTarget.getTargetIndex() != null) { count += getDatabase().getMetadata().getIndexManager().getIndex(parsedTarget.getTargetIndex()).getSize(); } else { final Iterable<? extends OIdentifiable> recs = parsedTarget.getTargetRecords(); if (recs != null) { if (recs instanceof Collection<?>) count += ((Collection<?>) recs).size(); else { for (Object o : recs) count++; } } } if (tempResult == null) tempResult = new ArrayList<OIdentifiable>(); ((Collection<OIdentifiable>) tempResult).add(new ODocument().field(entry.getKey(), count)); return true; } } } finally { context.setVariable("optimizationElapsed", (System.currentTimeMillis() - startOptimization)); } } if (orderedFields != null && !orderedFields.isEmpty()) { if (parsedTarget.getTargetClasses() != null) { final OClass cls = parsedTarget.getTargetClasses().keySet().iterator().next(); final OPair<String, String> orderByFirstField = orderedFields.iterator().next(); final OProperty p = cls.getProperty(orderByFirstField.getKey()); if (p != null) { final Set<OIndex<?>> involvedIndexes = cls.getInvolvedIndexes(orderByFirstField.getKey()); if (involvedIndexes != null && !involvedIndexes.isEmpty()) { for (OIndex<?> idx : involvedIndexes) { if (idx.getKeyTypes().length == 1 && idx.supportsOrderedIterations()) { if (idx.getType().startsWith("UNIQUE") && idx.getKeySize() < MIN_THRESHOLD_USE_INDEX_AS_TARGET || compiledFilter == null) { if (orderByFirstField.getValue().equalsIgnoreCase("asc")) target = (Iterator<? extends OIdentifiable>) idx.valuesIterator(); else target = (Iterator<? extends OIdentifiable>) idx.valuesInverseIterator(); if (context.isRecordingMetrics()) { Set<String> idxNames = (Set<String>) context.getVariable("involvedIndexes"); if (idxNames == null) { idxNames = new HashSet<String>(); context.setVariable("involvedIndexes", idxNames); } idxNames.add(idx.getName()); } orderedFields = null; fetchLimit = getQueryFetchLimit(); break; } } } } } } } return false; } private static class IndexComparator implements Comparator<OIndex<?>> { private static final IndexComparator INSTANCE = new IndexComparator(); public int compare(final OIndex<?> indexOne, final OIndex<?> indexTwo) { return indexOne.getDefinition().getParamCount() - indexTwo.getDefinition().getParamCount(); } } private final class IndexResultListener implements OQueryOperator.IndexResultListener { private final Set<OIdentifiable> result = new HashSet<OIdentifiable>(); @Override public Object getResult() { return result; } @Override public boolean addResult(OIdentifiable value) { if (compiledFilter == null || Boolean.TRUE.equals(compiledFilter.evaluate(value.getRecord(), null, context))) result.add(value); return fetchLimit < 0 || fetchLimit >= result.size(); } } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLSelect.java
871
public abstract class TransportSearchHelper { public static ShardSearchRequest internalSearchRequest(ShardRouting shardRouting, int numberOfShards, SearchRequest request, String[] filteringAliases, long nowInMillis) { ShardSearchRequest shardRequest = new ShardSearchRequest(request, shardRouting, numberOfShards); shardRequest.filteringAliases(filteringAliases); shardRequest.nowInMillis(nowInMillis); return shardRequest; } public static InternalScrollSearchRequest internalScrollSearchRequest(long id, SearchScrollRequest request) { return new InternalScrollSearchRequest(request, id); } public static String buildScrollId(SearchType searchType, AtomicArray<? extends SearchPhaseResult> searchPhaseResults, @Nullable Map<String, String> attributes) throws IOException { if (searchType == SearchType.DFS_QUERY_THEN_FETCH || searchType == SearchType.QUERY_THEN_FETCH) { return buildScrollId(ParsedScrollId.QUERY_THEN_FETCH_TYPE, searchPhaseResults, attributes); } else if (searchType == SearchType.QUERY_AND_FETCH || searchType == SearchType.DFS_QUERY_AND_FETCH) { return buildScrollId(ParsedScrollId.QUERY_AND_FETCH_TYPE, searchPhaseResults, attributes); } else if (searchType == SearchType.SCAN) { return buildScrollId(ParsedScrollId.SCAN, searchPhaseResults, attributes); } else { throw new ElasticsearchIllegalStateException(); } } public static String buildScrollId(String type, AtomicArray<? extends SearchPhaseResult> searchPhaseResults, @Nullable Map<String, String> attributes) throws IOException { StringBuilder sb = new StringBuilder().append(type).append(';'); sb.append(searchPhaseResults.asList().size()).append(';'); for (AtomicArray.Entry<? extends SearchPhaseResult> entry : searchPhaseResults.asList()) { SearchPhaseResult searchPhaseResult = entry.value; sb.append(searchPhaseResult.id()).append(':').append(searchPhaseResult.shardTarget().nodeId()).append(';'); } if (attributes == null) { sb.append("0;"); } else { sb.append(attributes.size()).append(";"); for (Map.Entry<String, String> entry : attributes.entrySet()) { sb.append(entry.getKey()).append(':').append(entry.getValue()).append(';'); } } BytesRef bytesRef = new BytesRef(); UnicodeUtil.UTF16toUTF8(sb, 0, sb.length(), bytesRef); return Base64.encodeBytes(bytesRef.bytes, bytesRef.offset, bytesRef.length, Base64.URL_SAFE); } public static ParsedScrollId parseScrollId(String scrollId) { CharsRef spare = new CharsRef(); try { byte[] decode = Base64.decode(scrollId, Base64.URL_SAFE); UnicodeUtil.UTF8toUTF16(decode, 0, decode.length, spare); } catch (IOException e) { throw new ElasticsearchIllegalArgumentException("Failed to decode scrollId", e); } String[] elements = Strings.splitStringToArray(spare, ';'); int index = 0; String type = elements[index++]; int contextSize = Integer.parseInt(elements[index++]); @SuppressWarnings({"unchecked"}) Tuple<String, Long>[] context = new Tuple[contextSize]; for (int i = 0; i < contextSize; i++) { String element = elements[index++]; int sep = element.indexOf(':'); if (sep == -1) { throw new ElasticsearchIllegalArgumentException("Malformed scrollId [" + scrollId + "]"); } context[i] = new Tuple<String, Long>(element.substring(sep + 1), Long.parseLong(element.substring(0, sep))); } Map<String, String> attributes; int attributesSize = Integer.parseInt(elements[index++]); if (attributesSize == 0) { attributes = ImmutableMap.of(); } else { attributes = Maps.newHashMapWithExpectedSize(attributesSize); for (int i = 0; i < attributesSize; i++) { String element = elements[index++]; int sep = element.indexOf(':'); attributes.put(element.substring(0, sep), element.substring(sep + 1)); } } return new ParsedScrollId(scrollId, type, context, attributes); } private TransportSearchHelper() { } }
1no label
src_main_java_org_elasticsearch_action_search_type_TransportSearchHelper.java
44
public class OSimpleImmutableEntry<K, V> implements Entry<K, V>, java.io.Serializable { private static final long serialVersionUID = 7138329143949025153L; private final K key; private final V value; /** * Creates an entry representing a mapping from the specified key to the specified value. * * @param key * the key represented by this entry * @param value * the value represented by this entry */ public OSimpleImmutableEntry(final K key, final V value) { this.key = key; this.value = value; } /** * Creates an entry representing the same mapping as the specified entry. * * @param entry * the entry to copy */ public OSimpleImmutableEntry(final Entry<? extends K, ? extends V> entry) { this.key = entry.getKey(); this.value = entry.getValue(); } /** * Returns the key corresponding to this entry. * * @return the key corresponding to this entry */ public K getKey() { return key; } /** * Returns the value corresponding to this entry. * * @return the value corresponding to this entry */ public V getValue() { return value; } /** * Replaces the value corresponding to this entry with the specified value (optional operation). This implementation simply throws * <tt>UnsupportedOperationException</tt>, as this class implements an <i>immutable</i> map entry. * * @param value * new value to be stored in this entry * @return (Does not return) * @throws UnsupportedOperationException * always */ public V setValue(V value) { throw new UnsupportedOperationException(); } /** * Compares the specified object with this entry for equality. Returns {@code true} if the given object is also a map entry and * the two entries represent the same mapping. More formally, two entries {@code e1} and {@code e2} represent the same mapping if * * <pre> * (e1.getKey() == null ? e2.getKey() == null : e1.getKey().equals(e2.getKey())) * &amp;&amp; (e1.getValue() == null ? e2.getValue() == null : e1.getValue().equals(e2.getValue())) * </pre> * * This ensures that the {@code equals} method works properly across different implementations of the {@code Map.Entry} interface. * * @param o * object to be compared for equality with this map entry * @return {@code true} if the specified object is equal to this map entry * @see #hashCode */ @Override public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?, ?> e = (Map.Entry<?, ?>) o; return eq(key, e.getKey()) && eq(value, e.getValue()); } private boolean eq(final Object o1, final Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } /** * Returns the hash code value for this map entry. The hash code of a map entry {@code e} is defined to be: * * <pre> * (e.getKey() == null ? 0 : e.getKey().hashCode()) &circ; (e.getValue() == null ? 0 : e.getValue().hashCode()) * </pre> * * This ensures that {@code e1.equals(e2)} implies that {@code e1.hashCode()==e2.hashCode()} for any two Entries {@code e1} and * {@code e2}, as required by the general contract of {@link Object#hashCode}. * * @return the hash code value for this map entry * @see #equals */ @Override public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } /** * Returns a String representation of this map entry. This implementation returns the string representation of this entry's key * followed by the equals character ("<tt>=</tt>") followed by the string representation of this entry's value. * * @return a String representation of this map entry */ @Override public String toString() { return key + "=" + value; } }
0true
commons_src_main_java_com_orientechnologies_common_collection_OSimpleImmutableEntry.java
1,341
public static class MappingUpdatedRequest extends MasterNodeOperationRequest<MappingUpdatedRequest> { private String index; private String indexUUID = IndexMetaData.INDEX_UUID_NA_VALUE; private String type; private CompressedString mappingSource; private long order = -1; // -1 means not set... private String nodeId = null; // null means not set MappingUpdatedRequest() { } public MappingUpdatedRequest(String index, String indexUUID, String type, CompressedString mappingSource, long order, String nodeId) { this.index = index; this.indexUUID = indexUUID; this.type = type; this.mappingSource = mappingSource; this.order = order; this.nodeId = nodeId; } public String index() { return index; } public String indexUUID() { return indexUUID; } public String type() { return type; } public CompressedString mappingSource() { return mappingSource; } /** * Returns -1 if not set... */ public long order() { return this.order; } /** * Returns null for not set. */ public String nodeId() { return this.nodeId; } @Override public ActionRequestValidationException validate() { return null; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); index = in.readString(); type = in.readString(); mappingSource = CompressedString.readCompressedString(in); indexUUID = in.readString(); order = in.readLong(); nodeId = in.readOptionalString(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(index); out.writeString(type); mappingSource.writeTo(out); out.writeString(indexUUID); out.writeLong(order); out.writeOptionalString(nodeId); } @Override public String toString() { return "index [" + index + "], indexUUID [" + indexUUID + "], type [" + type + "] and source [" + mappingSource + "]"; } }
0true
src_main_java_org_elasticsearch_cluster_action_index_MappingUpdatedAction.java
349
public class GenericEvent implements Serializable { final String value; public GenericEvent(String value) { this.value = value; } public String getValue() { return value; } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_GenericEvent.java
2,050
@Component("blCustomerStateRefresher") public class CustomerStateRefresher implements ApplicationListener<CustomerPersistedEvent> { /** * Removes the complete {@link Customer} stored in session and adds a new session variable for just the customer ID. This * should occur once the session-based {@link Customer} (all anonymous Customers start out this way) has been persisted. * * <p>Also updates {@link CustomerState} with the persisted {@link Customer} so that it will always represent the most * up-to-date version that is in the database</p> * * @param request * @param databaseCustomer */ @Override public void onApplicationEvent(final CustomerPersistedEvent event) { Customer dbCustomer = event.getCustomer(); //if there is an active request, remove the session-based customer if it exists and update CustomerState WebRequest request = BroadleafRequestContext.getBroadleafRequestContext().getWebRequest(); if (request != null) { String customerAttribute = CustomerStateRequestProcessor.getAnonymousCustomerSessionAttributeName(); String customerIdAttribute = CustomerStateRequestProcessor.getAnonymousCustomerIdSessionAttributeName(); Customer sessionCustomer = (Customer) request.getAttribute(customerAttribute, WebRequest.SCOPE_GLOBAL_SESSION); //invalidate the session-based customer if it's there and the ID is the same as the Customer that has been //persisted if (sessionCustomer != null && sessionCustomer.getId().equals(dbCustomer.getId())) { request.removeAttribute(customerAttribute, WebRequest.SCOPE_GLOBAL_SESSION); request.setAttribute(customerIdAttribute, dbCustomer.getId(), WebRequest.SCOPE_GLOBAL_SESSION); } //Update CustomerState if the persisted Customer ID is the same if (CustomerState.getCustomer() != null && CustomerState.getCustomer().getId().equals(dbCustomer.getId())) { CustomerState.setCustomer(event.getCustomer()); } } } }
1no label
core_broadleaf-profile-web_src_main_java_org_broadleafcommerce_profile_web_core_CustomerStateRefresher.java
193
public abstract class LockKeyColumnValueStoreTest extends AbstractKCVSTest { private static final Logger log = LoggerFactory.getLogger(LockKeyColumnValueStoreTest.class); public static final int CONCURRENCY = 8; public static final int NUM_TX = 2; public static final String DB_NAME = "test"; protected static final long EXPIRE_MS = 5000L; /* * Don't change these back to static. We can run test classes concurrently * now. There are multiple concrete subclasses of this abstract class. If * the subclasses run in separate threads and were to concurrently mutate * static state on this common superclass, then thread safety fails. * * Anything final and deeply immutable is of course fair game for static, * but these are mutable. */ public KeyColumnValueStoreManager[] manager; public StoreTransaction[][] tx; public KeyColumnValueStore[] store; private StaticBuffer k, c1, c2, v1, v2; private final String concreteClassName; public LockKeyColumnValueStoreTest() { concreteClassName = getClass().getSimpleName(); } @Before public void setUp() throws Exception { StoreManager tmp = null; try { tmp = openStorageManager(0); tmp.clearStorage(); } finally { tmp.close(); } for (int i = 0; i < CONCURRENCY; i++) { LocalLockMediators.INSTANCE.clear(concreteClassName + i); } open(); k = KeyValueStoreUtil.getBuffer("key"); c1 = KeyValueStoreUtil.getBuffer("col1"); c2 = KeyValueStoreUtil.getBuffer("col2"); v1 = KeyValueStoreUtil.getBuffer("val1"); v2 = KeyValueStoreUtil.getBuffer("val2"); } public abstract KeyColumnValueStoreManager openStorageManager(int id) throws BackendException; public void open() throws BackendException { manager = new KeyColumnValueStoreManager[CONCURRENCY]; tx = new StoreTransaction[CONCURRENCY][NUM_TX]; store = new KeyColumnValueStore[CONCURRENCY]; for (int i = 0; i < CONCURRENCY; i++) { manager[i] = openStorageManager(i); StoreFeatures storeFeatures = manager[i].getFeatures(); store[i] = manager[i].openDatabase(DB_NAME); for (int j = 0; j < NUM_TX; j++) { tx[i][j] = manager[i].beginTransaction(getTxConfig()); log.debug("Began transaction of class {}", tx[i][j].getClass().getCanonicalName()); } ModifiableConfiguration sc = GraphDatabaseConfiguration.buildConfiguration(); sc.set(GraphDatabaseConfiguration.LOCK_LOCAL_MEDIATOR_GROUP,concreteClassName + i); sc.set(GraphDatabaseConfiguration.UNIQUE_INSTANCE_ID,"inst"+i); sc.set(GraphDatabaseConfiguration.LOCK_RETRY,10); sc.set(GraphDatabaseConfiguration.LOCK_EXPIRE, new StandardDuration(EXPIRE_MS, TimeUnit.MILLISECONDS)); if (!storeFeatures.hasLocking()) { Preconditions.checkArgument(storeFeatures.isKeyConsistent(),"Store needs to support some form of locking"); KeyColumnValueStore lockerStore = manager[i].openDatabase(DB_NAME + "_lock_"); ConsistentKeyLocker c = new ConsistentKeyLocker.Builder(lockerStore, manager[i]).fromConfig(sc).mediatorName(concreteClassName + i).build(); store[i] = new ExpectedValueCheckingStore(store[i], c); for (int j = 0; j < NUM_TX; j++) tx[i][j] = new ExpectedValueCheckingTransaction(tx[i][j], manager[i].beginTransaction(getConsistentTxConfig(manager[i])), GraphDatabaseConfiguration.STORAGE_READ_WAITTIME.getDefaultValue()); } } } public StoreTransaction newTransaction(KeyColumnValueStoreManager manager) throws BackendException { StoreTransaction transaction = manager.beginTransaction(getTxConfig()); if (!manager.getFeatures().hasLocking() && manager.getFeatures().isKeyConsistent()) { transaction = new ExpectedValueCheckingTransaction(transaction, manager.beginTransaction(getConsistentTxConfig(manager)), GraphDatabaseConfiguration.STORAGE_READ_WAITTIME.getDefaultValue()); } return transaction; } @After public void tearDown() throws Exception { close(); } public void close() throws BackendException { for (int i = 0; i < CONCURRENCY; i++) { store[i].close(); for (int j = 0; j < NUM_TX; j++) { log.debug("Committing tx[{}][{}] = {}", new Object[]{i, j, tx[i][j]}); if (tx[i][j] != null) tx[i][j].commit(); } manager[i].close(); } LocalLockMediators.INSTANCE.clear(); } @Test public void singleLockAndUnlock() throws BackendException { store[0].acquireLock(k, c1, null, tx[0][0]); store[0].mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c1, v1)), NO_DELETIONS, tx[0][0]); tx[0][0].commit(); tx[0][0] = newTransaction(manager[0]); Assert.assertEquals(v1, KCVSUtil.get(store[0], k, c1, tx[0][0])); } @Test public void transactionMayReenterLock() throws BackendException { store[0].acquireLock(k, c1, null, tx[0][0]); store[0].acquireLock(k, c1, null, tx[0][0]); store[0].acquireLock(k, c1, null, tx[0][0]); store[0].mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c1, v1)), NO_DELETIONS, tx[0][0]); tx[0][0].commit(); tx[0][0] = newTransaction(manager[0]); Assert.assertEquals(v1, KCVSUtil.get(store[0], k, c1, tx[0][0])); } @Test(expected = PermanentLockingException.class) public void expectedValueMismatchCausesMutateFailure() throws BackendException { store[0].acquireLock(k, c1, v1, tx[0][0]); store[0].mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c1, v1)), NO_DELETIONS, tx[0][0]); } @Test public void testLocalLockContention() throws BackendException { store[0].acquireLock(k, c1, null, tx[0][0]); try { store[0].acquireLock(k, c1, null, tx[0][1]); Assert.fail("Lock contention exception not thrown"); } catch (BackendException e) { Assert.assertTrue(e instanceof PermanentLockingException || e instanceof TemporaryLockingException); } try { store[0].acquireLock(k, c1, null, tx[0][1]); Assert.fail("Lock contention exception not thrown (2nd try)"); } catch (BackendException e) { Assert.assertTrue(e instanceof PermanentLockingException || e instanceof TemporaryLockingException); } } @Test public void testRemoteLockContention() throws InterruptedException, BackendException { // acquire lock on "host1" store[0].acquireLock(k, c1, null, tx[0][0]); Thread.sleep(50L); try { // acquire same lock on "host2" store[1].acquireLock(k, c1, null, tx[1][0]); } catch (BackendException e) { /* Lock attempts between hosts with different LocalLockMediators, * such as tx[0][0] and tx[1][0] in this example, should * not generate locking failures until one of them tries * to issue a mutate or mutateMany call. An exception * thrown during the acquireLock call above suggests that * the LocalLockMediators for these two transactions are * not really distinct, which would be a severe and fundamental * bug in this test. */ Assert.fail("Contention between remote transactions detected too soon"); } Thread.sleep(50L); try { // This must fail since "host1" took the lock first store[1].mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c1, v2)), NO_DELETIONS, tx[1][0]); Assert.fail("Expected lock contention between remote transactions did not occur"); } catch (BackendException e) { Assert.assertTrue(e instanceof PermanentLockingException || e instanceof TemporaryLockingException); } // This should succeed store[0].mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c1, v1)), NO_DELETIONS, tx[0][0]); tx[0][0].commit(); tx[0][0] = newTransaction(manager[0]); Assert.assertEquals(v1, KCVSUtil.get(store[0], k, c1, tx[0][0])); } @Test public void singleTransactionWithMultipleLocks() throws BackendException { tryWrites(store[0], manager[0], tx[0][0], store[0], tx[0][0]); /* * tryWrites commits transactions. set committed tx references to null * to prevent a second commit attempt in close(). */ tx[0][0] = null; } @Test public void twoLocalTransactionsWithIndependentLocks() throws BackendException { tryWrites(store[0], manager[0], tx[0][0], store[0], tx[0][1]); /* * tryWrites commits transactions. set committed tx references to null * to prevent a second commit attempt in close(). */ tx[0][0] = null; tx[0][1] = null; } @Test public void twoTransactionsWithIndependentLocks() throws BackendException { tryWrites(store[0], manager[0], tx[0][0], store[1], tx[1][0]); /* * tryWrites commits transactions. set committed tx references to null * to prevent a second commit attempt in close(). */ tx[0][0] = null; tx[1][0] = null; } @Test public void expiredLocalLockIsIgnored() throws BackendException, InterruptedException { tryLocks(store[0], tx[0][0], store[0], tx[0][1], true); } @Test public void expiredRemoteLockIsIgnored() throws BackendException, InterruptedException { tryLocks(store[0], tx[0][0], store[1], tx[1][0], false); } @Test public void repeatLockingDoesNotExtendExpiration() throws BackendException, InterruptedException { /* * This test is intrinsically racy and unreliable. There's no guarantee * that the thread scheduler will put our test thread back on a core in * a timely fashion after our Thread.sleep() argument elapses. * Theoretically, Thread.sleep could also receive spurious wakeups that * alter the timing of the test. */ long start = System.currentTimeMillis(); long gracePeriodMS = 50L; long loopDurationMS = (EXPIRE_MS - gracePeriodMS); long targetMS = start + loopDurationMS; int steps = 20; // Initial lock acquisition by tx[0][0] store[0].acquireLock(k, k, null, tx[0][0]); // Repeat lock acquistion until just before expiration for (int i = 0; i <= steps; i++) { if (targetMS <= System.currentTimeMillis()) { break; } store[0].acquireLock(k, k, null, tx[0][0]); Thread.sleep(loopDurationMS / steps); } // tx[0][0]'s lock is about to expire (or already has) Thread.sleep(gracePeriodMS * 2); // tx[0][0]'s lock has expired (barring spurious wakeup) try { // Lock (k,k) with tx[0][1] now that tx[0][0]'s lock has expired store[0].acquireLock(k, k, null, tx[0][1]); // If acquireLock returns without throwing an Exception, we're OK } catch (BackendException e) { log.debug("Relocking exception follows", e); Assert.fail("Relocking following expiration failed"); } } @Test public void parallelNoncontendedLockStressTest() throws BackendException, InterruptedException { final Executor stressPool = Executors.newFixedThreadPool(CONCURRENCY); final CountDownLatch stressComplete = new CountDownLatch(CONCURRENCY); final long maxWalltimeAllowedMS = 90 * 1000L; final int lockOperationsPerThread = 100; final LockStressor[] ls = new LockStressor[CONCURRENCY]; for (int i = 0; i < CONCURRENCY; i++) { ls[i] = new LockStressor(manager[i], store[i], stressComplete, lockOperationsPerThread, KeyColumnValueStoreUtil.longToByteBuffer(i)); stressPool.execute(ls[i]); } Assert.assertTrue("Timeout exceeded", stressComplete.await(maxWalltimeAllowedMS, TimeUnit.MILLISECONDS)); // All runnables submitted to the executor are done for (int i = 0; i < CONCURRENCY; i++) { if (0 < ls[i].temporaryFailures) { log.warn("Recorded {} temporary failures for thread index {}", ls[i].temporaryFailures, i); } Assert.assertEquals(lockOperationsPerThread, ls[i].succeeded + ls[i].temporaryFailures); } } @Test public void testLocksOnMultipleStores() throws Exception { final int numStores = 6; Preconditions.checkState(numStores % 3 == 0); final StaticBuffer key = BufferUtil.getLongBuffer(1); final StaticBuffer col = BufferUtil.getLongBuffer(2); final StaticBuffer val2 = BufferUtil.getLongBuffer(8); // Create mocks LockerProvider mockLockerProvider = createStrictMock(LockerProvider.class); Locker mockLocker = createStrictMock(Locker.class); // Create EVCSManager with mockLockerProvider ExpectedValueCheckingStoreManager expManager = new ExpectedValueCheckingStoreManager(manager[0], "multi_store_lock_mgr", mockLockerProvider, new StandardDuration(100L, TimeUnit.MILLISECONDS)); // Begin EVCTransaction BaseTransactionConfig txCfg = StandardBaseTransactionConfig.of(times); ExpectedValueCheckingTransaction tx = expManager.beginTransaction(txCfg); // openDatabase calls getLocker, and we do it numStores times expect(mockLockerProvider.getLocker(anyObject(String.class))).andReturn(mockLocker).times(numStores); // acquireLock calls writeLock, and we do it 2/3 * numStores times mockLocker.writeLock(eq(new KeyColumn(key, col)), eq(tx.getConsistentTx())); expectLastCall().times(numStores / 3 * 2); // mutateMany calls checkLocks, and we do it 2/3 * numStores times mockLocker.checkLocks(tx.getConsistentTx()); expectLastCall().times(numStores / 3 * 2); replay(mockLockerProvider); replay(mockLocker); /* * Acquire a lock on several distinct stores (numStores total distinct * stores) and build mutations. */ ImmutableMap.Builder<String, Map<StaticBuffer, KCVMutation>> builder = ImmutableMap.builder(); for (int i = 0; i < numStores; i++) { String storeName = "multi_store_lock_" + i; KeyColumnValueStore s = expManager.openDatabase(storeName); if (i % 3 < 2) s.acquireLock(key, col, null, tx); if (i % 3 > 0) builder.put(storeName, ImmutableMap.of(key, new KCVMutation(ImmutableList.of(StaticArrayEntry.of(col, val2)), ImmutableList.<StaticBuffer>of()))); } // Mutate expManager.mutateMany(builder.build(), tx); // Shutdown expManager.close(); // Check the mocks verify(mockLockerProvider); verify(mockLocker); } private void tryWrites(KeyColumnValueStore store1, KeyColumnValueStoreManager checkmgr, StoreTransaction tx1, KeyColumnValueStore store2, StoreTransaction tx2) throws BackendException { Assert.assertNull(KCVSUtil.get(store1, k, c1, tx1)); Assert.assertNull(KCVSUtil.get(store2, k, c2, tx2)); store1.acquireLock(k, c1, null, tx1); store2.acquireLock(k, c2, null, tx2); store1.mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c1, v1)), NO_DELETIONS, tx1); store2.mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c2, v2)), NO_DELETIONS, tx2); tx1.commit(); if (tx2 != tx1) tx2.commit(); StoreTransaction checktx = newTransaction(checkmgr); Assert.assertEquals(v1, KCVSUtil.get(store1, k, c1, checktx)); Assert.assertEquals(v2, KCVSUtil.get(store2, k, c2, checktx)); checktx.commit(); } private void tryLocks(KeyColumnValueStore s1, StoreTransaction tx1, KeyColumnValueStore s2, StoreTransaction tx2, boolean detectLocally) throws BackendException, InterruptedException { s1.acquireLock(k, k, null, tx1); // Require local lock contention, if requested by our caller // Remote lock contention is checked by separate cases if (detectLocally) { try { s2.acquireLock(k, k, null, tx2); Assert.fail("Expected lock contention between transactions did not occur"); } catch (BackendException e) { Assert.assertTrue(e instanceof PermanentLockingException || e instanceof TemporaryLockingException); } } // Let the original lock expire Thread.sleep(EXPIRE_MS + 100L); // This should succeed now that the original lock is expired s2.acquireLock(k, k, null, tx2); // Mutate to check for remote contention s2.mutate(k, Arrays.<Entry>asList(StaticArrayEntry.of(c2, v2)), NO_DELETIONS, tx2); } /** * Run lots of acquireLock() and commit() ops on a provided store and txn. * <p/> * Used by {@link #parallelNoncontendedLockStressTest()}. * * @author "Dan LaRocque <[email protected]>" */ private class LockStressor implements Runnable { private final KeyColumnValueStoreManager manager; private final KeyColumnValueStore store; private final CountDownLatch doneLatch; private final int opCount; private final StaticBuffer toLock; private int succeeded = 0; private int temporaryFailures = 0; private LockStressor(KeyColumnValueStoreManager manager, KeyColumnValueStore store, CountDownLatch doneLatch, int opCount, StaticBuffer toLock) { this.manager = manager; this.store = store; this.doneLatch = doneLatch; this.opCount = opCount; this.toLock = toLock; } @Override public void run() { // Catch & log exceptions for (int opIndex = 0; opIndex < opCount; opIndex++) { StoreTransaction tx = null; try { tx = newTransaction(manager); store.acquireLock(toLock, toLock, null, tx); store.mutate(toLock, ImmutableList.<Entry>of(), Arrays.asList(toLock), tx); tx.commit(); succeeded++; } catch (TemporaryLockingException e) { temporaryFailures++; } catch (Throwable t) { log.error("Unexpected locking-related exception on iteration " + (opIndex + 1) + "/" + opCount, t); } } /* * This latch is the only thing guaranteeing that succeeded's true * value is observable by other threads once we're done with run() * and the latch's await() method returns. */ doneLatch.countDown(); } } }
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_LockKeyColumnValueStoreTest.java
272
public class ElasticsearchTimeoutException extends ElasticsearchException { public ElasticsearchTimeoutException(String message) { super(message); } public ElasticsearchTimeoutException(String message, Throwable cause) { super(message, cause); } }
0true
src_main_java_org_elasticsearch_ElasticsearchTimeoutException.java
1,374
public class OTransactionOptimistic extends OTransactionRealAbstract { private static final boolean useSBTree = OGlobalConfiguration.INDEX_USE_SBTREE_BY_DEFAULT.getValueAsBoolean(); private boolean usingLog; private static AtomicInteger txSerial = new AtomicInteger(); private int autoRetries = OGlobalConfiguration.TX_AUTO_RETRY.getValueAsInteger(); public OTransactionOptimistic(final ODatabaseRecordTx iDatabase) { super(iDatabase, txSerial.incrementAndGet()); usingLog = OGlobalConfiguration.TX_USE_LOG.getValueAsBoolean(); } public void begin() { status = TXSTATUS.BEGUN; } public void commit() { checkTransaction(); status = TXSTATUS.COMMITTING; if (OScenarioThreadLocal.INSTANCE.get() != RUN_MODE.RUNNING_DISTRIBUTED && !(database.getStorage() instanceof OStorageEmbedded)) database.getStorage().commit(this, null); else { final List<String> involvedIndexes = getInvolvedIndexes(); if (involvedIndexes != null) Collections.sort(involvedIndexes); for (int retry = 1; retry <= autoRetries; ++retry) { try { // LOCK INVOLVED INDEXES List<OIndexAbstract<?>> lockedIndexes = null; try { if (involvedIndexes != null) for (String indexName : involvedIndexes) { final OIndexAbstract<?> index = (OIndexAbstract<?>) database.getMetadata().getIndexManager() .getIndexInternal(indexName); if (lockedIndexes == null) lockedIndexes = new ArrayList<OIndexAbstract<?>>(); index.acquireModificationLock(); lockedIndexes.add(index); } if (!useSBTree) { // SEARCH FOR INDEX BASED ON DOCUMENT TOUCHED final Collection<? extends OIndex<?>> indexes = database.getMetadata().getIndexManager().getIndexes(); List<? extends OIndex<?>> indexesToLock = null; if (indexes != null) { indexesToLock = new ArrayList<OIndex<?>>(indexes); Collections.sort(indexesToLock, new Comparator<OIndex<?>>() { public int compare(final OIndex<?> indexOne, final OIndex<?> indexTwo) { return indexOne.getName().compareTo(indexTwo.getName()); } }); } if (indexesToLock != null && !indexesToLock.isEmpty()) { if (lockedIndexes == null) lockedIndexes = new ArrayList<OIndexAbstract<?>>(); for (OIndex<?> index : indexesToLock) { for (Entry<ORID, ORecordOperation> entry : recordEntries.entrySet()) { final ORecord<?> record = entry.getValue().record.getRecord(); if (record instanceof ODocument) { ODocument doc = (ODocument) record; if (!lockedIndexes.contains(index.getInternal()) && doc.getSchemaClass() != null && index.getDefinition() != null && doc.getSchemaClass().isSubClassOf(index.getDefinition().getClassName())) { index.getInternal().acquireModificationLock(); lockedIndexes.add((OIndexAbstract<?>) index.getInternal()); } } } } for (OIndexAbstract<?> index : lockedIndexes) index.acquireExclusiveLock(); } } final Map<String, OIndex> indexes = new HashMap<String, OIndex>(); for (OIndex index : database.getMetadata().getIndexManager().getIndexes()) indexes.put(index.getName(), index); final Runnable callback = new Runnable() { @Override public void run() { final ODocument indexEntries = getIndexChanges(); if (indexEntries != null) { final Map<String, OIndexInternal<?>> indexesToCommit = new HashMap<String, OIndexInternal<?>>(); for (Entry<String, Object> indexEntry : indexEntries) { final OIndexInternal<?> index = indexes.get(indexEntry.getKey()).getInternal(); indexesToCommit.put(index.getName(), index.getInternal()); } for (OIndexInternal<?> indexInternal : indexesToCommit.values()) indexInternal.preCommit(); for (Entry<String, Object> indexEntry : indexEntries) { final OIndexInternal<?> index = indexesToCommit.get(indexEntry.getKey()).getInternal(); if (index == null) { OLogManager.instance().error(this, "Index with name " + indexEntry.getKey() + " was not found."); throw new OIndexException("Index with name " + indexEntry.getKey() + " was not found."); } else index.addTxOperation((ODocument) indexEntry.getValue()); } try { for (OIndexInternal<?> indexInternal : indexesToCommit.values()) indexInternal.commit(); } finally { for (OIndexInternal<?> indexInternal : indexesToCommit.values()) indexInternal.postCommit(); } } } }; final String storageType = database.getStorage().getType(); if (storageType.equals(OEngineLocal.NAME) || storageType.equals(OEngineLocalPaginated.NAME)) database.getStorage().commit(OTransactionOptimistic.this, callback); else { database.getStorage().callInLock(new Callable<Object>() { @Override public Object call() throws Exception { database.getStorage().commit(OTransactionOptimistic.this, null); callback.run(); return null; } }, true); } // OK break; } finally { // RELEASE INDEX LOCKS IF ANY if (lockedIndexes != null) { if (!useSBTree) { for (OIndexAbstract<?> index : lockedIndexes) index.releaseExclusiveLock(); } for (OIndexAbstract<?> index : lockedIndexes) index.releaseModificationLock(); } } } catch (OTimeoutException e) { if (autoRetries == 0) { OLogManager.instance().debug(this, "Caught timeout exception during commit, but no automatic retry has been set", e); throw e; } else if (retry == autoRetries) { OLogManager.instance().debug(this, "Caught timeout exception during %d/%d. Retry limit is exceeded.", retry, autoRetries); throw e; } else { OLogManager.instance().debug(this, "Caught timeout exception during commit retrying %d/%d...", retry, autoRetries); } } } } } public void rollback() { checkTransaction(); status = TXSTATUS.ROLLBACKING; database.getStorage().callInLock(new Callable<Void>() { public Void call() throws Exception { database.getStorage().rollback(OTransactionOptimistic.this); return null; } }, true); // CLEAR THE CACHE MOVING GOOD RECORDS TO LEVEL-2 CACHE database.getLevel1Cache().clear(); // REMOVE ALL THE ENTRIES AND INVALIDATE THE DOCUMENTS TO AVOID TO BE RE-USED DIRTY AT USER-LEVEL. IN THIS WAY RE-LOADING MUST // EXECUTED for (ORecordOperation v : recordEntries.values()) v.getRecord().unload(); for (ORecordOperation v : allEntries.values()) v.getRecord().unload(); indexEntries.clear(); } public ORecordInternal<?> loadRecord(final ORID iRid, final ORecordInternal<?> iRecord, final String iFetchPlan, boolean ignoreCache, boolean loadTombstone) { checkTransaction(); final ORecordInternal<?> txRecord = getRecord(iRid); if (txRecord == OTransactionRealAbstract.DELETED_RECORD) // DELETED IN TX return null; if (txRecord != null) { if (iRecord != null && txRecord != iRecord) OLogManager.instance().warn( this, "Found record in transaction with the same RID %s but different instance. " + "Probably the record has been loaded from another transaction and reused on the current one: reload it " + "from current transaction before to update or delete it", iRecord.getIdentity()); return txRecord; } if (iRid.isTemporary()) return null; // DELEGATE TO THE STORAGE, NO TOMBSTONES SUPPORT IN TX MODE final ORecordInternal<?> record = database.executeReadRecord((ORecordId) iRid, iRecord, iFetchPlan, ignoreCache, false); if (record != null) addRecord(record, ORecordOperation.LOADED, null); return record; } public void deleteRecord(final ORecordInternal<?> iRecord, final OPERATION_MODE iMode) { if (!iRecord.getIdentity().isValid()) return; addRecord(iRecord, ORecordOperation.DELETED, null); } public void saveRecord(final ORecordInternal<?> iRecord, final String iClusterName, final OPERATION_MODE iMode, boolean iForceCreate, final ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<ORecordVersion> iRecordUpdatedCallback) { if (iRecord == null) return; final byte operation = iForceCreate ? ORecordOperation.CREATED : iRecord.getIdentity().isValid() ? ORecordOperation.UPDATED : ORecordOperation.CREATED; addRecord(iRecord, operation, iClusterName); } protected void addRecord(final ORecordInternal<?> iRecord, final byte iStatus, final String iClusterName) { checkTransaction(); switch (iStatus) { case ORecordOperation.CREATED: database.callbackHooks(TYPE.BEFORE_CREATE, iRecord); break; case ORecordOperation.LOADED: /** * Read hooks already invoked in {@link com.orientechnologies.orient.core.db.record.ODatabaseRecordAbstract#executeReadRecord} * . */ break; case ORecordOperation.UPDATED: database.callbackHooks(TYPE.BEFORE_UPDATE, iRecord); break; case ORecordOperation.DELETED: database.callbackHooks(TYPE.BEFORE_DELETE, iRecord); break; } try { if (iRecord.getIdentity().isTemporary()) temp2persistent.put(iRecord.getIdentity().copy(), iRecord); if ((status == OTransaction.TXSTATUS.COMMITTING) && database.getStorage() instanceof OStorageEmbedded) { // I'M COMMITTING: BYPASS LOCAL BUFFER switch (iStatus) { case ORecordOperation.CREATED: case ORecordOperation.UPDATED: final ORID oldRid = iRecord.getIdentity().copy(); database.executeSaveRecord(iRecord, iClusterName, iRecord.getRecordVersion(), iRecord.getRecordType(), false, OPERATION_MODE.SYNCHRONOUS, false, null, null); updateIdentityAfterCommit(oldRid, iRecord.getIdentity()); break; case ORecordOperation.DELETED: database.executeDeleteRecord(iRecord, iRecord.getRecordVersion(), false, false, OPERATION_MODE.SYNCHRONOUS, false); break; } final ORecordOperation txRecord = getRecordEntry(iRecord.getIdentity()); if (txRecord == null) { // NOT IN TX, SAVE IT ANYWAY allEntries.put(iRecord.getIdentity(), new ORecordOperation(iRecord, iStatus)); } else if (txRecord.record != iRecord) { // UPDATE LOCAL RECORDS TO AVOID MISMATCH OF VERSION/CONTENT final String clusterName = getDatabase().getClusterNameById(iRecord.getIdentity().getClusterId()); if (!clusterName.equals(OMetadataDefault.CLUSTER_MANUAL_INDEX_NAME) && !clusterName.equals(OMetadataDefault.CLUSTER_INDEX_NAME)) OLogManager .instance() .warn( this, "Found record in transaction with the same RID %s but different instance. Probably the record has been loaded from another transaction and reused on the current one: reload it from current transaction before to update or delete it", iRecord.getIdentity()); txRecord.record = iRecord; txRecord.type = iStatus; } } else { final ORecordId rid = (ORecordId) iRecord.getIdentity(); if (!rid.isValid()) { iRecord.onBeforeIdentityChanged(rid); // ASSIGN A UNIQUE SERIAL TEMPORARY ID if (rid.clusterId == ORID.CLUSTER_ID_INVALID) rid.clusterId = iClusterName != null ? database.getClusterIdByName(iClusterName) : database.getDefaultClusterId(); rid.clusterPosition = OClusterPositionFactory.INSTANCE.valueOf(newObjectCounter--); iRecord.onAfterIdentityChanged(iRecord); } else // REMOVE FROM THE DB'S CACHE database.getLevel1Cache().freeRecord(rid); ORecordOperation txEntry = getRecordEntry(rid); if (txEntry == null) { if (!(rid.isTemporary() && iStatus != ORecordOperation.CREATED)) { // NEW ENTRY: JUST REGISTER IT txEntry = new ORecordOperation(iRecord, iStatus); recordEntries.put(rid, txEntry); } } else { // UPDATE PREVIOUS STATUS txEntry.record = iRecord; switch (txEntry.type) { case ORecordOperation.LOADED: switch (iStatus) { case ORecordOperation.UPDATED: txEntry.type = ORecordOperation.UPDATED; break; case ORecordOperation.DELETED: txEntry.type = ORecordOperation.DELETED; break; } break; case ORecordOperation.UPDATED: switch (iStatus) { case ORecordOperation.DELETED: txEntry.type = ORecordOperation.DELETED; break; } break; case ORecordOperation.DELETED: break; case ORecordOperation.CREATED: switch (iStatus) { case ORecordOperation.DELETED: recordEntries.remove(rid); break; } break; } } } switch (iStatus) { case ORecordOperation.CREATED: database.callbackHooks(TYPE.AFTER_CREATE, iRecord); break; case ORecordOperation.LOADED: /** * Read hooks already invoked in * {@link com.orientechnologies.orient.core.db.record.ODatabaseRecordAbstract#executeReadRecord}. */ break; case ORecordOperation.UPDATED: database.callbackHooks(TYPE.AFTER_UPDATE, iRecord); break; case ORecordOperation.DELETED: database.callbackHooks(TYPE.AFTER_DELETE, iRecord); break; } } catch (Throwable t) { switch (iStatus) { case ORecordOperation.CREATED: database.callbackHooks(TYPE.CREATE_FAILED, iRecord); break; case ORecordOperation.UPDATED: database.callbackHooks(TYPE.UPDATE_FAILED, iRecord); break; case ORecordOperation.DELETED: database.callbackHooks(TYPE.DELETE_FAILED, iRecord); break; } if (t instanceof RuntimeException) throw (RuntimeException) t; else throw new ODatabaseException("Error on saving record " + iRecord.getIdentity(), t); } } @Override public boolean updateReplica(ORecordInternal<?> iRecord) { throw new UnsupportedOperationException("updateReplica()"); } @Override public String toString() { return "OTransactionOptimistic [id=" + id + ", status=" + status + ", recEntries=" + recordEntries.size() + ", idxEntries=" + indexEntries.size() + ']'; } public boolean isUsingLog() { return usingLog; } public void setUsingLog(final boolean useLog) { this.usingLog = useLog; } public int getAutoRetries() { return autoRetries; } public void setAutoRetries(final int autoRetries) { this.autoRetries = autoRetries; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_tx_OTransactionOptimistic.java
735
public class CollectionGetAllRequest extends CollectionRequest { public CollectionGetAllRequest() { } public CollectionGetAllRequest(String name) { super(name); } @Override protected Operation prepareOperation() { return new CollectionGetAllOperation(name); } @Override public int getClassId() { return CollectionPortableHook.COLLECTION_GET_ALL; } @Override public String getRequiredAction() { return ActionConstants.ACTION_READ; } }
0true
hazelcast_src_main_java_com_hazelcast_collection_client_CollectionGetAllRequest.java
433
static final class Fields { static final XContentBuilderString COUNT = new XContentBuilderString("count"); }
0true
src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsIndices.java
1,271
public class FaunusSchemaManager implements SchemaInspector { private static final FaunusSchemaManager DEFAULT_MANAGER = new FaunusSchemaManager(); private final ConcurrentMap<String,FaunusVertexLabel> vertexLabels; private final ConcurrentMap<String,FaunusRelationType> relationTypes; private SchemaProvider schemaProvider; private FaunusSchemaManager() { this(DefaultSchemaProvider.INSTANCE); } public FaunusSchemaManager(SchemaProvider provider) { vertexLabels = Maps.newConcurrentMap(); relationTypes = Maps.newConcurrentMap(); setSchemaProvider(provider); initialize(); } private final void initialize() { vertexLabels.put(FaunusVertexLabel.DEFAULT_VERTEXLABEL.getName(),FaunusVertexLabel.DEFAULT_VERTEXLABEL); relationTypes.put(FaunusPropertyKey.COUNT.getName(),FaunusPropertyKey.COUNT); relationTypes.put(FaunusEdgeLabel.LINK.getName(),FaunusEdgeLabel.LINK); relationTypes.put(FaunusPropertyKey.VALUE.getName(),FaunusPropertyKey.VALUE); relationTypes.put(FaunusPropertyKey.ID.getName(),FaunusPropertyKey.ID); relationTypes.put(FaunusPropertyKey._ID.getName(),FaunusPropertyKey._ID); relationTypes.put(FaunusPropertyKey.LABEL.getName(),FaunusPropertyKey.LABEL); } public void setSchemaProvider(SchemaProvider provider) { if (provider!=DefaultSchemaProvider.INSTANCE) { provider = DefaultSchemaProvider.asBackupProvider(provider); } this.schemaProvider=provider; } public void clear() { vertexLabels.clear(); relationTypes.clear(); initialize(); } public FaunusVertexLabel getVertexLabel(String name) { FaunusVertexLabel vl = vertexLabels.get(name); if (vl==null) { vertexLabels.putIfAbsent(name,new FaunusVertexLabel(schemaProvider.getVertexLabel(name))); vl = vertexLabels.get(name); } assert vl!=null; return vl; } @Override public boolean containsVertexLabel(String name) { return vertexLabels.containsKey(name) || schemaProvider.getVertexLabel(name)!=null; } @Override public boolean containsRelationType(String name) { return relationTypes.containsKey(name) || schemaProvider.getRelationType(name)!=null; } @Override public FaunusRelationType getRelationType(String name) { FaunusRelationType rt = relationTypes.get(name); if (rt==null) { RelationTypeDefinition def = schemaProvider.getRelationType(name); if (def==null) return null; if (def instanceof PropertyKeyDefinition) rt = new FaunusPropertyKey((PropertyKeyDefinition)def,false); else rt = new FaunusEdgeLabel((EdgeLabelDefinition)def,false); relationTypes.putIfAbsent(name,rt); rt = relationTypes.get(name); } assert rt!=null; return rt; } @Override public boolean containsPropertyKey(String name) { FaunusRelationType rt = getRelationType(name); return rt!=null && rt.isPropertyKey(); } @Override public boolean containsEdgeLabel(String name) { FaunusRelationType rt = getRelationType(name); return rt!=null && rt.isEdgeLabel(); } @Override public FaunusPropertyKey getOrCreatePropertyKey(String name) { FaunusRelationType rt = getRelationType(name); if (rt==null) { relationTypes.putIfAbsent(name,new FaunusPropertyKey(schemaProvider.getPropertyKey(name),false)); rt = relationTypes.get(name); } assert rt!=null; if (!(rt instanceof FaunusPropertyKey)) throw new IllegalArgumentException("Not a property key: " + name); return (FaunusPropertyKey)rt; } @Override public FaunusPropertyKey getPropertyKey(String name) { FaunusRelationType rt = getRelationType(name); Preconditions.checkArgument(rt==null || rt.isPropertyKey(),"Name does not identify a property key: ",name); return (FaunusPropertyKey)rt; } @Override public FaunusEdgeLabel getOrCreateEdgeLabel(String name) { FaunusRelationType rt = getRelationType(name); if (rt==null) { relationTypes.putIfAbsent(name,new FaunusEdgeLabel(schemaProvider.getEdgeLabel(name),false)); rt = relationTypes.get(name); } assert rt!=null; if (!(rt instanceof FaunusEdgeLabel)) throw new IllegalArgumentException("Not an edge label: " + name); return (FaunusEdgeLabel)rt; } @Override public FaunusEdgeLabel getEdgeLabel(String name) { FaunusRelationType rt = getRelationType(name); Preconditions.checkArgument(rt==null || rt.isEdgeLabel(),"Name does not identify an edge label: ",name); return (FaunusEdgeLabel)rt; } public static FaunusSchemaManager getTypeManager(Configuration config) { return DEFAULT_MANAGER; } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_FaunusSchemaManager.java
78
public enum Cmp implements TitanPredicate { EQUAL { @Override public boolean isValidValueType(Class<?> clazz) { return true; } @Override public boolean isValidCondition(Object condition) { return true; } @Override public boolean evaluate(Object value, Object condition) { if (condition==null) { return value==null; } else { return condition.equals(value); } } @Override public String toString() { return "="; } @Override public TitanPredicate negate() { return NOT_EQUAL; } }, NOT_EQUAL { @Override public boolean isValidValueType(Class<?> clazz) { return true; } @Override public boolean isValidCondition(Object condition) { return true; } @Override public boolean evaluate(Object value, Object condition) { if (condition==null) { return value!=null; } else { return !condition.equals(value); } } @Override public String toString() { return "<>"; } @Override public TitanPredicate negate() { return EQUAL; } }, LESS_THAN { @Override public boolean isValidValueType(Class<?> clazz) { Preconditions.checkNotNull(clazz); return Comparable.class.isAssignableFrom(clazz); } @Override public boolean isValidCondition(Object condition) { return condition!=null && condition instanceof Comparable; } @Override public boolean evaluate(Object value, Object condition) { Integer cmp = AttributeUtil.compare(value,condition); return cmp!=null?cmp<0:false; } @Override public String toString() { return "<"; } @Override public TitanPredicate negate() { return GREATER_THAN_EQUAL; } }, LESS_THAN_EQUAL { @Override public boolean isValidValueType(Class<?> clazz) { Preconditions.checkNotNull(clazz); return Comparable.class.isAssignableFrom(clazz); } @Override public boolean isValidCondition(Object condition) { return condition!=null && condition instanceof Comparable; } @Override public boolean evaluate(Object value, Object condition) { Integer cmp = AttributeUtil.compare(value,condition); return cmp!=null?cmp<=0:false; } @Override public String toString() { return "<="; } @Override public TitanPredicate negate() { return GREATER_THAN; } }, GREATER_THAN { @Override public boolean isValidValueType(Class<?> clazz) { Preconditions.checkNotNull(clazz); return Comparable.class.isAssignableFrom(clazz); } @Override public boolean isValidCondition(Object condition) { return condition!=null && condition instanceof Comparable; } @Override public boolean evaluate(Object value, Object condition) { Integer cmp = AttributeUtil.compare(value,condition); return cmp!=null?cmp>0:false; } @Override public String toString() { return ">"; } @Override public TitanPredicate negate() { return LESS_THAN_EQUAL; } }, GREATER_THAN_EQUAL { @Override public boolean isValidValueType(Class<?> clazz) { Preconditions.checkNotNull(clazz); return Comparable.class.isAssignableFrom(clazz); } @Override public boolean isValidCondition(Object condition) { return condition!=null && condition instanceof Comparable; } @Override public boolean evaluate(Object value, Object condition) { Integer cmp = AttributeUtil.compare(value,condition); return cmp!=null?cmp>=0:false; } @Override public String toString() { return ">="; } @Override public TitanPredicate negate() { return LESS_THAN; } }; @Override public boolean hasNegation() { return true; } @Override public boolean isQNF() { return true; } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java
820
public class AtomicLongReplicationOperation extends AbstractOperation implements IdentifiedDataSerializable { private Map<String, Long> migrationData; public AtomicLongReplicationOperation() { } public AtomicLongReplicationOperation(Map<String, Long> migrationData) { this.migrationData = migrationData; } @Override public void run() throws Exception { AtomicLongService atomicLongService = getService(); for (Map.Entry<String, Long> longEntry : migrationData.entrySet()) { String name = longEntry.getKey(); LongWrapper number = atomicLongService.getNumber(name); Long value = longEntry.getValue(); number.set(value); } } @Override public String getServiceName() { return AtomicLongService.SERVICE_NAME; } @Override public int getFactoryId() { return AtomicLongDataSerializerHook.F_ID; } @Override public int getId() { return AtomicLongDataSerializerHook.REPLICATION; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { out.writeInt(migrationData.size()); for (Map.Entry<String, Long> entry : migrationData.entrySet()) { out.writeUTF(entry.getKey()); out.writeLong(entry.getValue()); } } @Override protected void readInternal(ObjectDataInput in) throws IOException { int mapSize = in.readInt(); migrationData = new HashMap<String, Long>(mapSize); for (int i = 0; i < mapSize; i++) { String name = in.readUTF(); Long number = in.readLong(); migrationData.put(name, number); } } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_operations_AtomicLongReplicationOperation.java
534
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class ClientTxnTest { static HazelcastInstance hz; static HazelcastInstance server; static HazelcastInstance second; @Before public void init(){ server = Hazelcast.newHazelcastInstance(); final ClientConfig config = new ClientConfig(); config.getNetworkConfig().setRedoOperation(true); hz = HazelcastClient.newHazelcastClient(config); second = Hazelcast.newHazelcastInstance(); } @After public void destroy() { hz.shutdown(); Hazelcast.shutdownAll(); } @Test public void testTxnRollback() throws Exception { final String queueName = "testTxnRollback"; final TransactionContext context = hz.newTransactionContext(); CountDownLatch latch = new CountDownLatch(1); try { context.beginTransaction(); assertNotNull(context.getTxnId()); final TransactionalQueue queue = context.getQueue(queueName); queue.offer("item"); server.shutdown(); context.commitTransaction(); fail("commit should throw exception!!!"); } catch (Exception e){ context.rollbackTransaction(); latch.countDown(); } assertTrue(latch.await(10, TimeUnit.SECONDS)); final IQueue<Object> q = hz.getQueue(queueName); assertNull(q.poll()); assertEquals(0, q.size()); } @Test public void testTxnRollbackOnServerCrash() throws Exception { final String queueName = "testTxnRollbackOnServerCrash"; final TransactionContext context = hz.newTransactionContext(); CountDownLatch latch = new CountDownLatch(1); context.beginTransaction(); final TransactionalQueue queue = context.getQueue(queueName); String key = HazelcastTestSupport.generateKeyOwnedBy(server); queue.offer(key); server.getLifecycleService().terminate(); try{ context.commitTransaction(); fail("commit should throw exception !"); } catch (Exception e){ context.rollbackTransaction(); latch.countDown(); } assertTrue(latch.await(10, TimeUnit.SECONDS)); final IQueue<Object> q = hz.getQueue(queueName); assertNull(q.poll()); assertEquals(0, q.size()); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_txn_ClientTxnTest.java
418
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface AdminPresentationMapFields { /** * Members of this map can be displayed as form fields, rather than in a standard grid. When populated, * mapDisplayFields informs the form building process to create the fields described here and persist those fields * in this map structure. * * @return the fields to display that represent the members of this map */ AdminPresentationMapField[] mapDisplayFields(); }
0true
common_src_main_java_org_broadleafcommerce_common_presentation_AdminPresentationMapFields.java
396
public class CurrencyConsiderationContext { private static final ThreadLocal<CurrencyDeterminationService> currencyDeterminationService = ThreadLocalManager.createThreadLocal(CurrencyDeterminationService.class); private static final ThreadLocal<HashMap> currencyConsiderationContext = ThreadLocalManager.createThreadLocal(HashMap.class); public static HashMap getCurrencyConsiderationContext() { return CurrencyConsiderationContext.currencyConsiderationContext.get(); } public static void setCurrencyConsiderationContext(HashMap currencyConsiderationContext) { CurrencyConsiderationContext.currencyConsiderationContext.set(currencyConsiderationContext); } public static CurrencyDeterminationService getCurrencyDeterminationService() { return CurrencyConsiderationContext.currencyDeterminationService.get(); } public static void setCurrencyDeterminationService(CurrencyDeterminationService currencyDeterminationService) { CurrencyConsiderationContext.currencyDeterminationService.set(currencyDeterminationService); } }
0true
common_src_main_java_org_broadleafcommerce_common_money_CurrencyConsiderationContext.java
5,133
public abstract class InternalAggregation implements Aggregation, ToXContent, Streamable { /** * The aggregation type that holds all the string types that are associated with an aggregation: * <ul> * <li>name - used as the parser type</li> * <li>stream - used as the stream type</li> * </ul> */ public static class Type { private String name; private BytesReference stream; public Type(String name) { this(name, new BytesArray(name)); } public Type(String name, String stream) { this(name, new BytesArray(stream)); } public Type(String name, BytesReference stream) { this.name = name; this.stream = stream; } /** * @return The name of the type (mainly used for registering the parser for the aggregator (see {@link org.elasticsearch.search.aggregations.Aggregator.Parser#type()}). */ public String name() { return name; } /** * @return The name of the stream type (used for registering the aggregation stream * (see {@link AggregationStreams#registerStream(AggregationStreams.Stream, org.elasticsearch.common.bytes.BytesReference...)}). */ public BytesReference stream() { return stream; } } protected static class ReduceContext { private final List<InternalAggregation> aggregations; private final CacheRecycler cacheRecycler; public ReduceContext(List<InternalAggregation> aggregations, CacheRecycler cacheRecycler) { this.aggregations = aggregations; this.cacheRecycler = cacheRecycler; } public List<InternalAggregation> aggregations() { return aggregations; } public CacheRecycler cacheRecycler() { return cacheRecycler; } } protected String name; /** Constructs an un initialized addAggregation (used for serialization) **/ protected InternalAggregation() {} /** * Constructs an get with a given name. * * @param name The name of the get. */ protected InternalAggregation(String name) { this.name = name; } @Override public String getName() { return name; } /** * @return The {@link Type} of this aggregation */ public abstract Type type(); /** * Reduces the given addAggregation to a single one and returns it. In <b>most</b> cases, the assumption will be the all given * addAggregation are of the same type (the same type as this aggregation). For best efficiency, when implementing, * try reusing an existing get instance (typically the first in the given list) to save on redundant object * construction. */ public abstract InternalAggregation reduce(ReduceContext reduceContext); /** * Common xcontent fields that are shared among addAggregation */ public static final class CommonFields { public static final XContentBuilderString BUCKETS = new XContentBuilderString("buckets"); public static final XContentBuilderString VALUE = new XContentBuilderString("value"); public static final XContentBuilderString VALUE_AS_STRING = new XContentBuilderString("value_as_string"); public static final XContentBuilderString DOC_COUNT = new XContentBuilderString("doc_count"); public static final XContentBuilderString KEY = new XContentBuilderString("key"); public static final XContentBuilderString KEY_AS_STRING = new XContentBuilderString("key_as_string"); public static final XContentBuilderString FROM = new XContentBuilderString("from"); public static final XContentBuilderString FROM_AS_STRING = new XContentBuilderString("from_as_string"); public static final XContentBuilderString TO = new XContentBuilderString("to"); public static final XContentBuilderString TO_AS_STRING = new XContentBuilderString("to_as_string"); } }
1no label
src_main_java_org_elasticsearch_search_aggregations_InternalAggregation.java
288
public abstract class GenericAction<Request extends ActionRequest, Response extends ActionResponse> { private final String name; /** * @param name The name of the action, must be unique across actions. */ protected GenericAction(String name) { this.name = name; } /** * The name of the action. Must be unique across actions. */ public String name() { return this.name; } /** * Creates a new response instance. */ public abstract Response newResponse(); /** * Optional request options for the action. */ public TransportRequestOptions transportOptions(Settings settings) { return TransportRequestOptions.EMPTY; } @Override public boolean equals(Object o) { return name.equals(((GenericAction) o).name()); } @Override public int hashCode() { return name.hashCode(); } }
0true
src_main_java_org_elasticsearch_action_GenericAction.java
612
public interface BroadleafSiteResolver { /** * * @deprecated Use {@link #resolveSite(WebRequest)} instead */ @Deprecated public Site resolveSite(HttpServletRequest request) throws SiteNotFoundException; public Site resolveSite(WebRequest request) throws SiteNotFoundException; }
0true
common_src_main_java_org_broadleafcommerce_common_web_BroadleafSiteResolver.java
1,319
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
1,444
public static enum State { /** * Initializing state */ INIT((byte) 0), /** * Started state */ STARTED((byte) 1), /** * Restore finished successfully */ SUCCESS((byte) 2), /** * Restore failed */ FAILURE((byte) 3); private byte value; /** * Constructs new state * * @param value state code */ State(byte value) { this.value = value; } /** * Returns state code * * @return state code */ public byte value() { return value; } /** * Returns true if restore process completed (either successfully or with failure) * * @return true if restore process completed */ public boolean completed() { return this == SUCCESS || this == FAILURE; } /** * Returns state corresponding to state code * * @param value stat code * @return state */ public static State fromValue(byte value) { switch (value) { case 0: return INIT; case 1: return STARTED; case 2: return SUCCESS; case 3: return FAILURE; default: throw new ElasticsearchIllegalArgumentException("No snapshot state for value [" + value + "]"); } } }
0true
src_main_java_org_elasticsearch_cluster_metadata_RestoreMetaData.java
43
public class MultiPaxosServerFactory implements ProtocolServerFactory { private final ClusterConfiguration initialConfig; private final Logging logging; public MultiPaxosServerFactory( ClusterConfiguration initialConfig, Logging logging ) { this.initialConfig = initialConfig; this.logging = logging; } @Override public ProtocolServer newProtocolServer( InstanceId me, TimeoutStrategy timeoutStrategy, MessageSource input, MessageSender output, AcceptorInstanceStore acceptorInstanceStore, ElectionCredentialsProvider electionCredentialsProvider, Executor stateMachineExecutor, ObjectInputStreamFactory objectInputStreamFactory, ObjectOutputStreamFactory objectOutputStreamFactory ) { DelayedDirectExecutor executor = new DelayedDirectExecutor(); // Create state machines Timeouts timeouts = new Timeouts( timeoutStrategy ); final MultiPaxosContext context = new MultiPaxosContext( me, Iterables.<ElectionRole,ElectionRole>iterable( new ElectionRole(ClusterConfiguration.COORDINATOR )), new ClusterConfiguration( initialConfig.getName(), logging.getMessagesLog( ClusterConfiguration.class ), initialConfig.getMemberURIs() ), executor, logging, objectInputStreamFactory, objectOutputStreamFactory, acceptorInstanceStore, timeouts, electionCredentialsProvider); SnapshotContext snapshotContext = new SnapshotContext( context.getClusterContext(),context.getLearnerContext()); return newProtocolServer( me, input, output, stateMachineExecutor, executor, timeouts, context, snapshotContext ); } public ProtocolServer newProtocolServer( InstanceId me, MessageSource input, MessageSender output, Executor stateMachineExecutor, DelayedDirectExecutor executor, Timeouts timeouts, MultiPaxosContext context, SnapshotContext snapshotContext ) { return constructSupportingInfrastructureFor( me, input, output, executor, timeouts, stateMachineExecutor, context, new StateMachine[] { new StateMachine( context.getAtomicBroadcastContext(), AtomicBroadcastMessage.class, AtomicBroadcastState.start, logging ), new StateMachine( context.getAcceptorContext(), AcceptorMessage.class, AcceptorState.start, logging ), new StateMachine( context.getProposerContext(), ProposerMessage.class, ProposerState.start, logging ), new StateMachine( context.getLearnerContext(), LearnerMessage.class, LearnerState.start, logging ), new StateMachine( context.getHeartbeatContext(), HeartbeatMessage.class, HeartbeatState.start, logging ), new StateMachine( context.getElectionContext(), ElectionMessage.class, ElectionState.start, logging ), new StateMachine( snapshotContext, SnapshotMessage.class, SnapshotState.start, logging ), new StateMachine( context.getClusterContext(), ClusterMessage.class, ClusterState.start, logging ) }); } /** * Sets up the supporting infrastructure and communication hooks for our state machines. This is here to support * an external requirement for assembling protocol servers given an existing set of state machines (used to prove * correctness). * */ public ProtocolServer constructSupportingInfrastructureFor( InstanceId me, MessageSource input, MessageSender output, DelayedDirectExecutor executor, Timeouts timeouts, Executor stateMachineExecutor, final MultiPaxosContext context, StateMachine[] machines ) { StateMachines stateMachines = new StateMachines( input, output, timeouts, executor, stateMachineExecutor, me ); for ( StateMachine machine : machines ) { stateMachines.addStateMachine( machine ); } final ProtocolServer server = new ProtocolServer( me, stateMachines, logging ); server.addBindingListener( new BindingListener() { @Override public void listeningAt( URI me ) { context.getClusterContext().setBoundAt( me ); } } ); stateMachines.addMessageProcessor( new HeartbeatRefreshProcessor( stateMachines.getOutgoing (), context.getClusterContext() ) ); input.addMessageProcessor( new HeartbeatIAmAliveProcessor( stateMachines.getOutgoing(), context.getClusterContext() ) ); server.newClient( Cluster.class ).addClusterListener( new HeartbeatJoinListener( stateMachines .getOutgoing() ) ); context.getHeartbeatContext().addHeartbeatListener( new HeartbeatReelectionListener( server.newClient( Election.class ), logging.getMessagesLog( ClusterLeaveReelectionListener.class ) ) ); context.getClusterContext().addClusterListener( new ClusterLeaveReelectionListener( server.newClient( Election.class ), logging.getMessagesLog( ClusterLeaveReelectionListener.class ) ) ); StateMachineRules rules = new StateMachineRules( stateMachines.getOutgoing() ) .rule( ClusterState.start, ClusterMessage.create, ClusterState.entered, internal( AtomicBroadcastMessage.entered ), internal( ProposerMessage.join ), internal( AcceptorMessage.join ), internal( LearnerMessage.join ), internal( HeartbeatMessage.join ), internal( ElectionMessage.created ), internal( SnapshotMessage.join ) ) .rule( ClusterState.discovery, ClusterMessage.configurationResponse, ClusterState.joining, internal( AcceptorMessage.join ), internal( LearnerMessage.join ), internal( AtomicBroadcastMessage.join ) ) .rule( ClusterState.discovery, ClusterMessage.configurationResponse, ClusterState.entered, internal( AtomicBroadcastMessage.entered ), internal( ProposerMessage.join ), internal( AcceptorMessage.join ), internal( LearnerMessage.join ), internal( HeartbeatMessage.join ), internal( ElectionMessage.join ), internal( SnapshotMessage.join ) ) .rule( ClusterState.joining, ClusterMessage.configurationChanged, ClusterState.entered, internal( AtomicBroadcastMessage.entered ), internal( ProposerMessage.join ), internal( AcceptorMessage.join ), internal( LearnerMessage.join ), internal( HeartbeatMessage.join ), internal( ElectionMessage.join ), internal( SnapshotMessage.join ) ) .rule( ClusterState.joining, ClusterMessage.joinFailure, ClusterState.start, internal( AtomicBroadcastMessage.leave ), internal( AcceptorMessage.leave ), internal( LearnerMessage.leave ), internal( ProposerMessage.leave ) ) .rule( ClusterState.entered, ClusterMessage.leave, ClusterState.start, internal( AtomicBroadcastMessage.leave ), internal( AcceptorMessage.leave ), internal( LearnerMessage.leave ), internal( HeartbeatMessage.leave ), internal( SnapshotMessage.leave ), internal( ElectionMessage.leave ), internal( ProposerMessage.leave ) ) .rule( ClusterState.entered, ClusterMessage.leave, ClusterState.start, internal( AtomicBroadcastMessage.leave ), internal( AcceptorMessage.leave ), internal( LearnerMessage.leave ), internal( HeartbeatMessage.leave ), internal( ElectionMessage.leave ), internal( SnapshotMessage.leave ), internal( ProposerMessage.leave ) ) .rule( ClusterState.leaving, ClusterMessage.configurationChanged, ClusterState.start, internal( AtomicBroadcastMessage.leave ), internal( AcceptorMessage.leave ), internal( LearnerMessage.leave ), internal( HeartbeatMessage.leave ), internal( ElectionMessage.leave ), internal( SnapshotMessage.leave ), internal( ProposerMessage.leave ) ) .rule( ClusterState.leaving, ClusterMessage.leaveTimedout, ClusterState.start, internal( AtomicBroadcastMessage.leave ), internal( AcceptorMessage.leave ), internal( LearnerMessage.leave ), internal( HeartbeatMessage.leave ), internal( ElectionMessage.leave ), internal( SnapshotMessage.leave ), internal( ProposerMessage.leave ) ); stateMachines.addStateTransitionListener( rules ); return server; } }
1no label
enterprise_cluster_src_main_java_org_neo4j_cluster_MultiPaxosServerFactory.java
6,067
public class TermSuggestion extends Suggestion<TermSuggestion.Entry> { public static Comparator<Suggestion.Entry.Option> SCORE = new Score(); public static Comparator<Suggestion.Entry.Option> FREQUENCY = new Frequency(); // Same behaviour as comparators in suggest module, but for SuggestedWord // Highest score first, then highest freq first, then lowest term first public static class Score implements Comparator<Suggestion.Entry.Option> { @Override public int compare(Suggestion.Entry.Option first, Suggestion.Entry.Option second) { // first criteria: the distance int cmp = Float.compare(second.getScore(), first.getScore()); if (cmp != 0) { return cmp; } return FREQUENCY.compare(first, second); } } // Same behaviour as comparators in suggest module, but for SuggestedWord // Highest freq first, then highest score first, then lowest term first public static class Frequency implements Comparator<Suggestion.Entry.Option> { @Override public int compare(Suggestion.Entry.Option first, Suggestion.Entry.Option second) { // first criteria: the popularity int cmp = ((TermSuggestion.Entry.Option) second).getFreq() - ((TermSuggestion.Entry.Option) first).getFreq(); if (cmp != 0) { return cmp; } // second criteria (if first criteria is equal): the distance cmp = Float.compare(second.getScore(), first.getScore()); if (cmp != 0) { return cmp; } // third criteria: term text return first.getText().compareTo(second.getText()); } } public static final int TYPE = 1; private Sort sort; public TermSuggestion() { } public TermSuggestion(String name, int size, Sort sort) { super(name, size); this.sort = sort; } public int getType() { return TYPE; } @Override protected Comparator<Option> sortComparator() { switch (sort) { case SCORE: return SCORE; case FREQUENCY: return FREQUENCY; default: throw new ElasticsearchException("Could not resolve comparator for sort key: [" + sort + "]"); } } @Override protected void innerReadFrom(StreamInput in) throws IOException { super.innerReadFrom(in); sort = Sort.fromId(in.readByte()); } @Override public void innerWriteTo(StreamOutput out) throws IOException { super.innerWriteTo(out); out.writeByte(sort.id()); } protected Entry newEntry() { return new Entry(); } /** * Represents a part from the suggest text with suggested options. */ public static class Entry extends org.elasticsearch.search.suggest.Suggest.Suggestion.Entry<TermSuggestion.Entry.Option> { Entry(Text text, int offset, int length) { super(text, offset, length); } Entry() { } @Override protected Option newOption() { return new Option(); } /** * Contains the suggested text with its document frequency and score. */ public static class Option extends org.elasticsearch.search.suggest.Suggest.Suggestion.Entry.Option { static class Fields { static final XContentBuilderString FREQ = new XContentBuilderString("freq"); } private int freq; protected Option(Text text, int freq, float score) { super(text, score); this.freq = freq; } @Override protected void mergeInto(Suggestion.Entry.Option otherOption) { super.mergeInto(otherOption); freq += ((Option) otherOption).freq; } protected Option() { super(); } public void setFreq(int freq) { this.freq = freq; } /** * @return How often this suggested text appears in the index. */ public int getFreq() { return freq; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); freq = in.readVInt(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(freq); } @Override protected XContentBuilder innerToXContent(XContentBuilder builder, Params params) throws IOException { builder = super.innerToXContent(builder, params); builder.field(Fields.FREQ, freq); return builder; } } } }
1no label
src_main_java_org_elasticsearch_search_suggest_term_TermSuggestion.java
1,198
objectIntMap = build(type, limit, smartSize, availableProcessors, new Recycler.C<ObjectIntOpenHashMap>() { @Override public ObjectIntOpenHashMap newInstance(int sizing) { return new ObjectIntOpenHashMap(size(sizing)); } @Override public void clear(ObjectIntOpenHashMap value) { value.clear(); } });
0true
src_main_java_org_elasticsearch_cache_recycler_CacheRecycler.java