Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
320
private class GotoResourceFilter extends ResourceFilter { /* * (non-Javadoc) * * @see org.eclipse.ui.dialogs.FilteredResourcesSelectionDialog.ResourceFilter#matchItem(java.lang.Object) */ @Override public boolean matchItem(Object item) { IResource resource = (IResource) item; return super.matchItem(item) && select(resource); } /** * This is the orignal <code>select</code> method. Since * <code>GotoResourceDialog</code> needs to extend * <code>FilteredResourcesSelectionDialog</code> result of this * method must be combined with the <code>matchItem</code> method * from super class (<code>ResourceFilter</code>). * * @param resource * A resource * @return <code>true</code> if item matches against given * conditions <code>false</code> otherwise */ private boolean select(IResource resource) { IProject project= resource.getProject(); try { if (project.getNature(JavaCore.NATURE_ID) != null) return fJavaModel.contains(resource); } catch (CoreException e) { // do nothing. Consider resource; } return true; } /* * (non-Javadoc) * * @see org.eclipse.ui.dialogs.FilteredResourcesSelectionDialog.ResourceFilter#equalsFilter(org.eclipse.ui.dialogs.FilteredItemsSelectionDialog.ItemsFilter) */ @Override public boolean equalsFilter(ItemsFilter filter) { if (!super.equalsFilter(filter)) { return false; } if (!(filter instanceof GotoResourceFilter)) { return false; } return true; } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_explorer_GotoResourceAction.java
1,531
public class HazelcastConnectionImpl implements HazelcastConnection { /** * Identity generator */ private static AtomicInteger idGen = new AtomicInteger(); /** * Reference to this creator and access to container infrastructure */ final ManagedConnectionImpl managedConnection; /** * this identity */ private final int id; public HazelcastConnectionImpl(ManagedConnectionImpl managedConnectionImpl, Subject subject) { super(); this.managedConnection = managedConnectionImpl; id = idGen.incrementAndGet(); } /* (non-Javadoc) * @see javax.resource.cci.Connection#close() */ public void close() throws ResourceException { managedConnection.log(Level.FINEST, "close"); //important: inform the container! managedConnection.fireConnectionEvent(ConnectionEvent.CONNECTION_CLOSED, this); } public Interaction createInteraction() throws ResourceException { //TODO return null; } /** * @throws NotSupportedException as this is not supported by this resource adapter */ public ResultSetInfo getResultSetInfo() throws NotSupportedException { //as per spec 15.11.3 throw new NotSupportedException(); } public HazelcastTransaction getLocalTransaction() throws ResourceException { managedConnection.log(Level.FINEST, "getLocalTransaction"); return managedConnection.getLocalTransaction(); } public ConnectionMetaData getMetaData() throws ResourceException { return managedConnection.getMetaData(); } @Override public String toString() { return "hazelcast.ConnectionImpl [" + id + "]"; } /** * Method is not exposed to force all clients to go through this connection object and its * methods from {@link HazelcastConnection} * * @return the local hazelcast instance */ private HazelcastInstance getHazelcastInstance() { return managedConnection.getHazelcastInstance(); } /* (non-Javadoc) * @see com.hazelcast.jca.HazelcastConnection#getMap(java.lang.String) */ public <K, V> IMap<K, V> getMap(String name) { return getHazelcastInstance().getMap(name); } /* (non-Javadoc) * @see com.hazelcast.jca.HazelcastConnection#getQueue(java.lang.String) */ public <E> IQueue<E> getQueue(String name) { return getHazelcastInstance().getQueue(name); } /* (non-Javadoc) * @see com.hazelcast.jca.HazelcastConnection#getTopic(java.lang.String) */ public <E> ITopic<E> getTopic(String name) { return getHazelcastInstance().getTopic(name); } /* (non-Javadoc) * @see com.hazelcast.jca.HazelcastConnection#getSet(java.lang.String) */ public <E> ISet<E> getSet(String name) { return getHazelcastInstance().getSet(name); } /* (non-Javadoc) * @see com.hazelcast.jca.HazelcastConnection#getList(java.lang.String) */ public <E> IList<E> getList(String name) { return getHazelcastInstance().getList(name); } /* (non-Javadoc) * @see com.hazelcast.jca.HazelcastConnection#getMultiMap(java.lang.String) */ public <K, V> MultiMap<K, V> getMultiMap(String name) { return getHazelcastInstance().getMultiMap(name); } /* (non-Javadoc) * @see com.hazelcast.jca.HazelcastConnection#getExecutorService(java.lang.String) */ public ExecutorService getExecutorService(String name) { return getHazelcastInstance().getExecutorService(name); } /* (non-Javadoc) * @see com.hazelcast.jca.HazelcastConnection#getAtomicLong(java.lang.String) */ public IAtomicLong getAtomicLong(String name) { return getHazelcastInstance().getAtomicLong(name); } /* (non-Javadoc) * @see com.hazelcast.jca.HazelcastConnection#getCountDownLatch(java.lang.String) */ public ICountDownLatch getCountDownLatch(String name) { return getHazelcastInstance().getCountDownLatch(name); } /* (non-Javadoc) * @see com.hazelcast.jca.HazelcastConnection#getSemaphore(java.lang.String) */ public ISemaphore getSemaphore(String name) { return getHazelcastInstance().getSemaphore(name); } public <K, V> TransactionalMap<K, V> getTransactionalMap(String name) { final TransactionContext txContext = this.managedConnection.getTx().getTxContext(); if (txContext == null) { throw new IllegalStateException("Transaction is not active"); } return txContext.getMap(name); } public <E> TransactionalQueue<E> getTransactionalQueue(String name) { final TransactionContext txContext = this.managedConnection.getTx().getTxContext(); if (txContext == null) { throw new IllegalStateException("Transaction is not active"); } return txContext.getQueue(name); } public <K, V> TransactionalMultiMap<K, V> getTransactionalMultiMap(String name) { final TransactionContext txContext = this.managedConnection.getTx().getTxContext(); if (txContext == null) { throw new IllegalStateException("Transaction is not active"); } return txContext.getMultiMap(name); } public <E> TransactionalList<E> getTransactionalList(String name) { final TransactionContext txContext = this.managedConnection.getTx().getTxContext(); if (txContext == null) { throw new IllegalStateException("Transaction is not active"); } return txContext.getList(name); } public <E> TransactionalSet<E> getTransactionalSet(String name) { final TransactionContext txContext = this.managedConnection.getTx().getTxContext(); if (txContext == null) { throw new IllegalStateException("Transaction is not active"); } return txContext.getSet(name); } }
1no label
hazelcast-ra_hazelcast-jca_src_main_java_com_hazelcast_jca_HazelcastConnectionImpl.java
648
indexTemplateService.removeTemplates(new MetaDataIndexTemplateService.RemoveRequest(request.name()).masterTimeout(request.masterNodeTimeout()), new MetaDataIndexTemplateService.RemoveListener() { @Override public void onResponse(MetaDataIndexTemplateService.RemoveResponse response) { listener.onResponse(new DeleteIndexTemplateResponse(response.acknowledged())); } @Override public void onFailure(Throwable t) { logger.debug("failed to delete templates [{}]", t, request.name()); listener.onFailure(t); } });
0true
src_main_java_org_elasticsearch_action_admin_indices_template_delete_TransportDeleteIndexTemplateAction.java
3,472
class ApplySettings implements IndexSettingsService.Listener { @Override public synchronized void onRefreshSettings(Settings settings) { long indexWarnThreshold = settings.getAsTime(INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_WARN, TimeValue.timeValueNanos(ShardSlowLogIndexingService.this.indexWarnThreshold)).nanos(); if (indexWarnThreshold != ShardSlowLogIndexingService.this.indexWarnThreshold) { ShardSlowLogIndexingService.this.indexWarnThreshold = indexWarnThreshold; } long indexInfoThreshold = settings.getAsTime(INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_INFO, TimeValue.timeValueNanos(ShardSlowLogIndexingService.this.indexInfoThreshold)).nanos(); if (indexInfoThreshold != ShardSlowLogIndexingService.this.indexInfoThreshold) { ShardSlowLogIndexingService.this.indexInfoThreshold = indexInfoThreshold; } long indexDebugThreshold = settings.getAsTime(INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_DEBUG, TimeValue.timeValueNanos(ShardSlowLogIndexingService.this.indexDebugThreshold)).nanos(); if (indexDebugThreshold != ShardSlowLogIndexingService.this.indexDebugThreshold) { ShardSlowLogIndexingService.this.indexDebugThreshold = indexDebugThreshold; } long indexTraceThreshold = settings.getAsTime(INDEX_INDEXING_SLOWLOG_THRESHOLD_INDEX_TRACE, TimeValue.timeValueNanos(ShardSlowLogIndexingService.this.indexTraceThreshold)).nanos(); if (indexTraceThreshold != ShardSlowLogIndexingService.this.indexTraceThreshold) { ShardSlowLogIndexingService.this.indexTraceThreshold = indexTraceThreshold; } String level = settings.get(INDEX_INDEXING_SLOWLOG_LEVEL, ShardSlowLogIndexingService.this.level); if (!level.equals(ShardSlowLogIndexingService.this.level)) { ShardSlowLogIndexingService.this.indexLogger.setLevel(level.toUpperCase(Locale.ROOT)); ShardSlowLogIndexingService.this.deleteLogger.setLevel(level.toUpperCase(Locale.ROOT)); ShardSlowLogIndexingService.this.level = level; } boolean reformat = settings.getAsBoolean(INDEX_INDEXING_SLOWLOG_REFORMAT, ShardSlowLogIndexingService.this.reformat); if (reformat != ShardSlowLogIndexingService.this.reformat) { ShardSlowLogIndexingService.this.reformat = reformat; } } }
0true
src_main_java_org_elasticsearch_index_indexing_slowlog_ShardSlowLogIndexingService.java
548
public class GetFieldMappingsAction extends IndicesAction<GetFieldMappingsRequest, GetFieldMappingsResponse, GetFieldMappingsRequestBuilder> { public static final GetFieldMappingsAction INSTANCE = new GetFieldMappingsAction(); public static final String NAME = "mappings/fields/get"; private GetFieldMappingsAction() { super(NAME); } @Override public GetFieldMappingsRequestBuilder newRequestBuilder(IndicesAdminClient client) { return new GetFieldMappingsRequestBuilder((InternalGenericClient) client); } @Override public GetFieldMappingsResponse newResponse() { return new GetFieldMappingsResponse(); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_mapping_get_GetFieldMappingsAction.java
360
public class FilterDefinition { protected String name; protected List<FilterParameter> params; protected String entityImplementationClassName; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<FilterParameter> getParams() { return params; } public void setParams(List<FilterParameter> params) { this.params = params; } public String getEntityImplementationClassName() { return entityImplementationClassName; } public void setEntityImplementationClassName(String entityImplementationClassName) { this.entityImplementationClassName = entityImplementationClassName; } }
0true
common_src_main_java_org_broadleafcommerce_common_filter_FilterDefinition.java
1,001
public class OStreamSerializerInteger implements OStreamSerializer { public static final String NAME = "i"; public static final OStreamSerializerInteger INSTANCE = new OStreamSerializerInteger(); public String getName() { return NAME; } public Object fromStream(final byte[] iStream) throws IOException { return OBinaryProtocol.bytes2int(iStream); } public byte[] toStream(final Object iObject) throws IOException { return OBinaryProtocol.int2bytes((Integer) iObject); } }
0true
core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_stream_OStreamSerializerInteger.java
567
trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) { firedEvents.add(event); } });
0true
core_src_test_java_com_orientechnologies_orient_core_index_OCompositeIndexDefinitionTest.java
1,375
public class AliasMetaData { private final String alias; private final CompressedString filter; private final String indexRouting; private final String searchRouting; private final Set<String> searchRoutingValues; private AliasMetaData(String alias, CompressedString filter, String indexRouting, String searchRouting) { this.alias = alias; this.filter = filter; this.indexRouting = indexRouting; this.searchRouting = searchRouting; if (searchRouting != null) { searchRoutingValues = Collections.unmodifiableSet(Strings.splitStringByCommaToSet(searchRouting)); } else { searchRoutingValues = ImmutableSet.of(); } } public String alias() { return alias; } public String getAlias() { return alias(); } public CompressedString filter() { return filter; } public CompressedString getFilter() { return filter(); } public boolean filteringRequired() { return filter != null; } public String getSearchRouting() { return searchRouting(); } public String searchRouting() { return searchRouting; } public String getIndexRouting() { return indexRouting(); } public String indexRouting() { return indexRouting; } public Set<String> searchRoutingValues() { return searchRoutingValues; } public static Builder builder(String alias) { return new Builder(alias); } public static Builder newAliasMetaDataBuilder(String alias) { return new Builder(alias); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AliasMetaData that = (AliasMetaData) o; if (alias != null ? !alias.equals(that.alias) : that.alias != null) return false; if (filter != null ? !filter.equals(that.filter) : that.filter != null) return false; if (indexRouting != null ? !indexRouting.equals(that.indexRouting) : that.indexRouting != null) return false; if (searchRouting != null ? !searchRouting.equals(that.searchRouting) : that.searchRouting != null) return false; return true; } @Override public int hashCode() { int result = alias != null ? alias.hashCode() : 0; result = 31 * result + (filter != null ? filter.hashCode() : 0); result = 31 * result + (indexRouting != null ? indexRouting.hashCode() : 0); result = 31 * result + (searchRouting != null ? searchRouting.hashCode() : 0); return result; } public static class Builder { private String alias; private CompressedString filter; private String indexRouting; private String searchRouting; public Builder(String alias) { this.alias = alias; } public Builder(AliasMetaData aliasMetaData) { this(aliasMetaData.alias()); filter = aliasMetaData.filter(); indexRouting = aliasMetaData.indexRouting(); searchRouting = aliasMetaData.searchRouting(); } public String alias() { return alias; } public Builder filter(CompressedString filter) { this.filter = filter; return this; } public Builder filter(String filter) { if (!Strings.hasLength(filter)) { this.filter = null; return this; } try { XContentParser parser = XContentFactory.xContent(filter).createParser(filter); try { filter(parser.mapOrdered()); } finally { parser.close(); } return this; } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + filter + "]", e); } } public Builder filter(Map<String, Object> filter) { if (filter == null || filter.isEmpty()) { this.filter = null; return this; } try { XContentBuilder builder = XContentFactory.jsonBuilder().map(filter); this.filter = new CompressedString(builder.bytes()); return this; } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to build json for alias request", e); } } public Builder filter(XContentBuilder filterBuilder) { try { return filter(filterBuilder.string()); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to build json for alias request", e); } } public Builder routing(String routing) { this.indexRouting = routing; this.searchRouting = routing; return this; } public Builder indexRouting(String indexRouting) { this.indexRouting = indexRouting; return this; } public Builder searchRouting(String searchRouting) { this.searchRouting = searchRouting; return this; } public AliasMetaData build() { return new AliasMetaData(alias, filter, indexRouting, searchRouting); } public static void toXContent(AliasMetaData aliasMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(aliasMetaData.alias(), XContentBuilder.FieldCaseConversion.NONE); boolean binary = params.paramAsBoolean("binary", false); if (aliasMetaData.filter() != null) { if (binary) { builder.field("filter", aliasMetaData.filter.compressed()); } else { byte[] data = aliasMetaData.filter().uncompressed(); XContentParser parser = XContentFactory.xContent(data).createParser(data); Map<String, Object> filter = parser.mapOrdered(); parser.close(); builder.field("filter", filter); } } if (aliasMetaData.indexRouting() != null) { builder.field("index_routing", aliasMetaData.indexRouting()); } if (aliasMetaData.searchRouting() != null) { builder.field("search_routing", aliasMetaData.searchRouting()); } builder.endObject(); } public static AliasMetaData fromXContent(XContentParser parser) throws IOException { Builder builder = new Builder(parser.currentName()); String currentFieldName = null; XContentParser.Token token = parser.nextToken(); if (token == null) { // no data... return builder.build(); } while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { if ("filter".equals(currentFieldName)) { Map<String, Object> filter = parser.mapOrdered(); builder.filter(filter); } } else if (token == XContentParser.Token.VALUE_EMBEDDED_OBJECT) { if ("filter".equals(currentFieldName)) { builder.filter(new CompressedString(parser.binaryValue())); } } else if (token == XContentParser.Token.VALUE_STRING) { if ("routing".equals(currentFieldName)) { builder.routing(parser.text()); } else if ("index_routing".equals(currentFieldName) || "indexRouting".equals(currentFieldName)) { builder.indexRouting(parser.text()); } else if ("search_routing".equals(currentFieldName) || "searchRouting".equals(currentFieldName)) { builder.searchRouting(parser.text()); } } } return builder.build(); } public static void writeTo(AliasMetaData aliasMetaData, StreamOutput out) throws IOException { out.writeString(aliasMetaData.alias()); if (aliasMetaData.filter() != null) { out.writeBoolean(true); aliasMetaData.filter.writeTo(out); } else { out.writeBoolean(false); } if (aliasMetaData.indexRouting() != null) { out.writeBoolean(true); out.writeString(aliasMetaData.indexRouting()); } else { out.writeBoolean(false); } if (aliasMetaData.searchRouting() != null) { out.writeBoolean(true); out.writeString(aliasMetaData.searchRouting()); } else { out.writeBoolean(false); } } public static AliasMetaData readFrom(StreamInput in) throws IOException { String alias = in.readString(); CompressedString filter = null; if (in.readBoolean()) { filter = CompressedString.readCompressedString(in); } String indexRouting = null; if (in.readBoolean()) { indexRouting = in.readString(); } String searchRouting = null; if (in.readBoolean()) { searchRouting = in.readString(); } return new AliasMetaData(alias, filter, indexRouting, searchRouting); } } }
0true
src_main_java_org_elasticsearch_cluster_metadata_AliasMetaData.java
2,074
public class MultipleEntryOperation extends AbstractMapOperation implements BackupAwareOperation, PartitionAwareOperation { private static final EntryEventType __NO_NEED_TO_FIRE_EVENT = null; private EntryProcessor entryProcessor; private Set<Data> keys; MapEntrySet response; public MultipleEntryOperation() { } public MultipleEntryOperation(String name, Set<Data> keys, EntryProcessor entryProcessor) { super(name); this.keys = keys; this.entryProcessor = entryProcessor; } public void innerBeforeRun() { final ManagedContext managedContext = getNodeEngine().getSerializationService().getManagedContext(); managedContext.initialize(entryProcessor); } @Override public void run() throws Exception { response = new MapEntrySet(); final InternalPartitionService partitionService = getNodeEngine().getPartitionService(); final RecordStore recordStore = mapService.getRecordStore(getPartitionId(), name); final LocalMapStatsImpl mapStats = mapService.getLocalMapStatsImpl(name); MapEntrySimple entry; for (Data key : keys) { if (partitionService.getPartitionId(key) != getPartitionId()) continue; long start = System.currentTimeMillis(); Object objectKey = mapService.toObject(key); final Map.Entry<Data, Object> mapEntry = recordStore.getMapEntry(key); final Object valueBeforeProcess = mapEntry.getValue(); final Object valueBeforeProcessObject = mapService.toObject(valueBeforeProcess); entry = new MapEntrySimple(objectKey, valueBeforeProcessObject); final Object result = entryProcessor.process(entry); final Object valueAfterProcess = entry.getValue(); Data dataValue = null; if (result != null) { dataValue = mapService.toData(result); response.add(new AbstractMap.SimpleImmutableEntry<Data, Data>(key, dataValue)); } EntryEventType eventType; if (valueAfterProcess == null) { recordStore.remove(key); mapStats.incrementRemoves(getLatencyFrom(start)); eventType = EntryEventType.REMOVED; } else { if (valueBeforeProcessObject == null) { mapStats.incrementPuts(getLatencyFrom(start)); eventType = EntryEventType.ADDED; } // take this case as a read so no need to fire an event. else if (!entry.isModified()) { mapStats.incrementGets(getLatencyFrom(start)); eventType = __NO_NEED_TO_FIRE_EVENT; } else { mapStats.incrementPuts(getLatencyFrom(start)); eventType = EntryEventType.UPDATED; } // todo if this is a read only operation, record access operations should be done. if (eventType != __NO_NEED_TO_FIRE_EVENT) { recordStore.put(new AbstractMap.SimpleImmutableEntry<Data, Object>(key, valueAfterProcess)); } } if (eventType != __NO_NEED_TO_FIRE_EVENT) { final Data oldValue = mapService.toData(valueBeforeProcess); final Data value = mapService.toData(valueAfterProcess); mapService.publishEvent(getCallerAddress(), name, eventType, key, oldValue, value); if (mapService.isNearCacheAndInvalidationEnabled(name)) { mapService.invalidateAllNearCaches(name, key); } if (mapContainer.getWanReplicationPublisher() != null && mapContainer.getWanMergePolicy() != null) { if (EntryEventType.REMOVED.equals(eventType)) { mapService.publishWanReplicationRemove(name, key, Clock.currentTimeMillis()); } else { Record record = recordStore.getRecord(key); Data tempValue = mapService.toData(dataValue); final SimpleEntryView entryView = mapService.createSimpleEntryView(key, tempValue, record); mapService.publishWanReplicationUpdate(name, entryView); } } } } } @Override public boolean returnsResponse() { return true; } @Override public Object getResponse() { return response; } @Override public String toString() { return "MultipleEntryOperation{}"; } @Override public boolean shouldBackup() { return entryProcessor.getBackupProcessor() != null; } @Override public int getSyncBackupCount() { return 0; } @Override public int getAsyncBackupCount() { return mapContainer.getTotalBackupCount(); } @Override public Operation getBackupOperation() { EntryBackupProcessor backupProcessor = entryProcessor.getBackupProcessor(); return backupProcessor != null ? new MultipleEntryBackupOperation(name, keys, backupProcessor) : null; } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); entryProcessor = in.readObject(); int size = in.readInt(); keys = new HashSet<Data>(size); for (int i = 0; i < size; i++) { Data key = new Data(); key.readData(in); keys.add(key); } } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeObject(entryProcessor); out.writeInt(keys.size()); for (Data key : keys) { key.writeData(out); } } private long getLatencyFrom(long begin) { return Clock.currentTimeMillis() - begin; } }
1no label
hazelcast_src_main_java_com_hazelcast_map_operation_MultipleEntryOperation.java
532
new Thread() { public void run() { try { justBeforeBlocked.await(); sleepSeconds(1); queue1.offer(item); } catch (InterruptedException e) { fail("failed"+e); } } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_txn_ClientTxnQueueTest.java
103
public static class Presentation { public static class Tab { public static class Name { public static final String Rules = "PageImpl_Rules_Tab"; } public static class Order { public static final int Rules = 1000; } } public static class Group { public static class Name { public static final String Basic = "PageImpl_Basic"; public static final String Page = "PageImpl_Page"; public static final String Rules = "PageImpl_Rules"; } public static class Order { public static final int Basic = 1000; public static final int Page = 2000; public static final int Rules = 1000; } } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_domain_PageImpl.java
2,324
public static class Builder implements Settings.Builder { public static final Settings EMPTY_SETTINGS = new Builder().build(); private final Map<String, String> map = new LinkedHashMap<String, String>(); private ClassLoader classLoader; private Builder() { } public Map<String, String> internalMap() { return this.map; } /** * Removes the provided setting from the internal map holding the current list of settings. */ public String remove(String key) { return map.remove(key); } /** * Returns a setting value based on the setting key. */ public String get(String key) { String retVal = map.get(key); if (retVal != null) { return retVal; } // try camel case version return map.get(toCamelCase(key)); } /** * Puts tuples of key value pairs of settings. Simplified version instead of repeating calling * put for each one. */ public Builder put(Object... settings) { if (settings.length == 1) { // support cases where the actual type gets lost down the road... if (settings[0] instanceof Map) { //noinspection unchecked return put((Map) settings[0]); } else if (settings[0] instanceof Settings) { return put((Settings) settings[0]); } } if ((settings.length % 2) != 0) { throw new ElasticsearchIllegalArgumentException("array settings of key + value order doesn't hold correct number of arguments (" + settings.length + ")"); } for (int i = 0; i < settings.length; i++) { put(settings[i++].toString(), settings[i].toString()); } return this; } /** * Sets a setting with the provided setting key and value. * * @param key The setting key * @param value The setting value * @return The builder */ public Builder put(String key, String value) { map.put(key, value); return this; } /** * Sets a setting with the provided setting key and class as value. * * @param key The setting key * @param clazz The setting class value * @return The builder */ public Builder put(String key, Class clazz) { map.put(key, clazz.getName()); return this; } /** * Sets the setting with the provided setting key and the boolean value. * * @param setting The setting key * @param value The boolean value * @return The builder */ public Builder put(String setting, boolean value) { put(setting, String.valueOf(value)); return this; } /** * Sets the setting with the provided setting key and the int value. * * @param setting The setting key * @param value The int value * @return The builder */ public Builder put(String setting, int value) { put(setting, String.valueOf(value)); return this; } public Builder put(String setting, Version version) { put(setting, version.id); return this; } /** * Sets the setting with the provided setting key and the long value. * * @param setting The setting key * @param value The long value * @return The builder */ public Builder put(String setting, long value) { put(setting, String.valueOf(value)); return this; } /** * Sets the setting with the provided setting key and the float value. * * @param setting The setting key * @param value The float value * @return The builder */ public Builder put(String setting, float value) { put(setting, String.valueOf(value)); return this; } /** * Sets the setting with the provided setting key and the double value. * * @param setting The setting key * @param value The double value * @return The builder */ public Builder put(String setting, double value) { put(setting, String.valueOf(value)); return this; } /** * Sets the setting with the provided setting key and the time value. * * @param setting The setting key * @param value The time value * @return The builder */ public Builder put(String setting, long value, TimeUnit timeUnit) { put(setting, timeUnit.toMillis(value)); return this; } /** * Sets the setting with the provided setting key and the size value. * * @param setting The setting key * @param value The size value * @return The builder */ public Builder put(String setting, long value, ByteSizeUnit sizeUnit) { put(setting, sizeUnit.toBytes(value)); return this; } /** * Sets the setting with the provided setting key and an array of values. * * @param setting The setting key * @param values The values * @return The builder */ public Builder putArray(String setting, String... values) { remove(setting); int counter = 0; while (true) { String value = map.remove(setting + '.' + (counter++)); if (value == null) { break; } } for (int i = 0; i < values.length; i++) { put(setting + "." + i, values[i]); } return this; } /** * Sets the setting group. */ public Builder put(String settingPrefix, String groupName, String[] settings, String[] values) throws SettingsException { if (settings.length != values.length) { throw new SettingsException("The settings length must match the value length"); } for (int i = 0; i < settings.length; i++) { if (values[i] == null) { continue; } put(settingPrefix + "." + groupName + "." + settings[i], values[i]); } return this; } /** * Sets all the provided settings. */ public Builder put(Settings settings) { map.putAll(settings.getAsMap()); classLoader = settings.getClassLoaderIfSet(); return this; } /** * Sets all the provided settings. */ public Builder put(Map<String, String> settings) { map.putAll(settings); return this; } /** * Sets all the provided settings. */ public Builder put(Properties properties) { for (Map.Entry entry : properties.entrySet()) { map.put((String) entry.getKey(), (String) entry.getValue()); } return this; } public Builder loadFromDelimitedString(String value, char delimiter) { String[] values = Strings.splitStringToArray(value, delimiter); for (String s : values) { int index = s.indexOf('='); if (index == -1) { throw new ElasticsearchIllegalArgumentException("value [" + s + "] for settings loaded with delimiter [" + delimiter + "] is malformed, missing ="); } map.put(s.substring(0, index), s.substring(index + 1)); } return this; } /** * Loads settings from the actual string content that represents them using the * {@link SettingsLoaderFactory#loaderFromSource(String)}. */ public Builder loadFromSource(String source) { SettingsLoader settingsLoader = SettingsLoaderFactory.loaderFromSource(source); try { Map<String, String> loadedSettings = settingsLoader.load(source); put(loadedSettings); } catch (Exception e) { throw new SettingsException("Failed to load settings from [" + source + "]", e); } return this; } /** * Loads settings from a url that represents them using the * {@link SettingsLoaderFactory#loaderFromSource(String)}. */ public Builder loadFromUrl(URL url) throws SettingsException { try { return loadFromStream(url.toExternalForm(), url.openStream()); } catch (IOException e) { throw new SettingsException("Failed to open stream for url [" + url.toExternalForm() + "]", e); } } /** * Loads settings from a stream that represents them using the * {@link SettingsLoaderFactory#loaderFromSource(String)}. */ public Builder loadFromStream(String resourceName, InputStream is) throws SettingsException { SettingsLoader settingsLoader = SettingsLoaderFactory.loaderFromResource(resourceName); try { Map<String, String> loadedSettings = settingsLoader.load(Streams.copyToString(new InputStreamReader(is, Charsets.UTF_8))); put(loadedSettings); } catch (Exception e) { throw new SettingsException("Failed to load settings from [" + resourceName + "]", e); } return this; } /** * Loads settings from classpath that represents them using the * {@link SettingsLoaderFactory#loaderFromSource(String)}. */ public Builder loadFromClasspath(String resourceName) throws SettingsException { ClassLoader classLoader = this.classLoader; if (classLoader == null) { classLoader = Classes.getDefaultClassLoader(); } InputStream is = classLoader.getResourceAsStream(resourceName); if (is == null) { return this; } return loadFromStream(resourceName, is); } /** * Sets the class loader associated with the settings built. */ public Builder classLoader(ClassLoader classLoader) { this.classLoader = classLoader; return this; } /** * Puts all the properties with keys starting with the provided <tt>prefix</tt>. * * @param prefix The prefix to filter property key by * @param properties The properties to put * @return The builder */ public Builder putProperties(String prefix, Properties properties) { for (Object key1 : properties.keySet()) { String key = (String) key1; String value = properties.getProperty(key); if (key.startsWith(prefix)) { map.put(key.substring(prefix.length()), value); } } return this; } /** * Puts all the properties with keys starting with the provided <tt>prefix</tt>. * * @param prefix The prefix to filter property key by * @param properties The properties to put * @return The builder */ public Builder putProperties(String prefix, Properties properties, String[] ignorePrefixes) { for (Object key1 : properties.keySet()) { String key = (String) key1; String value = properties.getProperty(key); if (key.startsWith(prefix)) { boolean ignore = false; for (String ignorePrefix : ignorePrefixes) { if (key.startsWith(ignorePrefix)) { ignore = true; break; } } if (!ignore) { map.put(key.substring(prefix.length()), value); } } } return this; } /** * Runs across all the settings set on this builder and replaces <tt>${...}</tt> elements in the * each setting value according to the following logic: * <p/> * <p>First, tries to resolve it against a System property ({@link System#getProperty(String)}), next, * tries and resolve it against an environment variable ({@link System#getenv(String)}), and last, tries * and replace it with another setting already set on this builder. */ public Builder replacePropertyPlaceholders() { PropertyPlaceholder propertyPlaceholder = new PropertyPlaceholder("${", "}", false); PropertyPlaceholder.PlaceholderResolver placeholderResolver = new PropertyPlaceholder.PlaceholderResolver() { @Override public String resolvePlaceholder(String placeholderName) { if (placeholderName.startsWith("env.")) { // explicit env var prefix return System.getenv(placeholderName.substring("env.".length())); } String value = System.getProperty(placeholderName); if (value != null) { return value; } value = System.getenv(placeholderName); if (value != null) { return value; } return map.get(placeholderName); } @Override public boolean shouldIgnoreMissing(String placeholderName) { // if its an explicit env var, we are ok with not having a value for it and treat it as optional if (placeholderName.startsWith("env.")) { return true; } return false; } }; for (Map.Entry<String, String> entry : Maps.newHashMap(map).entrySet()) { String value = propertyPlaceholder.replacePlaceholders(entry.getValue(), placeholderResolver); // if the values exists and has length, we should maintain it in the map // otherwise, the replace process resolved into removing it if (Strings.hasLength(value)) { map.put(entry.getKey(), value); } else { map.remove(entry.getKey()); } } return this; } /** * Builds a {@link Settings} (underlying uses {@link ImmutableSettings}) based on everything * set on this builder. */ public Settings build() { return new ImmutableSettings(Collections.unmodifiableMap(map), classLoader); } }
0true
src_main_java_org_elasticsearch_common_settings_ImmutableSettings.java
835
public class SearchScrollRequest extends ActionRequest<SearchScrollRequest> { private String scrollId; private Scroll scroll; private SearchOperationThreading operationThreading = SearchOperationThreading.THREAD_PER_SHARD; public SearchScrollRequest() { } public SearchScrollRequest(String scrollId) { this.scrollId = scrollId; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (scrollId == null) { validationException = addValidationError("scrollId is missing", validationException); } return validationException; } /** * Controls the the search operation threading model. */ public SearchOperationThreading operationThreading() { return this.operationThreading; } /** * Controls the the search operation threading model. */ public SearchScrollRequest operationThreading(SearchOperationThreading operationThreading) { this.operationThreading = operationThreading; return this; } /** * The scroll id used to scroll the search. */ public String scrollId() { return scrollId; } public SearchScrollRequest scrollId(String scrollId) { this.scrollId = scrollId; return this; } /** * If set, will enable scrolling of the search request. */ public Scroll scroll() { return scroll; } /** * If set, will enable scrolling of the search request. */ public SearchScrollRequest scroll(Scroll scroll) { this.scroll = scroll; return this; } /** * If set, will enable scrolling of the search request for the specified timeout. */ public SearchScrollRequest scroll(TimeValue keepAlive) { return scroll(new Scroll(keepAlive)); } /** * If set, will enable scrolling of the search request for the specified timeout. */ public SearchScrollRequest scroll(String keepAlive) { return scroll(new Scroll(TimeValue.parseTimeValue(keepAlive, null))); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); operationThreading = SearchOperationThreading.fromId(in.readByte()); scrollId = in.readString(); if (in.readBoolean()) { scroll = readScroll(in); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeByte(operationThreading.id()); out.writeString(scrollId); if (scroll == null) { out.writeBoolean(false); } else { out.writeBoolean(true); scroll.writeTo(out); } } }
0true
src_main_java_org_elasticsearch_action_search_SearchScrollRequest.java
1,083
public class UpdateRequestBuilder extends InstanceShardOperationRequestBuilder<UpdateRequest, UpdateResponse, UpdateRequestBuilder> { public UpdateRequestBuilder(Client client) { super((InternalClient) client, new UpdateRequest()); } public UpdateRequestBuilder(Client client, String index, String type, String id) { super((InternalClient) client, new UpdateRequest(index, type, id)); } /** * Sets the type of the indexed document. */ public UpdateRequestBuilder setType(String type) { request.type(type); return this; } /** * Sets the id of the indexed document. */ public UpdateRequestBuilder setId(String id) { request.id(id); return this; } /** * Controls the shard routing of the request. Using this value to hash the shard * and not the id. */ public UpdateRequestBuilder setRouting(String routing) { request.routing(routing); return this; } public UpdateRequestBuilder setParent(String parent) { request.parent(parent); return this; } /** * The script to execute. Note, make sure not to send different script each times and instead * use script params if possible with the same (automatically compiled) script. */ public UpdateRequestBuilder setScript(String script) { request.script(script); return this; } /** * The language of the script to execute. */ public UpdateRequestBuilder setScriptLang(String scriptLang) { request.scriptLang(scriptLang); return this; } /** * Sets the script parameters to use with the script. */ public UpdateRequestBuilder setScriptParams(Map<String, Object> scriptParams) { request.scriptParams(scriptParams); return this; } /** * Add a script parameter. */ public UpdateRequestBuilder addScriptParam(String name, Object value) { request.addScriptParam(name, value); return this; } /** * Explicitly specify the fields that will be returned. By default, nothing is returned. */ public UpdateRequestBuilder setFields(String... fields) { request.fields(fields); return this; } /** * Sets the number of retries of a version conflict occurs because the document was updated between * getting it and updating it. Defaults to 0. */ public UpdateRequestBuilder setRetryOnConflict(int retryOnConflict) { request.retryOnConflict(retryOnConflict); return this; } /** * Sets the version, which will cause the index operation to only be performed if a matching * version exists and no changes happened on the doc since then. */ public UpdateRequestBuilder setVersion(long version) { request.version(version); return this; } /** * Sets the versioning type. Defaults to {@link org.elasticsearch.index.VersionType#INTERNAL}. */ public UpdateRequestBuilder setVersionType(VersionType versionType) { request.versionType(versionType); return this; } /** * Should a refresh be executed post this update operation causing the operation to * be searchable. Note, heavy indexing should not set this to <tt>true</tt>. Defaults * to <tt>false</tt>. */ public UpdateRequestBuilder setRefresh(boolean refresh) { request.refresh(refresh); return this; } /** * Sets the replication type. */ public UpdateRequestBuilder setReplicationType(ReplicationType replicationType) { request.replicationType(replicationType); return this; } /** * Sets the consistency level of write. Defaults to {@link org.elasticsearch.action.WriteConsistencyLevel#DEFAULT} */ public UpdateRequestBuilder setConsistencyLevel(WriteConsistencyLevel consistencyLevel) { request.consistencyLevel(consistencyLevel); return this; } /** * Sets the doc to use for updates when a script is not specified. */ public UpdateRequestBuilder setDoc(IndexRequest indexRequest) { request.doc(indexRequest); return this; } /** * Sets the doc to use for updates when a script is not specified. */ public UpdateRequestBuilder setDoc(XContentBuilder source) { request.doc(source); return this; } /** * Sets the doc to use for updates when a script is not specified. */ public UpdateRequestBuilder setDoc(Map source) { request.doc(source); return this; } /** * Sets the doc to use for updates when a script is not specified. */ public UpdateRequestBuilder setDoc(Map source, XContentType contentType) { request.doc(source, contentType); return this; } /** * Sets the doc to use for updates when a script is not specified. */ public UpdateRequestBuilder setDoc(String source) { request.doc(source); return this; } /** * Sets the doc to use for updates when a script is not specified. */ public UpdateRequestBuilder setDoc(byte[] source) { request.doc(source); return this; } /** * Sets the doc to use for updates when a script is not specified. */ public UpdateRequestBuilder setDoc(byte[] source, int offset, int length) { request.doc(source, offset, length); return this; } /** * Sets the doc to use for updates when a script is not specified. */ public UpdateRequestBuilder setDoc(String field, Object value) { request.doc(field, value); return this; } /** * Sets the doc to use for updates when a script is not specified, the doc provided * is a field and value pairs. */ public UpdateRequestBuilder setDoc(Object... source) { request.doc(source); return this; } /** * Sets the index request to be used if the document does not exists. Otherwise, a {@link org.elasticsearch.index.engine.DocumentMissingException} * is thrown. */ public UpdateRequestBuilder setUpsert(IndexRequest indexRequest) { request.upsert(indexRequest); return this; } /** * Sets the doc source of the update request to be used when the document does not exists. */ public UpdateRequestBuilder setUpsert(XContentBuilder source) { request.upsert(source); return this; } /** * Sets the doc source of the update request to be used when the document does not exists. */ public UpdateRequestBuilder setUpsert(Map source) { request.upsert(source); return this; } /** * Sets the doc source of the update request to be used when the document does not exists. */ public UpdateRequestBuilder setUpsert(Map source, XContentType contentType) { request.upsert(source, contentType); return this; } /** * Sets the doc source of the update request to be used when the document does not exists. */ public UpdateRequestBuilder setUpsert(String source) { request.upsert(source); return this; } /** * Sets the doc source of the update request to be used when the document does not exists. */ public UpdateRequestBuilder setUpsert(byte[] source) { request.upsert(source); return this; } /** * Sets the doc source of the update request to be used when the document does not exists. */ public UpdateRequestBuilder setUpsert(byte[] source, int offset, int length) { request.upsert(source, offset, length); return this; } /** * Sets the doc source of the update request to be used when the document does not exists. The doc * includes field and value pairs. */ public UpdateRequestBuilder setUpsert(Object... source) { request.upsert(source); return this; } public UpdateRequestBuilder setSource(XContentBuilder source) throws Exception { request.source(source); return this; } public UpdateRequestBuilder setSource(byte[] source) throws Exception { request.source(source); return this; } public UpdateRequestBuilder setSource(byte[] source, int offset, int length) throws Exception { request.source(source, offset, length); return this; } public UpdateRequestBuilder setSource(BytesReference source) throws Exception { request.source(source); return this; } /** * Sets whether the specified doc parameter should be used as upsert document. */ public UpdateRequestBuilder setDocAsUpsert(boolean shouldUpsertDoc) { request.docAsUpsert(shouldUpsertDoc); return this; } @Override protected void doExecute(ActionListener<UpdateResponse> listener) { ((Client) client).update(request, listener); } }
0true
src_main_java_org_elasticsearch_action_update_UpdateRequestBuilder.java
2,537
public class YamlXContentGenerator extends JsonXContentGenerator { public YamlXContentGenerator(JsonGenerator generator) { super(generator); } @Override public XContentType contentType() { return XContentType.YAML; } @Override public void usePrintLineFeedAtEnd() { // nothing here } @Override public void writeRawField(String fieldName, InputStream content, OutputStream bos) throws IOException { writeFieldName(fieldName); YAMLParser parser = YamlXContent.yamlFactory.createParser(content); try { parser.nextToken(); generator.copyCurrentStructure(parser); } finally { parser.close(); } } @Override public void writeRawField(String fieldName, byte[] content, OutputStream bos) throws IOException { writeFieldName(fieldName); YAMLParser parser = YamlXContent.yamlFactory.createParser(content); try { parser.nextToken(); generator.copyCurrentStructure(parser); } finally { parser.close(); } } @Override protected void writeObjectRaw(String fieldName, BytesReference content, OutputStream bos) throws IOException { writeFieldName(fieldName); YAMLParser parser; if (content.hasArray()) { parser = YamlXContent.yamlFactory.createParser(content.array(), content.arrayOffset(), content.length()); } else { parser = YamlXContent.yamlFactory.createParser(content.streamInput()); } try { parser.nextToken(); generator.copyCurrentStructure(parser); } finally { parser.close(); } } @Override public void writeRawField(String fieldName, byte[] content, int offset, int length, OutputStream bos) throws IOException { writeFieldName(fieldName); YAMLParser parser = YamlXContent.yamlFactory.createParser(content, offset, length); try { parser.nextToken(); generator.copyCurrentStructure(parser); } finally { parser.close(); } } }
0true
src_main_java_org_elasticsearch_common_xcontent_yaml_YamlXContentGenerator.java
1,906
EntryListener<Object, Object> listener = new EntryAdapter<Object, Object>() { public void entryAdded(EntryEvent<Object, Object> event) { addCount.incrementAndGet(); } };
0true
hazelcast_src_test_java_com_hazelcast_map_QueryListenerTest.java
2,607
public class TcpIpConnectionManager implements ConnectionManager { final int socketReceiveBufferSize; final IOService ioService; final int socketSendBufferSize; private final ConstructorFunction<Address, ConnectionMonitor> monitorConstructor = new ConstructorFunction<Address, ConnectionMonitor>() { public ConnectionMonitor createNew(Address endpoint) { return new ConnectionMonitor(TcpIpConnectionManager.this, endpoint); } }; private final ILogger logger; private final int socketLingerSeconds; private final boolean socketKeepAlive; private final boolean socketNoDelay; private final ConcurrentMap<Address, Connection> connectionsMap = new ConcurrentHashMap<Address, Connection>(100); private final ConcurrentMap<Address, ConnectionMonitor> monitors = new ConcurrentHashMap<Address, ConnectionMonitor>(100); private final Set<Address> connectionsInProgress = Collections.newSetFromMap(new ConcurrentHashMap<Address, Boolean>()); private final Set<ConnectionListener> connectionListeners = new CopyOnWriteArraySet<ConnectionListener>(); private final Set<SocketChannelWrapper> acceptedSockets = Collections.newSetFromMap(new ConcurrentHashMap<SocketChannelWrapper, Boolean>()); private final Set<TcpIpConnection> activeConnections = Collections.newSetFromMap(new ConcurrentHashMap<TcpIpConnection, Boolean>()); private final AtomicInteger allTextConnections = new AtomicInteger(); private final AtomicInteger connectionIdGen = new AtomicInteger(); private volatile boolean live; private final ServerSocketChannel serverSocketChannel; private final int selectorThreadCount; private final IOSelector[] inSelectors; private final IOSelector[] outSelectors; private final AtomicInteger nextSelectorIndex = new AtomicInteger(); private final MemberSocketInterceptor memberSocketInterceptor; private final SocketChannelWrapperFactory socketChannelWrapperFactory; private final int outboundPortCount; private final LinkedList<Integer> outboundPorts = new LinkedList<Integer>(); // accessed only in synchronized block private final SerializationContext serializationContext; private volatile Thread socketAcceptorThread; // accessed only in synchronized block public TcpIpConnectionManager(IOService ioService, ServerSocketChannel serverSocketChannel) { this.ioService = ioService; this.serverSocketChannel = serverSocketChannel; this.logger = ioService.getLogger(TcpIpConnectionManager.class.getName()); this.socketReceiveBufferSize = ioService.getSocketReceiveBufferSize() * IOService.KILO_BYTE; this.socketSendBufferSize = ioService.getSocketSendBufferSize() * IOService.KILO_BYTE; this.socketLingerSeconds = ioService.getSocketLingerSeconds(); this.socketKeepAlive = ioService.getSocketKeepAlive(); this.socketNoDelay = ioService.getSocketNoDelay(); selectorThreadCount = ioService.getSelectorThreadCount(); inSelectors = new IOSelector[selectorThreadCount]; outSelectors = new IOSelector[selectorThreadCount]; final Collection<Integer> ports = ioService.getOutboundPorts(); outboundPortCount = ports == null ? 0 : ports.size(); if (ports != null) { outboundPorts.addAll(ports); } SSLConfig sslConfig = ioService.getSSLConfig(); if (sslConfig != null && sslConfig.isEnabled()) { socketChannelWrapperFactory = new SSLSocketChannelWrapperFactory(sslConfig); logger.info("SSL is enabled"); } else { socketChannelWrapperFactory = new DefaultSocketChannelWrapperFactory(); } SocketInterceptor implementation = null; SocketInterceptorConfig sic = ioService.getSocketInterceptorConfig(); if (sic != null && sic.isEnabled()) { implementation = (SocketInterceptor) sic.getImplementation(); if (implementation == null && sic.getClassName() != null) { try { implementation = (SocketInterceptor) Class.forName(sic.getClassName()).newInstance(); } catch (Throwable e) { logger.severe("SocketInterceptor class cannot be instantiated!" + sic.getClassName(), e); } } if (implementation != null) { if (!(implementation instanceof MemberSocketInterceptor)) { logger.severe("SocketInterceptor must be instance of " + MemberSocketInterceptor.class.getName()); implementation = null; } } } memberSocketInterceptor = (MemberSocketInterceptor) implementation; if (memberSocketInterceptor != null) { logger.info("SocketInterceptor is enabled"); memberSocketInterceptor.init(sic.getProperties()); } serializationContext = ioService.getSerializationContext(); } @Override public int getActiveConnectionCount() { return activeConnections.size(); } public int getAllTextConnections() { return allTextConnections.get(); } @Override public int getConnectionCount() { return connectionsMap.size(); } @Override public boolean isSSLEnabled() { return socketChannelWrapperFactory instanceof SSLSocketChannelWrapperFactory; } public void incrementTextConnections() { allTextConnections.incrementAndGet(); } public SerializationContext getSerializationContext() { return serializationContext; } interface SocketChannelWrapperFactory { SocketChannelWrapper wrapSocketChannel(SocketChannel socketChannel, boolean client) throws Exception; } static class DefaultSocketChannelWrapperFactory implements SocketChannelWrapperFactory { public SocketChannelWrapper wrapSocketChannel(SocketChannel socketChannel, boolean client) throws Exception { return new DefaultSocketChannelWrapper(socketChannel); } } class SSLSocketChannelWrapperFactory implements SocketChannelWrapperFactory { final SSLContextFactory sslContextFactory; SSLSocketChannelWrapperFactory(SSLConfig sslConfig) { if (CipherHelper.isSymmetricEncryptionEnabled(ioService)) { throw new RuntimeException("SSL and SymmetricEncryption cannot be both enabled!"); } SSLContextFactory sslContextFactoryObject = (SSLContextFactory) sslConfig.getFactoryImplementation(); try { String factoryClassName = sslConfig.getFactoryClassName(); if (sslContextFactoryObject == null && factoryClassName != null) { sslContextFactoryObject = (SSLContextFactory) Class.forName(factoryClassName).newInstance(); } if (sslContextFactoryObject == null) { sslContextFactoryObject = new BasicSSLContextFactory(); } sslContextFactoryObject.init(sslConfig.getProperties()); } catch (Exception e) { throw new RuntimeException(e); } sslContextFactory = sslContextFactoryObject; } public SocketChannelWrapper wrapSocketChannel(SocketChannel socketChannel, boolean client) throws Exception { return new SSLSocketChannelWrapper(sslContextFactory.getSSLContext(), socketChannel, client); } } public IOService getIOHandler() { return ioService; } public MemberSocketInterceptor getMemberSocketInterceptor() { return memberSocketInterceptor; } public void addConnectionListener(ConnectionListener listener) { connectionListeners.add(listener); } public boolean bind(TcpIpConnection connection, Address remoteEndPoint, Address localEndpoint, final boolean replyBack) { if (logger.isFinestEnabled()) { log(Level.FINEST, "Binding " + connection + " to " + remoteEndPoint + ", replyBack is " + replyBack); } final Address thisAddress = ioService.getThisAddress(); if (!connection.isClient() && !thisAddress.equals(localEndpoint)) { log(Level.WARNING, "Wrong bind request from " + remoteEndPoint + "! This node is not requested endpoint: " + localEndpoint); connection.close(); return false; } connection.setEndPoint(remoteEndPoint); if (replyBack) { sendBindRequest(connection, remoteEndPoint, false); } final Connection existingConnection = connectionsMap.get(remoteEndPoint); if (existingConnection != null && existingConnection.live()) { if (existingConnection != connection) { if (logger.isFinestEnabled()) { log(Level.FINEST, existingConnection + " is already bound to " + remoteEndPoint + ", new one is " + connection); } activeConnections.add(connection); } return false; } if (!remoteEndPoint.equals(thisAddress)) { if (!connection.isClient()) { connection.setMonitor(getConnectionMonitor(remoteEndPoint, true)); } connectionsMap.put(remoteEndPoint, connection); connectionsInProgress.remove(remoteEndPoint); for (ConnectionListener listener : connectionListeners) { listener.connectionAdded(connection); } return true; } return false; } void sendBindRequest(final TcpIpConnection connection, final Address remoteEndPoint, final boolean replyBack) { connection.setEndPoint(remoteEndPoint); //make sure bind packet is the first packet sent to the end point. final BindOperation bind = new BindOperation(ioService.getThisAddress(), remoteEndPoint, replyBack); final Data bindData = ioService.toData(bind); final Packet packet = new Packet(bindData, serializationContext); packet.setHeader(Packet.HEADER_OP); connection.write(packet); //now you can send anything... } private int nextSelectorIndex() { return Math.abs(nextSelectorIndex.getAndIncrement()) % selectorThreadCount; } SocketChannelWrapper wrapSocketChannel(SocketChannel socketChannel, boolean client) throws Exception { final SocketChannelWrapper socketChannelWrapper = socketChannelWrapperFactory.wrapSocketChannel(socketChannel, client); acceptedSockets.add(socketChannelWrapper); return socketChannelWrapper; } TcpIpConnection assignSocketChannel(SocketChannelWrapper channel) { final int index = nextSelectorIndex(); final TcpIpConnection connection = new TcpIpConnection(this, inSelectors[index], outSelectors[index], connectionIdGen.incrementAndGet(), channel); activeConnections.add(connection); acceptedSockets.remove(channel); connection.getReadHandler().register(); log(Level.INFO, channel.socket().getLocalPort() + " accepted socket connection from " + channel.socket().getRemoteSocketAddress()); return connection; } void failedConnection(Address address, Throwable t, boolean silent) { connectionsInProgress.remove(address); ioService.onFailedConnection(address); if (!silent) { getConnectionMonitor(address, false).onError(t); } } public Connection getConnection(Address address) { return connectionsMap.get(address); } public Connection getOrConnect(Address address) { return getOrConnect(address, false); } public Connection getOrConnect(final Address address, final boolean silent) { Connection connection = connectionsMap.get(address); if (connection == null && live) { if (connectionsInProgress.add(address)) { ioService.shouldConnectTo(address); ioService.executeAsync(new SocketConnector(this, address, silent)); } } return connection; } private ConnectionMonitor getConnectionMonitor(Address endpoint, boolean reset) { final ConnectionMonitor monitor = ConcurrencyUtil.getOrPutIfAbsent(monitors, endpoint, monitorConstructor); if (reset) { monitor.reset(); } return monitor; } public void destroyConnection(Connection connection) { if (connection == null) { return; } if (logger.isFinestEnabled()) { log(Level.FINEST, "Destroying " + connection); } activeConnections.remove(connection); final Address endPoint = connection.getEndPoint(); if (endPoint != null) { connectionsInProgress.remove(endPoint); final Connection existingConn = connectionsMap.get(endPoint); if (existingConn == connection && live) { connectionsMap.remove(endPoint); for (ConnectionListener listener : connectionListeners) { listener.connectionRemoved(connection); } } } if (connection.live()) { connection.close(); } } protected void initSocket(Socket socket) throws Exception { if (socketLingerSeconds > 0) { socket.setSoLinger(true, socketLingerSeconds); } socket.setKeepAlive(socketKeepAlive); socket.setTcpNoDelay(socketNoDelay); socket.setReceiveBufferSize(socketReceiveBufferSize); socket.setSendBufferSize(socketSendBufferSize); } public synchronized void start() { if (live) { return; } live = true; log(Level.FINEST, "Starting ConnectionManager and IO selectors."); for (int i = 0; i < inSelectors.length; i++) { inSelectors[i] = new InSelectorImpl(ioService, i); outSelectors[i] = new OutSelectorImpl(ioService, i); inSelectors[i].start(); outSelectors[i].start(); } if (serverSocketChannel != null) { if (socketAcceptorThread != null) { logger.warning("SocketAcceptor thread is already live! Shutting down old acceptor..."); shutdownSocketAcceptor(); } Runnable acceptRunnable = new SocketAcceptor(serverSocketChannel, this); socketAcceptorThread = new Thread(ioService.getThreadGroup(), acceptRunnable, ioService.getThreadPrefix() + "Acceptor"); socketAcceptorThread.start(); } } public synchronized void restart() { stop(); start(); } public synchronized void shutdown() { try { if (live) { stop(); connectionListeners.clear(); } } finally { if (serverSocketChannel != null) { try { if (logger.isFinestEnabled()) { log(Level.FINEST, "Closing server socket channel: " + serverSocketChannel); } serverSocketChannel.close(); } catch (IOException ignore) { logger.finest(ignore); } } } } private void stop() { live = false; log(Level.FINEST, "Stopping ConnectionManager"); // interrupt acceptor thread after live=false shutdownSocketAcceptor(); for (SocketChannelWrapper socketChannel : acceptedSockets) { IOUtil.closeResource(socketChannel); } for (Connection conn : connectionsMap.values()) { try { destroyConnection(conn); } catch (final Throwable ignore) { logger.finest(ignore); } } for (TcpIpConnection conn : activeConnections) { try { destroyConnection(conn); } catch (final Throwable ignore) { logger.finest(ignore); } } shutdownIOSelectors(); connectionsInProgress.clear(); connectionsMap.clear(); monitors.clear(); activeConnections.clear(); } private synchronized void shutdownIOSelectors() { if (logger.isFinestEnabled()) { log(Level.FINEST, "Shutting down IO selectors... Total: " + selectorThreadCount); } for (int i = 0; i < selectorThreadCount; i++) { IOSelector ioSelector = inSelectors[i]; if (ioSelector != null) { ioSelector.shutdown(); } inSelectors[i] = null; ioSelector = outSelectors[i]; if (ioSelector != null) { ioSelector.shutdown(); } outSelectors[i] = null; } } private void shutdownSocketAcceptor() { log(Level.FINEST, "Shutting down SocketAcceptor thread."); Thread killingThread = socketAcceptorThread; if (killingThread == null) { return; } socketAcceptorThread = null; killingThread.interrupt(); try { killingThread.join(1000 * 10); } catch (InterruptedException e) { logger.finest(e); } } public int getCurrentClientConnections() { int count = 0; for (TcpIpConnection conn : activeConnections) { if (conn.live()) { if (conn.isClient()) { count++; } } } return count; } public boolean isLive() { return live; } public Map<Address, Connection> getReadonlyConnectionMap() { return Collections.unmodifiableMap(connectionsMap); } private void log(Level level, String message) { logger.log(level, message); ioService.getSystemLogService().logConnection(message); } boolean useAnyOutboundPort() { return outboundPortCount == 0; } int getOutboundPortCount() { return outboundPortCount; } int acquireOutboundPort() { if (useAnyOutboundPort()) { return 0; } synchronized (outboundPorts) { final Integer port = outboundPorts.removeFirst(); outboundPorts.addLast(port); return port; } } @Override public String toString() { final StringBuilder sb = new StringBuilder("Connections {"); for (Connection conn : connectionsMap.values()) { sb.append("\n"); sb.append(conn); } sb.append("\nlive="); sb.append(live); sb.append("\n}"); return sb.toString(); } }
1no label
hazelcast_src_main_java_com_hazelcast_nio_TcpIpConnectionManager.java
412
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.REMOVE); Assert.assertEquals(event.getOldValue(), "value2"); Assert.assertEquals(event.getKey().intValue(), 1); Assert.assertNull(event.getValue()); changed.value = true; } });
0true
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedListTest.java
472
public class BroadleafExternalAuthenticationUserDetails extends User { private String firstName; private String lastName; private String email; public BroadleafExternalAuthenticationUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities) { super(username, password, authorities); } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
0true
common_src_main_java_org_broadleafcommerce_common_security_BroadleafExternalAuthenticationUserDetails.java
269
public class ElasticsearchIllegalStateException extends ElasticsearchException { public ElasticsearchIllegalStateException() { super(null); } public ElasticsearchIllegalStateException(String msg) { super(msg); } public ElasticsearchIllegalStateException(String msg, Throwable cause) { super(msg, cause); } }
0true
src_main_java_org_elasticsearch_ElasticsearchIllegalStateException.java
599
public abstract class BLCAbstractHandlerMapping extends AbstractHandlerMapping { protected String controllerName; @Override /** * This handler mapping does not provide a default handler. This method * has been coded to always return null. */ public Object getDefaultHandler() { return null; } /** * Returns the controllerName if set or "blPageController" by default. * @return */ public String getControllerName() { return controllerName; } /** * Sets the name of the bean to use as the Handler. Typically the name of * a controller bean. * * @param controllerName */ public void setControllerName(String controllerName) { this.controllerName = controllerName; } }
0true
common_src_main_java_org_broadleafcommerce_common_web_BLCAbstractHandlerMapping.java
340
public class NodeReplaceInsert extends BaseHandler { private static final Log LOG = LogFactory.getLog(NodeReplaceInsert.class); private static final Comparator<Node> NODE_COMPARATOR = new Comparator<Node>() { public int compare(Node arg0, Node arg1) { int response = -1; if (arg0.isSameNode(arg1)) { response = 0; } //determine if the element is an ancestor if (response != 0) { boolean eof = false; Node parentNode = arg0; while (!eof) { parentNode = parentNode.getParentNode(); if (parentNode == null) { eof = true; } else if (arg1.isSameNode(parentNode)) { response = 0; eof = true; } } } return response; } }; public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) { if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) { return null; } Node[] primaryNodes = new Node[nodeList1.size()]; for (int j=0;j<primaryNodes.length;j++){ primaryNodes[j] = nodeList1.get(j); } ArrayList<Node> list = new ArrayList<Node>(); for (int j=0;j<nodeList2.size();j++){ list.add(nodeList2.get(j)); } List<Node> usedNodes = matchNodes(exhaustedNodes, primaryNodes, list); Node[] response = {}; response = usedNodes.toArray(response); return response; } private boolean exhaustedNodesContains(List<Node> exhaustedNodes, Node node) { boolean contains = false; for (Node exhaustedNode : exhaustedNodes) { if (NODE_COMPARATOR.compare(exhaustedNode, node) == 0) { contains = true; break; } } return contains; } private List<Node> matchNodes(List<Node> exhaustedNodes, Node[] primaryNodes, ArrayList<Node> list) { List<Node> usedNodes = new ArrayList<Node>(20); Iterator<Node> itr = list.iterator(); Node parentNode = primaryNodes[0].getParentNode(); Document ownerDocument = parentNode.getOwnerDocument(); while(itr.hasNext()) { Node node = itr.next(); if (Element.class.isAssignableFrom(node.getClass()) && !exhaustedNodesContains(exhaustedNodes, node)) { if(LOG.isDebugEnabled()) { StringBuffer sb = new StringBuffer(); sb.append("matching node for replacement: "); sb.append(node.getNodeName()); int attrLength = node.getAttributes().getLength(); for (int j=0;j<attrLength;j++){ sb.append(" : ("); sb.append(node.getAttributes().item(j).getNodeName()); sb.append("/"); sb.append(node.getAttributes().item(j).getNodeValue()); sb.append(")"); } LOG.debug(sb.toString()); } if (!checkNode(usedNodes, primaryNodes, node)) { //simply append the node if all the above fails Node newNode = ownerDocument.importNode(node.cloneNode(true), true); parentNode.appendChild(newNode); usedNodes.add(node); } } } return usedNodes; } protected boolean checkNode(List<Node> usedNodes, Node[] primaryNodes, Node node) { //find matching nodes based on id if (replaceNode(primaryNodes, node, "id", usedNodes)) { return true; } //find matching nodes based on name if (replaceNode(primaryNodes, node, "name", usedNodes)) { return true; } //check if this same node already exists if (exactNodeExists(primaryNodes, node, usedNodes)) { return true; } return false; } protected boolean exactNodeExists(Node[] primaryNodes, Node testNode, List<Node> usedNodes) { for (int j=0;j<primaryNodes.length;j++){ if (primaryNodes[j].isEqualNode(testNode)) { usedNodes.add(primaryNodes[j]); return true; } } return false; } protected boolean replaceNode(Node[] primaryNodes, Node testNode, final String attribute, List<Node> usedNodes) { if (testNode.getAttributes().getNamedItem(attribute) == null) { return false; } //filter out primary nodes that don't have the attribute ArrayList<Node> filterList = new ArrayList<Node>(); for (int j=0;j<primaryNodes.length;j++){ if (primaryNodes[j].getAttributes().getNamedItem(attribute) != null) { filterList.add(primaryNodes[j]); } } Node[] filtered = {}; filtered = filterList.toArray(filtered); Comparator<Node> idCompare = new Comparator<Node>() { public int compare(Node arg0, Node arg1) { Node id1 = arg0.getAttributes().getNamedItem(attribute); Node id2 = arg1.getAttributes().getNamedItem(attribute); String idVal1 = id1.getNodeValue(); String idVal2 = id2.getNodeValue(); return idVal1.compareTo(idVal2); } }; Arrays.sort(filtered, idCompare); int pos = Arrays.binarySearch(filtered, testNode, idCompare); if (pos >= 0) { Node newNode = filtered[pos].getOwnerDocument().importNode(testNode.cloneNode(true), true); filtered[pos].getParentNode().replaceChild(newNode, filtered[pos]); usedNodes.add(testNode); return true; } return false; } }
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_handlers_NodeReplaceInsert.java
235
private class InterceptingTransactionFactory extends TransactionFactory { @Override public XaTransaction create( long lastCommittedTxWhenTransactionStarted, TransactionState state ) { TransactionInterceptor first = providers.resolveChain( NeoStoreXaDataSource.this ); return new InterceptingWriteTransaction( lastCommittedTxWhenTransactionStarted, getLogicalLog(), neoStore, state, cacheAccess, indexingService, labelScanStore, first, integrityValidator, (KernelTransactionImplementation)kernel.newTransaction(), locks ); } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreXaDataSource.java
1,282
es.submit(new Runnable() { public void run() { Map<String, byte[]> map = hazelcast.getMap("default"); while (running) { try { int key = (int) (random.nextFloat() * entryCount); int operation = random(10); if (operation < 4) { map.put(String.valueOf(key), new byte[valueSize]); stats.mapPuts.incrementAndGet(); } else if (operation < 8) { map.get(String.valueOf(key)); stats.mapGets.incrementAndGet(); } else { map.remove(String.valueOf(key)); stats.mapRemoves.incrementAndGet(); } } catch (HazelcastInstanceNotActiveException ignored) { throw new RuntimeException(ignored); } catch (Throwable e) { throw new RuntimeException(e); } } } });
0true
hazelcast_src_main_java_com_hazelcast_examples_LongRunningTest.java
2,092
public class PutIfAbsentOperation extends BasePutOperation { private boolean successful; public PutIfAbsentOperation(String name, Data dataKey, Data value, long ttl) { super(name, dataKey, value, ttl); } public PutIfAbsentOperation() { } public void run() { dataOldValue = mapService.toData(recordStore.putIfAbsent(dataKey, dataValue, ttl)); successful = dataOldValue == null; } public void afterRun() { if (successful) super.afterRun(); } @Override public Object getResponse() { return dataOldValue; } public boolean shouldBackup() { return successful; } @Override public String toString() { return "PutIfAbsentOperation{" + name + "}"; } }
1no label
hazelcast_src_main_java_com_hazelcast_map_operation_PutIfAbsentOperation.java
498
private static class MapRewriter implements FieldRewriter<Map<String, Object>> { @Override public Map<String, Object> rewriteValue(Map<String, Object> mapValue) { boolean wasRewritten = false; Map<String, Object> result = new HashMap<String, Object>(); for (Map.Entry<String, Object> entry : mapValue.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); FieldRewriter<Object> fieldRewriter = RewritersFactory.INSTANCE.findRewriter(null, null, value); Object newValue = fieldRewriter.rewriteValue(value); if (newValue != null) { result.put(key, newValue); wasRewritten = true; } else result.put(key, value); } if (wasRewritten) return result; return null; } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseImport.java
637
public class ONullOutputListener implements OProgressListener { public final static ONullOutputListener INSTANCE = new ONullOutputListener(); @Override public void onBegin(Object iTask, long iTotal) { } @Override public boolean onProgress(Object iTask, long iCounter, float iPercent) { return true; } @Override public void onCompletition(Object iTask, boolean iSucceed) { } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_ONullOutputListener.java
502
public class CreateIndexClusterStateUpdateRequest extends ClusterStateUpdateRequest<CreateIndexClusterStateUpdateRequest> { final String cause; final String index; private IndexMetaData.State state = IndexMetaData.State.OPEN; private Settings settings = ImmutableSettings.Builder.EMPTY_SETTINGS; private Map<String, String> mappings = Maps.newHashMap(); private Map<String, IndexMetaData.Custom> customs = newHashMap(); private Set<ClusterBlock> blocks = Sets.newHashSet(); CreateIndexClusterStateUpdateRequest(String cause, String index) { this.cause = cause; this.index = index; } public CreateIndexClusterStateUpdateRequest settings(Settings settings) { this.settings = settings; return this; } public CreateIndexClusterStateUpdateRequest mappings(Map<String, String> mappings) { this.mappings.putAll(mappings); return this; } public CreateIndexClusterStateUpdateRequest customs(Map<String, IndexMetaData.Custom> customs) { this.customs.putAll(customs); return this; } public CreateIndexClusterStateUpdateRequest blocks(Set<ClusterBlock> blocks) { this.blocks.addAll(blocks); return this; } public CreateIndexClusterStateUpdateRequest state(IndexMetaData.State state) { this.state = state; return this; } public String cause() { return cause; } public String index() { return index; } public IndexMetaData.State state() { return state; } public Settings settings() { return settings; } public Map<String, String> mappings() { return mappings; } public Map<String, IndexMetaData.Custom> customs() { return customs; } public Set<ClusterBlock> blocks() { return blocks; } }
0true
src_main_java_org_elasticsearch_action_admin_indices_create_CreateIndexClusterStateUpdateRequest.java
2,549
public class BlockingClusterStatePublishResponseHandler implements ClusterStatePublishResponseHandler { private final CountDownLatch latch; /** * Creates a new BlockingClusterStatePublishResponseHandler * @param nonMasterNodes number of nodes that are supposed to reply to a cluster state publish from master */ public BlockingClusterStatePublishResponseHandler(int nonMasterNodes) { //Don't count the master, as it's the one that does the publish //the master won't call onResponse either this.latch = new CountDownLatch(nonMasterNodes); } @Override public void onResponse(DiscoveryNode node) { latch.countDown(); } @Override public void onFailure(DiscoveryNode node, Throwable t) { latch.countDown(); } @Override public boolean awaitAllNodes(TimeValue timeout) throws InterruptedException { return latch.await(timeout.millis(), TimeUnit.MILLISECONDS); } }
0true
src_main_java_org_elasticsearch_discovery_BlockingClusterStatePublishResponseHandler.java
476
@Deprecated public interface MergeCartProcessor { /** * Convenience method. This will wrap the given <b>request</b> and <b>response</b> inside of a {@link ServletWebRequest} * and forward to {@link #execute(WebRequest, Authentication)} * * @param request * @param response * @param authResult */ public void execute(HttpServletRequest request, HttpServletResponse response, Authentication authResult); /** * Merge the cart owned by the anonymous current session {@link Customer} with the {@link Customer} that has just * logged in * * @param request * @param authResult */ public void execute(WebRequest request, Authentication authResult); }
0true
common_src_main_java_org_broadleafcommerce_common_security_MergeCartProcessor.java
902
public class PromotableOrderItemPriceDetailAdjustmentImpl extends AbstractPromotionRounding implements PromotableOrderItemPriceDetailAdjustment, OfferHolder { private static final long serialVersionUID = 1L; protected PromotableCandidateItemOffer promotableCandidateItemOffer; protected PromotableOrderItemPriceDetail promotableOrderItemPriceDetail; protected Money saleAdjustmentValue; protected Money retailAdjustmentValue; protected Money adjustmentValue; protected boolean appliedToSalePrice; protected Offer offer; public PromotableOrderItemPriceDetailAdjustmentImpl(PromotableCandidateItemOffer promotableCandidateItemOffer, PromotableOrderItemPriceDetail orderItemPriceDetail) { assert (promotableCandidateItemOffer != null); assert (orderItemPriceDetail != null); this.promotableCandidateItemOffer = promotableCandidateItemOffer; this.promotableOrderItemPriceDetail = orderItemPriceDetail; this.offer = promotableCandidateItemOffer.getOffer(); computeAdjustmentValues(); } public PromotableOrderItemPriceDetailAdjustmentImpl(OrderItemPriceDetailAdjustment itemAdjustment, PromotableOrderItemPriceDetail orderItemPriceDetail) { assert (orderItemPriceDetail != null); adjustmentValue = itemAdjustment.getValue(); if (itemAdjustment.isAppliedToSalePrice()) { saleAdjustmentValue = itemAdjustment.getValue(); // This will just set to a Money value of zero in the correct currency. retailAdjustmentValue = itemAdjustment.getRetailPriceValue(); } else { retailAdjustmentValue = itemAdjustment.getValue(); // This will just set to a Money value of zero in the correct currency. saleAdjustmentValue = itemAdjustment.getSalesPriceValue(); } appliedToSalePrice = itemAdjustment.isAppliedToSalePrice(); promotableOrderItemPriceDetail = orderItemPriceDetail; offer = itemAdjustment.getOffer(); } /* * Calculates the value of the adjustment for both retail and sale prices. * If either adjustment is greater than the item value, it will be set to the * currentItemValue (e.g. no adjustment can cause a negative value). */ protected void computeAdjustmentValues() { saleAdjustmentValue = new Money(getCurrency()); retailAdjustmentValue = new Money(getCurrency()); Money currentPriceDetailRetailValue = promotableOrderItemPriceDetail.calculateItemUnitPriceWithAdjustments(false); Money currentPriceDetailSalesValue = promotableOrderItemPriceDetail.calculateItemUnitPriceWithAdjustments(true); if (currentPriceDetailSalesValue == null) { currentPriceDetailSalesValue = currentPriceDetailRetailValue; } BigDecimal offerUnitValue = PromotableOfferUtility.determineOfferUnitValue(offer, promotableCandidateItemOffer); retailAdjustmentValue = PromotableOfferUtility.computeAdjustmentValue(currentPriceDetailRetailValue, offerUnitValue, this, this); if (offer.getApplyDiscountToSalePrice() == true) { saleAdjustmentValue = PromotableOfferUtility.computeAdjustmentValue(currentPriceDetailSalesValue, offerUnitValue, this, this); } } @Override public Money getRetailAdjustmentValue() { return retailAdjustmentValue; } @Override public Money getSaleAdjustmentValue() { return saleAdjustmentValue; } @Override public BroadleafCurrency getCurrency() { return promotableOrderItemPriceDetail.getPromotableOrderItem().getCurrency(); } @Override public PromotableOrderItemPriceDetail getPromotableOrderItemPriceDetail() { return promotableOrderItemPriceDetail; } @Override public Offer getOffer() { return offer; } @Override public boolean isCombinable() { Boolean combinable = offer.isCombinableWithOtherOffers(); return (combinable != null && combinable); } @Override public boolean isTotalitarian() { Boolean totalitarian = offer.isTotalitarianOffer(); return (totalitarian != null && totalitarian.booleanValue()); } @Override public Long getOfferId() { return offer.getId(); } @Override public Money getAdjustmentValue() { return adjustmentValue; } @Override public boolean isAppliedToSalePrice() { return appliedToSalePrice; } @Override public void finalizeAdjustment(boolean useSalePrice) { appliedToSalePrice = useSalePrice; if (useSalePrice) { adjustmentValue = saleAdjustmentValue; } else { adjustmentValue = retailAdjustmentValue; } } @Override public PromotableOrderItemPriceDetailAdjustment copy() { PromotableOrderItemPriceDetailAdjustmentImpl newAdjustment = new PromotableOrderItemPriceDetailAdjustmentImpl( promotableCandidateItemOffer, promotableOrderItemPriceDetail); newAdjustment.adjustmentValue = adjustmentValue; newAdjustment.saleAdjustmentValue = saleAdjustmentValue; newAdjustment.retailAdjustmentValue = retailAdjustmentValue; newAdjustment.appliedToSalePrice = appliedToSalePrice; return newAdjustment; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_domain_PromotableOrderItemPriceDetailAdjustmentImpl.java
424
private class ClientJob<KeyIn, ValueIn> extends AbstractJob<KeyIn, ValueIn> { public ClientJob(String name, KeyValueSource<KeyIn, ValueIn> keyValueSource) { super(name, ClientMapReduceProxy.this, keyValueSource); } @Override protected <T> JobCompletableFuture<T> invoke(final Collator collator) { try { final String jobId = UuidUtil.buildRandomUuidString(); ClientContext context = getContext(); ClientInvocationService cis = context.getInvocationService(); ClientMapReduceRequest request = new ClientMapReduceRequest(name, jobId, keys, predicate, mapper, combinerFactory, reducerFactory, keyValueSource, chunkSize, topologyChangedStrategy); final ClientCompletableFuture completableFuture = new ClientCompletableFuture(jobId); ClientCallFuture future = (ClientCallFuture) cis.invokeOnRandomTarget(request, null); future.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { try { if (collator != null) { response = collator.collate(((Map) response).entrySet()); } } finally { completableFuture.setResult(response); trackableJobs.remove(jobId); } } @Override public void onFailure(Throwable t) { try { if (t instanceof ExecutionException && t.getCause() instanceof CancellationException) { t = t.getCause(); } completableFuture.setResult(t); } finally { trackableJobs.remove(jobId); } } }); Address runningMember = future.getConnection().getRemoteEndpoint(); trackableJobs.putIfAbsent(jobId, new ClientTrackableJob<T>(jobId, runningMember, completableFuture)); return completableFuture; } catch (Exception e) { throw new RuntimeException(e); } } }
0true
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientMapReduceProxy.java
3,371
final class OperationThread extends Thread { private final int threadId; private final boolean isPartitionSpecific; private final BlockingQueue workQueue; private final Queue priorityWorkQueue; public OperationThread(String name, boolean isPartitionSpecific, int threadId, BlockingQueue workQueue, Queue priorityWorkQueue) { super(node.threadGroup, name); setContextClassLoader(node.getConfigClassLoader()); this.isPartitionSpecific = isPartitionSpecific; this.workQueue = workQueue; this.priorityWorkQueue = priorityWorkQueue; this.threadId = threadId; } @Override public void run() { try { doRun(); } catch (OutOfMemoryError e) { onOutOfMemory(e); } catch (Throwable t) { logger.severe(t); } } private void doRun() { for (; ; ) { Object task; try { task = workQueue.take(); } catch (InterruptedException e) { if (shutdown) { return; } continue; } if (shutdown) { return; } processPriorityMessages(); process(task); } } private void process(Object task) { try { processor.process(task); } catch (Exception e) { logger.severe("Failed to process task: " + task + " on partitionThread:" + getName()); } } private void processPriorityMessages() { for (; ; ) { Object task = priorityWorkQueue.poll(); if (task == null) { return; } process(task); } } public void awaitTermination(int timeout, TimeUnit unit) throws InterruptedException { join(unit.toMillis(timeout)); } }
1no label
hazelcast_src_main_java_com_hazelcast_spi_impl_BasicOperationScheduler.java
2,144
public class SegmentReaderUtils { private static final Field FILTER_ATOMIC_READER_IN; static { Field in = null; try { // and another one bites the dust... in = FilterAtomicReader.class.getDeclaredField("in"); in.setAccessible(true); } catch (NoSuchFieldException e) { assert false : "Failed to get field: " + e.getMessage(); } FILTER_ATOMIC_READER_IN = in; } /** * Tries to extract a segment reader from the given index reader. * If no SegmentReader can be extracted an {@link org.elasticsearch.ElasticsearchIllegalStateException} is thrown. */ @Nullable public static SegmentReader segmentReader(AtomicReader reader) { return internalSegmentReader(reader, true); } /** * Tries to extract a segment reader from the given index reader and returns it, otherwise <code>null</code> * is returned */ @Nullable public static SegmentReader segmentReaderOrNull(AtomicReader reader) { return internalSegmentReader(reader, false); } public static boolean registerCoreListener(AtomicReader reader, SegmentReader.CoreClosedListener listener) { SegmentReader segReader = SegmentReaderUtils.segmentReaderOrNull(reader); if (segReader != null) { segReader.addCoreClosedListener(listener); return true; } return false; } private static SegmentReader internalSegmentReader(AtomicReader reader, boolean fail) { if (reader == null) { return null; } if (reader instanceof SegmentReader) { return (SegmentReader) reader; } else if (reader instanceof FilterAtomicReader) { final FilterAtomicReader fReader = (FilterAtomicReader) reader; try { return FILTER_ATOMIC_READER_IN == null ? null : segmentReader((AtomicReader) FILTER_ATOMIC_READER_IN.get(fReader)); } catch (IllegalAccessException e) { } } if (fail) { // hard fail - we can't get a SegmentReader throw new ElasticsearchIllegalStateException("Can not extract segment reader from given index reader [" + reader + "]"); } return null; } }
0true
src_main_java_org_elasticsearch_common_lucene_SegmentReaderUtils.java
1,026
return new Iterator<Node>() { private int index = 0; private Node next; private boolean findNext() { next = null; for (; index < maximum; index++) { final Node item = parent.item(index); if (nodeType == 0 || item.getNodeType() == nodeType) { next = item; return true; } } return false; } public boolean hasNext() { return findNext(); } public Node next() { if (findNext()) { index++; return next; } throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } };
0true
hazelcast_src_main_java_com_hazelcast_config_AbstractXmlConfigHelper.java
2,791
public class IndexAliasesServiceModule extends AbstractModule { @Override protected void configure() { bind(IndexAliasesService.class).asEagerSingleton(); } }
0true
src_main_java_org_elasticsearch_index_aliases_IndexAliasesServiceModule.java
1,460
public class OCommandExecutorSQLDeleteVertex extends OCommandExecutorSQLAbstract implements OCommandResultListener { public static final String NAME = "DELETE VERTEX"; private ORecordId rid; private int removed = 0; private ODatabaseRecord database; private OCommandRequest query; @SuppressWarnings("unchecked") public OCommandExecutorSQLDeleteVertex parse(final OCommandRequest iRequest) { database = getDatabase(); init((OCommandRequestText) iRequest); parserRequiredKeyword("DELETE"); parserRequiredKeyword("VERTEX"); OClass clazz = null; String temp = parseOptionalWord(true); while (temp != null) { if (temp.startsWith("#")) { rid = new ORecordId(temp); } else if (temp.equals(KEYWORD_WHERE)) { if (clazz == null) // ASSIGN DEFAULT CLASS clazz = database.getMetadata().getSchema().getClass(OrientVertex.CLASS_NAME); final String condition = parserGetCurrentPosition() > -1 ? " " + parserText.substring(parserGetPreviousPosition()) : ""; query = database.command(new OSQLAsynchQuery<ODocument>("select from " + clazz.getName() + condition, this)); break; } else if (temp.length() > 0) { // GET/CHECK CLASS NAME clazz = database.getMetadata().getSchema().getClass(temp); if (clazz == null) throw new OCommandSQLParsingException("Class '" + temp + " was not found"); } if (rid == null && clazz == null) // DELETE ALL VERTEXES query = database.command(new OSQLAsynchQuery<ODocument>("select from V", this)); temp = parseOptionalWord(true); if (parserIsEnded()) break; } return this; } /** * Execute the command and return the ODocument object created. */ public Object execute(final Map<Object, Object> iArgs) { if (rid == null && query == null) throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet"); final OrientBaseGraph graph = OGraphCommandExecutorSQLFactory.getGraph(); if (rid != null) { // REMOVE PUNCTUAL RID final OrientVertex v = graph.getVertex(rid); if (v != null) { v.remove(); removed = 1; } } else if (query != null) // TARGET IS A CLASS + OPTIONAL CONDITION query.execute(iArgs); else throw new OCommandExecutionException("Invalid target"); return removed; } /** * Delete the current vertex. */ public boolean result(final Object iRecord) { final OIdentifiable id = (OIdentifiable) iRecord; if (id.getIdentity().isValid()) { final OrientBaseGraph graph = OGraphCommandExecutorSQLFactory.getGraph(); final OrientVertex v = graph.getVertex(id); if (v != null) { v.remove(); removed++; return true; } } return false; } @Override public String getSyntax() { return "DELETE VERTEX <rid>|<[<class>] [WHERE <conditions>] [LIMIT <max-records>]>"; } @Override public void end() { } }
1no label
graphdb_src_main_java_com_orientechnologies_orient_graph_sql_OCommandExecutorSQLDeleteVertex.java
764
public interface ExtensionHandler { /** * Determines the priority of this extension handler. * @return */ public int getPriority(); /** * If false, the ExtensionManager should skip this Handler. * @return */ public boolean isEnabled(); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_extension_ExtensionHandler.java
163
public class TestStandaloneLogExtractor { @Test public void testRecreateCleanDbFromStandaloneExtractor() throws Exception { run( true, 1 ); } @Test public void testRecreateUncleanDbFromStandaloneExtractor() throws Exception { run( false, 2 ); } private void run( boolean cleanShutdown, int nr ) throws Exception { EphemeralFileSystemAbstraction fileSystem = new EphemeralFileSystemAbstraction(); String storeDir = "source" + nr; GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory(). setFileSystem( fileSystem ). newImpermanentDatabase( storeDir ); createSomeTransactions( db ); DbRepresentation rep = DbRepresentation.of( db ); EphemeralFileSystemAbstraction snapshot; if ( cleanShutdown ) { db.shutdown(); snapshot = fileSystem.snapshot(); } else { snapshot = fileSystem.snapshot(); db.shutdown(); } GraphDatabaseAPI newDb = (GraphDatabaseAPI) new TestGraphDatabaseFactory(). setFileSystem( snapshot ). newImpermanentDatabase( storeDir ); XaDataSource ds = newDb.getDependencyResolver().resolveDependency( XaDataSourceManager.class ) .getNeoStoreDataSource(); LogExtractor extractor = LogExtractor.from( snapshot, new File( storeDir ), new Monitors().newMonitor( ByteCounterMonitor.class ) ); long expectedTxId = 2; while ( true ) { InMemoryLogBuffer buffer = new InMemoryLogBuffer(); long txId = extractor.extractNext( buffer ); assertEquals( expectedTxId++, txId ); /* first tx=2 * 1 tx for relationship type * 1 tx for property index * 1 for the first tx * 5 additional tx + 1 tx for the other property index * ==> 11 */ if ( expectedTxId == 11 ) { expectedTxId = -1; } if ( txId == -1 ) { break; } ds.applyCommittedTransaction( txId, buffer ); } DbRepresentation newRep = DbRepresentation.of( newDb ); newDb.shutdown(); assertEquals( rep, newRep ); fileSystem.shutdown(); } private void createSomeTransactions( GraphDatabaseAPI db ) throws IOException { try ( BatchTransaction tx = beginBatchTx( db ) ) { Node node = db.createNode(); node.setProperty( "name", "First" ); Node otherNode = db.createNode(); node.createRelationshipTo( otherNode, MyRelTypes.TEST ); tx.intermediaryCommit(); db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ) .getNeoStoreDataSource().rotateLogicalLog(); for ( int i = 0; i < 5; i++ ) { db.createNode().setProperty( "type", i ); tx.intermediaryCommit(); } } } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestStandaloneLogExtractor.java
5,973
public class AnalyzingCompletionLookupProvider extends CompletionLookupProvider { // for serialization public static final int SERIALIZE_PRESERVE_SEPERATORS = 1; public static final int SERIALIZE_HAS_PAYLOADS = 2; public static final int SERIALIZE_PRESERVE_POSITION_INCREMENTS = 4; private static final int MAX_SURFACE_FORMS_PER_ANALYZED_FORM = 256; private static final int MAX_GRAPH_EXPANSIONS = -1; public static final String CODEC_NAME = "analyzing"; public static final int CODEC_VERSION_START = 1; public static final int CODEC_VERSION_LATEST = 2; private boolean preserveSep; private boolean preservePositionIncrements; private int maxSurfaceFormsPerAnalyzedForm; private int maxGraphExpansions; private boolean hasPayloads; private final XAnalyzingSuggester prototype; public AnalyzingCompletionLookupProvider(boolean preserveSep, boolean exactFirst, boolean preservePositionIncrements, boolean hasPayloads) { this.preserveSep = preserveSep; this.preservePositionIncrements = preservePositionIncrements; this.hasPayloads = hasPayloads; this.maxSurfaceFormsPerAnalyzedForm = MAX_SURFACE_FORMS_PER_ANALYZED_FORM; this.maxGraphExpansions = MAX_GRAPH_EXPANSIONS; int options = preserveSep ? XAnalyzingSuggester.PRESERVE_SEP : 0; // needs to fixed in the suggester first before it can be supported //options |= exactFirst ? XAnalyzingSuggester.EXACT_FIRST : 0; prototype = new XAnalyzingSuggester(null, null, options, maxSurfaceFormsPerAnalyzedForm, maxGraphExpansions, preservePositionIncrements, null, false, 1, XAnalyzingSuggester.SEP_LABEL, XAnalyzingSuggester.PAYLOAD_SEP, XAnalyzingSuggester.END_BYTE, XAnalyzingSuggester.HOLE_CHARACTER); } @Override public String getName() { return "analyzing"; } @Override public FieldsConsumer consumer(final IndexOutput output) throws IOException { CodecUtil.writeHeader(output, CODEC_NAME, CODEC_VERSION_LATEST); return new FieldsConsumer() { private Map<FieldInfo, Long> fieldOffsets = new HashMap<FieldInfo, Long>(); @Override public void close() throws IOException { try { /* * write the offsets per field such that we know where * we need to load the FSTs from */ long pointer = output.getFilePointer(); output.writeVInt(fieldOffsets.size()); for (Map.Entry<FieldInfo, Long> entry : fieldOffsets.entrySet()) { output.writeString(entry.getKey().name); output.writeVLong(entry.getValue()); } output.writeLong(pointer); output.flush(); } finally { IOUtils.close(output); } } @Override public TermsConsumer addField(final FieldInfo field) throws IOException { return new TermsConsumer() { final XAnalyzingSuggester.XBuilder builder = new XAnalyzingSuggester.XBuilder(maxSurfaceFormsPerAnalyzedForm, hasPayloads, XAnalyzingSuggester.PAYLOAD_SEP); final CompletionPostingsConsumer postingsConsumer = new CompletionPostingsConsumer(AnalyzingCompletionLookupProvider.this, builder); @Override public PostingsConsumer startTerm(BytesRef text) throws IOException { builder.startTerm(text); return postingsConsumer; } @Override public Comparator<BytesRef> getComparator() throws IOException { return BytesRef.getUTF8SortedAsUnicodeComparator(); } @Override public void finishTerm(BytesRef text, TermStats stats) throws IOException { builder.finishTerm(stats.docFreq); // use doc freq as a fallback } @Override public void finish(long sumTotalTermFreq, long sumDocFreq, int docCount) throws IOException { /* * Here we are done processing the field and we can * buid the FST and write it to disk. */ FST<Pair<Long, BytesRef>> build = builder.build(); assert build != null || docCount == 0 : "the FST is null but docCount is != 0 actual value: [" + docCount + "]"; /* * it's possible that the FST is null if we have 2 segments that get merged * and all docs that have a value in this field are deleted. This will cause * a consumer to be created but it doesn't consume any values causing the FSTBuilder * to return null. */ if (build != null) { fieldOffsets.put(field, output.getFilePointer()); build.save(output); /* write some more meta-info */ output.writeVInt(postingsConsumer.getMaxAnalyzedPathsForOneInput()); output.writeVInt(maxSurfaceFormsPerAnalyzedForm); output.writeInt(maxGraphExpansions); // can be negative int options = 0; options |= preserveSep ? SERIALIZE_PRESERVE_SEPERATORS : 0; options |= hasPayloads ? SERIALIZE_HAS_PAYLOADS : 0; options |= preservePositionIncrements ? SERIALIZE_PRESERVE_POSITION_INCREMENTS : 0; output.writeVInt(options); output.writeVInt(XAnalyzingSuggester.SEP_LABEL); output.writeVInt(XAnalyzingSuggester.END_BYTE); output.writeVInt(XAnalyzingSuggester.PAYLOAD_SEP); output.writeVInt(XAnalyzingSuggester.HOLE_CHARACTER); } } }; } }; } private static final class CompletionPostingsConsumer extends PostingsConsumer { private final SuggestPayload spare = new SuggestPayload(); private AnalyzingCompletionLookupProvider analyzingSuggestLookupProvider; private XAnalyzingSuggester.XBuilder builder; private int maxAnalyzedPathsForOneInput = 0; public CompletionPostingsConsumer(AnalyzingCompletionLookupProvider analyzingSuggestLookupProvider, XAnalyzingSuggester.XBuilder builder) { this.analyzingSuggestLookupProvider = analyzingSuggestLookupProvider; this.builder = builder; } @Override public void startDoc(int docID, int freq) throws IOException { } @Override public void addPosition(int position, BytesRef payload, int startOffset, int endOffset) throws IOException { analyzingSuggestLookupProvider.parsePayload(payload, spare); builder.addSurface(spare.surfaceForm, spare.payload, spare.weight); // multi fields have the same surface form so we sum up here maxAnalyzedPathsForOneInput = Math.max(maxAnalyzedPathsForOneInput, position + 1); } @Override public void finishDoc() throws IOException { } public int getMaxAnalyzedPathsForOneInput() { return maxAnalyzedPathsForOneInput; } } ; @Override public LookupFactory load(IndexInput input) throws IOException { long sizeInBytes = 0; int version = CodecUtil.checkHeader(input, CODEC_NAME, CODEC_VERSION_START, CODEC_VERSION_LATEST); final Map<String, AnalyzingSuggestHolder> lookupMap = new HashMap<String, AnalyzingSuggestHolder>(); input.seek(input.length() - 8); long metaPointer = input.readLong(); input.seek(metaPointer); int numFields = input.readVInt(); Map<Long, String> meta = new TreeMap<Long, String>(); for (int i = 0; i < numFields; i++) { String name = input.readString(); long offset = input.readVLong(); meta.put(offset, name); } for (Map.Entry<Long, String> entry : meta.entrySet()) { input.seek(entry.getKey()); FST<Pair<Long, BytesRef>> fst = new FST<Pair<Long, BytesRef>>(input, new PairOutputs<Long, BytesRef>( PositiveIntOutputs.getSingleton(), ByteSequenceOutputs.getSingleton())); int maxAnalyzedPathsForOneInput = input.readVInt(); int maxSurfaceFormsPerAnalyzedForm = input.readVInt(); int maxGraphExpansions = input.readInt(); int options = input.readVInt(); boolean preserveSep = (options & SERIALIZE_PRESERVE_SEPERATORS) != 0; boolean hasPayloads = (options & SERIALIZE_HAS_PAYLOADS) != 0; boolean preservePositionIncrements = (options & SERIALIZE_PRESERVE_POSITION_INCREMENTS) != 0; // first version did not include these three fields, so fall back to old default (before the analyzingsuggester // was updated in Lucene, so we cannot use the suggester defaults) int sepLabel, payloadSep, endByte, holeCharacter; switch (version) { case CODEC_VERSION_START: sepLabel = 0xFF; payloadSep = '\u001f'; endByte = 0x0; holeCharacter = '\u001E'; break; default: sepLabel = input.readVInt(); endByte = input.readVInt(); payloadSep = input.readVInt(); holeCharacter = input.readVInt(); } AnalyzingSuggestHolder holder = new AnalyzingSuggestHolder(preserveSep, preservePositionIncrements, maxSurfaceFormsPerAnalyzedForm, maxGraphExpansions, hasPayloads, maxAnalyzedPathsForOneInput, fst, sepLabel, payloadSep, endByte, holeCharacter); sizeInBytes += fst.sizeInBytes(); lookupMap.put(entry.getValue(), holder); } final long ramBytesUsed = sizeInBytes; return new LookupFactory() { @Override public Lookup getLookup(FieldMapper<?> mapper, CompletionSuggestionContext suggestionContext) { AnalyzingSuggestHolder analyzingSuggestHolder = lookupMap.get(mapper.names().indexName()); if (analyzingSuggestHolder == null) { return null; } int flags = analyzingSuggestHolder.preserveSep ? XAnalyzingSuggester.PRESERVE_SEP : 0; XAnalyzingSuggester suggester; if (suggestionContext.isFuzzy()) { suggester = new XFuzzySuggester(mapper.indexAnalyzer(), mapper.searchAnalyzer(), flags, analyzingSuggestHolder.maxSurfaceFormsPerAnalyzedForm, analyzingSuggestHolder.maxGraphExpansions, suggestionContext.getFuzzyEditDistance(), suggestionContext.isFuzzyTranspositions(), suggestionContext.getFuzzyPrefixLength(), suggestionContext.getFuzzyMinLength(), suggestionContext.isFuzzyUnicodeAware(), analyzingSuggestHolder.fst, analyzingSuggestHolder.hasPayloads, analyzingSuggestHolder.maxAnalyzedPathsForOneInput, analyzingSuggestHolder.sepLabel, analyzingSuggestHolder.payloadSep, analyzingSuggestHolder.endByte, analyzingSuggestHolder.holeCharacter); } else { suggester = new XAnalyzingSuggester(mapper.indexAnalyzer(), mapper.searchAnalyzer(), flags, analyzingSuggestHolder.maxSurfaceFormsPerAnalyzedForm, analyzingSuggestHolder.maxGraphExpansions, analyzingSuggestHolder.preservePositionIncrements, analyzingSuggestHolder.fst, analyzingSuggestHolder.hasPayloads, analyzingSuggestHolder.maxAnalyzedPathsForOneInput, analyzingSuggestHolder.sepLabel, analyzingSuggestHolder.payloadSep, analyzingSuggestHolder.endByte, analyzingSuggestHolder.holeCharacter); } return suggester; } @Override public CompletionStats stats(String... fields) { long sizeInBytes = 0; ObjectLongOpenHashMap<String> completionFields = null; if (fields != null && fields.length > 0) { completionFields = new ObjectLongOpenHashMap<String>(fields.length); } for (Map.Entry<String, AnalyzingSuggestHolder> entry : lookupMap.entrySet()) { sizeInBytes += entry.getValue().fst.sizeInBytes(); if (fields == null || fields.length == 0) { continue; } for (String field : fields) { // support for getting fields by regex as in fielddata if (Regex.simpleMatch(field, entry.getKey())) { long fstSize = entry.getValue().fst.sizeInBytes(); completionFields.addTo(field, fstSize); } } } return new CompletionStats(sizeInBytes, completionFields); } @Override AnalyzingSuggestHolder getAnalyzingSuggestHolder(FieldMapper<?> mapper) { return lookupMap.get(mapper.names().indexName()); } @Override public long ramBytesUsed() { return ramBytesUsed; } }; } static class AnalyzingSuggestHolder { final boolean preserveSep; final boolean preservePositionIncrements; final int maxSurfaceFormsPerAnalyzedForm; final int maxGraphExpansions; final boolean hasPayloads; final int maxAnalyzedPathsForOneInput; final FST<Pair<Long, BytesRef>> fst; final int sepLabel; final int payloadSep; final int endByte; final int holeCharacter; public AnalyzingSuggestHolder(boolean preserveSep, boolean preservePositionIncrements, int maxSurfaceFormsPerAnalyzedForm, int maxGraphExpansions, boolean hasPayloads, int maxAnalyzedPathsForOneInput, FST<Pair<Long, BytesRef>> fst) { this(preserveSep, preservePositionIncrements, maxSurfaceFormsPerAnalyzedForm, maxGraphExpansions, hasPayloads, maxAnalyzedPathsForOneInput, fst, XAnalyzingSuggester.SEP_LABEL, XAnalyzingSuggester.PAYLOAD_SEP, XAnalyzingSuggester.END_BYTE, XAnalyzingSuggester.HOLE_CHARACTER); } public AnalyzingSuggestHolder(boolean preserveSep, boolean preservePositionIncrements, int maxSurfaceFormsPerAnalyzedForm, int maxGraphExpansions, boolean hasPayloads, int maxAnalyzedPathsForOneInput, FST<Pair<Long, BytesRef>> fst, int sepLabel, int payloadSep, int endByte, int holeCharacter) { this.preserveSep = preserveSep; this.preservePositionIncrements = preservePositionIncrements; this.maxSurfaceFormsPerAnalyzedForm = maxSurfaceFormsPerAnalyzedForm; this.maxGraphExpansions = maxGraphExpansions; this.hasPayloads = hasPayloads; this.maxAnalyzedPathsForOneInput = maxAnalyzedPathsForOneInput; this.fst = fst; this.sepLabel = sepLabel; this.payloadSep = payloadSep; this.endByte = endByte; this.holeCharacter = holeCharacter; } } @Override public Set<IntsRef> toFiniteStrings(TokenStream stream) throws IOException { return prototype.toFiniteStrings(prototype.getTokenStreamToAutomaton(), stream); } }
1no label
src_main_java_org_elasticsearch_search_suggest_completion_AnalyzingCompletionLookupProvider.java
119
public class ExtractParameterProposal implements ICompletionProposal { private CeylonEditor editor; public ExtractParameterProposal(CeylonEditor editor) { this.editor = editor; } @Override public Point getSelection(IDocument doc) { return null; } @Override public Image getImage() { return CHANGE; } @Override public String getDisplayString() { return "Extract parameter"; } @Override public IContextInformation getContextInformation() { return null; } @Override public String getAdditionalProposalInfo() { return null; } @Override public void apply(IDocument doc) { if (useLinkedMode()) { new ExtractParameterLinkedMode(editor).start(); } else { new ExtractParameterRefactoringAction(editor).run(); } } public static void add(Collection<ICompletionProposal> proposals, CeylonEditor editor, Node node) { if (node instanceof Tree.BaseMemberExpression) { Tree.Identifier id = ((Tree.BaseMemberExpression) node).getIdentifier(); if (id==null || id.getToken().getType()==CeylonLexer.AIDENTIFIER) { return; } } ExtractParameterRefactoring epr = new ExtractParameterRefactoring(editor); if (epr.isEnabled()) { proposals.add(new ExtractParameterProposal(editor)); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ExtractParameterProposal.java
527
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class ClientTxnMultiMapTest { private static final String multiMapBackedByList = "BackedByList*"; static HazelcastInstance client; static HazelcastInstance server; @BeforeClass public static void init() { Config config = new Config(); MultiMapConfig multiMapConfig = config.getMultiMapConfig(multiMapBackedByList); multiMapConfig.setValueCollectionType(MultiMapConfig.ValueCollectionType.LIST); server = Hazelcast.newHazelcastInstance(config); client = HazelcastClient.newHazelcastClient(); } @AfterClass public static void destroy() { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } @Test public void testRemove() throws Exception { final String mapName = randomString(); final String key = "key"; final String val = "value"; MultiMap multiMap = client.getMultiMap(mapName); multiMap.put(key, val); TransactionContext tx = client.newTransactionContext(); tx.beginTransaction(); TransactionalMultiMap txnMultiMap = tx.getMultiMap(mapName); txnMultiMap.remove(key, val); tx.commitTransaction(); assertEquals(Collections.EMPTY_LIST, client.getMultiMap(mapName).get(key)); } @Test public void testRemoveAll() throws Exception { final String mapName = randomString(); final String key = "key"; MultiMap multiMap = client.getMultiMap(mapName); for (int i = 0; i < 10; i++) { multiMap.put(key, i); } TransactionContext tx = client.newTransactionContext(); tx.beginTransaction(); TransactionalMultiMap txnMultiMap = tx.getMultiMap(mapName); txnMultiMap.remove(key); tx.commitTransaction(); assertEquals(Collections.EMPTY_LIST, multiMap.get(key)); } @Test public void testConcrruentTxnPut() throws Exception { final String mapName = randomString(); final MultiMap multiMap = client.getMultiMap(mapName); final int threads = 10; final ExecutorService ex = Executors.newFixedThreadPool(threads); final CountDownLatch latch = new CountDownLatch(threads); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(null); for (int i = 0; i < threads; i++) { final int key = i; ex.execute(new Runnable() { public void run() { multiMap.put(key, "value"); final TransactionContext context = client.newTransactionContext(); try { context.beginTransaction(); final TransactionalMultiMap txnMultiMap = context.getMultiMap(mapName); txnMultiMap.put(key, "value"); txnMultiMap.put(key, "value1"); txnMultiMap.put(key, "value2"); assertEquals(3, txnMultiMap.get(key).size()); context.commitTransaction(); assertEquals(3, multiMap.get(key).size()); } catch (Exception e) { error.compareAndSet(null, e); } finally { latch.countDown(); } } }); } try { latch.await(1, TimeUnit.MINUTES); assertNull(error.get()); } finally { ex.shutdownNow(); } } @Test public void testPutAndRoleBack() throws Exception { final String mapName = randomString(); final String key = "key"; final String value = "value"; final MultiMap multiMap = client.getMultiMap(mapName); TransactionContext tx = client.newTransactionContext(); tx.beginTransaction(); TransactionalMultiMap mulitMapTxn = tx.getMultiMap(mapName); mulitMapTxn.put(key, value); mulitMapTxn.put(key, value); tx.rollbackTransaction(); assertEquals(Collections.EMPTY_LIST, multiMap.get(key)); } @Test public void testSize() throws Exception { final String mapName = randomString(); final String key = "key"; final String value = "value"; final MultiMap multiMap = client.getMultiMap(mapName); multiMap.put(key, value); TransactionContext tx = client.newTransactionContext(); tx.beginTransaction(); TransactionalMultiMap mulitMapTxn = tx.getMultiMap(mapName); mulitMapTxn.put(key, "newValue"); mulitMapTxn.put("newKey", value); assertEquals(3, mulitMapTxn.size()); tx.commitTransaction(); } @Test public void testCount() throws Exception { final String mapName = randomString(); final String key = "key"; final String value = "value"; final MultiMap multiMap = client.getMultiMap(mapName); multiMap.put(key, value); TransactionContext tx = client.newTransactionContext(); tx.beginTransaction(); TransactionalMultiMap mulitMapTxn = tx.getMultiMap(mapName); mulitMapTxn.put(key, "newValue"); assertEquals(2, mulitMapTxn.valueCount(key)); tx.commitTransaction(); } @Test public void testGet_whenBackedWithList() throws Exception { final String mapName = multiMapBackedByList+randomString(); final String key = "key"; final String value = "value"; final MultiMap multiMap = server.getMultiMap(mapName); multiMap.put(key, value); TransactionContext tx = client.newTransactionContext(); tx.beginTransaction(); TransactionalMultiMap mulitMapTxn = tx.getMultiMap(mapName); Collection c = mulitMapTxn.get(key); assertFalse(c.isEmpty()); tx.commitTransaction(); } @Test public void testRemove_whenBackedWithList() throws Exception { final String mapName = multiMapBackedByList+randomString(); final String key = "key"; final String value = "value"; final MultiMap multiMap = server.getMultiMap(mapName); multiMap.put(key, value); TransactionContext tx = client.newTransactionContext(); tx.beginTransaction(); TransactionalMultiMap mulitMapTxn = tx.getMultiMap(mapName); Collection c = mulitMapTxn.remove(key); assertFalse(c.isEmpty()); tx.commitTransaction(); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_txn_ClientTxnMultiMapTest.java
1,797
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class ListenerTest extends HazelcastTestSupport { private final String name = "fooMap"; private final AtomicInteger globalCount = new AtomicInteger(); private final AtomicInteger localCount = new AtomicInteger(); private final AtomicInteger valueCount = new AtomicInteger(); @Before public void before() { globalCount.set(0); localCount.set(0); valueCount.set(0); } @Test public void testConfigListenerRegistration() throws InterruptedException { Config config = new Config(); final String name = "default"; final CountDownLatch latch = new CountDownLatch(1); config.getMapConfig(name).addEntryListenerConfig(new EntryListenerConfig().setImplementation(new EntryAdapter() { public void entryAdded(EntryEvent event) { latch.countDown(); } })); final HazelcastInstance hz = createHazelcastInstance(config); hz.getMap(name).put(1, 1); assertTrue(latch.await(10, TimeUnit.SECONDS)); } @Test public void globalListenerTest() throws InterruptedException { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2); Config cfg = new Config(); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(cfg); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(cfg); IMap<String, String> map1 = h1.getMap(name); IMap<String, String> map2 = h2.getMap(name); map1.addEntryListener(createEntryListener(false), false); map1.addEntryListener(createEntryListener(false), true); map2.addEntryListener(createEntryListener(false), true); int k = 3; putDummyData(map1, k); checkCountWithExpected(k * 3, 0, k * 2); } @Test public void globalListenerRemoveTest() throws InterruptedException { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2); Config cfg = new Config(); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(cfg); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(cfg); IMap<String, String> map1 = h1.getMap(name); IMap<String, String> map2 = h2.getMap(name); String id1 = map1.addEntryListener(createEntryListener(false), false); String id2 = map1.addEntryListener(createEntryListener(false), true); String id3 = map2.addEntryListener(createEntryListener(false), true); int k = 3; map1.removeEntryListener(id1); map1.removeEntryListener(id2); map1.removeEntryListener(id3); putDummyData(map2, k); checkCountWithExpected(0, 0, 0); } @Test public void localListenerTest() throws InterruptedException { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2); Config cfg = new Config(); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(cfg); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(cfg); IMap<String, String> map1 = h1.getMap(name); IMap<String, String> map2 = h2.getMap(name); map1.addLocalEntryListener(createEntryListener(true)); map2.addLocalEntryListener(createEntryListener(true)); int k = 4; putDummyData(map1, k); checkCountWithExpected(0, k, k); } @Test /** * Test for issue 584 and 756 */ public void globalAndLocalListenerTest() throws InterruptedException { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2); Config cfg = new Config(); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(cfg); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(cfg); IMap<String, String> map1 = h1.getMap(name); IMap<String, String> map2 = h2.getMap(name); map1.addLocalEntryListener(createEntryListener(true)); map2.addLocalEntryListener(createEntryListener(true)); map1.addEntryListener(createEntryListener(false), false); map2.addEntryListener(createEntryListener(false), false); map2.addEntryListener(createEntryListener(false), true); int k = 1; putDummyData(map2, k); checkCountWithExpected(k * 3, k, k * 2); } @Test /** * Test for issue 584 and 756 */ public void globalAndLocalListenerTest2() throws InterruptedException { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2); Config cfg = new Config(); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(cfg); HazelcastInstance h2 = nodeFactory.newHazelcastInstance(cfg); IMap<String, String> map1 = h1.getMap(name); IMap<String, String> map2 = h2.getMap(name); // changed listener order map1.addEntryListener(createEntryListener(false), false); map1.addLocalEntryListener(createEntryListener(true)); map2.addEntryListener(createEntryListener(false), true); map2.addLocalEntryListener(createEntryListener(true)); map2.addEntryListener(createEntryListener(false), false); int k = 3; putDummyData(map1, k); checkCountWithExpected(k * 3, k, k * 2); } private static void putDummyData(IMap map, int k) { for (int i = 0; i < k; i++) { map.put("foo" + i, "bar"); } } private void checkCountWithExpected(final int expectedGlobal, final int expectedLocal, final int expectedValue) { assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(expectedLocal, localCount.get()); assertEquals(expectedGlobal, globalCount.get()); assertEquals(expectedValue, valueCount.get()); } }); } /** * test for issue 589 */ @Test public void setFiresAlwaysAddEvent() throws InterruptedException { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(2); Config cfg = new Config(); HazelcastInstance h1 = nodeFactory.newHazelcastInstance(cfg); IMap<Object, Object> map = h1.getMap("map"); final CountDownLatch updateLatch = new CountDownLatch(1); final CountDownLatch addLatch = new CountDownLatch(1); map.addEntryListener(new EntryAdapter<Object, Object>() { @Override public void entryAdded(EntryEvent<Object, Object> event) { addLatch.countDown(); } @Override public void entryUpdated(EntryEvent<Object, Object> event) { updateLatch.countDown(); } }, false); map.set(1, 1); map.set(1, 2); assertTrue(addLatch.await(5, TimeUnit.SECONDS)); assertTrue(updateLatch.await(5, TimeUnit.SECONDS)); } @Test public void testLocalEntryListener_singleInstance_with_MatchingPredicate() throws Exception { Config config = new Config(); HazelcastInstance instance = createHazelcastInstance(config); IMap<String, String> map = instance.getMap("map"); boolean includeValue = false; map.addLocalEntryListener(createEntryListener(false), matchingPredicate(), includeValue); int count = 1000; for (int i = 0; i < count; i++) { map.put("key" + i, "value" + i); } checkCountWithExpected(count, 0, 0); } @Test public void testLocalEntryListener_singleInstance_with_NonMatchingPredicate() throws Exception { Config config = new Config(); HazelcastInstance instance = createHazelcastInstance(config); IMap<String, String> map = instance.getMap("map"); boolean includeValue = false; map.addLocalEntryListener(createEntryListener(false), nonMatchingPredicate(), includeValue); int count = 1000; for (int i = 0; i < count; i++) { map.put("key" + i, "value" + i); } checkCountWithExpected(0, 0, 0); } @Test public void testLocalEntryListener_multipleInstance_with_MatchingPredicate() throws Exception { int instanceCount = 3; HazelcastInstance instance = createHazelcastInstanceFactory(instanceCount).newInstances(new Config())[0]; String mapName = "myMap"; IMap<String, String> map = instance.getMap(mapName); boolean includeValue = false; map.addLocalEntryListener(createEntryListener(false), matchingPredicate(), includeValue); int count = 1000; for (int i = 0; i < count; i++) { map.put("key" + i, "value" + i); } final int eventPerPartitionMin = count / instanceCount - count / 10; final int eventPerPartitionMax = count / instanceCount + count / 10; assertTrueEventually(new AssertTask() { @Override public void run() { assertTrue(globalCount.get() > eventPerPartitionMin && globalCount.get() < eventPerPartitionMax); } }); } @Test public void testLocalEntryListener_multipleInstance_with_MatchingPredicate_and_Key() throws Exception { int instanceCount = 1; HazelcastInstance instance = createHazelcastInstanceFactory(instanceCount).newInstances(new Config())[0]; String mapName = "myMap"; IMap<String, String> map = instance.getMap(mapName); boolean includeValue = false; map.addLocalEntryListener(createEntryListener(false), matchingPredicate(), "key500", includeValue); int count = 1000; for (int i = 0; i < count; i++) { map.put("key" + i, "value" + i); } assertTrueEventually(new AssertTask() { @Override public void run() { assertTrue(globalCount.get() == 1); } }); } private Predicate<String, String> matchingPredicate() { return new Predicate<String, String>() { @Override public boolean apply(Map.Entry<String, String> mapEntry) { return true; } }; } private Predicate<String, String> nonMatchingPredicate() { return new Predicate<String, String>() { @Override public boolean apply(Map.Entry<String, String> mapEntry) { return false; } }; } private EntryListener<String, String> createEntryListener(final boolean isLocal) { return new EntryAdapter<String, String>() { private final boolean local = isLocal; public void entryAdded(EntryEvent<String, String> event) { if (local) { localCount.incrementAndGet(); } else { globalCount.incrementAndGet(); } if (event.getValue() != null) { valueCount.incrementAndGet(); } } }; } }
0true
hazelcast_src_test_java_com_hazelcast_map_ListenerTest.java
713
public class CountRequestBuilder extends BroadcastOperationRequestBuilder<CountRequest, CountResponse, CountRequestBuilder> { private QuerySourceBuilder sourceBuilder; public CountRequestBuilder(Client client) { super((InternalClient) client, new CountRequest()); } /** * The types of documents the query will run against. Defaults to all types. */ public CountRequestBuilder setTypes(String... types) { request.types(types); return this; } /** * The minimum score of the documents to include in the count. Defaults to <tt>-1</tt> which means all * documents will be included in the count. */ public CountRequestBuilder setMinScore(float minScore) { request.minScore(minScore); return this; } /** * A comma separated list of routing values to control the shards the search will be executed on. */ public CountRequestBuilder setRouting(String routing) { request.routing(routing); 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, * _shards:x,y to operate on shards x & y, or a custom value, which guarantees that the same order * will be used across different requests. */ public CountRequestBuilder setPreference(String preference) { request.preference(preference); return this; } /** * The routing values to control the shards that the search will be executed on. */ public CountRequestBuilder setRouting(String... routing) { request.routing(routing); return this; } /** * The query source to execute. * * @see org.elasticsearch.index.query.QueryBuilders */ public CountRequestBuilder setQuery(QueryBuilder queryBuilder) { sourceBuilder().setQuery(queryBuilder); return this; } /** * The source to execute. */ public CountRequestBuilder setSource(BytesReference source) { request().source(source, false); return this; } /** * The source to execute. */ public CountRequestBuilder setSource(BytesReference source, boolean unsafe) { request().source(source, unsafe); return this; } /** * The query source to execute. */ public CountRequestBuilder setSource(byte[] querySource) { request.source(querySource); return this; } @Override protected void doExecute(ActionListener<CountResponse> listener) { if (sourceBuilder != null) { request.source(sourceBuilder); } ((InternalClient) client).count(request, listener); } private QuerySourceBuilder sourceBuilder() { if (sourceBuilder == null) { sourceBuilder = new QuerySourceBuilder(); } return sourceBuilder; } }
0true
src_main_java_org_elasticsearch_action_count_CountRequestBuilder.java
2,506
VALUE_BOOLEAN { @Override public boolean isValue() { return true; } },
0true
src_main_java_org_elasticsearch_common_xcontent_XContentParser.java
857
public abstract class AbstractAlterOperation extends AtomicReferenceBackupAwareOperation { protected Data function; protected Object response; protected Data backup; public AbstractAlterOperation() { } public AbstractAlterOperation(String name, Data function) { super(name); this.function = function; } @SuppressWarnings("BooleanMethodIsAlwaysInverted") protected boolean isEquals(Object o1, Object o2) { if (o1 == null) { return o2 == null; } if (o1 == o2) { return true; } return o1.equals(o2); } @Override public Object getResponse() { return response; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeObject(function); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); function = in.readObject(); } @Override public Operation getBackupOperation() { return new SetBackupOperation(name, backup); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_operations_AbstractAlterOperation.java
1,532
public class TenShardsOneReplicaRoutingTests extends ElasticsearchAllocationTestCase { private final ESLogger logger = Loggers.getLogger(TenShardsOneReplicaRoutingTests.class); @Test public void testSingleIndexFirstStartPrimaryThenBackups() { AllocationService strategy = createAllocationService(settingsBuilder() .put("cluster.routing.allocation.node_concurrent_recoveries", 10) .put("cluster.routing.allocation.node_initial_primaries_recoveries", 10) .put("cluster.routing.allocation.allow_rebalance", "always") .put("cluster.routing.allocation.cluster_concurrent_rebalance", -1) .put("cluster.routing.allocation.balance.index", 0.0f) .put("cluster.routing.allocation.balance.replica", 1.0f) .put("cluster.routing.allocation.balance.primary", 0.0f) .build()); logger.info("Building initial routing table"); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test").numberOfShards(10).numberOfReplicas(1)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); assertThat(routingTable.index("test").shards().size(), equalTo(10)); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).shards().get(0).state(), equalTo(UNASSIGNED)); assertThat(routingTable.index("test").shard(i).shards().get(1).state(), equalTo(UNASSIGNED)); assertThat(routingTable.index("test").shard(i).shards().get(0).currentNodeId(), nullValue()); assertThat(routingTable.index("test").shard(i).shards().get(1).currentNodeId(), nullValue()); } logger.info("Adding one node and performing rerouting"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1"))).build(); RoutingTable prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(10)); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test").shard(i).primaryShard().currentNodeId(), equalTo("node1")); assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).currentNodeId(), nullValue()); } logger.info("Add another node and perform rerouting, nothing will happen since primary not started"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node2"))).build(); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable == routingTable, equalTo(true)); logger.info("Start the primary shard (on node1)"); RoutingNodes routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.node("node1").shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(10)); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(i).primaryShard().currentNodeId(), equalTo("node1")); assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1)); // backup shards are initializing as well, we make sure that they recover from primary *started* shards in the IndicesClusterStateService assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).currentNodeId(), equalTo("node2")); } logger.info("Reroute, nothing should change"); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); assertThat(prevRoutingTable == routingTable, equalTo(true)); logger.info("Start the backup shard"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.node("node2").shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(10)); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(i).primaryShard().currentNodeId(), equalTo("node1")); assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).currentNodeId(), equalTo("node2")); } assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(10)); assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(10)); logger.info("Add another node and perform rerouting"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node3"))).build(); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(10)); assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED, RELOCATING), equalTo(10)); assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), lessThan(10)); assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED, RELOCATING), equalTo(10)); assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), lessThan(10)); assertThat(routingNodes.node("node3").numberOfShardsWithState(INITIALIZING), equalTo(6)); logger.info("Start the shards on node 3"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.node("node3").shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(10)); assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), equalTo(7)); assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), equalTo(7)); assertThat(routingNodes.node("node3").numberOfShardsWithState(STARTED), equalTo(6)); } }
0true
src_test_java_org_elasticsearch_cluster_routing_allocation_TenShardsOneReplicaRoutingTests.java
977
public class ReplicationShardOperationFailedException extends IndexShardException implements ElasticsearchWrapperException { public ReplicationShardOperationFailedException(ShardId shardId, String msg) { super(shardId, msg, null); } public ReplicationShardOperationFailedException(ShardId shardId, Throwable cause) { super(shardId, "", cause); } public ReplicationShardOperationFailedException(ShardId shardId, String msg, Throwable cause) { super(shardId, msg, cause); } }
0true
src_main_java_org_elasticsearch_action_support_replication_ReplicationShardOperationFailedException.java
1,313
public class ClusterInfoUpdateJob implements Runnable { // This boolean is used to signal to the ClusterInfoUpdateJob that it // needs to reschedule itself to run again at a later time. It can be // set to false to only run once private final boolean reschedule; public ClusterInfoUpdateJob(boolean reschedule) { this.reschedule = reschedule; } @Override public void run() { if (logger.isTraceEnabled()) { logger.trace("Performing ClusterInfoUpdateJob"); } if (isMaster && this.reschedule) { if (logger.isTraceEnabled()) { logger.trace("Scheduling next run for updating cluster info in: {}", updateFrequency.toString()); } try { threadPool.schedule(updateFrequency, executorName(), new SubmitReschedulingClusterInfoUpdatedJob()); } catch (EsRejectedExecutionException ex) { logger.debug("Reschedule cluster info service was rejected", ex); } } if (!enabled) { // Short-circuit if not enabled if (logger.isTraceEnabled()) { logger.trace("Skipping ClusterInfoUpdatedJob since it is disabled"); } return; } NodesStatsRequest nodesStatsRequest = new NodesStatsRequest("data:true"); nodesStatsRequest.clear(); nodesStatsRequest.fs(true); nodesStatsRequest.timeout(TimeValue.timeValueSeconds(15)); transportNodesStatsAction.execute(nodesStatsRequest, new ActionListener<NodesStatsResponse>() { @Override public void onResponse(NodesStatsResponse nodeStatses) { Map<String, DiskUsage> newUsages = new HashMap<String, DiskUsage>(); for (NodeStats nodeStats : nodeStatses.getNodes()) { if (nodeStats.getFs() == null) { logger.warn("Unable to retrieve node FS stats for {}", nodeStats.getNode().name()); } else { long available = 0; long total = 0; for (FsStats.Info info : nodeStats.getFs()) { available += info.getAvailable().bytes(); total += info.getTotal().bytes(); } String nodeId = nodeStats.getNode().id(); if (logger.isTraceEnabled()) { logger.trace("node: [{}], total disk: {}, available disk: {}", nodeId, total, available); } newUsages.put(nodeId, new DiskUsage(nodeId, total, available)); } } usages = ImmutableMap.copyOf(newUsages); } @Override public void onFailure(Throwable e) { logger.error("Failed to execute NodeStatsAction for ClusterInfoUpdateJob", e); } }); IndicesStatsRequest indicesStatsRequest = new IndicesStatsRequest(); indicesStatsRequest.clear(); indicesStatsRequest.store(true); transportIndicesStatsAction.execute(indicesStatsRequest, new ActionListener<IndicesStatsResponse>() { @Override public void onResponse(IndicesStatsResponse indicesStatsResponse) { ShardStats[] stats = indicesStatsResponse.getShards(); HashMap<String, Long> newShardSizes = new HashMap<String, Long>(); for (ShardStats s : stats) { long size = s.getStats().getStore().sizeInBytes(); String sid = shardIdentifierFromRouting(s.getShardRouting()); if (logger.isTraceEnabled()) { logger.trace("shard: {} size: {}", sid, size); } newShardSizes.put(sid, size); } shardSizes = ImmutableMap.copyOf(newShardSizes); } @Override public void onFailure(Throwable e) { logger.error("Failed to execute IndicesStatsAction for ClusterInfoUpdateJob", e); } }); if (logger.isTraceEnabled()) { logger.trace("Finished ClusterInfoUpdateJob"); } } }
0true
src_main_java_org_elasticsearch_cluster_InternalClusterInfoService.java
3,162
public abstract class BytesValues { /** * An empty {@link BytesValues instance} */ public static final BytesValues EMPTY = new Empty(); private boolean multiValued; protected final BytesRef scratch = new BytesRef(); protected int docId = -1; /** * Creates a new {@link BytesValues} instance * @param multiValued <code>true</code> iff this instance is multivalued. Otherwise <code>false</code>. */ protected BytesValues(boolean multiValued) { this.multiValued = multiValued; } /** * Is one of the documents in this field data values is multi valued? */ public final boolean isMultiValued() { return multiValued; } /** * Converts the current shared {@link BytesRef} to a stable instance. Note, * this calls makes the bytes safe for *reads*, not writes (into the same BytesRef). For example, * it makes it safe to be placed in a map. */ public BytesRef copyShared() { return BytesRef.deepCopyOf(scratch); } /** * Sets iteration to the specified docID and returns the number of * values for this document ID, * @param docId document ID * * @see #nextValue() */ public abstract int setDocument(int docId); /** * Returns the next value for the current docID set to {@link #setDocument(int)}. * This method should only be called <tt>N</tt> times where <tt>N</tt> is the number * returned from {@link #setDocument(int)}. If called more than <tt>N</tt> times the behavior * is undefined. This interface guarantees that the values are returned in order. * <p> * If this instance returns ordered values the <tt>Nth</tt> value is strictly less than the <tt>N+1</tt> value with * respect to the {@link AtomicFieldData.Order} returned from {@link #getOrder()}. If this instance returns * <i>unordered</i> values {@link #getOrder()} must return {@link AtomicFieldData.Order#NONE} * Note: the values returned are de-duplicated, only unique values are returned. * </p> * * Note: the returned {@link BytesRef} might be shared across invocations. * * @return the next value for the current docID set to {@link #setDocument(int)}. */ public abstract BytesRef nextValue(); /** * Returns the hash value of the previously returned shared {@link BytesRef} instances. * * @return the hash value of the previously returned shared {@link BytesRef} instances. */ public int currentValueHash() { return scratch.hashCode(); } /** * Returns the order the values are returned from {@link #nextValue()}. * <p> Note: {@link BytesValues} have {@link AtomicFieldData.Order#BYTES} by default.</p> */ public AtomicFieldData.Order getOrder() { return AtomicFieldData.Order.BYTES; } /** * Ordinal based {@link BytesValues}. */ public static abstract class WithOrdinals extends BytesValues { protected final Docs ordinals; protected WithOrdinals(Ordinals.Docs ordinals) { super(ordinals.isMultiValued()); this.ordinals = ordinals; } /** * Returns the associated ordinals instance. * @return the associated ordinals instance. */ public Ordinals.Docs ordinals() { return ordinals; } /** * Returns the value for the given ordinal. * @param ord the ordinal to lookup. * @return a shared {@link BytesRef} instance holding the value associated * with the given ordinal or <code>null</code> if ordinal is <tt>0</tt> */ public abstract BytesRef getValueByOrd(long ord); @Override public int setDocument(int docId) { this.docId = docId; int length = ordinals.setDocument(docId); assert (ordinals.getOrd(docId) != Ordinals.MISSING_ORDINAL) == length > 0 : "Doc: [" + docId + "] hasValue: [" + (ordinals.getOrd(docId) != Ordinals.MISSING_ORDINAL) + "] but length is [" + length + "]"; return length; } @Override public BytesRef nextValue() { assert docId != -1; return getValueByOrd(ordinals.nextOrd()); } } /** * An empty {@link BytesValues} implementation */ private final static class Empty extends BytesValues { Empty() { super(false); } @Override public int setDocument(int docId) { return 0; } @Override public BytesRef nextValue() { throw new ElasticsearchIllegalStateException("Empty BytesValues has no next value"); } @Override public int currentValueHash() { throw new ElasticsearchIllegalStateException("Empty BytesValues has no hash for the current Value"); } } }
0true
src_main_java_org_elasticsearch_index_fielddata_BytesValues.java
4,504
public class IndicesStore extends AbstractComponent implements ClusterStateListener { public static final String INDICES_STORE_THROTTLE_TYPE = "indices.store.throttle.type"; public static final String INDICES_STORE_THROTTLE_MAX_BYTES_PER_SEC = "indices.store.throttle.max_bytes_per_sec"; class ApplySettings implements NodeSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { String rateLimitingType = settings.get(INDICES_STORE_THROTTLE_TYPE, IndicesStore.this.rateLimitingType); // try and parse the type StoreRateLimiting.Type.fromString(rateLimitingType); if (!rateLimitingType.equals(IndicesStore.this.rateLimitingType)) { logger.info("updating indices.store.throttle.type from [{}] to [{}]", IndicesStore.this.rateLimitingType, rateLimitingType); IndicesStore.this.rateLimitingType = rateLimitingType; IndicesStore.this.rateLimiting.setType(rateLimitingType); } ByteSizeValue rateLimitingThrottle = settings.getAsBytesSize(INDICES_STORE_THROTTLE_MAX_BYTES_PER_SEC, IndicesStore.this.rateLimitingThrottle); if (!rateLimitingThrottle.equals(IndicesStore.this.rateLimitingThrottle)) { logger.info("updating indices.store.throttle.max_bytes_per_sec from [{}] to [{}], note, type is [{}]", IndicesStore.this.rateLimitingThrottle, rateLimitingThrottle, IndicesStore.this.rateLimitingType); IndicesStore.this.rateLimitingThrottle = rateLimitingThrottle; IndicesStore.this.rateLimiting.setMaxRate(rateLimitingThrottle); } } } private final NodeEnvironment nodeEnv; private final NodeSettingsService nodeSettingsService; private final IndicesService indicesService; private final ClusterService clusterService; private volatile String rateLimitingType; private volatile ByteSizeValue rateLimitingThrottle; private final StoreRateLimiting rateLimiting = new StoreRateLimiting(); private final ApplySettings applySettings = new ApplySettings(); @Inject public IndicesStore(Settings settings, NodeEnvironment nodeEnv, NodeSettingsService nodeSettingsService, IndicesService indicesService, ClusterService clusterService, ThreadPool threadPool) { super(settings); this.nodeEnv = nodeEnv; this.nodeSettingsService = nodeSettingsService; this.indicesService = indicesService; this.clusterService = clusterService; // we limit with 20MB / sec by default with a default type set to merge sice 0.90.1 this.rateLimitingType = componentSettings.get("throttle.type", StoreRateLimiting.Type.MERGE.name()); rateLimiting.setType(rateLimitingType); this.rateLimitingThrottle = componentSettings.getAsBytesSize("throttle.max_bytes_per_sec", new ByteSizeValue(20, ByteSizeUnit.MB)); rateLimiting.setMaxRate(rateLimitingThrottle); logger.debug("using indices.store.throttle.type [{}], with index.store.throttle.max_bytes_per_sec [{}]", rateLimitingType, rateLimitingThrottle); nodeSettingsService.addListener(applySettings); clusterService.addLast(this); } public StoreRateLimiting rateLimiting() { return this.rateLimiting; } public void close() { nodeSettingsService.removeListener(applySettings); clusterService.remove(this); } @Override public void clusterChanged(ClusterChangedEvent event) { if (!event.routingTableChanged()) { return; } if (event.state().blocks().disableStatePersistence()) { return; } for (IndexRoutingTable indexRoutingTable : event.state().routingTable()) { // Note, closed indices will not have any routing information, so won't be deleted for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) { ShardId shardId = indexShardRoutingTable.shardId(); // a shard can be deleted if all its copies are active, and its not allocated on this node boolean shardCanBeDeleted = true; if (indexShardRoutingTable.size() == 0) { // should not really happen, there should always be at least 1 (primary) shard in a // shard replication group, in any case, protected from deleting something by mistake shardCanBeDeleted = false; } else { for (ShardRouting shardRouting : indexShardRoutingTable) { // be conservative here, check on started, not even active if (!shardRouting.started()) { shardCanBeDeleted = false; break; } // if the allocated or relocation node id doesn't exists in the cluster state, its a stale // node, make sure we don't do anything with this until the routing table has properly been // rerouted to reflect the fact that the node does not exists if (!event.state().nodes().nodeExists(shardRouting.currentNodeId())) { shardCanBeDeleted = false; break; } if (shardRouting.relocatingNodeId() != null) { if (!event.state().nodes().nodeExists(shardRouting.relocatingNodeId())) { shardCanBeDeleted = false; break; } } // check if shard is active on the current node or is getting relocated to the our node String localNodeId = clusterService.localNode().id(); if (localNodeId.equals(shardRouting.currentNodeId()) || localNodeId.equals(shardRouting.relocatingNodeId())) { shardCanBeDeleted = false; break; } } } if (shardCanBeDeleted) { IndexService indexService = indicesService.indexService(indexRoutingTable.index()); if (indexService == null) { // not physical allocation of the index, delete it from the file system if applicable if (nodeEnv.hasNodeFile()) { File[] shardLocations = nodeEnv.shardLocations(shardId); if (FileSystemUtils.exists(shardLocations)) { logger.debug("[{}][{}] deleting shard that is no longer used", shardId.index().name(), shardId.id()); FileSystemUtils.deleteRecursively(shardLocations); } } } else { if (!indexService.hasShard(shardId.id())) { if (indexService.store().canDeleteUnallocated(shardId)) { logger.debug("[{}][{}] deleting shard that is no longer used", shardId.index().name(), shardId.id()); try { indexService.store().deleteUnallocated(indexShardRoutingTable.shardId()); } catch (Exception e) { logger.debug("[{}][{}] failed to delete unallocated shard, ignoring", e, indexShardRoutingTable.shardId().index().name(), indexShardRoutingTable.shardId().id()); } } } else { // this state is weird, should we log? // basically, it means that the shard is not allocated on this node using the routing // but its still physically exists on an IndexService // Note, this listener should run after IndicesClusterStateService... } } } } } } }
1no label
src_main_java_org_elasticsearch_indices_store_IndicesStore.java
858
public class OfferServiceTest extends CommonSetupBaseTest { @Resource protected OfferService offerService; @Resource(name = "blOrderService") protected OrderService orderService; @Resource protected CustomerService customerService; @Resource protected CatalogService catalogService; @Resource(name = "blOrderItemService") protected OrderItemService orderItemService; @Resource(name="blOrderMultishipOptionService") protected OrderMultishipOptionService orderMultishipOptionService; @Resource(name="blFulfillmentGroupService") protected FulfillmentGroupService fulfillmentGroupService; private Order createTestOrderWithOfferAndGiftWrap() throws PricingException { Customer customer = customerService.createCustomerFromId(null); Order order = orderService.createNewCartForCustomer(customer); customerService.saveCustomer(order.getCustomer()); createCountry(); createState(); Address address = new AddressImpl(); address.setAddressLine1("123 Test Rd"); address.setCity("Dallas"); address.setFirstName("Jeff"); address.setLastName("Fischer"); address.setPostalCode("75240"); address.setPrimaryPhone("972-978-9067"); address.setState(stateService.findStateByAbbreviation("KY")); address.setCountry(countryService.findCountryByAbbreviation("US")); FulfillmentGroup group = new FulfillmentGroupImpl(); group.setAddress(address); group.setIsShippingPriceTaxable(true); List<FulfillmentGroup> groups = new ArrayList<FulfillmentGroup>(); FixedPriceFulfillmentOption option = new FixedPriceFulfillmentOptionImpl(); option.setPrice(new Money("8.50")); option.setFulfillmentType(FulfillmentType.PHYSICAL_SHIP); group.setFulfillmentOption(option); group.setFulfillmentOption(option); group.setOrder(order); groups.add(group); order.setFulfillmentGroups(groups); Money total = new Money(5D); group.setRetailShippingPrice(total); group.setShippingPrice(total); DiscreteOrderItem item1; { item1 = new DiscreteOrderItemImpl(); Sku sku = new SkuImpl(); sku.setName("Test Sku"); sku.setRetailPrice(new Money(10D)); sku.setDiscountable(true); sku = catalogService.saveSku(sku); item1.setSku(sku); item1.setQuantity(2); item1.setOrder(order); item1.setOrderItemType(OrderItemType.DISCRETE); item1 = (DiscreteOrderItem) orderItemService.saveOrderItem(item1); order.addOrderItem(item1); FulfillmentGroupItem fgItem = new FulfillmentGroupItemImpl(); fgItem.setFulfillmentGroup(group); fgItem.setOrderItem(item1); fgItem.setQuantity(2); //fgItem.setPrice(new Money(0D)); group.addFulfillmentGroupItem(fgItem); } { DiscreteOrderItem item = new DiscreteOrderItemImpl(); Sku sku = new SkuImpl(); sku.setName("Test Product 2"); sku.setRetailPrice(new Money(20D)); sku.setDiscountable(true); sku = catalogService.saveSku(sku); item.setSku(sku); item.setQuantity(1); item.setOrder(order); item.setOrderItemType(OrderItemType.DISCRETE); item = (DiscreteOrderItem) orderItemService.saveOrderItem(item); order.addOrderItem(item); FulfillmentGroupItem fgItem = new FulfillmentGroupItemImpl(); fgItem.setFulfillmentGroup(group); fgItem.setOrderItem(item); fgItem.setQuantity(1); //fgItem.setPrice(new Money(0D)); group.addFulfillmentGroupItem(fgItem); } { GiftWrapOrderItem item = new GiftWrapOrderItemImpl(); Sku sku = new SkuImpl(); sku.setName("Test GiftWrap"); sku.setRetailPrice(new Money(1D)); sku.setDiscountable(true); sku = catalogService.saveSku(sku); item.setSku(sku); item.setQuantity(1); item.setOrder(order); item.getWrappedItems().add(item1); item.setOrderItemType(OrderItemType.GIFTWRAP); item = (GiftWrapOrderItem) orderItemService.saveOrderItem(item); order.addOrderItem(item); FulfillmentGroupItem fgItem = new FulfillmentGroupItemImpl(); fgItem.setFulfillmentGroup(group); fgItem.setOrderItem(item); fgItem.setQuantity(1); //fgItem.setPrice(new Money(0D)); group.addFulfillmentGroupItem(fgItem); } return order; } @Test(groups = {"testOffersWithGiftWrap"}, dependsOnGroups = { "testShippingInsert"}) @Transactional public void testOrderItemOfferWithGiftWrap() throws PricingException { Order order = createTestOrderWithOfferAndGiftWrap(); OfferDataItemProvider dataProvider = new OfferDataItemProvider(); List<Offer> offers = dataProvider.createItemBasedOfferWithItemCriteria( "order.subTotal.getAmount()>20", OfferDiscountType.PERCENT_OFF, "([MVEL.eval(\"toUpperCase()\",\"Test Sku\")] contains MVEL.eval(\"toUpperCase()\", discreteOrderItem.sku.name))", "([MVEL.eval(\"toUpperCase()\",\"Test Sku\")] contains MVEL.eval(\"toUpperCase()\", discreteOrderItem.sku.name))" ); for (Offer offer : offers) { offer.setName("testOffer"); // //reset the offer is the targets and qualifiers, otherwise the reference is incorrect // for (OfferItemCriteria criteria : offer.getTargetItemCriteria()) { // criteria.setTargetOffer(null); // } // for (OfferItemCriteria criteria : offer.getQualifyingItemCriteria()) { // criteria.setQualifyingOffer(null); // } offerService.save(offer); } order = orderService.save(order, false); Set<OrderMultishipOption> options = new HashSet<OrderMultishipOption>(); for (FulfillmentGroup fg : order.getFulfillmentGroups()) { Address address = fg.getAddress(); for (FulfillmentGroupItem fgItem : fg.getFulfillmentGroupItems()) { for (int j=0;j<fgItem.getQuantity();j++) { OrderMultishipOption option = new OrderMultishipOptionImpl(); option.setOrder(order); option.setAddress(address); option.setOrderItem(fgItem.getOrderItem()); option.setFulfillmentOption(fg.getFulfillmentOption()); options.add(option); } } } for (OrderMultishipOption option : options) { orderMultishipOptionService.save(option); } order = fulfillmentGroupService.matchFulfillmentGroupsToMultishipOptions(order, true); assert order.getOrderItems().size() == 3; assert order.getTotalTax().equals(new Money("2.00")); assert order.getTotalShipping().equals(new Money("8.50")); assert order.getSubTotal().equals(new Money("40.00")); assert order.getTotal().equals(new Money("50.50")); boolean foundGiftItemAndCorrectQuantity = false; for (OrderItem orderItem : order.getOrderItems()) { if (orderItem instanceof GiftWrapOrderItem && ((GiftWrapOrderItem) orderItem).getWrappedItems().size() == 1) { foundGiftItemAndCorrectQuantity = true; break; } } assert foundGiftItemAndCorrectQuantity; } }
0true
integration_src_test_java_org_broadleafcommerce_core_offer_service_OfferServiceTest.java
3,096
static interface Searcher extends Releasable { /** * The source that caused this searcher to be acquired. */ String source(); IndexReader reader(); IndexSearcher searcher(); }
0true
src_main_java_org_elasticsearch_index_engine_Engine.java
2,063
public static final Module EMPTY_MODULE = new Module() { public void configure(Binder binder) { } };
0true
src_main_java_org_elasticsearch_common_inject_util_Modules.java
1,683
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_ADMIN_PERMISSION_ENTITY") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") public class AdminPermissionQualifiedEntityImpl implements AdminPermissionQualifiedEntity { private static final Log LOG = LogFactory.getLog(AdminPermissionQualifiedEntityImpl.class); private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "AdminPermissionEntityId") @GenericGenerator( name="AdminPermissionEntityId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="AdminPermissionEntityImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.openadmin.server.security.domain.AdminPermissionQualifiedEntityImpl") } ) @Column(name = "ADMIN_PERMISSION_ENTITY_ID") protected Long id; @Column(name = "CEILING_ENTITY", nullable=false) @AdminPresentation(friendlyName = "AdminPermissionQualifiedEntityImpl_Ceiling_Entity_Name", order=1, group = "AdminPermissionQualifiedEntityImpl_Permission", prominent=true) protected String ceilingEntityFullyQualifiedName; @ManyToOne(targetEntity = AdminPermissionImpl.class) @JoinColumn(name = "ADMIN_PERMISSION_ID") protected AdminPermission adminPermission; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getCeilingEntityFullyQualifiedName() { return ceilingEntityFullyQualifiedName; } @Override public void setCeilingEntityFullyQualifiedName(String ceilingEntityFullyQualifiedName) { this.ceilingEntityFullyQualifiedName = ceilingEntityFullyQualifiedName; } @Override public AdminPermission getAdminPermission() { return adminPermission; } @Override public void setAdminPermission(AdminPermission adminPermission) { this.adminPermission = adminPermission; } public void checkCloneable(AdminPermissionQualifiedEntity qualifiedEntity) throws CloneNotSupportedException, SecurityException, NoSuchMethodException { Method cloneMethod = qualifiedEntity.getClass().getMethod("clone", new Class[]{}); if (cloneMethod.getDeclaringClass().getName().startsWith("org.broadleafcommerce") && !qualifiedEntity.getClass().getName().startsWith("org.broadleafcommerce")) { //subclass is not implementing the clone method throw new CloneNotSupportedException("Custom extensions and implementations should implement clone."); } } @Override public AdminPermissionQualifiedEntity clone() { AdminPermissionQualifiedEntity clone; try { clone = (AdminPermissionQualifiedEntity) Class.forName(this.getClass().getName()).newInstance(); try { checkCloneable(clone); } catch (CloneNotSupportedException e) { LOG.warn("Clone implementation missing in inheritance hierarchy outside of Broadleaf: " + clone.getClass().getName(), e); } clone.setId(id); clone.setCeilingEntityFullyQualifiedName(ceilingEntityFullyQualifiedName); //don't clone the AdminPermission, as it would cause a recursion } catch (Exception e) { throw new RuntimeException(e); } return clone; } }
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_security_domain_AdminPermissionQualifiedEntityImpl.java
1,557
public class OServerConfigurationLoaderXml { private Class<? extends OServerConfiguration> rootClass; private JAXBContext context; private InputStream inputStream; private File file; public OServerConfigurationLoaderXml(final Class<? extends OServerConfiguration> iRootClass, final InputStream iInputStream) { rootClass = iRootClass; inputStream = iInputStream; } public OServerConfigurationLoaderXml(final Class<? extends OServerConfiguration> iRootClass, final File iFile) { rootClass = iRootClass; file = iFile; } public OServerConfiguration load() throws IOException { try { if (file != null) { String path = OFileUtils.getPath(file.getAbsolutePath()); String current = OFileUtils.getPath(new File("").getAbsolutePath()); if (path.startsWith(current)) path = path.substring(current.length() + 1); OLogManager.instance().info(this, "Loading configuration from: %s...", path); } else { OLogManager.instance().info(this, "Loading configuration from input stream"); } context = JAXBContext.newInstance(rootClass); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setSchema(null); final OServerConfiguration obj; if (file != null) { if (file.exists()) obj = rootClass.cast(unmarshaller.unmarshal(file)); else { OLogManager.instance().error(this, "File not found: %s", file); return rootClass.getConstructor(OServerConfigurationLoaderXml.class).newInstance(this); } obj.location = file.getAbsolutePath(); } else { obj = rootClass.cast(unmarshaller.unmarshal(inputStream)); obj.location = "memory"; } // AUTO CONFIGURE SYSTEM CONFIGURATION OGlobalConfiguration config; if (obj.properties != null) for (OServerEntryConfiguration prop : obj.properties) { try { config = OGlobalConfiguration.findByKey(prop.name); if (config != null) { config.setValue(prop.value); } } catch (Exception e) { } } return obj; } catch (Exception e) { // SYNTAX ERROR? PRINT AN EXAMPLE OLogManager.instance().error(this, "Invalid syntax. Below an example of how it should be:", e); try { context = JAXBContext.newInstance(rootClass); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); Object example = rootClass.getConstructor(OServerConfigurationLoaderXml.class).newInstance(this); marshaller.marshal(example, System.out); } catch (Exception ex) { } throw new IOException(e); } } public void save(final OServerConfiguration iRootObject) throws IOException { if (file != null) try { context = JAXBContext.newInstance(rootClass); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(iRootObject, new FileWriter(file)); } catch (JAXBException e) { throw new IOException(e); } } public File getFile() { return file; } public void setFile(File file) { this.file = file; } }
0true
server_src_main_java_com_orientechnologies_orient_server_config_OServerConfigurationLoaderXml.java
1,788
public static enum GeoShapeType { POINT("point"), MULTIPOINT("multipoint"), LINESTRING("linestring"), MULTILINESTRING("multilinestring"), POLYGON("polygon"), MULTIPOLYGON("multipolygon"), ENVELOPE("envelope"), CIRCLE("circle"); protected final String shapename; private GeoShapeType(String shapename) { this.shapename = shapename; } public static GeoShapeType forName(String geoshapename) { String typename = geoshapename.toLowerCase(Locale.ROOT); for (GeoShapeType type : values()) { if(type.shapename.equals(typename)) { return type; } } throw new ElasticsearchIllegalArgumentException("unknown geo_shape ["+geoshapename+"]"); } public static ShapeBuilder parse(XContentParser parser) throws IOException { if (parser.currentToken() == XContentParser.Token.VALUE_NULL) { return null; } else if (parser.currentToken() != XContentParser.Token.START_OBJECT) { throw new ElasticsearchParseException("Shape must be an object consisting of type and coordinates"); } GeoShapeType shapeType = null; Distance radius = null; CoordinateNode node = null; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { String fieldName = parser.currentName(); if (FIELD_TYPE.equals(fieldName)) { parser.nextToken(); shapeType = GeoShapeType.forName(parser.text()); } else if (FIELD_COORDINATES.equals(fieldName)) { parser.nextToken(); node = parseCoordinates(parser); } else if (CircleBuilder.FIELD_RADIUS.equals(fieldName)) { parser.nextToken(); radius = Distance.parseDistance(parser.text()); } else { parser.nextToken(); parser.skipChildren(); } } } if (shapeType == null) { throw new ElasticsearchParseException("Shape type not included"); } else if (node == null) { throw new ElasticsearchParseException("Coordinates not included"); } else if (radius != null && GeoShapeType.CIRCLE != shapeType) { throw new ElasticsearchParseException("Field [" + CircleBuilder.FIELD_RADIUS + "] is supported for [" + CircleBuilder.TYPE + "] only"); } switch (shapeType) { case POINT: return parsePoint(node); case MULTIPOINT: return parseMultiPoint(node); case LINESTRING: return parseLineString(node); case MULTILINESTRING: return parseMultiLine(node); case POLYGON: return parsePolygon(node); case MULTIPOLYGON: return parseMultiPolygon(node); case CIRCLE: return parseCircle(node, radius); case ENVELOPE: return parseEnvelope(node); default: throw new ElasticsearchParseException("Shape type [" + shapeType + "] not included"); } } protected static PointBuilder parsePoint(CoordinateNode node) { return newPoint(node.coordinate); } protected static CircleBuilder parseCircle(CoordinateNode coordinates, Distance radius) { return newCircleBuilder().center(coordinates.coordinate).radius(radius); } protected static EnvelopeBuilder parseEnvelope(CoordinateNode coordinates) { return newEnvelope().topLeft(coordinates.children.get(0).coordinate).bottomRight(coordinates.children.get(1).coordinate); } protected static MultiPointBuilder parseMultiPoint(CoordinateNode coordinates) { MultiPointBuilder points = new MultiPointBuilder(); for (CoordinateNode node : coordinates.children) { points.point(node.coordinate); } return points; } protected static LineStringBuilder parseLineString(CoordinateNode coordinates) { LineStringBuilder line = newLineString(); for (CoordinateNode node : coordinates.children) { line.point(node.coordinate); } return line; } protected static MultiLineStringBuilder parseMultiLine(CoordinateNode coordinates) { MultiLineStringBuilder multiline = newMultiLinestring(); for (CoordinateNode node : coordinates.children) { multiline.linestring(parseLineString(node)); } return multiline; } protected static PolygonBuilder parsePolygon(CoordinateNode coordinates) { LineStringBuilder shell = parseLineString(coordinates.children.get(0)); PolygonBuilder polygon = new PolygonBuilder(shell.points); for (int i = 1; i < coordinates.children.size(); i++) { polygon.hole(parseLineString(coordinates.children.get(i))); } return polygon; } protected static MultiPolygonBuilder parseMultiPolygon(CoordinateNode coordinates) { MultiPolygonBuilder polygons = newMultiPolygon(); for (CoordinateNode node : coordinates.children) { polygons.polygon(parsePolygon(node)); } return polygons; } }
0true
src_main_java_org_elasticsearch_common_geo_builders_ShapeBuilder.java
2,412
public enum CollectionUtils { ; public static void sort(LongArrayList list) { sort(list.buffer, list.size()); } public static void sort(final long[] array, int len) { new IntroSorter() { long pivot; @Override protected void swap(int i, int j) { final long tmp = array[i]; array[i] = array[j]; array[j] = tmp; } @Override protected int compare(int i, int j) { return Longs.compare(array[i], array[j]); } @Override protected void setPivot(int i) { pivot = array[i]; } @Override protected int comparePivot(int j) { return Longs.compare(pivot, array[j]); } }.sort(0, len); } public static void sortAndDedup(LongArrayList list) { list.elementsCount = sortAndDedup(list.buffer, list.elementsCount); } /** Sort and deduplicate values in-place, then return the unique element count. */ public static int sortAndDedup(long[] array, int len) { if (len <= 1) { return len; } sort(array, len); int uniqueCount = 1; for (int i = 1; i < len; ++i) { if (array[i] != array[i - 1]) { array[uniqueCount++] = array[i]; } } return uniqueCount; } public static void sort(FloatArrayList list) { sort(list.buffer, list.size()); } public static void sort(final float[] array, int len) { new IntroSorter() { float pivot; @Override protected void swap(int i, int j) { final float tmp = array[i]; array[i] = array[j]; array[j] = tmp; } @Override protected int compare(int i, int j) { return Float.compare(array[i], array[j]); } @Override protected void setPivot(int i) { pivot = array[i]; } @Override protected int comparePivot(int j) { return Float.compare(pivot, array[j]); } }.sort(0, len); } public static void sortAndDedup(FloatArrayList list) { list.elementsCount = sortAndDedup(list.buffer, list.elementsCount); } /** Sort and deduplicate values in-place, then return the unique element count. */ public static int sortAndDedup(float[] array, int len) { if (len <= 1) { return len; } sort(array, len); int uniqueCount = 1; for (int i = 1; i < len; ++i) { if (Float.compare(array[i], array[i - 1]) != 0) { array[uniqueCount++] = array[i]; } } return uniqueCount; } public static void sort(DoubleArrayList list) { sort(list.buffer, list.size()); } public static void sort(final double[] array, int len) { new IntroSorter() { double pivot; @Override protected void swap(int i, int j) { final double tmp = array[i]; array[i] = array[j]; array[j] = tmp; } @Override protected int compare(int i, int j) { return Double.compare(array[i], array[j]); } @Override protected void setPivot(int i) { pivot = array[i]; } @Override protected int comparePivot(int j) { return Double.compare(pivot, array[j]); } }.sort(0, len); } public static void sortAndDedup(DoubleArrayList list) { list.elementsCount = sortAndDedup(list.buffer, list.elementsCount); } /** Sort and deduplicate values in-place, then return the unique element count. */ public static int sortAndDedup(double[] array, int len) { if (len <= 1) { return len; } sort(array, len); int uniqueCount = 1; for (int i = 1; i < len; ++i) { if (Double.compare(array[i], array[i - 1]) != 0) { array[uniqueCount++] = array[i]; } } return uniqueCount; } /** * Checks if the given array contains any elements. * * @param array The array to check * * @return false if the array contains an element, true if not or the array is null. */ public static boolean isEmpty(Object[] array) { return array == null || array.length == 0; } }
0true
src_main_java_org_elasticsearch_common_util_CollectionUtils.java
1,601
Arrays.sort(this.additionalForeignKeys, new Comparator<ForeignKey>() { public int compare(ForeignKey o1, ForeignKey o2) { return o1.getManyToField().compareTo(o2.getManyToField()); } });
0true
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_PersistencePerspective.java
483
public class AnalyzeResponse extends ActionResponse implements Iterable<AnalyzeResponse.AnalyzeToken>, ToXContent { public static class AnalyzeToken implements Streamable { private String term; private int startOffset; private int endOffset; private int position; private String type; AnalyzeToken() { } public AnalyzeToken(String term, int position, int startOffset, int endOffset, String type) { this.term = term; this.position = position; this.startOffset = startOffset; this.endOffset = endOffset; this.type = type; } public String getTerm() { return this.term; } public int getStartOffset() { return this.startOffset; } public int getEndOffset() { return this.endOffset; } public int getPosition() { return this.position; } public String getType() { return this.type; } public static AnalyzeToken readAnalyzeToken(StreamInput in) throws IOException { AnalyzeToken analyzeToken = new AnalyzeToken(); analyzeToken.readFrom(in); return analyzeToken; } @Override public void readFrom(StreamInput in) throws IOException { term = in.readString(); startOffset = in.readInt(); endOffset = in.readInt(); position = in.readVInt(); type = in.readOptionalString(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(term); out.writeInt(startOffset); out.writeInt(endOffset); out.writeVInt(position); out.writeOptionalString(type); } } private List<AnalyzeToken> tokens; AnalyzeResponse() { } public AnalyzeResponse(List<AnalyzeToken> tokens) { this.tokens = tokens; } public List<AnalyzeToken> getTokens() { return this.tokens; } @Override public Iterator<AnalyzeToken> iterator() { return tokens.iterator(); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startArray(Fields.TOKENS); for (AnalyzeToken token : tokens) { builder.startObject(); builder.field(Fields.TOKEN, token.getTerm()); builder.field(Fields.START_OFFSET, token.getStartOffset()); builder.field(Fields.END_OFFSET, token.getEndOffset()); builder.field(Fields.TYPE, token.getType()); builder.field(Fields.POSITION, token.getPosition()); builder.endObject(); } builder.endArray(); return builder; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); int size = in.readVInt(); tokens = new ArrayList<AnalyzeToken>(size); for (int i = 0; i < size; i++) { tokens.add(AnalyzeToken.readAnalyzeToken(in)); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(tokens.size()); for (AnalyzeToken token : tokens) { token.writeTo(out); } } static final class Fields { static final XContentBuilderString TOKENS = new XContentBuilderString("tokens"); static final XContentBuilderString TOKEN = new XContentBuilderString("token"); static final XContentBuilderString START_OFFSET = new XContentBuilderString("start_offset"); static final XContentBuilderString END_OFFSET = new XContentBuilderString("end_offset"); static final XContentBuilderString TYPE = new XContentBuilderString("type"); static final XContentBuilderString POSITION = new XContentBuilderString("position"); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_analyze_AnalyzeResponse.java
3,411
public class NodeEngineImpl implements NodeEngine { private final Node node; private final ILogger logger; private final ServiceManager serviceManager; private final TransactionManagerServiceImpl transactionManagerService; private final ProxyServiceImpl proxyService; private final WanReplicationService wanReplicationService; final InternalOperationService operationService; final ExecutionServiceImpl executionService; final EventServiceImpl eventService; final WaitNotifyServiceImpl waitNotifyService; public NodeEngineImpl(Node node) { this.node = node; logger = node.getLogger(NodeEngine.class.getName()); proxyService = new ProxyServiceImpl(this); serviceManager = new ServiceManager(this); executionService = new ExecutionServiceImpl(this); operationService = new BasicOperationService(this); eventService = new EventServiceImpl(this); waitNotifyService = new WaitNotifyServiceImpl(this); transactionManagerService = new TransactionManagerServiceImpl(this); wanReplicationService = node.initializer.geWanReplicationService(); } @PrivateApi public void start() { serviceManager.start(); proxyService.init(); } @Override public Address getThisAddress() { return node.getThisAddress(); } @Override public Address getMasterAddress() { return node.getMasterAddress(); } @Override public MemberImpl getLocalMember() { return node.getLocalMember(); } @Override public Config getConfig() { return node.getConfig(); } @Override public ClassLoader getConfigClassLoader() { return node.getConfigClassLoader(); } @Override public EventService getEventService() { return eventService; } @Override public SerializationService getSerializationService() { return node.getSerializationService(); } public SerializationContext getSerializationContext() { return node.getSerializationService().getSerializationContext(); } @Override public OperationService getOperationService() { return operationService; } @Override public ExecutionService getExecutionService() { return executionService; } @Override public InternalPartitionService getPartitionService() { return node.getPartitionService(); } @Override public ClusterService getClusterService() { return node.getClusterService(); } public ManagementCenterService getManagementCenterService() { return node.getManagementCenterService(); } @Override public ProxyService getProxyService() { return proxyService; } @Override public WaitNotifyService getWaitNotifyService() { return waitNotifyService; } @Override public WanReplicationService getWanReplicationService() { return wanReplicationService; } @Override public TransactionManagerService getTransactionManagerService() { return transactionManagerService; } @Override public Data toData(final Object object) { return node.getSerializationService().toData(object); } @Override public Object toObject(final Object object) { if (object instanceof Data) { return node.getSerializationService().toObject((Data) object); } return object; } @Override public boolean isActive() { return node.isActive(); } @Override public HazelcastInstance getHazelcastInstance() { return node.hazelcastInstance; } public boolean send(Packet packet, Connection connection) { if (connection == null || !connection.live()) { return false; } final MemberImpl memberImpl = node.getClusterService().getMember(connection.getEndPoint()); if (memberImpl != null) { memberImpl.didWrite(); } return connection.write(packet); } /** * Retries sending packet maximum 5 times until connection to target becomes available. */ public boolean send(Packet packet, Address target) { return send(packet, target, null); } private boolean send(Packet packet, Address target, FutureSend futureSend) { final ConnectionManager connectionManager = node.getConnectionManager(); final Connection connection = connectionManager.getConnection(target); if (connection != null) { return send(packet, connection); } else { if (futureSend == null) { futureSend = new FutureSend(packet, target); } final int retries = futureSend.retries; if (retries < 5 && node.isActive()) { connectionManager.getOrConnect(target, true); // TODO: Caution: may break the order guarantee of the packets sent from the same thread! executionService.schedule(futureSend, (retries + 1) * 100, TimeUnit.MILLISECONDS); return true; } return false; } } private class FutureSend implements Runnable { private final Packet packet; private final Address target; private volatile int retries; private FutureSend(Packet packet, Address target) { this.packet = packet; this.target = target; } //retries is incremented by a single thread, but will be read by multiple. So there is no problem. @edu.umd.cs.findbugs.annotations.SuppressWarnings("VO_VOLATILE_INCREMENT") @Override public void run() { retries++; if (logger.isFinestEnabled()) { logger.finest("Retrying[" + retries + "] packet send operation to: " + target); } send(packet, target, this); } } @Override public ILogger getLogger(String name) { return node.getLogger(name); } @Override public ILogger getLogger(Class clazz) { return node.getLogger(clazz); } @Override public GroupProperties getGroupProperties() { return node.getGroupProperties(); } @PrivateApi public void handlePacket(Packet packet) { if (packet.isHeaderSet(Packet.HEADER_OP)) { operationService.receive(packet); } else if (packet.isHeaderSet(Packet.HEADER_EVENT)) { eventService.handleEvent(packet); } else if (packet.isHeaderSet(Packet.HEADER_WAN_REPLICATION)) { wanReplicationService.handleEvent(packet); } else { logger.severe("Unknown packet type! Header: " + packet.getHeader()); } } @PrivateApi public <T> T getService(String serviceName) { final ServiceInfo serviceInfo = serviceManager.getServiceInfo(serviceName); return serviceInfo != null ? (T) serviceInfo.getService() : null; } public <T extends SharedService> T getSharedService(String serviceName) { final Object service = getService(serviceName); if (service == null) { return null; } if (service instanceof SharedService) { return (T) service; } throw new IllegalArgumentException("No SharedService registered with name: " + serviceName); } /** * Returns a list of services matching provides service class/interface. * <br></br> * <b>CoreServices will be placed at the beginning of the list.</b> */ @PrivateApi public <S> Collection<S> getServices(Class<S> serviceClass) { return serviceManager.getServices(serviceClass); } @PrivateApi public Collection<ServiceInfo> getServiceInfos(Class serviceClass) { return serviceManager.getServiceInfos(serviceClass); } @PrivateApi public Node getNode() { return node; } @PrivateApi public void onMemberLeft(MemberImpl member) { waitNotifyService.onMemberLeft(member); operationService.onMemberLeft(member); eventService.onMemberLeft(member); } @PrivateApi public void onClientDisconnected(String clientUuid) { waitNotifyService.onClientDisconnected(clientUuid); } @PrivateApi public void onPartitionMigrate(MigrationInfo migrationInfo) { waitNotifyService.onPartitionMigrate(getThisAddress(), migrationInfo); } /** * Post join operations must be lock free; means no locks at all; * no partition locks, no key-based locks, no service level locks! * <p/> * Post join operations should return response, at least a null response. * <p/> */ @PrivateApi public Operation[] getPostJoinOperations() { final Collection<Operation> postJoinOps = new LinkedList<Operation>(); Operation eventPostJoinOp = eventService.getPostJoinOperation(); if (eventPostJoinOp != null) { postJoinOps.add(eventPostJoinOp); } Collection<PostJoinAwareService> services = getServices(PostJoinAwareService.class); for (PostJoinAwareService service : services) { final Operation pjOp = service.getPostJoinOperation(); if (pjOp != null) { if (pjOp instanceof PartitionAwareOperation) { logger.severe( "Post-join operations cannot implement PartitionAwareOperation! Service: " + service + ", Operation: " + pjOp); continue; } postJoinOps.add(pjOp); } } return postJoinOps.isEmpty() ? null : postJoinOps.toArray(new Operation[postJoinOps.size()]); } public long getClusterTime() { return node.getClusterService().getClusterTime(); } @Override public Storage<DataRef> getOffHeapStorage() { return node.initializer.getOffHeapStorage(); } @PrivateApi public void shutdown(final boolean terminate) { logger.finest("Shutting down services..."); waitNotifyService.shutdown(); proxyService.shutdown(); serviceManager.shutdown(terminate); executionService.shutdown(); eventService.shutdown(); operationService.shutdown(); wanReplicationService.shutdown(); } }
1no label
hazelcast_src_main_java_com_hazelcast_spi_impl_NodeEngineImpl.java
1,152
public class OSQLMethodRemove extends OAbstractSQLMethod { public static final String NAME = "remove"; public OSQLMethodRemove() { super(NAME, 1, -1); } @Override public Object execute(final OIdentifiable iCurrentRecord, final OCommandContext iContext, Object ioResult, Object[] iMethodParams) { if (iMethodParams != null && iMethodParams.length > 0 && iMethodParams[0] != null) iMethodParams = OMultiValue.array(iMethodParams, Object.class, new OCallable<Object, Object>() { @Override public Object call(final Object iArgument) { if (iArgument instanceof String && ((String) iArgument).startsWith("$")) return iContext.getVariable((String) iArgument); return iArgument; } }); for (Object o : iMethodParams) { ioResult = OMultiValue.remove(ioResult, o, false); } return ioResult; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodRemove.java
1,280
protected class ShardCounter { public int active; public int relocating; public int initializing; public int unassigned; public int primaryActive; public int primaryInactive; public ClusterHealthStatus status() { if (primaryInactive > 0) { return ClusterHealthStatus.RED; } if (unassigned > 0 || initializing > 0) { return ClusterHealthStatus.YELLOW; } return ClusterHealthStatus.GREEN; } public void update(ShardRouting shardRouting) { if (shardRouting.active()) { active++; if (shardRouting.primary()) { primaryActive++; } if (shardRouting.relocating()) { relocating++; } return; } if (shardRouting.primary()) { primaryInactive++; } if (shardRouting.initializing()) { initializing++; } else { unassigned++; } } }
0true
src_test_java_org_elasticsearch_cluster_ClusterHealthResponsesTests.java
712
public interface ProductOptionValue extends Serializable { /** * Returns unique identifier of the product option value. * @return */ public Long getId(); /** * Sets the unique identifier of the product option value. * @param id */ public void setId(Long id); /** * Gets the option value. (e.g. "red") * @param */ public String getAttributeValue(); /** * Sets the option value. (e.g. "red") * @param attributeValue */ public void setAttributeValue(String attributeValue); /** * Returns the order that the option value should be displayed in. * @return */ public Long getDisplayOrder(); /** * Sets the display order. * @param order */ public void setDisplayOrder(Long order); /** * Gets the price adjustment associated with this value. For instance, * if this ProductOptionValue represented an extra-large shirt, that * might be a $1 upcharge. This adjustments will be automatically * added to the Sku retail price and sale price * <br /> * <br /> * Note: This could also be a negative value if you wanted to offer * a particular ProductOptionValue at a discount * * @return the price adjustment for this */ public Money getPriceAdjustment(); /** * Gets the price adjustment associated with this value. For instance, * if this ProductOptionValue represented an extra-large shirt, that * might be a $1 upcharge. These adjustments will be automatically * added to the Sku retail price and sale price. To offer this * particular ProductOptionValue at a discount, you could also provide * a negative value here * * @param priceAdjustment */ public void setPriceAdjustment(Money priceAdjustment); /** * Returns the associated ProductOption * * @return */ public ProductOption getProductOption(); /** * Sets the associated product option. * @param productOption */ public void setProductOption(ProductOption productOption); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_ProductOptionValue.java
2,984
public static final class FilterCacheSettings { public static final String FILTER_CACHE_TYPE = "index.cache.filter.type"; }
0true
src_main_java_org_elasticsearch_index_cache_filter_FilterCacheModule.java
3,772
public class TieredMergePolicyProvider extends AbstractMergePolicyProvider<TieredMergePolicy> { private final IndexSettingsService indexSettingsService; private final Set<CustomTieredMergePolicyProvider> policies = new CopyOnWriteArraySet<CustomTieredMergePolicyProvider>(); private volatile double forceMergeDeletesPctAllowed; private volatile ByteSizeValue floorSegment; private volatile int maxMergeAtOnce; private volatile int maxMergeAtOnceExplicit; private volatile ByteSizeValue maxMergedSegment; private volatile double segmentsPerTier; private volatile double reclaimDeletesWeight; private boolean asyncMerge; private final ApplySettings applySettings = new ApplySettings(); @Inject public TieredMergePolicyProvider(Store store, IndexSettingsService indexSettingsService) { super(store); this.indexSettingsService = indexSettingsService; this.asyncMerge = indexSettings.getAsBoolean("index.merge.async", true); this.forceMergeDeletesPctAllowed = componentSettings.getAsDouble("expunge_deletes_allowed", 10d); // percentage this.floorSegment = componentSettings.getAsBytesSize("floor_segment", new ByteSizeValue(2, ByteSizeUnit.MB)); this.maxMergeAtOnce = componentSettings.getAsInt("max_merge_at_once", 10); this.maxMergeAtOnceExplicit = componentSettings.getAsInt("max_merge_at_once_explicit", 30); // TODO is this really a good default number for max_merge_segment, what happens for large indices, won't they end up with many segments? this.maxMergedSegment = componentSettings.getAsBytesSize("max_merged_segment", componentSettings.getAsBytesSize("max_merge_segment", new ByteSizeValue(5, ByteSizeUnit.GB))); this.segmentsPerTier = componentSettings.getAsDouble("segments_per_tier", 10.0d); this.reclaimDeletesWeight = componentSettings.getAsDouble("reclaim_deletes_weight", 2.0d); fixSettingsIfNeeded(); logger.debug("using [tiered] merge policy with expunge_deletes_allowed[{}], floor_segment[{}], max_merge_at_once[{}], max_merge_at_once_explicit[{}], max_merged_segment[{}], segments_per_tier[{}], reclaim_deletes_weight[{}], async_merge[{}]", forceMergeDeletesPctAllowed, floorSegment, maxMergeAtOnce, maxMergeAtOnceExplicit, maxMergedSegment, segmentsPerTier, reclaimDeletesWeight, asyncMerge); indexSettingsService.addListener(applySettings); } private void fixSettingsIfNeeded() { // fixing maxMergeAtOnce, see TieredMergePolicy#setMaxMergeAtOnce if (!(segmentsPerTier >= maxMergeAtOnce)) { int newMaxMergeAtOnce = (int) segmentsPerTier; // max merge at once should be at least 2 if (newMaxMergeAtOnce <= 1) { newMaxMergeAtOnce = 2; } logger.debug("[tiered] merge policy changing max_merge_at_once from [{}] to [{}] because segments_per_tier [{}] has to be higher or equal to it", maxMergeAtOnce, newMaxMergeAtOnce, segmentsPerTier); this.maxMergeAtOnce = newMaxMergeAtOnce; } } @Override public TieredMergePolicy newMergePolicy() { CustomTieredMergePolicyProvider mergePolicy; if (asyncMerge) { mergePolicy = new EnableMergeTieredMergePolicyProvider(this); } else { mergePolicy = new CustomTieredMergePolicyProvider(this); } mergePolicy.setNoCFSRatio(noCFSRatio); mergePolicy.setForceMergeDeletesPctAllowed(forceMergeDeletesPctAllowed); mergePolicy.setFloorSegmentMB(floorSegment.mbFrac()); mergePolicy.setMaxMergeAtOnce(maxMergeAtOnce); mergePolicy.setMaxMergeAtOnceExplicit(maxMergeAtOnceExplicit); mergePolicy.setMaxMergedSegmentMB(maxMergedSegment.mbFrac()); mergePolicy.setSegmentsPerTier(segmentsPerTier); mergePolicy.setReclaimDeletesWeight(reclaimDeletesWeight); return mergePolicy; } @Override public void close() throws ElasticsearchException { indexSettingsService.removeListener(applySettings); } public static final String INDEX_MERGE_POLICY_EXPUNGE_DELETES_ALLOWED = "index.merge.policy.expunge_deletes_allowed"; public static final String INDEX_MERGE_POLICY_FLOOR_SEGMENT = "index.merge.policy.floor_segment"; public static final String INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE = "index.merge.policy.max_merge_at_once"; public static final String INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_EXPLICIT = "index.merge.policy.max_merge_at_once_explicit"; public static final String INDEX_MERGE_POLICY_MAX_MERGED_SEGMENT = "index.merge.policy.max_merged_segment"; public static final String INDEX_MERGE_POLICY_SEGMENTS_PER_TIER = "index.merge.policy.segments_per_tier"; public static final String INDEX_MERGE_POLICY_RECLAIM_DELETES_WEIGHT = "index.merge.policy.reclaim_deletes_weight"; class ApplySettings implements IndexSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { double expungeDeletesPctAllowed = settings.getAsDouble(INDEX_MERGE_POLICY_EXPUNGE_DELETES_ALLOWED, TieredMergePolicyProvider.this.forceMergeDeletesPctAllowed); if (expungeDeletesPctAllowed != TieredMergePolicyProvider.this.forceMergeDeletesPctAllowed) { logger.info("updating [expunge_deletes_allowed] from [{}] to [{}]", TieredMergePolicyProvider.this.forceMergeDeletesPctAllowed, expungeDeletesPctAllowed); TieredMergePolicyProvider.this.forceMergeDeletesPctAllowed = expungeDeletesPctAllowed; for (CustomTieredMergePolicyProvider policy : policies) { policy.setForceMergeDeletesPctAllowed(expungeDeletesPctAllowed); } } ByteSizeValue floorSegment = settings.getAsBytesSize(INDEX_MERGE_POLICY_FLOOR_SEGMENT, TieredMergePolicyProvider.this.floorSegment); if (!floorSegment.equals(TieredMergePolicyProvider.this.floorSegment)) { logger.info("updating [floor_segment] from [{}] to [{}]", TieredMergePolicyProvider.this.floorSegment, floorSegment); TieredMergePolicyProvider.this.floorSegment = floorSegment; for (CustomTieredMergePolicyProvider policy : policies) { policy.setFloorSegmentMB(floorSegment.mbFrac()); } } int maxMergeAtOnce = settings.getAsInt(INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE, TieredMergePolicyProvider.this.maxMergeAtOnce); if (maxMergeAtOnce != TieredMergePolicyProvider.this.maxMergeAtOnce) { logger.info("updating [max_merge_at_once] from [{}] to [{}]", TieredMergePolicyProvider.this.maxMergeAtOnce, maxMergeAtOnce); TieredMergePolicyProvider.this.maxMergeAtOnce = maxMergeAtOnce; for (CustomTieredMergePolicyProvider policy : policies) { policy.setMaxMergeAtOnce(maxMergeAtOnce); } } int maxMergeAtOnceExplicit = settings.getAsInt(INDEX_MERGE_POLICY_MAX_MERGE_AT_ONCE_EXPLICIT, TieredMergePolicyProvider.this.maxMergeAtOnceExplicit); if (maxMergeAtOnceExplicit != TieredMergePolicyProvider.this.maxMergeAtOnceExplicit) { logger.info("updating [max_merge_at_once_explicit] from [{}] to [{}]", TieredMergePolicyProvider.this.maxMergeAtOnceExplicit, maxMergeAtOnceExplicit); TieredMergePolicyProvider.this.maxMergeAtOnceExplicit = maxMergeAtOnceExplicit; for (CustomTieredMergePolicyProvider policy : policies) { policy.setMaxMergeAtOnceExplicit(maxMergeAtOnceExplicit); } } ByteSizeValue maxMergedSegment = settings.getAsBytesSize(INDEX_MERGE_POLICY_MAX_MERGED_SEGMENT, TieredMergePolicyProvider.this.maxMergedSegment); if (!maxMergedSegment.equals(TieredMergePolicyProvider.this.maxMergedSegment)) { logger.info("updating [max_merged_segment] from [{}] to [{}]", TieredMergePolicyProvider.this.maxMergedSegment, maxMergedSegment); TieredMergePolicyProvider.this.maxMergedSegment = maxMergedSegment; for (CustomTieredMergePolicyProvider policy : policies) { policy.setFloorSegmentMB(maxMergedSegment.mbFrac()); } } double segmentsPerTier = settings.getAsDouble(INDEX_MERGE_POLICY_SEGMENTS_PER_TIER, TieredMergePolicyProvider.this.segmentsPerTier); if (segmentsPerTier != TieredMergePolicyProvider.this.segmentsPerTier) { logger.info("updating [segments_per_tier] from [{}] to [{}]", TieredMergePolicyProvider.this.segmentsPerTier, segmentsPerTier); TieredMergePolicyProvider.this.segmentsPerTier = segmentsPerTier; for (CustomTieredMergePolicyProvider policy : policies) { policy.setSegmentsPerTier(segmentsPerTier); } } double reclaimDeletesWeight = settings.getAsDouble(INDEX_MERGE_POLICY_RECLAIM_DELETES_WEIGHT, TieredMergePolicyProvider.this.reclaimDeletesWeight); if (reclaimDeletesWeight != TieredMergePolicyProvider.this.reclaimDeletesWeight) { logger.info("updating [reclaim_deletes_weight] from [{}] to [{}]", TieredMergePolicyProvider.this.reclaimDeletesWeight, reclaimDeletesWeight); TieredMergePolicyProvider.this.reclaimDeletesWeight = reclaimDeletesWeight; for (CustomTieredMergePolicyProvider policy : policies) { policy.setReclaimDeletesWeight(reclaimDeletesWeight); } } final double noCFSRatio = parseNoCFSRatio(settings.get(INDEX_COMPOUND_FORMAT, Double.toString(TieredMergePolicyProvider.this.noCFSRatio))); if (noCFSRatio != TieredMergePolicyProvider.this.noCFSRatio) { logger.info("updating index.compound_format from [{}] to [{}]", formatNoCFSRatio(TieredMergePolicyProvider.this.noCFSRatio), formatNoCFSRatio(noCFSRatio)); TieredMergePolicyProvider.this.noCFSRatio = noCFSRatio; for (CustomTieredMergePolicyProvider policy : policies) { policy.setNoCFSRatio(noCFSRatio); } } fixSettingsIfNeeded(); } } public static class CustomTieredMergePolicyProvider extends TieredMergePolicy { private final TieredMergePolicyProvider provider; public CustomTieredMergePolicyProvider(TieredMergePolicyProvider provider) { super(); this.provider = provider; } @Override public void close() { super.close(); provider.policies.remove(this); } @Override public MergePolicy clone() { // Lucene IW makes a clone internally but since we hold on to this instance // the clone will just be the identity. return this; } } public static class EnableMergeTieredMergePolicyProvider extends CustomTieredMergePolicyProvider { public EnableMergeTieredMergePolicyProvider(TieredMergePolicyProvider provider) { super(provider); } @Override public MergePolicy.MergeSpecification findMerges(MergeTrigger trigger, SegmentInfos infos) throws IOException { // we don't enable merges while indexing documents, we do them in the background if (trigger == MergeTrigger.SEGMENT_FLUSH) { return null; } return super.findMerges(trigger, infos); } } }
1no label
src_main_java_org_elasticsearch_index_merge_policy_TieredMergePolicyProvider.java
1,476
public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> { private boolean isVertex; private HashSet set = new HashSet(); @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class); } @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { long pathsFiltered = 0l; if (this.isVertex) { if (value.hasPaths()) { final Iterator<List<FaunusPathElement.MicroElement>> itty = value.getPaths().iterator(); while (itty.hasNext()) { final List<FaunusPathElement.MicroElement> path = itty.next(); this.set.clear(); this.set.addAll(path); if (path.size() != this.set.size()) { itty.remove(); pathsFiltered++; } } } } else { for (final Edge e : value.getEdges(Direction.BOTH)) { final StandardFaunusEdge edge = (StandardFaunusEdge) e; if (edge.hasPaths()) { final Iterator<List<FaunusPathElement.MicroElement>> itty = edge.getPaths().iterator(); while (itty.hasNext()) { final List<FaunusPathElement.MicroElement> path = itty.next(); this.set.clear(); this.set.addAll(path); if (path.size() != this.set.size()) { itty.remove(); pathsFiltered++; } } } } } DEFAULT_COMPAT.incrementContextCounter(context, Counters.PATHS_FILTERED, pathsFiltered); context.write(NullWritable.get(), value); } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_filter_CyclicPathFilterMap.java
2,237
public abstract class ScoreFunction { private final CombineFunction scoreCombiner; public abstract void setNextReader(AtomicReaderContext context); public abstract double score(int docId, float subQueryScore); public abstract Explanation explainScore(int docId, Explanation subQueryExpl); public CombineFunction getDefaultScoreCombiner() { return scoreCombiner; } protected ScoreFunction(CombineFunction scoreCombiner) { this.scoreCombiner = scoreCombiner; } }
1no label
src_main_java_org_elasticsearch_common_lucene_search_function_ScoreFunction.java
770
public class OEmptyIterator implements Iterator<Map.Entry<String, Object>> { public static final OEmptyIterator INSTANCE = new OEmptyIterator(); public boolean hasNext() { return false; } public Map.Entry<String, Object> next() { return null; } public void remove() { } }
0true
core_src_main_java_com_orientechnologies_orient_core_iterator_OEmptyIterator.java
616
indexEngine.getEntriesMinor(iRangeTo, isInclusive, MultiValuesTransformer.INSTANCE, new OIndexEngine.EntriesResultListener() { @Override public boolean addResult(ODocument entry) { return entriesResultListener.addResult(entry); } });
1no label
core_src_main_java_com_orientechnologies_orient_core_index_OIndexMultiValues.java
241
public class BroadleafCurrencyProvider { @DataProvider(name = "USCurrency") public static Object[][] provideUSCurrency() { BroadleafCurrency currency=new BroadleafCurrencyImpl(); currency.setCurrencyCode("USD"); currency.setDefaultFlag(true); currency.setFriendlyName("US Dollar"); return new Object[][] { { currency } }; } @DataProvider(name = "FRCurrency") public static Object[][] provideFRCurrency() { BroadleafCurrency currency=new BroadleafCurrencyImpl(); currency.setCurrencyCode("EUR"); currency.setDefaultFlag(true); currency.setFriendlyName("EURO Dollar"); return new Object[][] { { currency } }; } }
0true
integration_src_test_java_org_broadleafcommerce_common_currency_BroadleafCurrencyProvider.java
76
public class ThreadAssociatedWithOtherTransactionException extends IllegalStateException { public ThreadAssociatedWithOtherTransactionException( Thread thread, Transaction alreadyAssociatedTx, Transaction tx ) { super( "Thread '" + thread.getName() + "' tried to resume " + tx + ", but had already " + alreadyAssociatedTx + " associated" ); } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_ThreadAssociatedWithOtherTransactionException.java
3,401
public class JustUidFieldsVisitor extends FieldsVisitor { @Override public Status needsField(FieldInfo fieldInfo) throws IOException { if (UidFieldMapper.NAME.equals(fieldInfo.name)) { return Status.YES; } return uid != null ? Status.STOP : Status.NO; } }
0true
src_main_java_org_elasticsearch_index_fieldvisitor_JustUidFieldsVisitor.java
1,648
public abstract class AbstractEntryProcessor<K, V> implements EntryProcessor<K, V> { private final EntryBackupProcessor<K,V> entryBackupProcessor; /** * Creates an AbstractEntryProcessor that applies the {@link #process(java.util.Map.Entry)} to primary and backups. */ public AbstractEntryProcessor(){ this(true); } /** * Creates an AbstractEntryProcessor. * * @param applyOnBackup if the {@link #process(java.util.Map.Entry)} should also be applied on the backup. */ public AbstractEntryProcessor(boolean applyOnBackup){ if(applyOnBackup){ entryBackupProcessor = new EntryBackupProcessorImpl(); }else{ entryBackupProcessor = null; } } @Override public final EntryBackupProcessor<K, V> getBackupProcessor() { return entryBackupProcessor; } private class EntryBackupProcessorImpl implements EntryBackupProcessor<K,V>{ @Override public void processBackup(Map.Entry<K, V> entry) { process(entry); } } }
0true
hazelcast_src_main_java_com_hazelcast_map_AbstractEntryProcessor.java
281
public class ActionModule extends AbstractModule { private final Map<String, ActionEntry> actions = Maps.newHashMap(); static class ActionEntry<Request extends ActionRequest, Response extends ActionResponse> { public final GenericAction<Request, Response> action; public final Class<? extends TransportAction<Request, Response>> transportAction; public final Class[] supportTransportActions; ActionEntry(GenericAction<Request, Response> action, Class<? extends TransportAction<Request, Response>> transportAction, Class... supportTransportActions) { this.action = action; this.transportAction = transportAction; this.supportTransportActions = supportTransportActions; } } private final boolean proxy; public ActionModule(boolean proxy) { this.proxy = proxy; } /** * Registers an action. * * @param action The action type. * @param transportAction The transport action implementing the actual action. * @param supportTransportActions Any support actions that are needed by the transport action. * @param <Request> The request type. * @param <Response> The response type. */ public <Request extends ActionRequest, Response extends ActionResponse> void registerAction(GenericAction<Request, Response> action, Class<? extends TransportAction<Request, Response>> transportAction, Class... supportTransportActions) { actions.put(action.name(), new ActionEntry<Request, Response>(action, transportAction, supportTransportActions)); } @Override protected void configure() { registerAction(NodesInfoAction.INSTANCE, TransportNodesInfoAction.class); registerAction(NodesStatsAction.INSTANCE, TransportNodesStatsAction.class); registerAction(NodesShutdownAction.INSTANCE, TransportNodesShutdownAction.class); registerAction(NodesRestartAction.INSTANCE, TransportNodesRestartAction.class); registerAction(NodesHotThreadsAction.INSTANCE, TransportNodesHotThreadsAction.class); registerAction(ClusterStatsAction.INSTANCE, TransportClusterStatsAction.class); registerAction(ClusterStateAction.INSTANCE, TransportClusterStateAction.class); registerAction(ClusterHealthAction.INSTANCE, TransportClusterHealthAction.class); registerAction(ClusterUpdateSettingsAction.INSTANCE, TransportClusterUpdateSettingsAction.class); registerAction(ClusterRerouteAction.INSTANCE, TransportClusterRerouteAction.class); registerAction(ClusterSearchShardsAction.INSTANCE, TransportClusterSearchShardsAction.class); registerAction(PendingClusterTasksAction.INSTANCE, TransportPendingClusterTasksAction.class); registerAction(PutRepositoryAction.INSTANCE, TransportPutRepositoryAction.class); registerAction(GetRepositoriesAction.INSTANCE, TransportGetRepositoriesAction.class); registerAction(DeleteRepositoryAction.INSTANCE, TransportDeleteRepositoryAction.class); registerAction(GetSnapshotsAction.INSTANCE, TransportGetSnapshotsAction.class); registerAction(DeleteSnapshotAction.INSTANCE, TransportDeleteSnapshotAction.class); registerAction(CreateSnapshotAction.INSTANCE, TransportCreateSnapshotAction.class); registerAction(RestoreSnapshotAction.INSTANCE, TransportRestoreSnapshotAction.class); registerAction(IndicesStatsAction.INSTANCE, TransportIndicesStatsAction.class); registerAction(IndicesStatusAction.INSTANCE, TransportIndicesStatusAction.class); registerAction(IndicesSegmentsAction.INSTANCE, TransportIndicesSegmentsAction.class); registerAction(CreateIndexAction.INSTANCE, TransportCreateIndexAction.class); registerAction(DeleteIndexAction.INSTANCE, TransportDeleteIndexAction.class); registerAction(OpenIndexAction.INSTANCE, TransportOpenIndexAction.class); registerAction(CloseIndexAction.INSTANCE, TransportCloseIndexAction.class); registerAction(IndicesExistsAction.INSTANCE, TransportIndicesExistsAction.class); registerAction(TypesExistsAction.INSTANCE, TransportTypesExistsAction.class); registerAction(GetMappingsAction.INSTANCE, TransportGetMappingsAction.class); registerAction(GetFieldMappingsAction.INSTANCE, TransportGetFieldMappingsAction.class); registerAction(PutMappingAction.INSTANCE, TransportPutMappingAction.class); registerAction(DeleteMappingAction.INSTANCE, TransportDeleteMappingAction.class); registerAction(IndicesAliasesAction.INSTANCE, TransportIndicesAliasesAction.class); registerAction(UpdateSettingsAction.INSTANCE, TransportUpdateSettingsAction.class); registerAction(AnalyzeAction.INSTANCE, TransportAnalyzeAction.class); registerAction(PutIndexTemplateAction.INSTANCE, TransportPutIndexTemplateAction.class); registerAction(GetIndexTemplatesAction.INSTANCE, TransportGetIndexTemplatesAction.class); registerAction(DeleteIndexTemplateAction.INSTANCE, TransportDeleteIndexTemplateAction.class); registerAction(ValidateQueryAction.INSTANCE, TransportValidateQueryAction.class); registerAction(GatewaySnapshotAction.INSTANCE, TransportGatewaySnapshotAction.class); registerAction(RefreshAction.INSTANCE, TransportRefreshAction.class); registerAction(FlushAction.INSTANCE, TransportFlushAction.class); registerAction(OptimizeAction.INSTANCE, TransportOptimizeAction.class); registerAction(ClearIndicesCacheAction.INSTANCE, TransportClearIndicesCacheAction.class); registerAction(PutWarmerAction.INSTANCE, TransportPutWarmerAction.class); registerAction(DeleteWarmerAction.INSTANCE, TransportDeleteWarmerAction.class); registerAction(GetWarmersAction.INSTANCE, TransportGetWarmersAction.class); registerAction(GetAliasesAction.INSTANCE, TransportGetAliasesAction.class); registerAction(AliasesExistAction.INSTANCE, TransportAliasesExistAction.class); registerAction(GetSettingsAction.INSTANCE, TransportGetSettingsAction.class); registerAction(IndexAction.INSTANCE, TransportIndexAction.class); registerAction(GetAction.INSTANCE, TransportGetAction.class); registerAction(TermVectorAction.INSTANCE, TransportSingleShardTermVectorAction.class); registerAction(MultiTermVectorsAction.INSTANCE, TransportMultiTermVectorsAction.class, TransportSingleShardMultiTermsVectorAction.class); registerAction(DeleteAction.INSTANCE, TransportDeleteAction.class, TransportIndexDeleteAction.class, TransportShardDeleteAction.class); registerAction(CountAction.INSTANCE, TransportCountAction.class); registerAction(SuggestAction.INSTANCE, TransportSuggestAction.class); registerAction(UpdateAction.INSTANCE, TransportUpdateAction.class); registerAction(MultiGetAction.INSTANCE, TransportMultiGetAction.class, TransportShardMultiGetAction.class); registerAction(BulkAction.INSTANCE, TransportBulkAction.class, TransportShardBulkAction.class); registerAction(DeleteByQueryAction.INSTANCE, TransportDeleteByQueryAction.class, TransportIndexDeleteByQueryAction.class, TransportShardDeleteByQueryAction.class); registerAction(SearchAction.INSTANCE, TransportSearchAction.class, TransportSearchDfsQueryThenFetchAction.class, TransportSearchQueryThenFetchAction.class, TransportSearchDfsQueryAndFetchAction.class, TransportSearchQueryAndFetchAction.class, TransportSearchScanAction.class ); registerAction(SearchScrollAction.INSTANCE, TransportSearchScrollAction.class, TransportSearchScrollScanAction.class, TransportSearchScrollQueryThenFetchAction.class, TransportSearchScrollQueryAndFetchAction.class ); registerAction(MultiSearchAction.INSTANCE, TransportMultiSearchAction.class); registerAction(MoreLikeThisAction.INSTANCE, TransportMoreLikeThisAction.class); registerAction(PercolateAction.INSTANCE, TransportPercolateAction.class); registerAction(MultiPercolateAction.INSTANCE, TransportMultiPercolateAction.class, TransportShardMultiPercolateAction.class); registerAction(ExplainAction.INSTANCE, TransportExplainAction.class); registerAction(ClearScrollAction.INSTANCE, TransportClearScrollAction.class); // register Name -> GenericAction Map that can be injected to instances. MapBinder<String, GenericAction> actionsBinder = MapBinder.newMapBinder(binder(), String.class, GenericAction.class); for (Map.Entry<String, ActionEntry> entry : actions.entrySet()) { actionsBinder.addBinding(entry.getKey()).toInstance(entry.getValue().action); } // register GenericAction -> transportAction Map that can be injected to instances. // also register any supporting classes if (!proxy) { MapBinder<GenericAction, TransportAction> transportActionsBinder = MapBinder.newMapBinder(binder(), GenericAction.class, TransportAction.class); for (Map.Entry<String, ActionEntry> entry : actions.entrySet()) { // bind the action as eager singleton, so the map binder one will reuse it bind(entry.getValue().transportAction).asEagerSingleton(); transportActionsBinder.addBinding(entry.getValue().action).to(entry.getValue().transportAction).asEagerSingleton(); for (Class supportAction : entry.getValue().supportTransportActions) { bind(supportAction).asEagerSingleton(); } } } } }
0true
src_main_java_org_elasticsearch_action_ActionModule.java
1,643
public class OHazelcastPlugin extends ODistributedAbstractPlugin implements MembershipListener, EntryListener<String, Object> { protected static final String CONFIG_NODE_PREFIX = "node."; protected static final String CONFIG_DATABASE_PREFIX = "database."; protected String nodeId; protected String hazelcastConfigFile = "hazelcast.xml"; protected Map<String, Member> cachedClusterNodes = new ConcurrentHashMap<String, Member>(); protected OHazelcastDistributedMessageService messageService; protected long timeOffset = 0; protected Date startedOn = new Date(); protected volatile STATUS status = STATUS.OFFLINE; protected String membershipListenerRegistration; protected volatile HazelcastInstance hazelcastInstance; protected Object installDatabaseLock = new Object(); public OHazelcastPlugin() { } @Override public void config(final OServer iServer, final OServerParameterConfiguration[] iParams) { super.config(iServer, iParams); if (nodeName == null) { // GENERATE NODE NAME nodeName = "node" + System.currentTimeMillis(); OLogManager.instance().warn(this, "Generating new node name for current node: %s", nodeName); // SALVE THE NODE NAME IN CONFIGURATION boolean found = false; final OServerConfiguration cfg = iServer.getConfiguration(); for (OServerHandlerConfiguration h : cfg.handlers) { if (h.clazz.equals(getClass().getName())) { for (OServerParameterConfiguration p : h.parameters) { if (p.name.equals("nodeName")) { found = true; p.value = nodeName; break; } } if (!found) { h.parameters = OArrays.copyOf(h.parameters, h.parameters.length + 1); h.parameters[h.parameters.length - 1] = new OServerParameterConfiguration("nodeName", nodeName); } try { iServer.saveConfiguration(); } catch (IOException e) { throw new OConfigurationException("Cannot save server configuration", e); } break; } } } for (OServerParameterConfiguration param : iParams) { if (param.name.equalsIgnoreCase("configuration.hazelcast")) hazelcastConfigFile = OSystemVariableResolver.resolveSystemVariables(param.value); } } @Override public void startup() { if (!enabled) return; super.startup(); status = STATUS.STARTING; OLogManager.instance().info(this, "Starting distributed server '%s'...", getLocalNodeName()); cachedClusterNodes.clear(); try { hazelcastInstance = Hazelcast.newHazelcastInstance(new FileSystemXmlConfig(hazelcastConfigFile)); nodeId = hazelcastInstance.getCluster().getLocalMember().getUuid(); timeOffset = System.currentTimeMillis() - hazelcastInstance.getCluster().getClusterTime(); cachedClusterNodes.put(getLocalNodeName(), hazelcastInstance.getCluster().getLocalMember()); membershipListenerRegistration = hazelcastInstance.getCluster().addMembershipListener(this); OServer.registerServerInstance(getLocalNodeName(), serverInstance); final IMap<String, Object> configurationMap = getConfigurationMap(); configurationMap.addEntryListener(this, true); // REGISTER CURRENT NODES for (Member m : hazelcastInstance.getCluster().getMembers()) { final String memberName = getNodeName(m); if (memberName != null) cachedClusterNodes.put(memberName, m); } messageService = new OHazelcastDistributedMessageService(this); // PUBLISH LOCAL NODE CFG getConfigurationMap().put(CONFIG_NODE_PREFIX + getLocalNodeId(), getLocalNodeConfiguration()); installNewDatabases(true); loadDistributedDatabases(); // REGISTER CURRENT MEMBERS setStatus(STATUS.ONLINE); } catch (FileNotFoundException e) { throw new OConfigurationException("Error on creating Hazelcast instance", e); } } @Override public long getDistributedTime(final long iTime) { return iTime - timeOffset; } @Override public void sendShutdown() { shutdown(); } @Override public void shutdown() { if (!enabled) return; setStatus(STATUS.SHUTDOWNING); messageService.shutdown(); super.shutdown(); cachedClusterNodes.clear(); if (membershipListenerRegistration != null) { hazelcastInstance.getCluster().removeMembershipListener(membershipListenerRegistration); } try { hazelcastInstance.shutdown(); } catch (Exception e) { OLogManager.instance().error(this, "Error on shutting down Hazelcast instance", e); } finally { hazelcastInstance = null; } setStatus(STATUS.OFFLINE); getConfigurationMap().remove(CONFIG_NODE_PREFIX + getLocalNodeId()); } @Override public ODocument getClusterConfiguration() { if (!enabled) return null; final ODocument cluster = new ODocument(); final HazelcastInstance instance = getHazelcastInstance(); cluster.field("localName", instance.getName()); cluster.field("localId", instance.getCluster().getLocalMember().getUuid()); // INSERT MEMBERS final List<ODocument> members = new ArrayList<ODocument>(); cluster.field("members", members, OType.EMBEDDEDLIST); // members.add(getLocalNodeConfiguration()); for (Member member : cachedClusterNodes.values()) { members.add(getNodeConfigurationById(member.getUuid())); } return cluster; } public ODocument getNodeConfigurationById(final String iNodeId) { return (ODocument) getConfigurationMap().get(CONFIG_NODE_PREFIX + iNodeId); } @Override public ODocument getLocalNodeConfiguration() { final ODocument nodeCfg = new ODocument(); nodeCfg.field("id", getLocalNodeId()); nodeCfg.field("name", getLocalNodeName()); nodeCfg.field("startedOn", startedOn); List<Map<String, Object>> listeners = new ArrayList<Map<String, Object>>(); nodeCfg.field("listeners", listeners, OType.EMBEDDEDLIST); for (OServerNetworkListener listener : serverInstance.getNetworkListeners()) { final Map<String, Object> listenerCfg = new HashMap<String, Object>(); listeners.add(listenerCfg); listenerCfg.put("protocol", listener.getProtocolType().getSimpleName()); listenerCfg.put("listen", listener.getListeningAddress()); } nodeCfg.field("databases", getManagedDatabases()); return nodeCfg; } public boolean isEnabled() { return enabled; } public STATUS getStatus() { return status; } public boolean checkStatus(final STATUS iStatus2Check) { return status.equals(iStatus2Check); } @Override public void setStatus(final STATUS iStatus) { if (status.equals(iStatus)) // NO CHANGE return; status = iStatus; // DON'T PUT THE STATUS IN CFG ANYMORE // getConfigurationMap().put(CONFIG_NODE_PREFIX + getLocalNodeId(), getLocalNodeConfiguration()); ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "updated node status to '%s'", status); } @Override public Object sendRequest(final String iDatabaseName, final String iClusterName, final OAbstractRemoteTask iTask, final EXECUTION_MODE iExecutionMode) { final OHazelcastDistributedRequest req = new OHazelcastDistributedRequest(getLocalNodeName(), iDatabaseName, iClusterName, iTask, iExecutionMode); final OHazelcastDistributedDatabase db = messageService.getDatabase(iDatabaseName); final ODistributedResponse response = db.send(req); if (response != null) return response.getPayload(); return null; } @Override public void sendRequest2Node(final String iDatabaseName, final String iTargetNodeName, final OAbstractRemoteTask iTask) { final OHazelcastDistributedRequest req = new OHazelcastDistributedRequest(getLocalNodeName(), iDatabaseName, null, iTask, EXECUTION_MODE.NO_RESPONSE); final OHazelcastDistributedDatabase db = messageService.getDatabase(iDatabaseName); db.send2Node(req, iTargetNodeName); } public Set<String> getManagedDatabases() { return messageService.getDatabases(); } public String getLocalNodeName() { return nodeName; } @Override public String getLocalNodeId() { return nodeId; } @Override public void onCreate(final ODatabase iDatabase) { final OHazelcastDistributedDatabase distribDatabase = messageService.registerDatabase(iDatabase.getName()); distribDatabase.configureDatabase((ODatabaseDocumentTx) ((ODatabaseComplex<?>) iDatabase).getDatabaseOwner(), false, false) .setOnline(); onOpen(iDatabase); } @SuppressWarnings("unchecked") public ODocument getStats() { final ODocument doc = new ODocument(); final Map<String, HashMap<String, Object>> nodes = new HashMap<String, HashMap<String, Object>>(); doc.field("nodes", nodes); Map<String, Object> localNode = new HashMap<String, Object>(); doc.field("localNode", localNode); localNode.put("name", getLocalNodeName()); Map<String, Object> databases = new HashMap<String, Object>(); localNode.put("databases", databases); for (String dbName : messageService.getDatabases()) { Map<String, Object> db = new HashMap<String, Object>(); databases.put(dbName, db); final OProfilerEntry chrono = Orient.instance().getProfiler().getChrono("distributed.replication." + dbName + ".resynch"); if (chrono != null) db.put("resync", new ODocument().fromJSON(chrono.toJSON())); } for (Entry<String, QueueConfig> entry : hazelcastInstance.getConfig().getQueueConfigs().entrySet()) { final String queueName = entry.getKey(); if (!queueName.startsWith(OHazelcastDistributedMessageService.NODE_QUEUE_PREFIX)) continue; final IQueue<Object> queue = hazelcastInstance.getQueue(queueName); final String[] names = queueName.split("\\."); HashMap<String, Object> node = nodes.get(names[2]); if (node == null) { node = new HashMap<String, Object>(); nodes.put(names[2], node); } if (names[3].equals("response")) { node.put("responses", queue.size()); } else { final String dbName = names[3]; Map<String, Object> db = (HashMap<String, Object>) node.get(dbName); if (db == null) { db = new HashMap<String, Object>(2); node.put(dbName, db); } db.put("requests", queue.size()); final Object lastMessage = queue.peek(); if (lastMessage != null) db.put("lastMessage", lastMessage.toString()); } } return doc; } public String getNodeName(final Member iMember) { final ODocument cfg = getNodeConfigurationById(iMember.getUuid()); return (String) (cfg != null ? cfg.field("name") : null); } public Set<String> getRemoteNodeIds() { return cachedClusterNodes.keySet(); } @Override public void memberAdded(final MembershipEvent iEvent) { ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "added new node id=%s name=%s", iEvent.getMember(), getNodeName(iEvent.getMember())); } /** * Removes the node map entry. */ @Override public void memberRemoved(final MembershipEvent iEvent) { ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "node removed id=%s name=%s", iEvent.getMember(), getNodeName(iEvent.getMember())); final Member member = iEvent.getMember(); final String nodeName = getNodeName(member); if (nodeName != null) { cachedClusterNodes.remove(nodeName); for (String dbName : messageService.getDatabases()) { final OHazelcastDistributedDatabase db = messageService.getDatabase(dbName); db.removeNodeInConfiguration(nodeName, false); } } OClientConnectionManager.instance().pushDistribCfg2Clients(getClusterConfiguration()); } @Override public void entryAdded(EntryEvent<String, Object> iEvent) { final String key = iEvent.getKey(); if (key.startsWith(CONFIG_NODE_PREFIX)) { if (!iEvent.getMember().equals(hazelcastInstance.getCluster().getLocalMember())) { final ODocument cfg = (ODocument) iEvent.getValue(); cachedClusterNodes.put((String) cfg.field("name"), (Member) iEvent.getMember()); ODistributedServerLog.info(this, getLocalNodeName(), null, DIRECTION.NONE, "added node configuration id=%s name=%s, now %d nodes are configured", iEvent.getMember(), getNodeName(iEvent.getMember()), cachedClusterNodes.size()); installNewDatabases(false); } } else if (key.startsWith(CONFIG_DATABASE_PREFIX)) { saveDatabaseConfiguration(key.substring(CONFIG_DATABASE_PREFIX.length()), (ODocument) iEvent.getValue()); OClientConnectionManager.instance().pushDistribCfg2Clients(getClusterConfiguration()); } } @Override public void entryUpdated(EntryEvent<String, Object> iEvent) { final String key = iEvent.getKey(); if (key.startsWith(CONFIG_NODE_PREFIX)) { ODistributedServerLog.info(this, getLocalNodeName(), null, DIRECTION.NONE, "updated node configuration id=%s name=%s", iEvent.getMember(), getNodeName(iEvent.getMember())); final ODocument cfg = (ODocument) iEvent.getValue(); cachedClusterNodes.put((String) cfg.field("name"), (Member) iEvent.getMember()); } else if (key.startsWith(CONFIG_DATABASE_PREFIX)) { if (!iEvent.getMember().equals(hazelcastInstance.getCluster().getLocalMember())) { final String dbName = key.substring(CONFIG_DATABASE_PREFIX.length()); ODistributedServerLog.info(this, getLocalNodeName(), null, DIRECTION.NONE, "update configuration db=%s from=%s", dbName, getNodeName(iEvent.getMember())); installNewDatabases(false); saveDatabaseConfiguration(dbName, (ODocument) iEvent.getValue()); OClientConnectionManager.instance().pushDistribCfg2Clients(getClusterConfiguration()); } } } @Override public void entryRemoved(EntryEvent<String, Object> iEvent) { final String key = iEvent.getKey(); if (key.startsWith(CONFIG_NODE_PREFIX)) { final String nName = getNodeName(iEvent.getMember()); ODistributedServerLog.info(this, getLocalNodeName(), null, DIRECTION.NONE, "removed node configuration id=%s name=%s", iEvent.getMember(), nName); cachedClusterNodes.remove(nName); } else if (key.startsWith(CONFIG_DATABASE_PREFIX)) { synchronized (cachedDatabaseConfiguration) { cachedDatabaseConfiguration.remove(key.substring(CONFIG_DATABASE_PREFIX.length())); } } } @Override public void entryEvicted(EntryEvent<String, Object> iEvent) { } @Override public boolean isNodeAvailable(final String iNodeName) { return cachedClusterNodes.containsKey(iNodeName); } public boolean isOffline() { return status != STATUS.ONLINE; } public void waitUntilOnline() throws InterruptedException { while (!status.equals(STATUS.ONLINE)) Thread.sleep(100); } public HazelcastInstance getHazelcastInstance() { while (hazelcastInstance == null) { // WAIT UNTIL THE INSTANCE IS READY try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } return hazelcastInstance; } public Lock getLock(final String iName) { return getHazelcastInstance().getLock(iName); } public Class<? extends OReplicationConflictResolver> getConfictResolverClass() { return confictResolverClass; } @Override public String toString() { return getLocalNodeName(); } /** * Executes the request on local node. In case of error returns the Exception itself * * @param database */ public Serializable executeOnLocalNode(final ODistributedRequest req, ODatabaseDocumentTx database) { final OAbstractRemoteTask task = req.getTask(); try { return (Serializable) task.execute(serverInstance, this, database); } catch (Throwable e) { return e; } } @Override public ODistributedPartition newPartition(final List<String> partition) { return new OHazelcastDistributionPartition(partition); } protected IMap<String, Object> getConfigurationMap() { return getHazelcastInstance().getMap("orientdb"); } /** * Initializes all the available server's databases as distributed. */ protected void loadDistributedDatabases() { for (Entry<String, String> storageEntry : serverInstance.getAvailableStorageNames().entrySet()) { final String databaseName = storageEntry.getKey(); if (messageService.getDatabase(databaseName) == null) { ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "opening database '%s'...", databaseName); final ODistributedConfiguration cfg = getDatabaseConfiguration(databaseName); if (!getConfigurationMap().containsKey(CONFIG_DATABASE_PREFIX + databaseName)) { // PUBLISH CFG FIRST TIME getConfigurationMap().put(CONFIG_DATABASE_PREFIX + databaseName, cfg.serialize()); } final boolean hotAlignment = cfg.isHotAlignment(); messageService.registerDatabase(databaseName).configureDatabase(null, hotAlignment, hotAlignment).setOnline(); } } } @SuppressWarnings("unchecked") protected void installNewDatabases(final boolean iStartup) { if (cachedClusterNodes.size() <= 1) // NO OTHER NODES WHERE ALIGN return; // LOCKING THIS RESOURCE PREVENT CONCURRENT INSTALL OF THE SAME DB synchronized (installDatabaseLock) { for (Entry<String, Object> entry : getConfigurationMap().entrySet()) { if (entry.getKey().startsWith(CONFIG_DATABASE_PREFIX)) { final String databaseName = entry.getKey().substring(CONFIG_DATABASE_PREFIX.length()); final ODocument config = (ODocument) entry.getValue(); final Boolean autoDeploy = config.field("autoDeploy"); if (autoDeploy != null && autoDeploy) { final Boolean hotAlignment = config.field("hotAlignment"); final String dbPath = serverInstance.getDatabaseDirectory() + databaseName; final Set<String> configuredDatabases = serverInstance.getAvailableStorageNames().keySet(); if (configuredDatabases.contains(databaseName)) { if (iStartup && hotAlignment != null && !hotAlignment) { // DROP THE DATABASE ON CURRENT NODE ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "dropping local database %s in %s and get a fresh copy from a remote node...", databaseName, dbPath); Orient.instance().unregisterStorageByName(databaseName); OFileUtils.deleteRecursively(new File(dbPath)); } else // HOT ALIGNMENT RUNNING, DON'T INSTALL THE DB FROM SCRATCH BUT RATHER LET TO THE NODE TO ALIGN BY READING THE QUEUE continue; } final OHazelcastDistributedDatabase distrDatabase = messageService.registerDatabase(databaseName); // READ ALL THE MESSAGES DISCARDING EVERYTHING UNTIL DEPLOY distrDatabase.setWaitForTaskType(ODeployDatabaseTask.class); distrDatabase.configureDatabase(null, false, false); final Map<String, OBuffer> results = (Map<String, OBuffer>) sendRequest(databaseName, null, new ODeployDatabaseTask(), EXECUTION_MODE.RESPONSE); // EXTRACT THE REAL RESULT OBuffer result = null; for (Entry<String, OBuffer> r : results.entrySet()) if (r.getValue().getBuffer() != null && r.getValue().getBuffer().length > 0) { result = r.getValue(); ODistributedServerLog.warn(this, getLocalNodeName(), r.getKey(), DIRECTION.IN, "installing database %s in %s...", databaseName, dbPath); break; } if (result == null) throw new ODistributedException("No response received from remote nodes for auto-deploy of database"); new File(dbPath).mkdirs(); final ODatabaseDocumentTx db = new ODatabaseDocumentTx("local:" + dbPath); final ByteArrayInputStream in = new ByteArrayInputStream(result.getBuffer()); try { db.restore(in, null, null); in.close(); db.close(); Orient.instance().unregisterStorageByName(db.getName()); ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "installed database %s in %s, setting it online...", databaseName, dbPath); distrDatabase.setOnline(); ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "database %s is online", databaseName); } catch (IOException e) { ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.IN, "error on copying database '%s' on local server", e, databaseName); } } } } } } @Override protected ODocument loadDatabaseConfiguration(final String iDatabaseName, final File file) { // FIRST LOOK IN THE CLUSTER if (hazelcastInstance != null) { final ODocument cfg = (ODocument) getConfigurationMap().get(CONFIG_DATABASE_PREFIX + iDatabaseName); if (cfg != null) { ODistributedServerLog.info(this, getLocalNodeName(), null, DIRECTION.NONE, "loaded database configuration from active cluster"); updateCachedDatabaseConfiguration(iDatabaseName, cfg); return cfg; } } // NO NODE IN CLUSTER, LOAD FROM FILE return super.loadDatabaseConfiguration(iDatabaseName, file); } }
1no label
distributed_src_main_java_com_orientechnologies_orient_server_hazelcast_OHazelcastPlugin.java
305
public interface ConcurrentWriteConfiguration extends WriteConfiguration { public<O> void set(String key, O value, O expectedValue); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_ConcurrentWriteConfiguration.java
1,815
interface ContextualCallable<T> { T call(InternalContext context) throws ErrorsException; }
0true
src_main_java_org_elasticsearch_common_inject_ContextualCallable.java
2,921
public class PreBuiltAnalyzerProviderFactoryTests extends ElasticsearchTestCase { @Test public void testVersioningInFactoryProvider() throws Exception { PreBuiltAnalyzerProviderFactory factory = new PreBuiltAnalyzerProviderFactory("default", AnalyzerScope.INDEX, PreBuiltAnalyzers.STANDARD.getAnalyzer(Version.CURRENT)); AnalyzerProvider currentAnalyzerProvider = factory.create("default", ImmutableSettings.Builder.EMPTY_SETTINGS); AnalyzerProvider former090AnalyzerProvider = factory.create("default", ImmutableSettings.settingsBuilder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.V_0_90_0).build()); AnalyzerProvider currentAnalyzerProviderReference = factory.create("default", ImmutableSettings.settingsBuilder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build()); // would love to access the version inside of the lucene analyzer, but that is not possible... assertThat(currentAnalyzerProvider, is(currentAnalyzerProviderReference)); assertThat(currentAnalyzerProvider, is(not(former090AnalyzerProvider))); } }
0true
src_test_java_org_elasticsearch_index_analysis_PreBuiltAnalyzerProviderFactoryTests.java
1,052
public class JobTrackerConfig { public static final int DEFAULT_MAX_THREAD_SIZE = Runtime.getRuntime().availableProcessors(); public static final int DEFAULT_RETRY_COUNT = 0; public static final int DEFAULT_CHUNK_SIZE = 1000; public static final int DEFAULT_QUEUE_SIZE = 0; public static final boolean DEFAULT_COMMUNICATE_STATS = true; public static final TopologyChangedStrategy DEFAULT_TOPOLOGY_CHANGED_STRATEGY = TopologyChangedStrategy.CANCEL_RUNNING_OPERATION; private String name; private int maxThreadSize = DEFAULT_MAX_THREAD_SIZE; private int retryCount = DEFAULT_RETRY_COUNT; private int chunkSize = DEFAULT_CHUNK_SIZE; private int queueSize = DEFAULT_QUEUE_SIZE; private boolean communicateStats = DEFAULT_COMMUNICATE_STATS; private TopologyChangedStrategy topologyChangedStrategy = DEFAULT_TOPOLOGY_CHANGED_STRATEGY; public JobTrackerConfig() { } public JobTrackerConfig(JobTrackerConfig source) { this.name = source.name; this.maxThreadSize = source.maxThreadSize; this.retryCount = source.retryCount; this.chunkSize = source.chunkSize; this.queueSize = source.queueSize; this.communicateStats = source.communicateStats; this.topologyChangedStrategy = source.topologyChangedStrategy; } public JobTrackerConfig setName(String name) { this.name = name; return this; } public String getName() { return name; } public int getMaxThreadSize() { return maxThreadSize; } public void setMaxThreadSize(int maxThreadSize) { this.maxThreadSize = maxThreadSize; } public int getRetryCount() { return retryCount; } public void setRetryCount(int retryCount) { this.retryCount = retryCount; } public int getChunkSize() { return chunkSize; } public void setChunkSize(int chunkSize) { this.chunkSize = chunkSize; } public JobTrackerConfig getAsReadOnly() { return new JobTrackerConfigReadOnly(this); } public int getQueueSize() { return queueSize; } public void setQueueSize(int queueSize) { this.queueSize = queueSize; } public boolean isCommunicateStats() { return communicateStats; } public void setCommunicateStats(boolean communicateStats) { this.communicateStats = communicateStats; } public TopologyChangedStrategy getTopologyChangedStrategy() { return topologyChangedStrategy; } public void setTopologyChangedStrategy(TopologyChangedStrategy topologyChangedStrategy) { this.topologyChangedStrategy = topologyChangedStrategy; } }
0true
hazelcast_src_main_java_com_hazelcast_config_JobTrackerConfig.java
408
public class IdOverrideTableGenerator extends TableGenerator { public static final String ENTITY_NAME_PARAM = "entity_name"; private static final Map<String, Field> FIELD_CACHE = MapUtils.synchronizedMap(new HashMap<String, Field>()); private String entityName; private Field getIdField(Class<?> clazz) { Field response = null; Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.getAnnotation(Id.class) != null) { response = field; break; } } if (response == null && clazz.getSuperclass() != null) { response = getIdField(clazz.getSuperclass()); } return response; } @Override public Serializable generate(SessionImplementor session, Object obj) { /* This works around an issue in Hibernate where if the entityPersister is retrieved from the session and used to get the Id, the entity configuration can be recycled, which is messing with the load persister and current persister on some collections. This may be a jrebel thing, but this workaround covers all environments */ String objName = obj.getClass().getName(); if (!FIELD_CACHE.containsKey(objName)) { Field field = getIdField(obj.getClass()); if (field == null) { throw new IllegalArgumentException("Cannot specify IdOverrideTableGenerator for an entity (" + objName + ") that does not have an Id field declared using the @Id annotation."); } field.setAccessible(true); FIELD_CACHE.put(objName, field); } Field field = FIELD_CACHE.get(objName); final Serializable id; try { id = (Serializable) field.get(obj); } catch (IllegalAccessException e) { throw new RuntimeException(e); } if ( id != null ) { return id; } return super.generate(session, obj); } @Override public void configure(Type type, Properties params, Dialect dialect) throws MappingException { if (params.get("table_name") == null) { params.put("table_name", "SEQUENCE_GENERATOR"); } if (params.get("segment_column_name") == null) { params.put("segment_column_name", "ID_NAME"); } if (params.get("value_column_name") == null) { params.put("value_column_name", "ID_VAL"); } if (params.get("increment_size") == null) { params.put("increment_size", 50); } super.configure(type, params, dialect); entityName = (String) params.get(ENTITY_NAME_PARAM); } public String getEntityName() { return entityName; } public void setEntityName(String entityName) { this.entityName = entityName; } }
0true
common_src_main_java_org_broadleafcommerce_common_persistence_IdOverrideTableGenerator.java
1,845
public class MapService implements ManagedService, MigrationAwareService, TransactionalService, RemoteService, EventPublishingService<EventData, EntryListener>, PostJoinAwareService, SplitBrainHandlerService, ReplicationSupportingService { /** * Service name. */ public static final String SERVICE_NAME = "hz:impl:mapService"; private final ILogger logger; private final NodeEngine nodeEngine; private final PartitionContainer[] partitionContainers; private final ConcurrentMap<String, MapContainer> mapContainers = new ConcurrentHashMap<String, MapContainer>(); private final ConcurrentMap<String, NearCache> nearCacheMap = new ConcurrentHashMap<String, NearCache>(); private final AtomicReference<List<Integer>> ownedPartitions; private final Map<String, MapMergePolicy> mergePolicyMap; // we added following latency to be sure the ongoing migration is completed if the owner of // the record could not complete task before migration public MapService(NodeEngine nodeEngine) { this.nodeEngine = nodeEngine; logger = nodeEngine.getLogger(MapService.class.getName()); partitionContainers = new PartitionContainer[nodeEngine.getPartitionService().getPartitionCount()]; ownedPartitions = new AtomicReference<List<Integer>>(); mergePolicyMap = new ConcurrentHashMap<String, MapMergePolicy>(); mergePolicyMap.put(PutIfAbsentMapMergePolicy.class.getName(), new PutIfAbsentMapMergePolicy()); mergePolicyMap.put(HigherHitsMapMergePolicy.class.getName(), new HigherHitsMapMergePolicy()); mergePolicyMap.put(PassThroughMergePolicy.class.getName(), new PassThroughMergePolicy()); mergePolicyMap.put(LatestUpdateMapMergePolicy.class.getName(), new LatestUpdateMapMergePolicy()); } private final ConcurrentMap<String, LocalMapStatsImpl> statsMap = new ConcurrentHashMap<String, LocalMapStatsImpl>(1000); private final ConstructorFunction<String, LocalMapStatsImpl> localMapStatsConstructorFunction = new ConstructorFunction<String, LocalMapStatsImpl>() { public LocalMapStatsImpl createNew(String key) { return new LocalMapStatsImpl(); } }; public LocalMapStatsImpl getLocalMapStatsImpl(String name) { return ConcurrencyUtil.getOrPutIfAbsent(statsMap, name, localMapStatsConstructorFunction); } public void init(final NodeEngine nodeEngine, Properties properties) { int partitionCount = nodeEngine.getPartitionService().getPartitionCount(); for (int i = 0; i < partitionCount; i++) { partitionContainers[i] = new PartitionContainer(this, i); } final LockService lockService = nodeEngine.getSharedService(LockService.SERVICE_NAME); if (lockService != null) { lockService.registerLockStoreConstructor(SERVICE_NAME, new ConstructorFunction<ObjectNamespace, LockStoreInfo>() { public LockStoreInfo createNew(final ObjectNamespace key) { final MapContainer mapContainer = getMapContainer(key.getObjectName()); return new LockStoreInfo() { public int getBackupCount() { return mapContainer.getBackupCount(); } public int getAsyncBackupCount() { return mapContainer.getAsyncBackupCount(); } }; } }); } } public void reset() { final PartitionContainer[] containers = partitionContainers; for (PartitionContainer container : containers) { if (container != null) { container.clear(); } } for (NearCache nearCache : nearCacheMap.values()) { nearCache.clear(); } } public void shutdown(boolean terminate) { if (!terminate) { flushMapsBeforeShutdown(); destroyMapStores(); final PartitionContainer[] containers = partitionContainers; for (PartitionContainer container : containers) { if (container != null) { container.clear(); } } for (NearCache nearCache : nearCacheMap.values()) { nearCache.clear(); } nearCacheMap.clear(); mapContainers.clear(); } } private void destroyMapStores() { for (MapContainer mapContainer : mapContainers.values()) { MapStoreWrapper store = mapContainer.getStore(); if (store != null) { store.destroy(); } } } private void flushMapsBeforeShutdown() { for (PartitionContainer partitionContainer : partitionContainers) { for (String mapName : mapContainers.keySet()) { RecordStore recordStore = partitionContainer.getRecordStore(mapName); recordStore.setLoaded(true); recordStore.flush(); } } } private final ConstructorFunction<String, MapContainer> mapConstructor = new ConstructorFunction<String, MapContainer>() { public MapContainer createNew(String mapName) { return new MapContainer(mapName, nodeEngine.getConfig().findMapConfig(mapName), MapService.this); } }; public Operation getPostJoinOperation() { PostJoinMapOperation o = new PostJoinMapOperation(); for (MapContainer mapContainer : mapContainers.values()) { o.addMapIndex(mapContainer); o.addMapInterceptors(mapContainer); } return o; } @Override public Runnable prepareMergeRunnable() { Map<MapContainer, Collection<Record>> recordMap = new HashMap<MapContainer, Collection<Record>>(mapContainers.size()); InternalPartitionService partitionService = nodeEngine.getPartitionService(); int partitionCount = partitionService.getPartitionCount(); Address thisAddress = nodeEngine.getClusterService().getThisAddress(); for (MapContainer mapContainer : mapContainers.values()) { for (int i = 0; i < partitionCount; i++) { RecordStore recordStore = getPartitionContainer(i).getRecordStore(mapContainer.getName()); // add your owned entries to the map so they will be merged if (thisAddress.equals(partitionService.getPartitionOwner(i))) { Collection<Record> records = recordMap.get(mapContainer); if (records == null) { records = new ArrayList<Record>(); recordMap.put(mapContainer, records); } records.addAll(recordStore.getReadonlyRecordMap().values()); } // clear all records either owned or backup recordStore.reset(); } } return new Merger(recordMap); } @Override public void onReplicationEvent(WanReplicationEvent replicationEvent) { Object eventObject = replicationEvent.getEventObject(); if (eventObject instanceof MapReplicationUpdate) { MapReplicationUpdate replicationUpdate = (MapReplicationUpdate) eventObject; EntryView entryView = replicationUpdate.getEntryView(); MapMergePolicy mergePolicy = replicationUpdate.getMergePolicy(); String mapName = replicationUpdate.getMapName(); MapContainer mapContainer = getMapContainer(mapName); MergeOperation operation = new MergeOperation(mapName, toData(entryView.getKey(), mapContainer.getPartitioningStrategy()), entryView, mergePolicy); try { int partitionId = nodeEngine.getPartitionService().getPartitionId(entryView.getKey()); Future f = nodeEngine.getOperationService().invokeOnPartition(SERVICE_NAME, operation, partitionId); f.get(); } catch (Throwable t) { throw ExceptionUtil.rethrow(t); } } else if (eventObject instanceof MapReplicationRemove) { MapReplicationRemove replicationRemove = (MapReplicationRemove) eventObject; WanOriginatedDeleteOperation operation = new WanOriginatedDeleteOperation(replicationRemove.getMapName(), replicationRemove.getKey()); try { int partitionId = nodeEngine.getPartitionService().getPartitionId(replicationRemove.getKey()); Future f = nodeEngine.getOperationService().invokeOnPartition(SERVICE_NAME, operation, partitionId); f.get(); } catch (Throwable t) { throw ExceptionUtil.rethrow(t); } } } public MapMergePolicy getMergePolicy(String mergePolicyName) { MapMergePolicy mergePolicy = mergePolicyMap.get(mergePolicyName); if (mergePolicy == null && mergePolicyName != null) { try { // check if user has entered custom class name instead of policy name mergePolicy = ClassLoaderUtil.newInstance(nodeEngine.getConfigClassLoader(), mergePolicyName); mergePolicyMap.put(mergePolicyName, mergePolicy); } catch (Exception e) { logger.severe(e); throw ExceptionUtil.rethrow(e); } } if (mergePolicy == null) { return mergePolicyMap.get(MapConfig.DEFAULT_MAP_MERGE_POLICY); } return mergePolicy; } public class Merger implements Runnable { Map<MapContainer, Collection<Record>> recordMap; public Merger(Map<MapContainer, Collection<Record>> recordMap) { this.recordMap = recordMap; } public void run() { for (final MapContainer mapContainer : recordMap.keySet()) { Collection<Record> recordList = recordMap.get(mapContainer); String mergePolicyName = mapContainer.getMapConfig().getMergePolicy(); MapMergePolicy mergePolicy = getMergePolicy(mergePolicyName); // todo number of records may be high. below can be optimized a many records can be send in single invocation final MapMergePolicy finalMergePolicy = mergePolicy; for (final Record record : recordList) { // todo too many submission. should submit them in subgroups nodeEngine.getExecutionService().submit("hz:map-merge", new Runnable() { public void run() { final SimpleEntryView entryView = createSimpleEntryView(record.getKey(), toData(record.getValue()), record); MergeOperation operation = new MergeOperation(mapContainer.getName(), record.getKey(), entryView, finalMergePolicy); try { int partitionId = nodeEngine.getPartitionService().getPartitionId(record.getKey()); Future f = nodeEngine.getOperationService().invokeOnPartition(SERVICE_NAME, operation, partitionId); f.get(); } catch (Throwable t) { throw ExceptionUtil.rethrow(t); } } }); } } } } public MapContainer getMapContainer(String mapName) { return ConcurrencyUtil.getOrPutSynchronized(mapContainers, mapName, mapContainers, mapConstructor); } public Map<String, MapContainer> getMapContainers() { return Collections.unmodifiableMap(mapContainers); } public PartitionContainer getPartitionContainer(int partitionId) { return partitionContainers[partitionId]; } public RecordStore getRecordStore(int partitionId, String mapName) { return getPartitionContainer(partitionId).getRecordStore(mapName); } public RecordStore getExistingRecordStore(int partitionId, String mapName) { return getPartitionContainer(partitionId).getExistingRecordStore(mapName); } public List<Integer> getOwnedPartitions() { List<Integer> partitions = ownedPartitions.get(); if (partitions == null) { partitions = getMemberPartitions(); ownedPartitions.set(partitions); } return partitions; } private List<Integer> getMemberPartitions() { InternalPartitionService partitionService = nodeEngine.getPartitionService(); List<Integer> partitions = partitionService.getMemberPartitions(nodeEngine.getThisAddress()); return Collections.unmodifiableList(partitions); } @Override public void beforeMigration(PartitionMigrationEvent event) { } @Override public Operation prepareReplicationOperation(PartitionReplicationEvent event) { final PartitionContainer container = partitionContainers[event.getPartitionId()]; final MapReplicationOperation operation = new MapReplicationOperation(this, container, event.getPartitionId(), event.getReplicaIndex()); operation.setService(MapService.this); return operation.isEmpty() ? null : operation; } @Override public void commitMigration(PartitionMigrationEvent event) { migrateIndex(event); if (event.getMigrationEndpoint() == MigrationEndpoint.SOURCE) { clearPartitionData(event.getPartitionId()); } ownedPartitions.set(getMemberPartitions()); } private void migrateIndex(PartitionMigrationEvent event) { final PartitionContainer container = partitionContainers[event.getPartitionId()]; for (RecordStore recordStore : container.getMaps().values()) { final MapContainer mapContainer = getMapContainer(recordStore.getName()); final IndexService indexService = mapContainer.getIndexService(); if (indexService.hasIndex()) { for (Record record : recordStore.getReadonlyRecordMap().values()) { if (event.getMigrationEndpoint() == MigrationEndpoint.SOURCE) { indexService.removeEntryIndex(record.getKey()); } else { Object value = record.getValue(); if (value != null) { indexService.saveEntryIndex(new QueryEntry(getSerializationService(), record.getKey(), record.getKey(), value)); } } } } } } @Override public void rollbackMigration(PartitionMigrationEvent event) { if (event.getMigrationEndpoint() == MigrationEndpoint.DESTINATION) { clearPartitionData(event.getPartitionId()); } ownedPartitions.set(getMemberPartitions()); } private void clearPartitionData(final int partitionId) { final PartitionContainer container = partitionContainers[partitionId]; if (container != null) { for (RecordStore mapPartition : container.getMaps().values()) { mapPartition.clearPartition(); } container.getMaps().clear(); } } @Override public void clearPartitionReplica(int partitionId) { clearPartitionData(partitionId); } public Record createRecord(String name, Data dataKey, Object value, long ttl) { final long nowInNanos = System.nanoTime(); MapContainer mapContainer = getMapContainer(name); Record record = mapContainer.getRecordFactory().newRecord(dataKey, value); record.setLastAccessTime(nowInNanos); record.setLastUpdateTime(nowInNanos); final int timeToLiveSeconds = mapContainer.getMapConfig().getTimeToLiveSeconds(); if (ttl < 0L && timeToLiveSeconds > 0) { record.setTtl(TimeUnit.SECONDS.toNanos(timeToLiveSeconds)); } else if (ttl > 0L) { record.setTtl(TimeUnit.MILLISECONDS.toNanos(ttl)); } return record; } @SuppressWarnings("unchecked") public TransactionalMapProxy createTransactionalObject(String name, TransactionSupport transaction) { return new TransactionalMapProxy(name, this, nodeEngine, transaction); } @Override public void rollbackTransaction(String transactionId) { } private final ConstructorFunction<String, NearCache> nearCacheConstructor = new ConstructorFunction<String, NearCache>() { public NearCache createNew(String mapName) { return new NearCache(mapName, MapService.this); } }; public NearCache getNearCache(String mapName) { return ConcurrencyUtil.getOrPutIfAbsent(nearCacheMap, mapName, nearCacheConstructor); } // this operation returns the given value in near-cache memory format (data or object) // if near-cache is not enabled, it returns null public Object putNearCache(String mapName, Data key, Data value) { // todo assert near-cache is enabled might be better if (!isNearCacheEnabled(mapName)) { return null; } NearCache nearCache = getNearCache(mapName); return nearCache.put(key, value); } public void invalidateNearCache(String mapName, Data key) { if (!isNearCacheEnabled(mapName)) { return; } NearCache nearCache = getNearCache(mapName); nearCache.invalidate(key); } public void invalidateNearCache(String mapName, Set<Data> keys) { if (!isNearCacheEnabled(mapName)) { return; } NearCache nearCache = getNearCache(mapName); nearCache.invalidate(keys); } public void clearNearCache(String mapName) { if (!isNearCacheEnabled(mapName)) { return; } final NearCache nearCache = nearCacheMap.get(mapName); if (nearCache != null) { nearCache.clear(); } } public void invalidateAllNearCaches(String mapName, Data key) { if (!isNearCacheEnabled(mapName)) { return; } Collection<MemberImpl> members = nodeEngine.getClusterService().getMemberList(); for (MemberImpl member : members) { try { if (member.localMember()) continue; Operation operation = new InvalidateNearCacheOperation(mapName, key).setServiceName(SERVICE_NAME); nodeEngine.getOperationService().send(operation, member.getAddress()); } catch (Throwable throwable) { throw new HazelcastException(throwable); } } // below local invalidation is for the case the data is cached before partition is owned/migrated invalidateNearCache(mapName, key); } public boolean isNearCacheAndInvalidationEnabled(String mapName) { final MapContainer mapContainer = getMapContainer(mapName); return mapContainer.isNearCacheEnabled() && mapContainer.getMapConfig().getNearCacheConfig().isInvalidateOnChange(); } public boolean isNearCacheEnabled(String mapName) { final MapContainer mapContainer = getMapContainer(mapName); return mapContainer.isNearCacheEnabled(); } public void invalidateAllNearCaches(String mapName, Set<Data> keys) { if (!isNearCacheEnabled(mapName)) { return; } if (keys == null || keys.isEmpty()) { return; } //send operation. Operation operation = new NearCacheKeySetInvalidationOperation(mapName, keys).setServiceName(SERVICE_NAME); Collection<MemberImpl> members = nodeEngine.getClusterService().getMemberList(); for (MemberImpl member : members) { try { if (member.localMember()) continue; nodeEngine.getOperationService().send(operation, member.getAddress()); } catch (Throwable throwable) { logger.warning(throwable); } } // below local invalidation is for the case the data is cached before partition is owned/migrated for (final Data key : keys) { invalidateNearCache(mapName, key); } } public Object getFromNearCache(String mapName, Data key) { if (!isNearCacheEnabled(mapName)) { return null; } NearCache nearCache = getNearCache(mapName); return nearCache.get(key); } public NodeEngine getNodeEngine() { return nodeEngine; } public MapProxyImpl createDistributedObject(String name) { return new MapProxyImpl(name, this, nodeEngine); } public void destroyDistributedObject(String name) { MapContainer mapContainer = mapContainers.remove(name); if (mapContainer != null) { if (mapContainer.isNearCacheEnabled()) { NearCache nearCache = nearCacheMap.remove(name); if (nearCache != null) { nearCache.clear(); } } mapContainer.shutDownMapStoreScheduledExecutor(); } final PartitionContainer[] containers = partitionContainers; for (PartitionContainer container : containers) { if (container != null) { container.destroyMap(name); } } nodeEngine.getEventService().deregisterAllListeners(SERVICE_NAME, name); } public String addInterceptor(String mapName, MapInterceptor interceptor) { return getMapContainer(mapName).addInterceptor(interceptor); } public void removeInterceptor(String mapName, String id) { getMapContainer(mapName).removeInterceptor(id); } // todo interceptors should get a wrapped object which includes the serialized version public Object interceptGet(String mapName, Object value) { List<MapInterceptor> interceptors = getMapContainer(mapName).getInterceptors(); Object result = null; if (!interceptors.isEmpty()) { result = toObject(value); for (MapInterceptor interceptor : interceptors) { Object temp = interceptor.interceptGet(result); if (temp != null) { result = temp; } } } return result == null ? value : result; } public void interceptAfterGet(String mapName, Object value) { List<MapInterceptor> interceptors = getMapContainer(mapName).getInterceptors(); if (!interceptors.isEmpty()) { value = toObject(value); for (MapInterceptor interceptor : interceptors) { interceptor.afterGet(value); } } } public Object interceptPut(String mapName, Object oldValue, Object newValue) { List<MapInterceptor> interceptors = getMapContainer(mapName).getInterceptors(); Object result = null; if (!interceptors.isEmpty()) { result = toObject(newValue); oldValue = toObject(oldValue); for (MapInterceptor interceptor : interceptors) { Object temp = interceptor.interceptPut(oldValue, result); if (temp != null) { result = temp; } } } return result == null ? newValue : result; } public void interceptAfterPut(String mapName, Object newValue) { List<MapInterceptor> interceptors = getMapContainer(mapName).getInterceptors(); if (!interceptors.isEmpty()) { newValue = toObject(newValue); for (MapInterceptor interceptor : interceptors) { interceptor.afterPut(newValue); } } } public Object interceptRemove(String mapName, Object value) { List<MapInterceptor> interceptors = getMapContainer(mapName).getInterceptors(); Object result = null; if (!interceptors.isEmpty()) { result = toObject(value); for (MapInterceptor interceptor : interceptors) { Object temp = interceptor.interceptRemove(result); if (temp != null) { result = temp; } } } return result == null ? value : result; } public void interceptAfterRemove(String mapName, Object value) { List<MapInterceptor> interceptors = getMapContainer(mapName).getInterceptors(); if (!interceptors.isEmpty()) { for (MapInterceptor interceptor : interceptors) { value = toObject(value); interceptor.afterRemove(value); } } } public void publishWanReplicationUpdate(String mapName, EntryView entryView) { MapContainer mapContainer = getMapContainer(mapName); MapReplicationUpdate replicationEvent = new MapReplicationUpdate(mapName, mapContainer.getWanMergePolicy(), entryView); mapContainer.getWanReplicationPublisher().publishReplicationEvent(SERVICE_NAME, replicationEvent); } public void publishWanReplicationRemove(String mapName, Data key, long removeTime) { MapContainer mapContainer = getMapContainer(mapName); MapReplicationRemove replicationEvent = new MapReplicationRemove(mapName, key, removeTime); mapContainer.getWanReplicationPublisher().publishReplicationEvent(SERVICE_NAME, replicationEvent); } public void publishEvent(Address caller, String mapName, EntryEventType eventType, Data dataKey, Data dataOldValue, Data dataValue) { Collection<EventRegistration> candidates = nodeEngine.getEventService().getRegistrations(SERVICE_NAME, mapName); Set<EventRegistration> registrationsWithValue = new HashSet<EventRegistration>(); Set<EventRegistration> registrationsWithoutValue = new HashSet<EventRegistration>(); if (candidates.isEmpty()) return; Object key = null; Object value = null; Object oldValue = null; for (EventRegistration candidate : candidates) { EventFilter filter = candidate.getFilter(); if (filter instanceof EventServiceImpl.EmptyFilter) { registrationsWithValue.add(candidate); } else if (filter instanceof QueryEventFilter) { Object testValue; if (eventType == EntryEventType.REMOVED || eventType == EntryEventType.EVICTED) { oldValue = oldValue != null ? oldValue : toObject(dataOldValue); testValue = oldValue; } else { value = value != null ? value : toObject(dataValue); testValue = value; } key = key != null ? key : toObject(dataKey); QueryEventFilter queryEventFilter = (QueryEventFilter) filter; QueryEntry entry = new QueryEntry(getSerializationService(), dataKey, key, testValue); if (queryEventFilter.eval(entry)) { if (queryEventFilter.isIncludeValue()) { registrationsWithValue.add(candidate); } else { registrationsWithoutValue.add(candidate); } } } else if (filter.eval(dataKey)) { EntryEventFilter eventFilter = (EntryEventFilter) filter; if (eventFilter.isIncludeValue()) { registrationsWithValue.add(candidate); } else { registrationsWithoutValue.add(candidate); } } } if (registrationsWithValue.isEmpty() && registrationsWithoutValue.isEmpty()) return; String source = nodeEngine.getThisAddress().toString(); if (eventType == EntryEventType.REMOVED || eventType == EntryEventType.EVICTED) { dataValue = dataValue != null ? dataValue : dataOldValue; } EventData event = new EventData(source, mapName, caller, dataKey, dataValue, dataOldValue, eventType.getType()); int orderKey = dataKey.hashCode(); nodeEngine.getEventService().publishEvent(SERVICE_NAME, registrationsWithValue, event, orderKey); nodeEngine.getEventService().publishEvent(SERVICE_NAME, registrationsWithoutValue, event.cloneWithoutValues(), orderKey); } public String addLocalEventListener(EntryListener entryListener, String mapName) { EventRegistration registration = nodeEngine.getEventService().registerLocalListener(SERVICE_NAME, mapName, entryListener); return registration.getId(); } public String addLocalEventListener(EntryListener entryListener, EventFilter eventFilter, String mapName) { EventRegistration registration = nodeEngine.getEventService().registerLocalListener(SERVICE_NAME, mapName, eventFilter, entryListener); return registration.getId(); } public String addEventListener(EntryListener entryListener, EventFilter eventFilter, String mapName) { EventRegistration registration = nodeEngine.getEventService().registerListener(SERVICE_NAME, mapName, eventFilter, entryListener); return registration.getId(); } public boolean removeEventListener(String mapName, String registrationId) { return nodeEngine.getEventService().deregisterListener(SERVICE_NAME, mapName, registrationId); } public void applyRecordInfo(Record record, RecordInfo replicationInfo) { record.setStatistics(replicationInfo.getStatistics()); record.setVersion(replicationInfo.getVersion()); record.setEvictionCriteriaNumber(replicationInfo.getEvictionCriteriaNumber()); record.setTtl(replicationInfo.getTtl()); record.setLastAccessTime(replicationInfo.getLastAccessTime()); record.setLastUpdateTime(replicationInfo.getLastUpdateTime()); } public RecordReplicationInfo createRecordReplicationInfo(Record record) { final RecordInfo info = createRecordInfo(record); return new RecordReplicationInfo(record.getKey(), toData(record.getValue()), info); } public RecordInfo createRecordInfo(Record record) { final RecordInfo info = new RecordInfo(); info.setStatistics(record.getStatistics()); info.setVersion(record.getVersion()); info.setEvictionCriteriaNumber(record.getEvictionCriteriaNumber()); info.setLastAccessTime(record.getLastAccessTime()); info.setLastUpdateTime(record.getLastUpdateTime()); info.setTtl(record.getTtl()); return info; } public DelayedEntry<Data, Object> constructDelayedEntry(Data key, Object value, int partitionId, long writeDelayMillis) { final long now = System.nanoTime(); final long nanoWriteDelay = TimeUnit.MILLISECONDS.toNanos(writeDelayMillis); final DelayedEntry<Data, Object> delayedEntry = DelayedEntry.create(key, value, now + nanoWriteDelay, partitionId); return delayedEntry; } public <K, V> SimpleEntryView<K, V> createSimpleEntryView(K key, V value, Record record) { final TimeUnit unit = TimeUnit.NANOSECONDS; final SimpleEntryView simpleEntryView = new SimpleEntryView(key, value); simpleEntryView.setCost(record.getCost()); simpleEntryView.setVersion(record.getVersion()); simpleEntryView.setEvictionCriteriaNumber(record.getEvictionCriteriaNumber()); simpleEntryView.setLastAccessTime(unit.toMillis(record.getLastAccessTime())); simpleEntryView.setLastUpdateTime(unit.toMillis(record.getLastUpdateTime())); simpleEntryView.setTtl(unit.toMillis(record.getTtl())); final RecordStatistics statistics = record.getStatistics(); if (statistics != null) { simpleEntryView.setHits(statistics.getHits()); simpleEntryView.setCreationTime(unit.toMillis(statistics.getCreationTime())); simpleEntryView.setExpirationTime(unit.toMillis(statistics.getExpirationTime())); simpleEntryView.setLastStoredTime(unit.toMillis(statistics.getLastStoredTime())); } return simpleEntryView; } public Object toObject(Object data) { if (data == null) return null; if (data instanceof Data) { return nodeEngine.toObject(data); } else { return data; } } public Data toData(Object object, PartitioningStrategy partitionStrategy) { if (object == null) return null; if (object instanceof Data) { return (Data) object; } else { return nodeEngine.getSerializationService().toData(object, partitionStrategy); } } public Data toData(Object object) { if (object == null) return null; if (object instanceof Data) { return (Data) object; } else { return nodeEngine.getSerializationService().toData(object); } } public boolean compare(String mapName, Object value1, Object value2) { if (value1 == null && value2 == null) { return true; } if (value1 == null) { return false; } if (value2 == null) { return false; } MapContainer mapContainer = getMapContainer(mapName); return mapContainer.getRecordFactory().isEquals(value1, value2); } @SuppressWarnings("unchecked") public void dispatchEvent(EventData eventData, EntryListener listener) { Member member = nodeEngine.getClusterService().getMember(eventData.getCaller()); EntryEvent event = new DataAwareEntryEvent(member, eventData.getEventType(), eventData.getMapName(), eventData.getDataKey(), eventData.getDataNewValue(), eventData.getDataOldValue(), getSerializationService()); switch (event.getEventType()) { case ADDED: listener.entryAdded(event); break; case EVICTED: listener.entryEvicted(event); break; case UPDATED: listener.entryUpdated(event); break; case REMOVED: listener.entryRemoved(event); break; default: throw new IllegalArgumentException("Invalid event type: " + event.getEventType()); } MapContainer mapContainer = getMapContainer(eventData.getMapName()); if (mapContainer.getMapConfig().isStatisticsEnabled()) { getLocalMapStatsImpl(eventData.getMapName()).incrementReceivedEvents(); } } public SerializationService getSerializationService() { return nodeEngine.getSerializationService(); } public QueryResult queryOnPartition(String mapName, Predicate predicate, int partitionId) { final QueryResult result = new QueryResult(); List<QueryEntry> list = new LinkedList<QueryEntry>(); PartitionContainer container = getPartitionContainer(partitionId); RecordStore recordStore = container.getRecordStore(mapName); Map<Data, Record> records = recordStore.getReadonlyRecordMap(); SerializationService serializationService = nodeEngine.getSerializationService(); final PagingPredicate pagingPredicate = predicate instanceof PagingPredicate ? (PagingPredicate) predicate : null; Comparator<Map.Entry> wrapperComparator = SortingUtil.newComparator(pagingPredicate); for (Record record : records.values()) { Data key = record.getKey(); Object value = record.getValue(); if (value == null) { continue; } QueryEntry queryEntry = new QueryEntry(serializationService, key, key, value); if (predicate.apply(queryEntry)) { if (pagingPredicate != null) { Map.Entry anchor = pagingPredicate.getAnchor(); if (anchor != null && SortingUtil.compare(pagingPredicate.getComparator(), pagingPredicate.getIterationType(), anchor, queryEntry) >= 0) { continue; } } list.add(queryEntry); } } if (pagingPredicate != null) { Collections.sort(list, wrapperComparator); if (list.size() > pagingPredicate.getPageSize()) { list = list.subList(0, pagingPredicate.getPageSize()); } } for (QueryEntry entry : list) { result.add(new QueryResultEntryImpl(entry.getKeyData(), entry.getKeyData(), entry.getValueData())); } return result; } public LocalMapStatsImpl createLocalMapStats(String mapName) { MapContainer mapContainer = getMapContainer(mapName); LocalMapStatsImpl localMapStats = getLocalMapStatsImpl(mapName); if (!mapContainer.getMapConfig().isStatisticsEnabled()) { return localMapStats; } long ownedEntryCount = 0; long backupEntryCount = 0; long dirtyCount = 0; long ownedEntryMemoryCost = 0; long backupEntryMemoryCost = 0; long hits = 0; long lockedEntryCount = 0; long heapCost = 0; int backupCount = mapContainer.getTotalBackupCount(); ClusterService clusterService = nodeEngine.getClusterService(); final InternalPartitionService partitionService = nodeEngine.getPartitionService(); final TimeUnit unit = TimeUnit.NANOSECONDS; Address thisAddress = clusterService.getThisAddress(); for (int partitionId = 0; partitionId < partitionService.getPartitionCount(); partitionId++) { InternalPartition partition = partitionService.getPartition(partitionId); Address owner = partition.getOwnerOrNull(); if (owner == null) { //no-op because no owner is set yet. Therefor we don't know anything about the map continue; } if (owner.equals(thisAddress)) { PartitionContainer partitionContainer = getPartitionContainer(partitionId); RecordStore recordStore = partitionContainer.getExistingRecordStore(mapName); //we don't want to force loading the record store because we are loading statistics. So that is why //we ask for 'getExistingRecordStore' instead of 'getRecordStore' which does the load. if (recordStore != null) { heapCost += recordStore.getHeapCost(); Map<Data, Record> records = recordStore.getReadonlyRecordMap(); for (Record record : records.values()) { RecordStatistics stats = record.getStatistics(); // there is map store and the record is dirty (waits to be stored) ownedEntryCount++; ownedEntryMemoryCost += record.getCost(); localMapStats.setLastAccessTime(unit.toMillis(record.getLastAccessTime())); localMapStats.setLastUpdateTime(unit.toMillis(record.getLastUpdateTime())); hits += stats.getHits(); if (recordStore.isLocked(record.getKey())) { lockedEntryCount++; } } dirtyCount += recordStore.getWriteBehindQueue().size(); } } else { for (int replica = 1; replica <= backupCount; replica++) { Address replicaAddress = partition.getReplicaAddress(replica); int tryCount = 30; // wait if the partition table is not updated yet while (replicaAddress == null && clusterService.getSize() > backupCount && tryCount-- > 0) { try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { throw ExceptionUtil.rethrow(e); } replicaAddress = partition.getReplicaAddress(replica); } if (replicaAddress != null && replicaAddress.equals(thisAddress)) { PartitionContainer partitionContainer = getPartitionContainer(partitionId); RecordStore recordStore = partitionContainer.getRecordStore(mapName); heapCost += recordStore.getHeapCost(); Map<Data, Record> records = recordStore.getReadonlyRecordMap(); for (Record record : records.values()) { backupEntryCount++; backupEntryMemoryCost += record.getCost(); } } else if (replicaAddress == null && clusterService.getSize() > backupCount) { logger.warning("Partition: " + partition + ", replica: " + replica + " has no owner!"); } } } } localMapStats.setBackupCount(backupCount); localMapStats.setDirtyEntryCount(zeroOrPositive(dirtyCount)); localMapStats.setLockedEntryCount(zeroOrPositive(lockedEntryCount)); localMapStats.setHits(zeroOrPositive(hits)); localMapStats.setOwnedEntryCount(zeroOrPositive(ownedEntryCount)); localMapStats.setBackupEntryCount(zeroOrPositive(backupEntryCount)); localMapStats.setOwnedEntryMemoryCost(zeroOrPositive(ownedEntryMemoryCost)); localMapStats.setBackupEntryMemoryCost(zeroOrPositive(backupEntryMemoryCost)); // add near cache heap cost. heapCost += mapContainer.getNearCacheSizeEstimator().getSize(); localMapStats.setHeapCost(heapCost); if (mapContainer.getMapConfig().isNearCacheEnabled()) { NearCacheStatsImpl nearCacheStats = getNearCache(mapName).getNearCacheStats(); localMapStats.setNearCacheStats(nearCacheStats); } return localMapStats; } static long zeroOrPositive(long value) { return (value > 0) ? value : 0; } }
1no label
hazelcast_src_main_java_com_hazelcast_map_MapService.java
746
public class ListSubRequest extends CollectionRequest { private int from; private int to; public ListSubRequest() { } public ListSubRequest(String name, int from, int to) { super(name); this.from = from; this.to = to; } @Override protected Operation prepareOperation() { return new ListSubOperation(name, from, to); } @Override public int getClassId() { return CollectionPortableHook.LIST_SUB; } public void write(PortableWriter writer) throws IOException { super.write(writer); writer.writeInt("f", from); writer.writeInt("t", to); } public void read(PortableReader reader) throws IOException { super.read(reader); from = reader.readInt("f"); to = reader.readInt("t"); } @Override public String getRequiredAction() { return ActionConstants.ACTION_READ; } }
0true
hazelcast_src_main_java_com_hazelcast_collection_client_ListSubRequest.java
1,060
public enum LoginModuleUsage { REQUIRED, REQUISITE, SUFFICIENT, OPTIONAL; public static LoginModuleUsage get(String v) { try { return LoginModuleUsage.valueOf(v.toUpperCase()); } catch (Exception ignore) { } return REQUIRED; } }
0true
hazelcast_src_main_java_com_hazelcast_config_LoginModuleConfig.java
658
@Repository("blCategoryXrefDao") public class CategoryXrefDaoImpl implements CategoryXrefDao { @PersistenceContext(unitName="blPU") protected EntityManager em; @Resource(name="blEntityConfiguration") protected EntityConfiguration entityConfiguration; @Override public List<CategoryXrefImpl> readXrefsByCategoryId(Long categoryId){ TypedQuery<CategoryXrefImpl> query = em.createNamedQuery("BC_READ_CATEGORY_XREF_BY_CATEGORYID", CategoryXrefImpl.class); query.setParameter("categoryId", categoryId); return query.getResultList(); } @Override public List<CategoryXrefImpl> readXrefsBySubCategoryId(Long subCategoryId){ TypedQuery<CategoryXrefImpl> query = em.createNamedQuery("BC_READ_CATEGORY_XREF_BY_SUBCATEGORYID", CategoryXrefImpl.class); query.setParameter("subCategoryId", subCategoryId); return query.getResultList(); } @Override public CategoryXrefImpl readXrefByIds(Long categoryId, Long subCategoryId){ Query query = em.createNamedQuery("BC_READ_CATEGORY_XREF_BY_IDS"); query.setParameter("categoryId", categoryId); query.setParameter("subCategoryId", subCategoryId); return (CategoryXrefImpl)query.getSingleResult(); } @Override public CategoryXref save(CategoryXrefImpl categoryXref){ return em.merge(categoryXref); } @Override public void delete(CategoryXrefImpl categoryXref){ if (!em.contains(categoryXref)) { categoryXref = readXrefByIds(categoryXref.getCategory().getId(), categoryXref.getSubCategory().getId()); } em.remove(categoryXref); } @Override public CategoryProductXrefImpl save(CategoryProductXrefImpl categoryProductXref){ return em.merge(categoryProductXref); } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_dao_CategoryXrefDaoImpl.java
3,107
public interface IgnoreOnRecoveryEngineException { }
0true
src_main_java_org_elasticsearch_index_engine_IgnoreOnRecoveryEngineException.java
759
public class OSBTreeBonsaiBucket<K, V> extends OBonsaiBucketAbstract { /** * Maximum size of key-value pair which can be put in SBTreeBonsai in bytes (24576000 by default) */ private static final int MAX_ENTREE_SIZE = 24576000; private static final int FREE_POINTER_OFFSET = WAL_POSITION_OFFSET + OLongSerializer.LONG_SIZE; private static final int SIZE_OFFSET = FREE_POINTER_OFFSET + OIntegerSerializer.INT_SIZE; private static final int IS_LEAF_OFFSET = SIZE_OFFSET + OIntegerSerializer.INT_SIZE; private static final int FREE_LIST_POINTER_OFFSET = IS_LEAF_OFFSET + OByteSerializer.BYTE_SIZE; private static final int LEFT_SIBLING_OFFSET = FREE_LIST_POINTER_OFFSET + OBonsaiBucketPointer.SIZE; private static final int RIGHT_SIBLING_OFFSET = LEFT_SIBLING_OFFSET + OBonsaiBucketPointer.SIZE; private static final int TREE_SIZE_OFFSET = RIGHT_SIBLING_OFFSET + OBonsaiBucketPointer.SIZE; private static final int KEY_SERIALIZER_OFFSET = TREE_SIZE_OFFSET + OLongSerializer.LONG_SIZE; private static final int VALUE_SERIALIZER_OFFSET = KEY_SERIALIZER_OFFSET + OByteSerializer.BYTE_SIZE; private static final int POSITIONS_ARRAY_OFFSET = VALUE_SERIALIZER_OFFSET + OByteSerializer.BYTE_SIZE; public static final int MAX_BUCKET_SIZE_BYTES = OGlobalConfiguration.SBTREEBONSAI_BUCKET_SIZE.getValueAsInteger() * 1024; private final boolean isLeaf; private final int offset; private final OBinarySerializer<K> keySerializer; private final OBinarySerializer<V> valueSerializer; private final Comparator<? super K> comparator = ODefaultComparator.INSTANCE; public OSBTreeBonsaiBucket(ODirectMemoryPointer cachePointer, int pageOffset, boolean isLeaf, OBinarySerializer<K> keySerializer, OBinarySerializer<V> valueSerializer, TrackMode trackMode) throws IOException { super(cachePointer, trackMode); this.offset = pageOffset; this.isLeaf = isLeaf; this.keySerializer = keySerializer; this.valueSerializer = valueSerializer; setIntValue(offset + FREE_POINTER_OFFSET, MAX_BUCKET_SIZE_BYTES); setIntValue(offset + SIZE_OFFSET, 0); setByteValue(offset + IS_LEAF_OFFSET, (byte) (isLeaf ? 1 : 0)); setLongValue(offset + LEFT_SIBLING_OFFSET, -1); setLongValue(offset + RIGHT_SIBLING_OFFSET, -1); setLongValue(offset + TREE_SIZE_OFFSET, 0); setByteValue(offset + KEY_SERIALIZER_OFFSET, keySerializer.getId()); setByteValue(offset + VALUE_SERIALIZER_OFFSET, valueSerializer.getId()); } public OSBTreeBonsaiBucket(ODirectMemoryPointer cachePointer, int pageOffset, OBinarySerializer<K> keySerializer, OBinarySerializer<V> valueSerializer, TrackMode trackMode) { super(cachePointer, trackMode); this.offset = pageOffset; this.isLeaf = getByteValue(offset + IS_LEAF_OFFSET) > 0; this.keySerializer = keySerializer; this.valueSerializer = valueSerializer; } public byte getKeySerializerId() { return getByteValue(offset + KEY_SERIALIZER_OFFSET); } public void setKeySerializerId(byte keySerializerId) { setByteValue(offset + KEY_SERIALIZER_OFFSET, keySerializerId); } public byte getValueSerializerId() { return getByteValue(offset + VALUE_SERIALIZER_OFFSET); } public void setValueSerializerId(byte valueSerializerId) { setByteValue(offset + VALUE_SERIALIZER_OFFSET, valueSerializerId); } public void setTreeSize(long size) throws IOException { setLongValue(offset + TREE_SIZE_OFFSET, size); } public long getTreeSize() { return getLongValue(offset + TREE_SIZE_OFFSET); } public boolean isEmpty() { return size() == 0; } public int find(K key) { int low = 0; int high = size() - 1; while (low <= high) { int mid = (low + high) >>> 1; K midVal = getKey(mid); int cmp = comparator.compare(midVal, key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } public void remove(int entryIndex) throws IOException { int entryPosition = getIntValue(offset + POSITIONS_ARRAY_OFFSET + entryIndex * OIntegerSerializer.INT_SIZE); int entrySize = keySerializer.getObjectSizeInDirectMemory(pagePointer, offset + entryPosition); if (isLeaf) { if (valueSerializer.isFixedLength()) entrySize += valueSerializer.getFixedLength(); else entrySize += valueSerializer.getObjectSizeInDirectMemory(pagePointer, offset + entryPosition + entrySize); } else { throw new IllegalStateException("Remove is applies to leaf buckets only"); } int size = size(); if (entryIndex < size - 1) { moveData(offset + POSITIONS_ARRAY_OFFSET + (entryIndex + 1) * OIntegerSerializer.INT_SIZE, offset + POSITIONS_ARRAY_OFFSET + entryIndex * OIntegerSerializer.INT_SIZE, (size - entryIndex - 1) * OIntegerSerializer.INT_SIZE); } size--; setIntValue(offset + SIZE_OFFSET, size); int freePointer = getIntValue(offset + FREE_POINTER_OFFSET); if (size > 0 && entryPosition > freePointer) { moveData(offset + freePointer, offset + freePointer + entrySize, entryPosition - freePointer); } setIntValue(offset + FREE_POINTER_OFFSET, freePointer + entrySize); int currentPositionOffset = offset + POSITIONS_ARRAY_OFFSET; for (int i = 0; i < size; i++) { int currentEntryPosition = getIntValue(currentPositionOffset); if (currentEntryPosition < entryPosition) setIntValue(currentPositionOffset, currentEntryPosition + entrySize); currentPositionOffset += OIntegerSerializer.INT_SIZE; } } public int size() { return getIntValue(offset + SIZE_OFFSET); } public SBTreeEntry<K, V> getEntry(int entryIndex) { int entryPosition = getIntValue(offset + entryIndex * OIntegerSerializer.INT_SIZE + POSITIONS_ARRAY_OFFSET); if (isLeaf) { K key = keySerializer.deserializeFromDirectMemory(pagePointer, offset + entryPosition); entryPosition += keySerializer.getObjectSizeInDirectMemory(pagePointer, offset + entryPosition); V value = valueSerializer.deserializeFromDirectMemory(pagePointer, offset + entryPosition); return new SBTreeEntry<K, V>(OBonsaiBucketPointer.NULL, OBonsaiBucketPointer.NULL, key, value); } else { OBonsaiBucketPointer leftChild = getBucketPointer(offset + entryPosition); entryPosition += OBonsaiBucketPointer.SIZE; OBonsaiBucketPointer rightChild = getBucketPointer(offset + entryPosition); entryPosition += OBonsaiBucketPointer.SIZE; K key = keySerializer.deserializeFromDirectMemory(pagePointer, offset + entryPosition); return new SBTreeEntry<K, V>(leftChild, rightChild, key, null); } } public K getKey(int index) { int entryPosition = getIntValue(offset + index * OIntegerSerializer.INT_SIZE + POSITIONS_ARRAY_OFFSET); if (!isLeaf) entryPosition += 2 * (OLongSerializer.LONG_SIZE + OIntegerSerializer.INT_SIZE); return keySerializer.deserializeFromDirectMemory(pagePointer, offset + entryPosition); } public boolean isLeaf() { return isLeaf; } public void addAll(List<SBTreeEntry<K, V>> entries) throws IOException { for (int i = 0; i < entries.size(); i++) addEntry(i, entries.get(i), false); } public void shrink(int newSize) throws IOException { List<SBTreeEntry<K, V>> treeEntries = new ArrayList<SBTreeEntry<K, V>>(newSize); for (int i = 0; i < newSize; i++) { treeEntries.add(getEntry(i)); } setIntValue(offset + FREE_POINTER_OFFSET, MAX_BUCKET_SIZE_BYTES); setIntValue(offset + SIZE_OFFSET, 0); int index = 0; for (SBTreeEntry<K, V> entry : treeEntries) { addEntry(index, entry, false); index++; } } public boolean addEntry(int index, SBTreeEntry<K, V> treeEntry, boolean updateNeighbors) throws IOException { final int keySize = keySerializer.getObjectSize(treeEntry.key); int valueSize = 0; int entrySize = keySize; if (isLeaf) { if (valueSerializer.isFixedLength()) valueSize = valueSerializer.getFixedLength(); else valueSize = valueSerializer.getObjectSize(treeEntry.value); entrySize += valueSize; checkEntreeSize(entrySize); } else entrySize += 2 * (OLongSerializer.LONG_SIZE + OIntegerSerializer.INT_SIZE); int size = size(); int freePointer = getIntValue(offset + FREE_POINTER_OFFSET); if (freePointer - entrySize < (size + 1) * OIntegerSerializer.INT_SIZE + POSITIONS_ARRAY_OFFSET) { if (size > 1) return false; else throw new OSBTreeException("Entry size ('key + value') is more than is more than allowed " + (freePointer - 2 * OIntegerSerializer.INT_SIZE + POSITIONS_ARRAY_OFFSET) + " bytes, either increase page size using '" + OGlobalConfiguration.SBTREEBONSAI_BUCKET_SIZE.getKey() + "' parameter, or decrease 'key + value' size."); } if (index <= size - 1) { moveData(offset + POSITIONS_ARRAY_OFFSET + index * OIntegerSerializer.INT_SIZE, offset + POSITIONS_ARRAY_OFFSET + (index + 1) * OIntegerSerializer.INT_SIZE, (size - index) * OIntegerSerializer.INT_SIZE); } freePointer -= entrySize; setIntValue(offset + FREE_POINTER_OFFSET, freePointer); setIntValue(offset + POSITIONS_ARRAY_OFFSET + index * OIntegerSerializer.INT_SIZE, freePointer); setIntValue(offset + SIZE_OFFSET, size + 1); if (isLeaf) { byte[] serializedKey = new byte[keySize]; keySerializer.serializeNative(treeEntry.key, serializedKey, 0); setBinaryValue(offset + freePointer, serializedKey); freePointer += keySize; byte[] serializedValue = new byte[valueSize]; valueSerializer.serializeNative(treeEntry.value, serializedValue, 0); setBinaryValue(offset + freePointer, serializedValue); } else { setBucketPointer(offset + freePointer, treeEntry.leftChild); freePointer += OLongSerializer.LONG_SIZE + OIntegerSerializer.INT_SIZE; setBucketPointer(offset + freePointer, treeEntry.rightChild); freePointer += OLongSerializer.LONG_SIZE + OIntegerSerializer.INT_SIZE; byte[] serializedKey = new byte[keySize]; keySerializer.serializeNative(treeEntry.key, serializedKey, 0); setBinaryValue(offset + freePointer, serializedKey); size++; if (updateNeighbors && size > 1) { if (index < size - 1) { final int nextEntryPosition = getIntValue(offset + POSITIONS_ARRAY_OFFSET + (index + 1) * OIntegerSerializer.INT_SIZE); setBucketPointer(offset + nextEntryPosition, treeEntry.rightChild); } if (index > 0) { final int prevEntryPosition = getIntValue(offset + POSITIONS_ARRAY_OFFSET + (index - 1) * OIntegerSerializer.INT_SIZE); setBucketPointer(offset + prevEntryPosition + OLongSerializer.LONG_SIZE + OIntegerSerializer.INT_SIZE, treeEntry.leftChild); } } } return true; } public int updateValue(int index, V value) throws IOException { assert valueSerializer.isFixedLength(); int entryPosition = getIntValue(offset + index * OIntegerSerializer.INT_SIZE + POSITIONS_ARRAY_OFFSET); entryPosition += keySerializer.getObjectSizeInDirectMemory(pagePointer, offset + entryPosition); final int size = valueSerializer.getFixedLength(); byte[] serializedValue = new byte[size]; valueSerializer.serializeNative(value, serializedValue, 0); byte[] oldSerializedValue = pagePointer.get(offset + entryPosition, size); if (ODefaultComparator.INSTANCE.compare(oldSerializedValue, serializedValue) == 0) return 0; setBinaryValue(offset + entryPosition, serializedValue); return 1; } private void checkEntreeSize(int entreeSize) { if (entreeSize > MAX_ENTREE_SIZE) throw new OSBTreeException("Serialized key-value pair size bigger than allowed " + entreeSize + " vs " + MAX_ENTREE_SIZE + "."); } public void setFreeListPointer(OBonsaiBucketPointer pointer) throws IOException { setBucketPointer(offset + FREE_LIST_POINTER_OFFSET, pointer); } public OBonsaiBucketPointer getFreeListPointer() { return getBucketPointer(offset + FREE_LIST_POINTER_OFFSET); } public void setLeftSibling(OBonsaiBucketPointer pointer) throws IOException { setBucketPointer(offset + LEFT_SIBLING_OFFSET, pointer); } public OBonsaiBucketPointer getLeftSibling() { return getBucketPointer(offset + LEFT_SIBLING_OFFSET); } public void setRightSibling(OBonsaiBucketPointer pointer) throws IOException { setBucketPointer(offset + RIGHT_SIBLING_OFFSET, pointer); } public OBonsaiBucketPointer getRightSibling() { return getBucketPointer(offset + RIGHT_SIBLING_OFFSET); } public static final class SBTreeEntry<K, V> implements Map.Entry<K, V>, Comparable<SBTreeEntry<K, V>> { private final Comparator<? super K> comparator = ODefaultComparator.INSTANCE; public final OBonsaiBucketPointer leftChild; public final OBonsaiBucketPointer rightChild; public final K key; public final V value; public SBTreeEntry(OBonsaiBucketPointer leftChild, OBonsaiBucketPointer rightChild, K key, V value) { this.leftChild = leftChild; this.rightChild = rightChild; this.key = key; this.value = value; } @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(V value) { throw new UnsupportedOperationException("SBTreeEntry.setValue"); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SBTreeEntry that = (SBTreeEntry) o; if (!leftChild.equals(that.leftChild)) return false; if (!rightChild.equals(that.rightChild)) return false; if (!key.equals(that.key)) return false; if (value != null ? !value.equals(that.value) : that.value != null) return false; return true; } @Override public int hashCode() { int result = leftChild.hashCode(); result = 31 * result + rightChild.hashCode(); result = 31 * result + key.hashCode(); result = 31 * result + (value != null ? value.hashCode() : 0); return result; } @Override public String toString() { return "SBTreeEntry{" + "leftChild=" + leftChild + ", rightChild=" + rightChild + ", key=" + key + ", value=" + value + '}'; } @Override public int compareTo(SBTreeEntry<K, V> other) { return comparator.compare(key, other.key); } } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_sbtreebonsai_local_OSBTreeBonsaiBucket.java
2,347
public class StringText implements Text { public static final Text[] EMPTY_ARRAY = new Text[0]; public static Text[] convertFromStringArray(String[] strings) { if (strings.length == 0) { return EMPTY_ARRAY; } Text[] texts = new Text[strings.length]; for (int i = 0; i < strings.length; i++) { texts[i] = new StringText(strings[i]); } return texts; } private final String text; private int hash; public StringText(String text) { this.text = text; } @Override public boolean hasBytes() { return false; } @Override public BytesReference bytes() { return new BytesArray(text.getBytes(Charsets.UTF_8)); } @Override public boolean hasString() { return true; } @Override public String string() { return text; } @Override public String toString() { return string(); } @Override public int hashCode() { // we use bytes here so we can be consistent with other text implementations if (hash == 0) { hash = bytes().hashCode(); } return hash; } @Override public boolean equals(Object obj) { // we use bytes here so we can be consistent with other text implementations return bytes().equals(((Text) obj).bytes()); } @Override public int compareTo(Text text) { return UTF8SortedAsUnicodeComparator.utf8SortedAsUnicodeSortOrder.compare(bytes(), text.bytes()); } }
0true
src_main_java_org_elasticsearch_common_text_StringText.java
1,298
new OCommandOutputListener() { @Override public void onMessage(String text) { System.out.println(text); } });
0true
core_src_test_java_com_orientechnologies_orient_core_storage_impl_local_paginated_LocalPaginatedStorageRestoreTx.java
1,273
public abstract class OStorageLocalAbstract extends OStorageEmbedded implements OFreezableStorage { protected volatile OWriteAheadLog writeAheadLog; protected volatile ODiskCache diskCache; protected OStorageTransaction transaction = null; public OStorageLocalAbstract(String name, String filePath, String mode) { super(name, filePath, mode); } public abstract OStorageVariableParser getVariableParser(); public abstract String getMode(); public abstract String getStoragePath(); protected abstract OPhysicalPosition updateRecord(OCluster cluster, ORecordId rid, byte[] recordContent, ORecordVersion recordVersion, byte recordType); protected abstract OPhysicalPosition createRecord(ODataLocal dataSegment, OCluster cluster, byte[] recordContent, byte recordType, ORecordId rid, ORecordVersion recordVersion); public abstract ODiskCache getDiskCache(); public abstract boolean wasClusterSoftlyClosed(String clusterIndexName); public abstract boolean check(boolean b, OCommandOutputListener dbCheckTest); public OStorageTransaction getStorageTransaction() { lock.acquireSharedLock(); try { return transaction; } finally { lock.releaseSharedLock(); } } @Override public void backup(OutputStream out, Map<String, Object> options, final Callable<Object> callable) throws IOException { freeze(false); try { if (callable != null) try { callable.call(); } catch (Exception e) { OLogManager.instance().error(this, "Error on callback invocation during backup", e); } OZIPCompressionUtil.compressDirectory(getStoragePath(), out); } finally { release(); } } @Override public void restore(InputStream in, Map<String, Object> options, final Callable<Object> callable) throws IOException { if (!isClosed()) close(); OZIPCompressionUtil.uncompressDirectory(in, getStoragePath()); } protected void endStorageTx() throws IOException { if (writeAheadLog == null) return; writeAheadLog.log(new OAtomicUnitEndRecord(transaction.getOperationUnitId(), false)); } protected void startStorageTx(OTransaction clientTx) throws IOException { if (writeAheadLog == null) return; if (transaction != null && transaction.getClientTx().getId() != clientTx.getId()) rollback(clientTx); transaction = new OStorageTransaction(clientTx, OOperationUnitId.generateId()); OLogSequenceNumber startLSN = writeAheadLog.log(new OAtomicUnitStartRecord(true, transaction.getOperationUnitId())); transaction.setStartLSN(startLSN); } protected void rollbackStorageTx() throws IOException { if (writeAheadLog == null || transaction == null) return; writeAheadLog.log(new OAtomicUnitEndRecord(transaction.getOperationUnitId(), true)); final List<OWALRecord> operationUnit = readOperationUnit(transaction.getStartLSN(), transaction.getOperationUnitId()); undoOperation(operationUnit); } private List<OWALRecord> readOperationUnit(OLogSequenceNumber startLSN, OOperationUnitId unitId) throws IOException { final OLogSequenceNumber beginSequence = writeAheadLog.begin(); if (startLSN == null) startLSN = beginSequence; if (startLSN.compareTo(beginSequence) < 0) startLSN = beginSequence; List<OWALRecord> operationUnit = new ArrayList<OWALRecord>(); OLogSequenceNumber lsn = startLSN; while (lsn != null) { OWALRecord record = writeAheadLog.read(lsn); if (!(record instanceof OOperationUnitRecord)) { lsn = writeAheadLog.next(lsn); continue; } OOperationUnitRecord operationUnitRecord = (OOperationUnitRecord) record; if (operationUnitRecord.getOperationUnitId().equals(unitId)) { operationUnit.add(record); if (record instanceof OAtomicUnitEndRecord) break; } lsn = writeAheadLog.next(lsn); } return operationUnit; } protected void undoOperation(List<OWALRecord> operationUnit) throws IOException { for (int i = operationUnit.size() - 1; i >= 0; i--) { OWALRecord record = operationUnit.get(i); if (checkFirstAtomicUnitRecord(i, record)) { assert ((OAtomicUnitStartRecord) record).isRollbackSupported(); continue; } if (checkLastAtomicUnitRecord(i, record, operationUnit.size())) { assert ((OAtomicUnitEndRecord) record).isRollback(); continue; } if (record instanceof OUpdatePageRecord) { OUpdatePageRecord updatePageRecord = (OUpdatePageRecord) record; final long fileId = updatePageRecord.getFileId(); final long pageIndex = updatePageRecord.getPageIndex(); if (!diskCache.isOpen(fileId)) diskCache.openFile(fileId); OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, true); OCachePointer cachePointer = cacheEntry.getCachePointer(); cachePointer.acquireExclusiveLock(); try { ODurablePage durablePage = new ODurablePage(cachePointer.getDataPointer(), ODurablePage.TrackMode.NONE); OPageChanges pageChanges = updatePageRecord.getChanges(); durablePage.revertChanges(pageChanges); durablePage.setLsn(updatePageRecord.getPrevLsn()); } finally { cachePointer.releaseExclusiveLock(); diskCache.release(cacheEntry); } } else { OLogManager.instance().error(this, "Invalid WAL record type was passed %s. Given record will be skipped.", record.getClass()); assert false : "Invalid WAL record type was passed " + record.getClass().getName(); } } } protected boolean checkFirstAtomicUnitRecord(int index, OWALRecord record) { boolean isAtomicUnitStartRecord = record instanceof OAtomicUnitStartRecord; if (isAtomicUnitStartRecord && index != 0) { OLogManager.instance().error(this, "Record %s should be the first record in WAL record list.", OAtomicUnitStartRecord.class.getName()); assert false : "Record " + OAtomicUnitStartRecord.class.getName() + " should be the first record in WAL record list."; } if (index == 0 && !isAtomicUnitStartRecord) { OLogManager.instance().error(this, "Record %s should be the first record in WAL record list.", OAtomicUnitStartRecord.class.getName()); assert false : "Record " + OAtomicUnitStartRecord.class.getName() + " should be the first record in WAL record list."; } return isAtomicUnitStartRecord; } protected boolean checkLastAtomicUnitRecord(int index, OWALRecord record, int size) { boolean isAtomicUnitEndRecord = record instanceof OAtomicUnitEndRecord; if (isAtomicUnitEndRecord && index != size - 1) { OLogManager.instance().error(this, "Record %s should be the last record in WAL record list.", OAtomicUnitEndRecord.class.getName()); assert false : "Record " + OAtomicUnitEndRecord.class.getName() + " should be the last record in WAL record list."; } if (index == size - 1 && !isAtomicUnitEndRecord) { OLogManager.instance().error(this, "Record %s should be the last record in WAL record list.", OAtomicUnitEndRecord.class.getName()); assert false : "Record " + OAtomicUnitEndRecord.class.getName() + " should be the last record in WAL record list."; } return isAtomicUnitEndRecord; } public OWriteAheadLog getWALInstance() { return writeAheadLog; } }
0true
core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_OStorageLocalAbstract.java
3,051
public class MemoryPostingsFormatProvider extends AbstractPostingsFormatProvider { private final boolean packFst; private final float acceptableOverheadRatio; private final MemoryPostingsFormat postingsFormat; @Inject public MemoryPostingsFormatProvider(@Assisted String name, @Assisted Settings postingsFormatSettings) { super(name); this.packFst = postingsFormatSettings.getAsBoolean("pack_fst", false); this.acceptableOverheadRatio = postingsFormatSettings.getAsFloat("acceptable_overhead_ratio", PackedInts.DEFAULT); // TODO this should really be an ENUM? this.postingsFormat = new MemoryPostingsFormat(packFst, acceptableOverheadRatio); } public boolean packFst() { return packFst; } public float acceptableOverheadRatio() { return acceptableOverheadRatio; } @Override public PostingsFormat get() { return postingsFormat; } }
0true
src_main_java_org_elasticsearch_index_codec_postingsformat_MemoryPostingsFormatProvider.java
424
restoreService.restoreSnapshot(restoreRequest, new RestoreSnapshotListener() { @Override public void onResponse(RestoreInfo restoreInfo) { if (restoreInfo == null) { if (request.waitForCompletion()) { restoreService.addListener(new RestoreService.RestoreCompletionListener() { SnapshotId snapshotId = new SnapshotId(request.repository(), request.snapshot()); @Override public void onRestoreCompletion(SnapshotId snapshotId, RestoreInfo snapshot) { if (this.snapshotId.equals(snapshotId)) { listener.onResponse(new RestoreSnapshotResponse(snapshot)); restoreService.removeListener(this); } } }); } else { listener.onResponse(new RestoreSnapshotResponse(null)); } } else { listener.onResponse(new RestoreSnapshotResponse(restoreInfo)); } } @Override public void onFailure(Throwable t) { listener.onFailure(t); } });
0true
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_restore_TransportRestoreSnapshotAction.java
1,066
class TransportHandler extends BaseTransportRequestHandler<MultiTermVectorsRequest> { @Override public MultiTermVectorsRequest newInstance() { return new MultiTermVectorsRequest(); } @Override public void messageReceived(final MultiTermVectorsRequest request, final TransportChannel channel) throws Exception { // no need to use threaded listener, since we just send a response request.listenerThreaded(false); execute(request, new ActionListener<MultiTermVectorsResponse>() { @Override public void onResponse(MultiTermVectorsResponse response) { try { channel.sendResponse(response); } catch (Throwable t) { onFailure(t); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(e); } catch (Throwable t) { logger.warn("Failed to send error response for action [" + MultiTermVectorsAction.NAME + "] and request [" + request + "]", t); } } }); } @Override public String executor() { return ThreadPool.Names.SAME; } }
0true
src_main_java_org_elasticsearch_action_termvector_TransportMultiTermVectorsAction.java
2,553
public class DiscoveryException extends ElasticsearchException { public DiscoveryException(String message) { super(message); } public DiscoveryException(String message, Throwable cause) { super(message, cause); } }
0true
src_main_java_org_elasticsearch_discovery_DiscoveryException.java
2,214
public static final class PrettyPrintFieldCacheTermsFilter extends FieldCacheTermsFilter { private final String value; private final String field; public PrettyPrintFieldCacheTermsFilter(String field, String value) { super(field, value); this.field = field; this.value = value; } @Override public String toString() { return "SLOW(" + field + ":" + value + ")"; } }
0true
src_test_java_org_elasticsearch_common_lucene_search_XBooleanFilterTests.java
102
public class TestTransactionImpl { @Test public void shouldBeAbleToAccessAllExceptionsOccurringInSynchronizationsBeforeCompletion() throws IllegalStateException, RollbackException { TxManager mockedTxManager = mock( TxManager.class ); TransactionImpl tx = new TransactionImpl( getNewGlobalId( DEFAULT_SEED, 0 ), mockedTxManager, ForceMode.forced, TransactionStateFactory.noStateFactory( new DevNullLoggingService() ), new SystemOutLogging().getMessagesLog( TxManager.class ) ); // Evil synchronizations final RuntimeException firstException = new RuntimeException( "Ex1" ); Synchronization meanSync1 = new Synchronization() { @Override public void beforeCompletion() { throw firstException; } @Override public void afterCompletion( int status ) { } }; final RuntimeException secondException = new RuntimeException( "Ex1" ); Synchronization meanSync2 = new Synchronization() { @Override public void beforeCompletion() { throw secondException; } @Override public void afterCompletion( int status ) { } }; tx.registerSynchronization( meanSync1 ); tx.registerSynchronization( meanSync2 ); tx.doBeforeCompletion(); assertThat( tx.getRollbackCause(), is( instanceOf( MultipleCauseException.class ) ) ); MultipleCauseException error = (MultipleCauseException) tx.getRollbackCause(); assertThat( error.getCause(), is( (Throwable) firstException ) ); assertThat( error.getCauses().size(), is( 2 ) ); assertThat( error.getCauses().get( 0 ), is( (Throwable) firstException ) ); assertThat( error.getCauses().get( 1 ), is( (Throwable) secondException ) ); } @Test public void shouldNotThrowMultipleCauseIfOnlyOneErrorOccursInBeforeCompletion() throws IllegalStateException, RollbackException { TxManager mockedTxManager = mock( TxManager.class ); TransactionImpl tx = new TransactionImpl( getNewGlobalId( DEFAULT_SEED, 0 ), mockedTxManager, ForceMode.forced, TransactionStateFactory.noStateFactory( new DevNullLoggingService() ), new SystemOutLogging().getMessagesLog( TxManager.class ) ); // Evil synchronizations final RuntimeException firstException = new RuntimeException( "Ex1" ); Synchronization meanSync1 = new Synchronization() { @Override public void beforeCompletion() { throw firstException; } @Override public void afterCompletion( int status ) { } }; tx.registerSynchronization( meanSync1 ); tx.doBeforeCompletion(); assertThat( tx.getRollbackCause(), is( (Throwable) firstException ) ); } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestTransactionImpl.java
34
@Service("blRequestFieldService") public class RequestFieldServiceImpl extends AbstractRuleBuilderFieldService { @Override public void init() { fields.add(new FieldData.Builder() .label("rule_requestFullUrl") .name("fullUrlWithQueryString") .operators("blcOperators_Text") .options("[]") .type(SupportedFieldType.STRING) .build()); fields.add(new FieldData.Builder() .label("rule_requestUri") .name("requestURI") .operators("blcOperators_Text") .options("[]") .type(SupportedFieldType.STRING) .build()); fields.add(new FieldData.Builder() .label("rule_requestIsSecure") .name("secure") .operators("blcOperators_Boolean") .options("[]") .type(SupportedFieldType.BOOLEAN) .build()); } @Override public String getName() { return RuleIdentifier.REQUEST; } @Override public String getDtoClassName() { return "org.broadleafcommerce.common.RequestDTOImpl"; } }
0true
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_web_rulebuilder_service_RequestFieldServiceImpl.java
3,174
private static enum Type { Float(AtomicFieldData.Order.NUMERIC), Double(AtomicFieldData.Order.NUMERIC), Integer(AtomicFieldData.Order.NUMERIC), Long(AtomicFieldData.Order.NUMERIC), Bytes(AtomicFieldData.Order.BYTES), GeoPoint(AtomicFieldData.Order.NONE); private final AtomicFieldData.Order order; Type(AtomicFieldData.Order order) { this.order = order; } public AtomicFieldData.Order order() { return order; } }
0true
src_test_java_org_elasticsearch_index_fielddata_DuelFieldDataTests.java
699
@Entity @Inheritance(strategy = InheritanceType.JOINED) @javax.persistence.Table(name="BLC_PRODUCT") //multi-column indexes don't appear to get exported correctly when declared at the field level, so declaring here as a workaround @org.hibernate.annotations.Table(appliesTo = "BLC_PRODUCT", indexes = { @Index(name = "PRODUCT_URL_INDEX", columnNames = {"URL","URL_KEY"} ) }) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "baseProduct") @SQLDelete(sql="UPDATE BLC_PRODUCT SET ARCHIVED = 'Y' WHERE PRODUCT_ID = ?") public class ProductImpl implements Product, Status, AdminMainEntity { private static final Log LOG = LogFactory.getLog(ProductImpl.class); /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** The id. */ @Id @GeneratedValue(generator= "ProductId") @GenericGenerator( name="ProductId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="ProductImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.catalog.domain.ProductImpl") } ) @Column(name = "PRODUCT_ID") @AdminPresentation(friendlyName = "ProductImpl_Product_ID", visibility = VisibilityEnum.HIDDEN_ALL) protected Long id; @Column(name = "URL") @AdminPresentation(friendlyName = "ProductImpl_Product_Url", order = Presentation.FieldOrder.URL, group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General, prominent = true, gridOrder = 3, columnWidth = "200px", requiredOverride = RequiredOverride.REQUIRED, validationConfigurations = { @ValidationConfiguration(validationImplementation = "blUriPropertyValidator") }) protected String url; @Column(name = "URL_KEY") @AdminPresentation(friendlyName = "ProductImpl_Product_UrlKey", tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General, excluded = true) protected String urlKey; @Column(name = "DISPLAY_TEMPLATE") @AdminPresentation(friendlyName = "ProductImpl_Product_Display_Template", tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced) protected String displayTemplate; @Column(name = "MODEL") @AdminPresentation(friendlyName = "ProductImpl_Product_Model", tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced) protected String model; @Column(name = "MANUFACTURE") @AdminPresentation(friendlyName = "ProductImpl_Product_Manufacturer", order = Presentation.FieldOrder.MANUFACTURER, group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General, prominent = true, gridOrder = 4) protected String manufacturer; @Column(name = "TAX_CODE") protected String taxCode; @Column(name = "IS_FEATURED_PRODUCT", nullable=false) @AdminPresentation(friendlyName = "ProductImpl_Is_Featured_Product", requiredOverride = RequiredOverride.NOT_REQUIRED, tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing, group = Presentation.Group.Name.Badges, groupOrder = Presentation.Group.Order.Badges) protected Boolean isFeaturedProduct = false; @OneToOne(optional = false, targetEntity = SkuImpl.class, cascade={CascadeType.ALL}, mappedBy = "defaultProduct") @Cascade(value={org.hibernate.annotations.CascadeType.ALL}) protected Sku defaultSku; @Column(name = "CAN_SELL_WITHOUT_OPTIONS") @AdminPresentation(friendlyName = "ProductImpl_Can_Sell_Without_Options", tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced) protected Boolean canSellWithoutOptions = false; @Transient protected List<Sku> skus = new ArrayList<Sku>(); @Transient protected String promoMessage; @OneToMany(mappedBy = "product", targetEntity = CrossSaleProductImpl.class, cascade = {CascadeType.ALL}) @Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @OrderBy(value="sequence") @AdminPresentationAdornedTargetCollection(friendlyName = "crossSaleProductsTitle", order = 1000, tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing, targetObjectProperty = "relatedSaleProduct", sortProperty = "sequence", maintainedAdornedTargetFields = { "promotionMessage" }, gridVisibleFields = { "defaultSku.name", "promotionMessage" }) protected List<RelatedProduct> crossSaleProducts = new ArrayList<RelatedProduct>(); @OneToMany(mappedBy = "product", targetEntity = UpSaleProductImpl.class, cascade = {CascadeType.ALL}) @Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @OrderBy(value="sequence") @AdminPresentationAdornedTargetCollection(friendlyName = "upsaleProductsTitle", order = 2000, tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing, targetObjectProperty = "relatedSaleProduct", sortProperty = "sequence", maintainedAdornedTargetFields = { "promotionMessage" }, gridVisibleFields = { "defaultSku.name", "promotionMessage" }) protected List<RelatedProduct> upSaleProducts = new ArrayList<RelatedProduct>(); @OneToMany(fetch = FetchType.LAZY, targetEntity = SkuImpl.class, mappedBy="product") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @BatchSize(size = 50) @AdminPresentationCollection(friendlyName="ProductImpl_Additional_Skus", order = 1000, tab = Presentation.Tab.Name.ProductOptions, tabOrder = Presentation.Tab.Order.ProductOptions) protected List<Sku> additionalSkus = new ArrayList<Sku>(); @ManyToOne(targetEntity = CategoryImpl.class) @JoinColumn(name = "DEFAULT_CATEGORY_ID") @Index(name="PRODUCT_CATEGORY_INDEX", columnNames={"DEFAULT_CATEGORY_ID"}) @AdminPresentation(friendlyName = "ProductImpl_Product_Default_Category", order = Presentation.FieldOrder.DEFAULT_CATEGORY, group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General, prominent = true, gridOrder = 2, requiredOverride = RequiredOverride.REQUIRED) @AdminPresentationToOneLookup() protected Category defaultCategory; @OneToMany(targetEntity = CategoryProductXrefImpl.class, mappedBy = "categoryProductXref.product") @Cascade(value={org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.PERSIST}) @OrderBy(value="displayOrder") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @BatchSize(size = 50) @AdminPresentationAdornedTargetCollection(friendlyName = "allParentCategoriesTitle", order = 3000, tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing, joinEntityClass = "org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl", targetObjectProperty = "categoryProductXref.category", parentObjectProperty = "categoryProductXref.product", sortProperty = "displayOrder", gridVisibleFields = { "name" }) protected List<CategoryProductXref> allParentCategoryXrefs = new ArrayList<CategoryProductXref>(); @OneToMany(mappedBy = "product", targetEntity = ProductAttributeImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true) @Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blStandardElements") @MapKey(name="name") @BatchSize(size = 50) @AdminPresentationMap(friendlyName = "productAttributesTitle", tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, deleteEntityUponRemove = true, forceFreeFormKeys = true, keyPropertyFriendlyName = "ProductAttributeImpl_Attribute_Name" ) protected Map<String, ProductAttribute> productAttributes = new HashMap<String, ProductAttribute>(); @ManyToMany(fetch = FetchType.LAZY, targetEntity = ProductOptionImpl.class) @JoinTable(name = "BLC_PRODUCT_OPTION_XREF", joinColumns = @JoinColumn(name = "PRODUCT_ID", referencedColumnName = "PRODUCT_ID"), inverseJoinColumns = @JoinColumn(name = "PRODUCT_OPTION_ID", referencedColumnName = "PRODUCT_OPTION_ID")) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @BatchSize(size = 50) @AdminPresentationCollection(friendlyName = "productOptionsTitle", tab = Presentation.Tab.Name.ProductOptions, tabOrder = Presentation.Tab.Order.ProductOptions, addType = AddMethodType.LOOKUP, manyToField = "products", operationTypes = @AdminPresentationOperationTypes(removeType = OperationType.NONDESTRUCTIVEREMOVE)) protected List<ProductOption> productOptions = new ArrayList<ProductOption>(); @Embedded protected ArchiveStatus archiveStatus = new ArchiveStatus(); @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getName() { return getDefaultSku().getName(); } @Override public void setName(String name) { getDefaultSku().setName(name); } @Override public String getDescription() { return getDefaultSku().getDescription(); } @Override public void setDescription(String description) { getDefaultSku().setDescription(description); } @Override public String getLongDescription() { return getDefaultSku().getLongDescription(); } @Override public void setLongDescription(String longDescription) { getDefaultSku().setLongDescription(longDescription); } @Override public Date getActiveStartDate() { return getDefaultSku().getActiveStartDate(); } @Override public void setActiveStartDate(Date activeStartDate) { getDefaultSku().setActiveStartDate(activeStartDate); } @Override public Date getActiveEndDate() { return getDefaultSku().getActiveEndDate(); } @Override public void setActiveEndDate(Date activeEndDate) { getDefaultSku().setActiveEndDate(activeEndDate); } @Override public boolean isActive() { if (LOG.isDebugEnabled()) { if (!DateUtil.isActive(getActiveStartDate(), getActiveEndDate(), true)) { LOG.debug("product, " + id + ", inactive due to date"); } if ('Y'==getArchived()) { LOG.debug("product, " + id + ", inactive due to archived status"); } } return DateUtil.isActive(getActiveStartDate(), getActiveEndDate(), true) && 'Y'!=getArchived(); } @Override public String getModel() { return model; } @Override public void setModel(String model) { this.model = model; } @Override public String getManufacturer() { return manufacturer; } @Override public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } @Override public boolean isFeaturedProduct() { return isFeaturedProduct; } @Override public void setFeaturedProduct(boolean isFeaturedProduct) { this.isFeaturedProduct = isFeaturedProduct; } @Override public Sku getDefaultSku() { return defaultSku; } @Override public Boolean getCanSellWithoutOptions() { return canSellWithoutOptions == null ? false : canSellWithoutOptions; } @Override public void setCanSellWithoutOptions(Boolean canSellWithoutOptions) { this.canSellWithoutOptions = canSellWithoutOptions; } @Override public void setDefaultSku(Sku defaultSku) { defaultSku.setDefaultProduct(this); this.defaultSku = defaultSku; } @Override public String getPromoMessage() { return promoMessage; } @Override public void setPromoMessage(String promoMessage) { this.promoMessage = promoMessage; } @Override public List<Sku> getAllSkus() { List<Sku> allSkus = new ArrayList<Sku>(); allSkus.add(getDefaultSku()); for (Sku additionalSku : additionalSkus) { if (!additionalSku.getId().equals(getDefaultSku().getId())) { allSkus.add(additionalSku); } } return allSkus; } @Override public List<Sku> getSkus() { if (skus.size() == 0) { List<Sku> additionalSkus = getAdditionalSkus(); for (Sku sku : additionalSkus) { if (sku.isActive()) { skus.add(sku); } } } return skus; } @Override public List<Sku> getAdditionalSkus() { return additionalSkus; } @Override public void setAdditionalSkus(List<Sku> skus) { this.additionalSkus.clear(); for(Sku sku : skus){ this.additionalSkus.add(sku); } //this.skus.clear(); } @Override public Category getDefaultCategory() { return defaultCategory; } @Override public Map<String, Media> getMedia() { return getDefaultSku().getSkuMedia(); } @Override public void setMedia(Map<String, Media> media) { getDefaultSku().setSkuMedia(media); } @Override public Map<String, Media> getAllSkuMedia() { Map<String, Media> result = new HashMap<String, Media>(); result.putAll(getMedia()); for (Sku additionalSku : getAdditionalSkus()) { if (!additionalSku.getId().equals(getDefaultSku().getId())) { result.putAll(additionalSku.getSkuMedia()); } } return result; } @Override public void setDefaultCategory(Category defaultCategory) { this.defaultCategory = defaultCategory; } @Override public List<CategoryProductXref> getAllParentCategoryXrefs() { return allParentCategoryXrefs; } @Override public void setAllParentCategoryXrefs(List<CategoryProductXref> allParentCategories) { this.allParentCategoryXrefs.clear(); allParentCategoryXrefs.addAll(allParentCategories); } @Override @Deprecated public List<Category> getAllParentCategories() { List<Category> parents = new ArrayList<Category>(); for (CategoryProductXref xref : allParentCategoryXrefs) { parents.add(xref.getCategory()); } return Collections.unmodifiableList(parents); } @Override @Deprecated public void setAllParentCategories(List<Category> allParentCategories) { throw new UnsupportedOperationException("Not Supported - Use setAllParentCategoryXrefs()"); } @Override public Dimension getDimension() { return getDefaultSku().getDimension(); } @Override public void setDimension(Dimension dimension) { getDefaultSku().setDimension(dimension); } @Override public BigDecimal getWidth() { return getDefaultSku().getDimension().getWidth(); } @Override public void setWidth(BigDecimal width) { getDefaultSku().getDimension().setWidth(width); } @Override public BigDecimal getHeight() { return getDefaultSku().getDimension().getHeight(); } @Override public void setHeight(BigDecimal height) { getDefaultSku().getDimension().setHeight(height); } @Override public BigDecimal getDepth() { return getDefaultSku().getDimension().getDepth(); } @Override public void setDepth(BigDecimal depth) { getDefaultSku().getDimension().setDepth(depth); } @Override public BigDecimal getGirth() { return getDefaultSku().getDimension().getGirth(); } @Override public void setGirth(BigDecimal girth) { getDefaultSku().getDimension().setGirth(girth); } @Override public ContainerSizeType getSize() { return getDefaultSku().getDimension().getSize(); } @Override public void setSize(ContainerSizeType size) { getDefaultSku().getDimension().setSize(size); } @Override public ContainerShapeType getContainer() { return getDefaultSku().getDimension().getContainer(); } @Override public void setContainer(ContainerShapeType container) { getDefaultSku().getDimension().setContainer(container); } @Override public String getDimensionString() { return getDefaultSku().getDimension().getDimensionString(); } @Override public Weight getWeight() { return getDefaultSku().getWeight(); } @Override public void setWeight(Weight weight) { getDefaultSku().setWeight(weight); } @Override public List<RelatedProduct> getCrossSaleProducts() { List<RelatedProduct> returnProducts = new ArrayList<RelatedProduct>(); if (crossSaleProducts != null) { returnProducts.addAll(crossSaleProducts); CollectionUtils.filter(returnProducts, new Predicate() { @Override public boolean evaluate(Object arg) { return 'Y'!=((Status)((CrossSaleProductImpl) arg).getRelatedProduct()).getArchived(); } }); } return returnProducts; } @Override public void setCrossSaleProducts(List<RelatedProduct> crossSaleProducts) { this.crossSaleProducts.clear(); for(RelatedProduct relatedProduct : crossSaleProducts){ this.crossSaleProducts.add(relatedProduct); } } @Override public List<RelatedProduct> getUpSaleProducts() { List<RelatedProduct> returnProducts = new ArrayList<RelatedProduct>(); if (upSaleProducts != null) { returnProducts.addAll(upSaleProducts); CollectionUtils.filter(returnProducts, new Predicate() { @Override public boolean evaluate(Object arg) { return 'Y'!=((Status)((UpSaleProductImpl) arg).getRelatedProduct()).getArchived(); } }); } return returnProducts; } @Override public void setUpSaleProducts(List<RelatedProduct> upSaleProducts) { this.upSaleProducts.clear(); for(RelatedProduct relatedProduct : upSaleProducts){ this.upSaleProducts.add(relatedProduct); } this.upSaleProducts = upSaleProducts; } @Override public List<RelatedProduct> getCumulativeCrossSaleProducts() { List<RelatedProduct> returnProducts = getCrossSaleProducts(); if (defaultCategory != null) { List<RelatedProduct> categoryProducts = defaultCategory.getCumulativeCrossSaleProducts(); if (categoryProducts != null) { returnProducts.addAll(categoryProducts); } } Iterator<RelatedProduct> itr = returnProducts.iterator(); while(itr.hasNext()) { RelatedProduct relatedProduct = itr.next(); if (relatedProduct.getRelatedProduct().equals(this)) { itr.remove(); } } return returnProducts; } @Override public List<RelatedProduct> getCumulativeUpSaleProducts() { List<RelatedProduct> returnProducts = getUpSaleProducts(); if (defaultCategory != null) { List<RelatedProduct> categoryProducts = defaultCategory.getCumulativeUpSaleProducts(); if (categoryProducts != null) { returnProducts.addAll(categoryProducts); } } Iterator<RelatedProduct> itr = returnProducts.iterator(); while(itr.hasNext()) { RelatedProduct relatedProduct = itr.next(); if (relatedProduct.getRelatedProduct().equals(this)) { itr.remove(); } } return returnProducts; } @Override public Map<String, ProductAttribute> getProductAttributes() { return productAttributes; } @Override public void setProductAttributes(Map<String, ProductAttribute> productAttributes) { this.productAttributes = productAttributes; } @Override public List<ProductOption> getProductOptions() { return productOptions; } @Override public void setProductOptions(List<ProductOption> productOptions) { this.productOptions = productOptions; } @Override public String getUrl() { if (url == null) { return getGeneratedUrl(); } else { return url; } } @Override public void setUrl(String url) { this.url = url; } @Override public String getDisplayTemplate() { return displayTemplate; } @Override public void setDisplayTemplate(String displayTemplate) { this.displayTemplate = displayTemplate; } @Override public Character getArchived() { if (archiveStatus == null) { archiveStatus = new ArchiveStatus(); } return archiveStatus.getArchived(); } @Override public void setArchived(Character archived) { if (archiveStatus == null) { archiveStatus = new ArchiveStatus(); } archiveStatus.setArchived(archived); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((skus == null) ? 0 : skus.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; ProductImpl other = (ProductImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (skus == null) { if (other.skus != null) return false; } else if (!skus.equals(other.skus)) return false; return true; } @Override public String getUrlKey() { if (urlKey != null) { return urlKey; } else { if (getName() != null) { String returnKey = getName().toLowerCase(); returnKey = returnKey.replaceAll(" ","-"); return returnKey.replaceAll("[^A-Za-z0-9/-]", ""); } } return null; } @Override public void setUrlKey(String urlKey) { this.urlKey = urlKey; } @Override public String getGeneratedUrl() { if (getDefaultCategory() != null && getDefaultCategory().getGeneratedUrl() != null) { String generatedUrl = getDefaultCategory().getGeneratedUrl(); if (generatedUrl.endsWith("//")) { return generatedUrl + getUrlKey(); } else { return generatedUrl + "//" + getUrlKey(); } } return null; } @Override public void clearDynamicPrices() { for (Sku sku : getAllSkus()) { sku.clearDynamicPrices(); } } @Override public String getMainEntityName() { String manufacturer = getManufacturer(); return StringUtils.isBlank(manufacturer) ? getName() : manufacturer + " " + getName(); } public static class Presentation { public static class Tab { public static class Name { public static final String Marketing = "ProductImpl_Marketing_Tab"; public static final String Media = "SkuImpl_Media_Tab"; public static final String ProductOptions = "ProductImpl_Product_Options_Tab"; public static final String Inventory = "ProductImpl_Inventory_Tab"; public static final String Shipping = "ProductImpl_Shipping_Tab"; public static final String Advanced = "ProductImpl_Advanced_Tab"; } public static class Order { public static final int Marketing = 2000; public static final int Media = 3000; public static final int ProductOptions = 4000; public static final int Inventory = 5000; public static final int Shipping = 6000; public static final int Advanced = 7000; } } public static class Group { public static class Name { public static final String General = "ProductImpl_Product_Description"; public static final String Price = "SkuImpl_Price"; public static final String ActiveDateRange = "ProductImpl_Product_Active_Date_Range"; public static final String Advanced = "ProductImpl_Advanced"; public static final String Inventory = "SkuImpl_Sku_Inventory"; public static final String Badges = "ProductImpl_Badges"; public static final String Shipping = "ProductWeight_Shipping"; public static final String Financial = "ProductImpl_Financial"; } public static class Order { public static final int General = 1000; public static final int Price = 2000; public static final int ActiveDateRange = 3000; public static final int Advanced = 1000; public static final int Inventory = 1000; public static final int Badges = 1000; public static final int Shipping = 1000; } } public static class FieldOrder { public static final int NAME = 1000; public static final int SHORT_DESCRIPTION = 2000; public static final int PRIMARY_MEDIA = 3000; public static final int LONG_DESCRIPTION = 4000; public static final int DEFAULT_CATEGORY = 5000; public static final int MANUFACTURER = 6000; public static final int URL = 7000; } } @Override public String getTaxCode() { if (StringUtils.isEmpty(taxCode) && getDefaultCategory() != null) { return getDefaultCategory().getTaxCode(); } return taxCode; } @Override public void setTaxCode(String taxCode) { this.taxCode = taxCode; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_ProductImpl.java