Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
1,218 | public interface TransactionalSet<E> extends TransactionalObject {
/**
* Add new item to transactional set
* @param e item
* @return true if item is added successfully
*/
boolean add(E e);
/**
* Add item from transactional set
* @param e item
* @return true if item is remove successfully
*/
boolean remove(E e);
/**
* Returns the size of the set
* @return size
*/
int size();
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_TransactionalSet.java |
1,648 | public class AddMetadataFromMappingDataRequest {
private final List<Property> componentProperties;
private final SupportedFieldType type;
private final SupportedFieldType secondaryType;
private final Type requestedEntityType;
private final String propertyName;
private final MergedPropertyType mergedPropertyType;
private final DynamicEntityDao dynamicEntityDao;
public AddMetadataFromMappingDataRequest(List<Property> componentProperties, SupportedFieldType type, SupportedFieldType secondaryType, Type requestedEntityType, String propertyName, MergedPropertyType mergedPropertyType, DynamicEntityDao dynamicEntityDao) {
this.componentProperties = componentProperties;
this.type = type;
this.secondaryType = secondaryType;
this.requestedEntityType = requestedEntityType;
this.propertyName = propertyName;
this.mergedPropertyType = mergedPropertyType;
this.dynamicEntityDao = dynamicEntityDao;
}
public List<Property> getComponentProperties() {
return componentProperties;
}
public SupportedFieldType getType() {
return type;
}
public SupportedFieldType getSecondaryType() {
return secondaryType;
}
public Type getRequestedEntityType() {
return requestedEntityType;
}
public String getPropertyName() {
return propertyName;
}
public MergedPropertyType getMergedPropertyType() {
return mergedPropertyType;
}
public DynamicEntityDao getDynamicEntityDao() {
return dynamicEntityDao;
}
} | 0true
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_dao_provider_metadata_request_AddMetadataFromMappingDataRequest.java |
1,698 | runnable = new Runnable() { public void run() { map.replace("key", null); } }; | 0true
| hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java |
1,992 | Runnable runnable = new Runnable() {
public void run() {
HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(cfg);
final IMap<Object, Object> map = instance2.getMap("testInitialLoadModeEagerMultipleThread");
assertEquals(size, map.size());
countDownLatch.countDown();
}
}; | 0true
| hazelcast_src_test_java_com_hazelcast_map_mapstore_MapStoreTest.java |
2,678 | public class FuzzyLikeThisActionTests extends ElasticsearchIntegrationTest {
@Test
// See issue https://github.com/elasticsearch/elasticsearch/issues/3252
public void testNumericField() throws Exception {
assertAcked(prepareCreate("test")
.setSettings(settingsBuilder()
.put(SETTING_NUMBER_OF_SHARDS, between(1, 5))
.put(SETTING_NUMBER_OF_REPLICAS, between(0, 1)))
.addMapping("type", "int_value", "type=integer"));
ensureGreen();
client().prepareIndex("test", "type", "1")
.setSource(jsonBuilder().startObject().field("string_value", "lucene index").field("int_value", 1).endObject())
.execute().actionGet();
client().prepareIndex("test", "type", "2")
.setSource(jsonBuilder().startObject().field("string_value", "elasticsearch index").field("int_value", 42).endObject())
.execute().actionGet();
refresh();
// flt query with no field -> OK
SearchResponse searchResponse = client().prepareSearch().setQuery(fuzzyLikeThisQuery().likeText("index")).execute().actionGet();
assertThat(searchResponse.getFailedShards(), equalTo(0));
assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
// flt query with string fields
searchResponse = client().prepareSearch().setQuery(fuzzyLikeThisQuery("string_value").likeText("index")).execute().actionGet();
assertThat(searchResponse.getFailedShards(), equalTo(0));
assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
// flt query with at least a numeric field -> fail by default
assertThrows(client().prepareSearch().setQuery(fuzzyLikeThisQuery("string_value", "int_value").likeText("index")), SearchPhaseExecutionException.class);
// flt query with at least a numeric field -> fail by command
assertThrows(client().prepareSearch().setQuery(fuzzyLikeThisQuery("string_value", "int_value").likeText("index").failOnUnsupportedField(true)), SearchPhaseExecutionException.class);
// flt query with at least a numeric field but fail_on_unsupported_field set to false
searchResponse = client().prepareSearch().setQuery(fuzzyLikeThisQuery("string_value", "int_value").likeText("index").failOnUnsupportedField(false)).execute().actionGet();
assertThat(searchResponse.getFailedShards(), equalTo(0));
assertThat(searchResponse.getHits().getTotalHits(), equalTo(2L));
// flt field query on a numeric field -> failure by default
assertThrows(client().prepareSearch().setQuery(fuzzyLikeThisFieldQuery("int_value").likeText("42")), SearchPhaseExecutionException.class);
// flt field query on a numeric field -> failure by command
assertThrows(client().prepareSearch().setQuery(fuzzyLikeThisFieldQuery("int_value").likeText("42").failOnUnsupportedField(true)), SearchPhaseExecutionException.class);
// flt field query on a numeric field but fail_on_unsupported_field set to false
searchResponse = client().prepareSearch().setQuery(fuzzyLikeThisFieldQuery("int_value").likeText("42").failOnUnsupportedField(false)).execute().actionGet();
assertThat(searchResponse.getFailedShards(), equalTo(0));
assertThat(searchResponse.getHits().getTotalHits(), equalTo(0L));
}
} | 0true
| src_test_java_org_elasticsearch_flt_FuzzyLikeThisActionTests.java |
241 | private static class AstyanaxGetter implements StaticArrayEntry.GetColVal<Column<ByteBuffer>,ByteBuffer> {
private final EntryMetaData[] schema;
private AstyanaxGetter(EntryMetaData[] schema) {
this.schema = schema;
}
@Override
public ByteBuffer getColumn(Column<ByteBuffer> element) {
return element.getName();
}
@Override
public ByteBuffer getValue(Column<ByteBuffer> element) {
return element.getByteBufferValue();
}
@Override
public EntryMetaData[] getMetaSchema(Column<ByteBuffer> element) {
return schema;
}
@Override
public Object getMetaData(Column<ByteBuffer> element, EntryMetaData meta) {
switch(meta) {
case TIMESTAMP:
return element.getTimestamp();
case TTL:
return element.getTtl();
default:
throw new UnsupportedOperationException("Unsupported meta data: " + meta);
}
}
} | 0true
| titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_astyanax_AstyanaxKeyColumnValueStore.java |
2,371 | public static class Distance implements Comparable<Distance> {
public final double value;
public final DistanceUnit unit;
public Distance(double value, DistanceUnit unit) {
super();
this.value = value;
this.unit = unit;
}
/**
* Converts a {@link Distance} value given in a specific {@link DistanceUnit} into
* a value equal to the specified value but in a other {@link DistanceUnit}.
*
* @param unit unit of the result
* @return converted distance
*/
public Distance convert(DistanceUnit unit) {
if(this.unit == unit) {
return this;
} else {
return new Distance(DistanceUnit.convert(value, this.unit, unit), unit);
}
}
@Override
public boolean equals(Object obj) {
if(obj == null) {
return false;
} else if (obj instanceof Distance) {
Distance other = (Distance) obj;
return DistanceUnit.convert(value, unit, other.unit) == other.value;
} else {
return false;
}
}
@Override
public int hashCode() {
return Double.valueOf(value * unit.meters).hashCode();
}
@Override
public int compareTo(Distance o) {
return Double.compare(value, DistanceUnit.convert(o.value, o.unit, unit));
}
@Override
public String toString() {
return unit.toString(value);
}
/**
* Parse a {@link Distance} from a given String. If no unit is given
* <code>DistanceUnit.DEFAULT</code> will be used
*
* @param distance String defining a {@link Distance}
* @return parsed {@link Distance}
*/
public static Distance parseDistance(String distance) {
return parseDistance(distance, DEFAULT);
}
/**
* Parse a {@link Distance} from a given String
*
* @param distance String defining a {@link Distance}
* @param defaultUnit {@link DistanceUnit} to be assumed
* if not unit is provided in the first argument
* @return parsed {@link Distance}
*/
private static Distance parseDistance(String distance, DistanceUnit defaultUnit) {
for (DistanceUnit unit : values()) {
for (String name : unit.names) {
if(distance.endsWith(name)) {
return new Distance(Double.parseDouble(distance.substring(0, distance.length() - name.length())), unit);
}
}
}
return new Distance(Double.parseDouble(distance), defaultUnit);
}
} | 0true
| src_main_java_org_elasticsearch_common_unit_DistanceUnit.java |
5,129 | public static class Builder {
private List<AggregatorFactory> factories = new ArrayList<AggregatorFactory>();
public Builder add(AggregatorFactory factory) {
factories.add(factory);
return this;
}
public AggregatorFactories build() {
if (factories.isEmpty()) {
return EMPTY;
}
return new AggregatorFactories(factories.toArray(new AggregatorFactory[factories.size()]));
}
} | 1no label
| src_main_java_org_elasticsearch_search_aggregations_AggregatorFactories.java |
1,532 | public interface HazelcastTransaction extends javax.resource.cci.LocalTransaction, javax.resource.spi.LocalTransaction {
} | 0true
| hazelcast-ra_hazelcast-jca_src_main_java_com_hazelcast_jca_HazelcastTransaction.java |
1,638 | public class AdvancedCollectionFieldMetadataProvider extends FieldMetadataProviderAdapter {
protected boolean canHandleFieldForTypeMetadata(AddMetadataFromFieldTypeRequest addMetadataFromFieldTypeRequest, Map<String, FieldMetadata> metadata) {
AdminPresentationMap map = addMetadataFromFieldTypeRequest.getRequestedField().getAnnotation(AdminPresentationMap.class);
AdminPresentationCollection collection = addMetadataFromFieldTypeRequest.getRequestedField().getAnnotation(AdminPresentationCollection.class);
return map != null || collection != null;
}
@Override
public FieldProviderResponse addMetadataFromFieldType(AddMetadataFromFieldTypeRequest addMetadataFromFieldTypeRequest, Map<String, FieldMetadata> metadata) {
if (!canHandleFieldForTypeMetadata(addMetadataFromFieldTypeRequest, metadata)) {
return FieldProviderResponse.NOT_HANDLED;
}
CollectionMetadata fieldMetadata = (CollectionMetadata) addMetadataFromFieldTypeRequest.getPresentationAttribute();
if (StringUtils.isEmpty(fieldMetadata.getCollectionCeilingEntity())) {
ParameterizedType listType = (ParameterizedType) addMetadataFromFieldTypeRequest.getRequestedField().getGenericType();
Class<?> listClass = (Class<?>) listType.getActualTypeArguments()[0];
fieldMetadata.setCollectionCeilingEntity(listClass.getName());
}
if (addMetadataFromFieldTypeRequest.getTargetClass() != null) {
if (StringUtils.isEmpty(fieldMetadata.getInheritedFromType())) {
fieldMetadata.setInheritedFromType(addMetadataFromFieldTypeRequest.getTargetClass().getName());
}
if (ArrayUtils.isEmpty(fieldMetadata.getAvailableToTypes())) {
fieldMetadata.setAvailableToTypes(new String[]{addMetadataFromFieldTypeRequest.getTargetClass().getName()});
}
}
metadata.put(addMetadataFromFieldTypeRequest.getRequestedPropertyName(), fieldMetadata);
return FieldProviderResponse.HANDLED;
}
} | 1no label
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_dao_provider_metadata_AdvancedCollectionFieldMetadataProvider.java |
606 | updateSettingsService.updateSettings(clusterStateUpdateRequest, new ClusterStateUpdateListener() {
@Override
public void onResponse(ClusterStateUpdateResponse response) {
listener.onResponse(new UpdateSettingsResponse(response.isAcknowledged()));
}
@Override
public void onFailure(Throwable t) {
logger.debug("failed to update settings on indices [{}]", t, request.indices());
listener.onFailure(t);
}
}); | 1no label
| src_main_java_org_elasticsearch_action_admin_indices_settings_put_TransportUpdateSettingsAction.java |
451 | 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_db_record_TrackedSetTest.java |
739 | public class OSBTreeValuePage extends ODurablePage {
private static final int FREE_LIST_NEXT_PAGE_OFFSET = NEXT_FREE_POSITION;
private static final int WHOLE_VALUE_SIZE_OFFSET = FREE_LIST_NEXT_PAGE_OFFSET + OLongSerializer.LONG_SIZE;
private static final int PAGE_VALUE_SIZE_OFFSET = WHOLE_VALUE_SIZE_OFFSET + OIntegerSerializer.INT_SIZE;
private static final int NEXT_VALUE_PAGE_OFFSET = PAGE_VALUE_SIZE_OFFSET + OIntegerSerializer.INT_SIZE;
private static final int BINARY_CONTENT_OFFSET = NEXT_VALUE_PAGE_OFFSET + OLongSerializer.LONG_SIZE;
public static final int MAX_BINARY_VALUE_SIZE = MAX_PAGE_SIZE_BYTES - BINARY_CONTENT_OFFSET;
public OSBTreeValuePage(ODirectMemoryPointer pagePointer, TrackMode trackMode, boolean isNew) throws IOException {
super(pagePointer, trackMode);
if (isNew) {
setNextFreeListPage(-1);
setNextPage(-1);
}
}
public void setNextPage(long nextPage) throws IOException {
setLongValue(NEXT_VALUE_PAGE_OFFSET, nextPage);
}
public int getSize() {
return getIntValue(WHOLE_VALUE_SIZE_OFFSET);
}
public int fillBinaryContent(byte[] data, int offset) throws IOException {
setIntValue(WHOLE_VALUE_SIZE_OFFSET, data.length);
int maxSize = Math.min(data.length - offset, MAX_BINARY_VALUE_SIZE);
setIntValue(PAGE_VALUE_SIZE_OFFSET, maxSize);
byte[] pageValue = new byte[maxSize];
System.arraycopy(data, offset, pageValue, 0, maxSize);
setBinaryValue(BINARY_CONTENT_OFFSET, pageValue);
return offset + maxSize;
}
public int readBinaryContent(byte[] data, int offset) throws IOException {
int valueSize = getIntValue(PAGE_VALUE_SIZE_OFFSET);
byte[] content = getBinaryValue(BINARY_CONTENT_OFFSET, valueSize);
System.arraycopy(content, 0, data, offset, valueSize);
return offset + valueSize;
}
public long getNextPage() {
return getLongValue(NEXT_VALUE_PAGE_OFFSET);
}
public void setNextFreeListPage(long pageIndex) throws IOException {
setLongValue(FREE_LIST_NEXT_PAGE_OFFSET, pageIndex);
}
public long getNextFreeListPage() {
return getLongValue(FREE_LIST_NEXT_PAGE_OFFSET);
}
public static int calculateAmountOfPage(int contentSize) {
return (int) Math.ceil(1.0 * contentSize / MAX_BINARY_VALUE_SIZE);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_sbtree_local_OSBTreeValuePage.java |
1,642 | public interface FieldMetadataProvider extends Ordered {
//standard ordering constants for BLC providers
public static final int BASIC = Integer.MAX_VALUE;
public static final int COLLECTION = 20000;
public static final int ADORNED_TARGET = 30000;
public static final int MAP = 40000;
public static final int MAP_FIELD = 50000;
/**
* Contribute to metadata inspection for the {@link java.lang.reflect.Field} instance in the request. Implementations should
* add values to the metadata parameter.
*
* @param addMetadataRequest contains the requested field and support classes.
* @param metadata implementations should add metadata for the requested field here
* @return whether or not this implementation adjusted metadata
*/
FieldProviderResponse addMetadata(AddMetadataRequest addMetadataRequest, Map<String, FieldMetadata> metadata);
/**
* Contribute to metadata inspection for the {@link java.lang.reflect.Field} instance in the request. Implementations should
* add values to the metadata parameter.
*
* This method differs from {@link #addMetadata(AddMetadataRequest, Map)} in that it will be invoked after the cacheable
* properties are assembled. It is therefore useful in scenarios where you may want to contribute properties to
* metadata that are dynamic and should not be cached normally.
*
* @param lateStageAddMetadataRequest contains the requested field name and support classes.
* @param metadata implementations should add metadata for the requested field here
* @return whether or not this implementation adjusted metadata
*/
FieldProviderResponse lateStageAddMetadata(LateStageAddMetadataRequest addMetadataRequest, Map<String, FieldMetadata> metadata);
/**
* Contribute to metadata inspection for the entity in the request. Implementations should override values
* in the metadata parameter.
*
* @param overrideViaAnnotationRequest contains the requested entity and support classes.
* @param metadata implementations should override metadata here
* @return whether or not this implementation adjusted metadata
*/
FieldProviderResponse overrideViaAnnotation(OverrideViaAnnotationRequest overrideViaAnnotationRequest, Map<String, FieldMetadata> metadata);
/**
* Contribute to metadata inspection for the ceiling entity and config key. Implementations should override
* values in the metadata parameter.
*
* @param overrideViaXmlRequest contains the requested config key, ceiling entity and support classes.
* @param metadata implementations should override metadata here
* @return whether or not this implementation adjusted metadata
*/
FieldProviderResponse overrideViaXml(OverrideViaXmlRequest overrideViaXmlRequest, Map<String, FieldMetadata> metadata);
/**
* Contribute to metadata inspection using Hibernate column information. Implementations should impact values
* in the metadata parameter.
*
* @param addMetadataFromMappingDataRequest contains the requested Hibernate type and support classes.
* @param metadata implementations should impact values for the metadata for the field here
* @return whether or not this implementation adjusted metadata
*/
FieldProviderResponse addMetadataFromMappingData(AddMetadataFromMappingDataRequest addMetadataFromMappingDataRequest, FieldMetadata metadata);
/**
* Contribute to metadata inspection for the {@link java.lang.reflect.Field} instance in the request. Implementations should
* add values to the metadata parameter. This is metadata based on the field type.
*
* @param addMetadataFromFieldTypeRequest contains the requested field, property name and support classes.
* @param metadata implementations should add values for the field here
* @return whether or not this implementation adjusted metadata
*/
FieldProviderResponse addMetadataFromFieldType(AddMetadataFromFieldTypeRequest addMetadataFromFieldTypeRequest, Map<String, FieldMetadata> metadata);
} | 0true
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_dao_provider_metadata_FieldMetadataProvider.java |
766 | public class TransportShardMultiGetAction extends TransportShardSingleOperationAction<MultiGetShardRequest, MultiGetShardResponse> {
private final IndicesService indicesService;
private final boolean realtime;
@Inject
public TransportShardMultiGetAction(Settings settings, ClusterService clusterService, TransportService transportService,
IndicesService indicesService, ThreadPool threadPool) {
super(settings, threadPool, clusterService, transportService);
this.indicesService = indicesService;
this.realtime = settings.getAsBoolean("action.get.realtime", true);
}
@Override
protected String executor() {
return ThreadPool.Names.GET;
}
@Override
protected String transportAction() {
return MultiGetAction.NAME + "/shard";
}
@Override
protected MultiGetShardRequest newRequest() {
return new MultiGetShardRequest();
}
@Override
protected MultiGetShardResponse newResponse() {
return new MultiGetShardResponse();
}
@Override
protected ClusterBlockException checkGlobalBlock(ClusterState state, MultiGetShardRequest request) {
return state.blocks().globalBlockedException(ClusterBlockLevel.READ);
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, MultiGetShardRequest request) {
return state.blocks().indexBlockedException(ClusterBlockLevel.READ, request.index());
}
@Override
protected ShardIterator shards(ClusterState state, MultiGetShardRequest request) {
return clusterService.operationRouting()
.getShards(clusterService.state(), request.index(), request.shardId(), request.preference());
}
@Override
protected void resolveRequest(ClusterState state, MultiGetShardRequest request) {
if (request.realtime == null) {
request.realtime = this.realtime;
}
// no need to set concrete index and routing here, it has already been set by the multi get action on the item
//request.index(state.metaData().concreteIndex(request.index()));
}
@Override
protected MultiGetShardResponse shardOperation(MultiGetShardRequest request, int shardId) throws ElasticsearchException {
IndexService indexService = indicesService.indexServiceSafe(request.index());
IndexShard indexShard = indexService.shardSafe(shardId);
if (request.refresh() && !request.realtime()) {
indexShard.refresh(new Engine.Refresh("refresh_flag_mget").force(TransportGetAction.REFRESH_FORCE));
}
MultiGetShardResponse response = new MultiGetShardResponse();
for (int i = 0; i < request.locations.size(); i++) {
String type = request.types.get(i);
String id = request.ids.get(i);
String[] fields = request.fields.get(i);
long version = request.versions.get(i);
VersionType versionType = request.versionTypes.get(i);
if (versionType == null) {
versionType = VersionType.INTERNAL;
}
FetchSourceContext fetchSourceContext = request.fetchSourceContexts.get(i);
try {
GetResult getResult = indexShard.getService().get(type, id, fields, request.realtime(), version, versionType, fetchSourceContext);
response.add(request.locations.get(i), new GetResponse(getResult));
} catch (Throwable t) {
if (TransportActions.isShardNotAvailableException(t)) {
throw (ElasticsearchException) t;
} else {
logger.debug("[{}][{}] failed to execute multi_get for [{}]/[{}]", t, request.index(), shardId, type, id);
response.add(request.locations.get(i), new MultiGetResponse.Failure(request.index(), type, id, ExceptionsHelper.detailedMessage(t)));
}
}
}
return response;
}
} | 1no label
| src_main_java_org_elasticsearch_action_get_TransportShardMultiGetAction.java |
3,422 | public class IndexShardGatewayRecoveryException extends IndexShardGatewayException {
public IndexShardGatewayRecoveryException(ShardId shardId, String msg) {
super(shardId, msg);
}
public IndexShardGatewayRecoveryException(ShardId shardId, String msg, Throwable cause) {
super(shardId, msg, cause);
}
} | 0true
| src_main_java_org_elasticsearch_index_gateway_IndexShardGatewayRecoveryException.java |
26 | final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> {
SubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) {
super(first, fence);
}
public Map.Entry<K, V> next() {
final Map.Entry<K, V> e = OMVRBTree.exportEntry(next);
nextEntry();
return e;
}
public void remove() {
removeAscending();
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
1,656 | public class ParseField {
private final String camelCaseName;
private final String underscoreName;
private final String[] deprecatedNames;
public static final EnumSet<Flag> EMPTY_FLAGS = EnumSet.noneOf(Flag.class);
public static enum Flag {
STRICT
}
public ParseField(String value, String... deprecatedNames) {
camelCaseName = Strings.toCamelCase(value);
underscoreName = Strings.toUnderscoreCase(value);
if (deprecatedNames == null || deprecatedNames.length == 0) {
this.deprecatedNames = Strings.EMPTY_ARRAY;
} else {
final HashSet<String> set = new HashSet<String>();
for (String depName : deprecatedNames) {
set.add(Strings.toCamelCase(depName));
set.add(Strings.toUnderscoreCase(depName));
}
this.deprecatedNames = set.toArray(new String[0]);
}
}
public String getPreferredName(){
return underscoreName;
}
public ParseField withDeprecation(String... deprecatedNames) {
return new ParseField(this.underscoreName, deprecatedNames);
}
public boolean match(String currentFieldName) {
return match(currentFieldName, EMPTY_FLAGS);
}
public boolean match(String currentFieldName, EnumSet<Flag> flags) {
if (currentFieldName.equals(camelCaseName) || currentFieldName.equals(underscoreName)) {
return true;
}
for (String depName : deprecatedNames) {
if (currentFieldName.equals(depName)) {
if (flags.contains(Flag.STRICT)) {
throw new ElasticsearchIllegalArgumentException("Deprecated field [" + currentFieldName + "] used expected [" + underscoreName + "] instead");
}
return true;
}
}
return false;
}
} | 0true
| src_main_java_org_elasticsearch_common_ParseField.java |
856 | public class TransportSearchCountAction extends TransportSearchTypeAction {
@Inject
public TransportSearchCountAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController) {
super(settings, threadPool, clusterService, searchService, searchPhaseController);
}
@Override
protected void doExecute(SearchRequest searchRequest, ActionListener<SearchResponse> listener) {
new AsyncAction(searchRequest, listener).start();
}
private class AsyncAction extends BaseAsyncAction<QuerySearchResult> {
private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) {
super(request, listener);
}
@Override
protected String firstPhaseName() {
return "query";
}
@Override
protected void sendExecuteFirstPhase(DiscoveryNode node, ShardSearchRequest request, SearchServiceListener<QuerySearchResult> listener) {
searchService.sendExecuteQuery(node, request, listener);
}
@Override
protected void moveToSecondPhase() throws Exception {
// no need to sort, since we know we have no hits back
final InternalSearchResponse internalResponse = searchPhaseController.merge(SearchPhaseController.EMPTY_DOCS, firstResults, (AtomicArray<? extends FetchSearchResultProvider>) AtomicArray.empty());
String scrollId = null;
if (request.scroll() != null) {
scrollId = buildScrollId(request.searchType(), firstResults, null);
}
listener.onResponse(new SearchResponse(internalResponse, scrollId, expectedSuccessfulOps, successulOps.get(), buildTookInMillis(), buildShardFailures()));
}
}
} | 0true
| src_main_java_org_elasticsearch_action_search_type_TransportSearchCountAction.java |
3,349 | static class WithOrdinals extends GeoPointCompressedAtomicFieldData {
private final GeoPointFieldMapper.Encoding encoding;
private final PagedMutable lon, lat;
private final Ordinals ordinals;
public WithOrdinals(GeoPointFieldMapper.Encoding encoding, PagedMutable lon, PagedMutable lat, int numDocs, Ordinals ordinals) {
super(numDocs);
this.encoding = encoding;
this.lon = lon;
this.lat = lat;
this.ordinals = ordinals;
}
@Override
public boolean isMultiValued() {
return ordinals.isMultiValued();
}
@Override
public boolean isValuesOrdered() {
return true;
}
@Override
public long getNumberUniqueValues() {
return ordinals.getNumOrds();
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = RamUsageEstimator.NUM_BYTES_INT/*size*/ + RamUsageEstimator.NUM_BYTES_INT/*numDocs*/ + lon.ramBytesUsed() + lat.ramBytesUsed();
}
return size;
}
@Override
public GeoPointValues getGeoPointValues() {
return new GeoPointValuesWithOrdinals(encoding, lon, lat, ordinals.ordinals());
}
public static class GeoPointValuesWithOrdinals extends GeoPointValues {
private final GeoPointFieldMapper.Encoding encoding;
private final PagedMutable lon, lat;
private final Ordinals.Docs ordinals;
private final GeoPoint scratch = new GeoPoint();
GeoPointValuesWithOrdinals(GeoPointFieldMapper.Encoding encoding, PagedMutable lon, PagedMutable lat, Ordinals.Docs ordinals) {
super(ordinals.isMultiValued());
this.encoding = encoding;
this.lon = lon;
this.lat = lat;
this.ordinals = ordinals;
}
@Override
public GeoPoint nextValue() {
final long ord = ordinals.nextOrd();
assert ord > 0;
return encoding.decode(lat.get(ord), lon.get(ord), scratch);
}
@Override
public int setDocument(int docId) {
this.docId = docId;
return ordinals.setDocument(docId);
}
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_GeoPointCompressedAtomicFieldData.java |
2,416 | public interface DoubleArray extends BigArray {
/**
* Get an element given its index.
*/
public abstract double get(long index);
/**
* Set a value at the given index and return the previous value.
*/
public abstract double set(long index, double value);
/**
* Increment value at the given index by <code>inc</code> and return the value.
*/
public abstract double increment(long index, double inc);
/**
* Fill slots between <code>fromIndex</code> inclusive to <code>toIndex</code> exclusive with <code>value</code>.
*/
public abstract void fill(long fromIndex, long toIndex, double value);
} | 0true
| src_main_java_org_elasticsearch_common_util_DoubleArray.java |
1,501 | public static class GroupProperty {
private final String name;
private final String value;
GroupProperty(Config config, String name) {
this(config, name, (String) null);
}
GroupProperty(Config config, String name, GroupProperty defaultValue) {
this(config, name, defaultValue != null ? defaultValue.getString() : null);
}
GroupProperty(Config config, String name, String defaultValue) {
this.name = name;
String configValue = (config != null) ? config.getProperty(name) : null;
if (configValue != null) {
value = configValue;
} else if (System.getProperty(name) != null) {
value = System.getProperty(name);
} else {
value = defaultValue;
}
}
public String getName() {
return this.name;
}
public String getValue() {
return value;
}
public int getInteger() {
return Integer.parseInt(this.value);
}
public byte getByte() {
return Byte.parseByte(this.value);
}
public boolean getBoolean() {
return Boolean.valueOf(this.value);
}
public String getString() {
return value;
}
public long getLong() {
return Long.parseLong(this.value);
}
@Override
public String toString() {
return "GroupProperty [name=" + this.name + ", value=" + this.value + "]";
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_instance_GroupProperties.java |
3,183 | public class FilterLongValues extends LongValues {
protected final LongValues delegate;
protected FilterLongValues(LongValues delegate) {
super(delegate.isMultiValued());
this.delegate = delegate;
}
@Override
public int setDocument(int docId) {
return delegate.setDocument(docId);
}
@Override
public long nextValue() {
return delegate.nextValue();
}
@Override
public AtomicFieldData.Order getOrder() {
return delegate.getOrder();
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_FilterLongValues.java |
176 | @RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientAtomicLongTest {
static final String name = "test1";
static HazelcastInstance client;
static HazelcastInstance server;
static IAtomicLong l;
@BeforeClass
public static void init(){
server = Hazelcast.newHazelcastInstance();
client = HazelcastClient.newHazelcastClient();
l = client.getAtomicLong(name);
}
@AfterClass
public static void destroy() {
client.shutdown();
Hazelcast.shutdownAll();
}
@Before
@After
public void clear() throws IOException {
l.set(0);
}
@Test
public void test() throws Exception {
assertEquals(0, l.getAndAdd(2));
assertEquals(2, l.get());
l.set(5);
assertEquals(5, l.get());
assertEquals(8, l.addAndGet(3));
assertFalse(l.compareAndSet(7, 4));
assertEquals(8, l.get());
assertTrue(l.compareAndSet(8, 4));
assertEquals(4, l.get());
assertEquals(3, l.decrementAndGet());
assertEquals(3, l.getAndIncrement());
assertEquals(4, l.getAndSet(9));
assertEquals(10, l.incrementAndGet());
}
@Test(expected = IllegalArgumentException.class)
public void apply_whenCalledWithNullFunction() {
IAtomicLong ref = client.getAtomicLong("apply_whenCalledWithNullFunction");
ref.apply(null);
}
@Test
public void apply() {
IAtomicLong ref = client.getAtomicLong("apply");
assertEquals(new Long(1), ref.apply(new AddOneFunction()));
assertEquals(0, ref.get());
}
@Test
public void apply_whenException() {
IAtomicLong ref = client.getAtomicLong("apply_whenException");
ref.set(1);
try {
ref.apply(new FailingFunction());
fail();
} catch (WoohaaException expected) {
}
assertEquals(1, ref.get());
}
@Test(expected = IllegalArgumentException.class)
public void alter_whenCalledWithNullFunction() {
IAtomicLong ref = client.getAtomicLong("alter_whenCalledWithNullFunction");
ref.alter(null);
}
@Test
public void alter_whenException() {
IAtomicLong ref = client.getAtomicLong("alter_whenException");
ref.set(10);
try {
ref.alter(new FailingFunction());
fail();
} catch (WoohaaException expected) {
}
assertEquals(10, ref.get());
}
@Test
public void alter() {
IAtomicLong ref = client.getAtomicLong("alter");
ref.set(10);
ref.alter(new AddOneFunction());
assertEquals(11, ref.get());
}
@Test(expected = IllegalArgumentException.class)
public void alterAndGet_whenCalledWithNullFunction() {
IAtomicLong ref = client.getAtomicLong("alterAndGet_whenCalledWithNullFunction");
ref.alterAndGet(null);
}
@Test
public void alterAndGet_whenException() {
IAtomicLong ref = client.getAtomicLong("alterAndGet_whenException");
ref.set(10);
try {
ref.alterAndGet(new FailingFunction());
fail();
} catch (WoohaaException expected) {
}
assertEquals(10, ref.get());
}
@Test
public void alterAndGet() {
IAtomicLong ref = client.getAtomicLong("alterAndGet");
ref.set(10);
assertEquals(11, ref.alterAndGet(new AddOneFunction()));
assertEquals(11, ref.get());
}
@Test(expected = IllegalArgumentException.class)
public void getAndAlter_whenCalledWithNullFunction() {
IAtomicLong ref = client.getAtomicLong("getAndAlter_whenCalledWithNullFunction");
ref.getAndAlter(null);
}
@Test
public void getAndAlter_whenException() {
IAtomicLong ref = client.getAtomicLong("getAndAlter_whenException");
ref.set(10);
try {
ref.getAndAlter(new FailingFunction());
fail();
} catch (WoohaaException expected) {
}
assertEquals(10, ref.get());
}
@Test
public void getAndAlter() {
IAtomicLong ref = client.getAtomicLong("getAndAlter");
ref.set(10);
assertEquals(10, ref.getAndAlter(new AddOneFunction()));
assertEquals(11, ref.get());
}
private static class AddOneFunction implements IFunction<Long, Long> {
@Override
public Long apply(Long input) {
return input+1;
}
}
private static class FailingFunction implements IFunction<Long, Long> {
@Override
public Long apply(Long input) {
throw new WoohaaException();
}
}
private static class WoohaaException extends RuntimeException {
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_atomiclong_ClientAtomicLongTest.java |
1,135 | public interface Cluster {
/**
* Adds MembershipListener to listen for membership updates.
*
* If the MembershipListener implements the {@link InitialMembershipListener} interface, it will also receive
* the {@link InitialMembershipEvent}.
*
* @param listener membership listener
* @return returns registration id.
*/
String addMembershipListener(MembershipListener listener);
/**
* Removes the specified membership listener.
*
*
* @param registrationId Id of listener registration.
*
* @return true if registration is removed, false otherwise
*/
boolean removeMembershipListener(final String registrationId);
/**
* Set of current members of the cluster.
* Returning set instance is not modifiable.
* Every member in the cluster has the same member list in the same
* order. First member is the oldest member.
*
* @return current members of the cluster
*/
Set<Member> getMembers();
/**
* Returns this Hazelcast instance member
*
* @return this Hazelcast instance member
*/
Member getLocalMember();
/**
* Returns the cluster-wide time in milliseconds.
* <p/>
* Cluster tries to keep a cluster-wide time which is
* might be different than the member's own system time.
* Cluster-wide time is -almost- the same on all members
* of the cluster.
*
* @return cluster-wide time
*/
long getClusterTime();
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_Cluster.java |
111 | public class DoubleMaxUpdater extends Striped64 implements Serializable {
private static final long serialVersionUID = 7249069246863182397L;
/**
* Long representation of negative infinity. See class Double
* internal documentation for explanation.
*/
private static final long MIN_AS_LONG = 0xfff0000000000000L;
/**
* Update function. See class DoubleAdder for rationale
* for using conversions from/to long.
*/
final long fn(long v, long x) {
return Double.longBitsToDouble(v) > Double.longBitsToDouble(x) ? v : x;
}
/**
* Creates a new instance with initial value of {@code
* Double.NEGATIVE_INFINITY}.
*/
public DoubleMaxUpdater() {
base = MIN_AS_LONG;
}
/**
* Updates the maximum to be at least the given value.
*
* @param x the value to update
*/
public void update(double x) {
long lx = Double.doubleToRawLongBits(x);
Cell[] as; long b, v; HashCode hc; Cell a; int n;
if ((as = cells) != null ||
(Double.longBitsToDouble(b = base) < x && !casBase(b, lx))) {
boolean uncontended = true;
int h = (hc = threadHashCode.get()).code;
if (as == null || (n = as.length) < 1 ||
(a = as[(n - 1) & h]) == null ||
(Double.longBitsToDouble(v = a.value) < x &&
!(uncontended = a.cas(v, lx))))
retryUpdate(lx, hc, uncontended);
}
}
/**
* Returns the current maximum. The returned value is
* <em>NOT</em> an atomic snapshot; invocation in the absence of
* concurrent updates returns an accurate result, but concurrent
* updates that occur while the value is being calculated might
* not be incorporated.
*
* @return the maximum
*/
public double max() {
Cell[] as = cells;
double max = Double.longBitsToDouble(base);
if (as != null) {
int n = as.length;
double v;
for (int i = 0; i < n; ++i) {
Cell a = as[i];
if (a != null && (v = Double.longBitsToDouble(a.value)) > max)
max = v;
}
}
return max;
}
/**
* Resets variables maintaining updates to {@code
* Double.NEGATIVE_INFINITY}. This method may be a useful
* alternative to creating a new updater, but is only effective if
* there are no concurrent updates. Because this method is
* intrinsically racy, it should only be used when it is known
* that no threads are concurrently updating.
*/
public void reset() {
internalReset(MIN_AS_LONG);
}
/**
* Equivalent in effect to {@link #max} followed by {@link
* #reset}. This method may apply for example during quiescent
* points between multithreaded computations. If there are
* updates concurrent with this method, the returned value is
* <em>not</em> guaranteed to be the final value occurring before
* the reset.
*
* @return the maximum
*/
public double maxThenReset() {
Cell[] as = cells;
double max = Double.longBitsToDouble(base);
base = MIN_AS_LONG;
if (as != null) {
int n = as.length;
for (int i = 0; i < n; ++i) {
Cell a = as[i];
if (a != null) {
double v = Double.longBitsToDouble(a.value);
a.value = MIN_AS_LONG;
if (v > max)
max = v;
}
}
}
return max;
}
/**
* Returns the String representation of the {@link #max}.
* @return the String representation of the {@link #max}
*/
public String toString() {
return Double.toString(max());
}
/**
* Equivalent to {@link #max}.
*
* @return the max
*/
public double doubleValue() {
return max();
}
/**
* Returns the {@link #max} as a {@code long} after a
* narrowing primitive conversion.
*/
public long longValue() {
return (long)max();
}
/**
* Returns the {@link #max} as an {@code int} after a
* narrowing primitive conversion.
*/
public int intValue() {
return (int)max();
}
/**
* Returns the {@link #max} as a {@code float}
* after a narrowing primitive conversion.
*/
public float floatValue() {
return (float)max();
}
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject();
s.writeDouble(max());
}
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
busy = 0;
cells = null;
base = Double.doubleToRawLongBits(s.readDouble());
}
} | 0true
| src_main_java_jsr166e_DoubleMaxUpdater.java |
1,197 | public class MigrationEvent implements DataSerializable {
private int partitionId;
private Member oldOwner;
private Member newOwner;
private MigrationStatus status;
public MigrationEvent() {
}
public MigrationEvent(int partitionId, Member oldOwner, Member newOwner, MigrationStatus status) {
this.partitionId = partitionId;
this.oldOwner = oldOwner;
this.newOwner = newOwner;
this.status = status;
}
/**
* Returns the id of the partition which is (or being) migrated
* @return partition id
*/
public int getPartitionId() {
return partitionId;
}
/**
* Returns the old owner of the migrating partition
* @return old owner of partition
*/
public Member getOldOwner() {
return oldOwner;
}
/**
* Returns the new owner of the migrating partition
* @return new owner of partition
*/
public Member getNewOwner() {
return newOwner;
}
/**
* Returns the status of the migration: Started, completed or failed
* @return migration status
*/
public MigrationStatus getStatus() {
return status;
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(partitionId);
out.writeObject(oldOwner);
out.writeObject(newOwner);
MigrationStatus.writeTo(status, out);
}
public void readData(ObjectDataInput in) throws IOException {
partitionId = in.readInt();
oldOwner = in.readObject();
newOwner = in.readObject();
status = MigrationStatus.readFrom(in);
}
/**
* Migration status: Started, completed or failed
*/
public static enum MigrationStatus {
STARTED(0),
COMPLETED(1),
FAILED(-1);
private final byte code;
private MigrationStatus(final int code) {
this.code = (byte) code;
}
public static void writeTo(MigrationStatus status, DataOutput out) throws IOException {
out.writeByte(status.code);
}
public static MigrationStatus readFrom(DataInput in) throws IOException {
final byte code = in.readByte();
switch (code) {
case 0:
return STARTED;
case 1:
return COMPLETED;
case -1:
return FAILED;
}
return null;
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("MigrationEvent{");
sb.append("partitionId=").append(partitionId);
sb.append(", status=").append(status);
sb.append(", oldOwner=").append(oldOwner);
sb.append(", newOwner=").append(newOwner);
sb.append('}');
return sb.toString();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_MigrationEvent.java |
1,323 | public class OStorageTransaction {
private final OTransaction clientTx;
private final OOperationUnitId operationUnitId;
private OLogSequenceNumber startLSN;
public OStorageTransaction(OTransaction clientTx, OOperationUnitId operationUnitId) {
this.clientTx = clientTx;
this.operationUnitId = operationUnitId;
}
public OTransaction getClientTx() {
return clientTx;
}
public OOperationUnitId getOperationUnitId() {
return operationUnitId;
}
public OLogSequenceNumber getStartLSN() {
return startLSN;
}
public void setStartLSN(OLogSequenceNumber startLSN) {
this.startLSN = startLSN;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
OStorageTransaction that = (OStorageTransaction) o;
if (!operationUnitId.equals(that.operationUnitId))
return false;
return true;
}
@Override
public int hashCode() {
return operationUnitId.hashCode();
}
@Override
public String toString() {
return "OStorageTransaction{" + "clientTx=" + clientTx + ", operationUnitId=" + operationUnitId + ", startLSN=" + startLSN
+ "} ";
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_OStorageTransaction.java |
893 | private class AsyncAction {
private final SearchScrollRequest request;
private final ActionListener<SearchResponse> listener;
private final ParsedScrollId scrollId;
private final DiscoveryNodes nodes;
private volatile AtomicArray<ShardSearchFailure> shardFailures;
private final AtomicArray<QueryFetchSearchResult> queryFetchResults;
private final AtomicInteger successfulOps;
private final AtomicInteger counter;
private final long startTime = System.currentTimeMillis();
private AsyncAction(SearchScrollRequest request, ParsedScrollId scrollId, ActionListener<SearchResponse> listener) {
this.request = request;
this.listener = listener;
this.scrollId = scrollId;
this.nodes = clusterService.state().nodes();
this.successfulOps = new AtomicInteger(scrollId.getContext().length);
this.counter = new AtomicInteger(scrollId.getContext().length);
this.queryFetchResults = new AtomicArray<QueryFetchSearchResult>(scrollId.getContext().length);
}
protected final ShardSearchFailure[] buildShardFailures() {
if (shardFailures == null) {
return ShardSearchFailure.EMPTY_ARRAY;
}
List<AtomicArray.Entry<ShardSearchFailure>> entries = shardFailures.asList();
ShardSearchFailure[] failures = new ShardSearchFailure[entries.size()];
for (int i = 0; i < failures.length; i++) {
failures[i] = entries.get(i).value;
}
return failures;
}
// we do our best to return the shard failures, but its ok if its not fully concurrently safe
// we simply try and return as much as possible
protected final void addShardFailure(final int shardIndex, ShardSearchFailure failure) {
if (shardFailures == null) {
shardFailures = new AtomicArray<ShardSearchFailure>(scrollId.getContext().length);
}
shardFailures.set(shardIndex, failure);
}
public void start() {
if (scrollId.getContext().length == 0) {
final InternalSearchResponse internalResponse = new InternalSearchResponse(new InternalSearchHits(InternalSearchHits.EMPTY, Long.parseLong(this.scrollId.getAttributes().get("total_hits")), 0.0f), null, null, null, false);
listener.onResponse(new SearchResponse(internalResponse, request.scrollId(), 0, 0, 0l, buildShardFailures()));
return;
}
int localOperations = 0;
Tuple<String, Long>[] context = scrollId.getContext();
for (int i = 0; i < context.length; i++) {
Tuple<String, Long> target = context[i];
DiscoveryNode node = nodes.get(target.v1());
if (node != null) {
if (nodes.localNodeId().equals(node.id())) {
localOperations++;
} else {
executePhase(i, node, target.v2());
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Node [" + target.v1() + "] not available for scroll request [" + scrollId.getSource() + "]");
}
successfulOps.decrementAndGet();
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
}
if (localOperations > 0) {
if (request.operationThreading() == SearchOperationThreading.SINGLE_THREAD) {
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
Tuple<String, Long>[] context1 = scrollId.getContext();
for (int i = 0; i < context1.length; i++) {
Tuple<String, Long> target = context1[i];
DiscoveryNode node = nodes.get(target.v1());
if (node != null && nodes.localNodeId().equals(node.id())) {
executePhase(i, node, target.v2());
}
}
}
});
} else {
boolean localAsync = request.operationThreading() == SearchOperationThreading.THREAD_PER_SHARD;
Tuple<String, Long>[] context1 = scrollId.getContext();
for (int i = 0; i < context1.length; i++) {
final Tuple<String, Long> target = context1[i];
final int shardIndex = i;
final DiscoveryNode node = nodes.get(target.v1());
if (node != null && nodes.localNodeId().equals(node.id())) {
try {
if (localAsync) {
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
executePhase(shardIndex, node, target.v2());
}
});
} else {
executePhase(shardIndex, node, target.v2());
}
} catch (Throwable t) {
onPhaseFailure(t, target.v2(), shardIndex);
}
}
}
}
}
for (Tuple<String, Long> target : scrollId.getContext()) {
DiscoveryNode node = nodes.get(target.v1());
if (node == null) {
if (logger.isDebugEnabled()) {
logger.debug("Node [" + target.v1() + "] not available for scroll request [" + scrollId.getSource() + "]");
}
successfulOps.decrementAndGet();
if (counter.decrementAndGet() == 0) {
finishHim();
}
} else {
}
}
}
void executePhase(final int shardIndex, DiscoveryNode node, final long searchId) {
searchService.sendExecuteScan(node, internalScrollSearchRequest(searchId, request), new SearchServiceListener<QueryFetchSearchResult>() {
@Override
public void onResult(QueryFetchSearchResult result) {
queryFetchResults.set(shardIndex, result);
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
@Override
public void onFailure(Throwable t) {
onPhaseFailure(t, searchId, shardIndex);
}
});
}
void onPhaseFailure(Throwable t, long searchId, int shardIndex) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] Failed to execute query phase", t, searchId);
}
addShardFailure(shardIndex, new ShardSearchFailure(t));
successfulOps.decrementAndGet();
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
private void finishHim() {
try {
innerFinishHim();
} catch (Throwable e) {
ReduceSearchPhaseException failure = new ReduceSearchPhaseException("fetch", "", e, buildShardFailures());
if (logger.isDebugEnabled()) {
logger.debug("failed to reduce search", failure);
}
listener.onFailure(failure);
}
}
private void innerFinishHim() throws IOException {
int numberOfHits = 0;
for (AtomicArray.Entry<QueryFetchSearchResult> entry : queryFetchResults.asList()) {
numberOfHits += entry.value.queryResult().topDocs().scoreDocs.length;
}
ScoreDoc[] docs = new ScoreDoc[numberOfHits];
int counter = 0;
for (AtomicArray.Entry<QueryFetchSearchResult> entry : queryFetchResults.asList()) {
ScoreDoc[] scoreDocs = entry.value.queryResult().topDocs().scoreDocs;
for (ScoreDoc scoreDoc : scoreDocs) {
scoreDoc.shardIndex = entry.index;
docs[counter++] = scoreDoc;
}
}
final InternalSearchResponse internalResponse = searchPhaseController.merge(docs, queryFetchResults, queryFetchResults);
((InternalSearchHits) internalResponse.hits()).totalHits = Long.parseLong(this.scrollId.getAttributes().get("total_hits"));
for (AtomicArray.Entry<QueryFetchSearchResult> entry : queryFetchResults.asList()) {
if (entry.value.queryResult().topDocs().scoreDocs.length < entry.value.queryResult().size()) {
// we found more than we want for this round, remove this from our scrolling
queryFetchResults.set(entry.index, null);
}
}
String scrollId = null;
if (request.scroll() != null) {
// we rebuild the scroll id since we remove shards that we finished scrolling on
scrollId = TransportSearchHelper.buildScrollId(this.scrollId.getType(), queryFetchResults, this.scrollId.getAttributes()); // continue moving the total_hits
}
listener.onResponse(new SearchResponse(internalResponse, scrollId, this.scrollId.getContext().length, successfulOps.get(),
System.currentTimeMillis() - startTime, buildShardFailures()));
}
} | 0true
| src_main_java_org_elasticsearch_action_search_type_TransportSearchScrollScanAction.java |
430 | EventHandler<PortableItemEvent> eventHandler = new EventHandler<PortableItemEvent>() {
public void handle(PortableItemEvent portableItemEvent) {
E item = includeValue ? (E) getContext().getSerializationService().toObject(portableItemEvent.getItem()) : null;
Member member = getContext().getClusterService().getMember(portableItemEvent.getUuid());
ItemEvent<E> itemEvent = new ItemEvent<E>(name, portableItemEvent.getEventType(), item, member);
if (portableItemEvent.getEventType() == ItemEventType.ADDED) {
listener.itemAdded(itemEvent);
} else {
listener.itemRemoved(itemEvent);
}
}
@Override
public void onListenerRegister() {
}
}; | 1no label
| hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientQueueProxy.java |
1,982 | public class SourceProvider {
/**
* Indicates that the source is unknown.
*/
public static final Object UNKNOWN_SOURCE = "[unknown source]";
private final ImmutableSet<String> classNamesToSkip;
public SourceProvider() {
this.classNamesToSkip = ImmutableSet.of(SourceProvider.class.getName());
}
public static final SourceProvider DEFAULT_INSTANCE
= new SourceProvider(ImmutableSet.of(SourceProvider.class.getName()));
private SourceProvider(Iterable<String> classesToSkip) {
this.classNamesToSkip = ImmutableSet.copyOf(classesToSkip);
}
/**
* Returns a new instance that also skips {@code moreClassesToSkip}.
*/
public SourceProvider plusSkippedClasses(Class... moreClassesToSkip) {
return new SourceProvider(Iterables.concat(classNamesToSkip, asStrings(moreClassesToSkip)));
}
/**
* Returns the class names as Strings
*/
private static List<String> asStrings(Class... classes) {
List<String> strings = Lists.newArrayList();
for (Class c : classes) {
strings.add(c.getName());
}
return strings;
}
/**
* Returns the calling line of code. The selected line is the nearest to the top of the stack that
* is not skipped.
*/
public StackTraceElement get() {
for (final StackTraceElement element : new Throwable().getStackTrace()) {
String className = element.getClassName();
if (!classNamesToSkip.contains(className)) {
return element;
}
}
throw new AssertionError();
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_internal_SourceProvider.java |
692 | @Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_PRODUCT_FEATURED")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
public class FeaturedProductImpl implements FeaturedProduct {
private static final long serialVersionUID = 1L;
/** The id. */
@Id
@GeneratedValue(generator= "FeaturedProductId")
@GenericGenerator(
name="FeaturedProductId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="FeaturedProductImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.catalog.domain.FeaturedProductImpl")
}
)
@Column(name = "FEATURED_PRODUCT_ID")
protected Long id;
@Column(name = "SEQUENCE")
@AdminPresentation(visibility = VisibilityEnum.HIDDEN_ALL)
protected Long sequence;
@Column(name = "PROMOTION_MESSAGE")
@AdminPresentation(friendlyName = "FeaturedProductImpl_Featured_Product_Promotion_Message", largeEntry=true)
protected String promotionMessage;
@ManyToOne(targetEntity = CategoryImpl.class)
@JoinColumn(name = "CATEGORY_ID")
@Index(name="PRODFEATURED_CATEGORY_INDEX", columnNames={"CATEGORY_ID"})
protected Category category = new CategoryImpl();
@ManyToOne(targetEntity = ProductImpl.class)
@JoinColumn(name = "PRODUCT_ID")
@Index(name="PRODFEATURED_PRODUCT_INDEX", columnNames={"PRODUCT_ID"})
protected Product product = new ProductImpl();
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public void setSequence(Long sequence) {
this.sequence = sequence;
}
@Override
public Long getSequence() {
return this.sequence;
}
@Override
public String getPromotionMessage() {
return promotionMessage;
}
@Override
public void setPromotionMessage(String promotionMessage) {
this.promotionMessage = promotionMessage;
}
@Override
public Category getCategory() {
return category;
}
@Override
public void setCategory(Category category) {
this.category = category;
}
@Override
public Product getProduct() {
return product;
}
@Override
public void setProduct(Product product) {
this.product = product;
}
@Override
public Product getRelatedProduct() {
return product;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_FeaturedProductImpl.java |
1,128 | public interface BaseMap<K, V> extends DistributedObject {
/**
* Returns {@code true} if this map contains an entry for the specified
* key.
*
* @param key key
* @return {@code true} if this map contains an entry for the specified key
*/
boolean containsKey(Object key);
/**
* Returns the value for the specified key, or {@code null} if this map does not contain this key.
*
* @param key key
* @return value
*/
V get(Object key);
/**
* Associates the specified value with the specified key in this map
* If the map previously contained a mapping for
* the key, the old value is replaced by the specified value.
*
* @param key key
* @param value value
* @return previous value associated with {@code key} or {@code null}
* if there was no mapping for {@code key}.
*/
V put(K key, V value);
/**
* Associates the specified value with the specified key in this map
* If the map previously contained a mapping for
* the key, the old value is replaced by the specified value.
*
* <p/> This method is preferred to {@link #put(Object, Object)}
* if the old value is not needed.
*
* @param key key
* @param value value
*/
void set(K key, V value);
/**
* If the specified key is not already associated
* with a value, associate it with the given value.
* This is equivalent to
* <pre>
* if (!map.containsKey(key))
* return map.put(key, value);
* else
* return map.get(key);</pre>
* except that the action is performed atomically.
*
* @param key key
* @param value value
* @return previous value associated with {@code key} or {@code null}
* if there was no mapping for {@code key}.
*/
V putIfAbsent(K key, V value);
/**
* Replaces the entry for a key only if currently mapped to some value.
* This is equivalent to
* <pre>
* if (map.containsKey(key)) {
* return map.put(key, value);
* } else return null;</pre>
* except that the action is performed atomically.
*
* @param key key
* @param value value
* @return previous value associated with {@code key} or {@code null}
* if there was no mapping for {@code key}.
*/
V replace(K key, V value);
/**
* Replaces the entry for a key only if currently mapped to a given value.
* This is equivalent to
* <pre>
* if (map.containsKey(key) && map.get(key).equals(oldValue)) {
* map.put(key, newValue);
* return true;
* } else return false;</pre>
* except that the action is performed atomically.
*
* @param key key
* @param oldValue old value
* @param newValue new value
* @return {@code true} if the value was replaced
*/
boolean replace(K key, V oldValue, V newValue);
/**
* Removes the mapping for a key from this map if it is present.
* <p>The map will not contain a mapping for the specified key once the
* call returns.
*
* @param key key
* @return previous value associated with {@code key} or {@code null}
* if there was no mapping for {@code key}.
*/
V remove(Object key);
/**
* Removes the mapping for a key from this map if it is present.
* <p>The map will not contain a mapping for the specified key once the
* call returns.
*
* * <p> This method is preferred to {@link #remove(Object)}
* if the old value is not needed.
*
* @param key key
*/
void delete(Object key);
/**
* Removes the entry for a key only if currently mapped to a given value.
* This is equivalent to
* <pre>
* if (map.containsKey(key) && map.get(key).equals(value)) {
* map.remove(key);
* return true;
* } else return false;</pre>
* except that the action is performed atomically.
*
* @param key key
* @param value value
* @return {@code true} if the value was removed
*/
boolean remove(Object key, Object value);
/**
* Returns <tt>true</tt> if this map contains no entries.
*
* @return <tt>true</tt> if this map contains no entries
*/
boolean isEmpty();
/**
* Returns the number of entries in this map.
*
* @return the number of entries in this map
*/
int size();
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_BaseMap.java |
1,658 | public class ParseFieldTests extends ElasticsearchTestCase {
public void testParse() {
String[] values = new String[]{"foo_bar", "fooBar"};
ParseField field = new ParseField(randomFrom(values));
String[] deprecated = new String[]{"barFoo", "bar_foo"};
ParseField withDepredcations = field.withDeprecation("Foobar", randomFrom(deprecated));
assertThat(field, not(sameInstance(withDepredcations)));
assertThat(field.match(randomFrom(values), ParseField.EMPTY_FLAGS), is(true));
assertThat(field.match("foo bar", ParseField.EMPTY_FLAGS), is(false));
assertThat(field.match(randomFrom(deprecated), ParseField.EMPTY_FLAGS), is(false));
assertThat(field.match("barFoo", ParseField.EMPTY_FLAGS), is(false));
assertThat(withDepredcations.match(randomFrom(values), ParseField.EMPTY_FLAGS), is(true));
assertThat(withDepredcations.match("foo bar", ParseField.EMPTY_FLAGS), is(false));
assertThat(withDepredcations.match(randomFrom(deprecated), ParseField.EMPTY_FLAGS), is(true));
assertThat(withDepredcations.match("barFoo", ParseField.EMPTY_FLAGS), is(true));
// now with strict mode
EnumSet<ParseField.Flag> flags = EnumSet.of(ParseField.Flag.STRICT);
assertThat(field.match(randomFrom(values), flags), is(true));
assertThat(field.match("foo bar", flags), is(false));
assertThat(field.match(randomFrom(deprecated), flags), is(false));
assertThat(field.match("barFoo", flags), is(false));
assertThat(withDepredcations.match(randomFrom(values), flags), is(true));
assertThat(withDepredcations.match("foo bar", flags), is(false));
try {
withDepredcations.match(randomFrom(deprecated), flags);
fail();
} catch (ElasticsearchIllegalArgumentException ex) {
}
try {
withDepredcations.match("barFoo", flags);
fail();
} catch (ElasticsearchIllegalArgumentException ex) {
}
}
} | 0true
| src_test_java_org_elasticsearch_common_ParseFieldTests.java |
186 | public class OPair<K extends Comparable<K>, V> implements Entry<K, V>, Comparable<OPair<K, V>> {
public K key;
public V value;
public OPair() {
}
public OPair(final K iKey, final V iValue) {
key = iKey;
value = iValue;
}
public OPair(final Entry<K, V> iSource) {
key = iSource.getKey();
value = iSource.getValue();
}
public void init(final K iKey, final V iValue) {
key = iKey;
value = iValue;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(final V iValue) {
V oldValue = value;
value = iValue;
return oldValue;
}
@Override
public String toString() {
return key + ":" + value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.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;
OPair<?, ?> other = (OPair<?, ?>) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
public int compareTo(final OPair<K, V> o) {
return key.compareTo(o.key);
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_util_OPair.java |
1,372 | @Scope("singleton")
@Provider
public class BroadleafRestExceptionMapper implements ExceptionMapper<Throwable>, MessageSourceAware {
private static final Log LOG = LogFactory.getLog(BroadleafRestExceptionMapper.class);
protected MessageSource messageSource;
@Override
public Response toResponse(Throwable t) {
Response response = null;
if (t instanceof WebApplicationException) {
response = ((WebApplicationException) t).getResponse();
if (response.getStatus() == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
LOG.error("An exception was caught by the JAX-RS framework: Status: " + response.getStatus() + " Message: " + response.getEntity(), t);
} else if (response.getStatus() == Response.Status.FORBIDDEN.getStatusCode()) {
LOG.warn("Someone tried to access a resource that was forbidden: Status: " + response.getStatus() + " Message: " + response.getEntity(), t);
} else if (response.getStatus() == Response.Status.BAD_REQUEST.getStatusCode() && LOG.isDebugEnabled()) {
LOG.debug("Bad Request: Status: " + response.getStatus() + " Message: " + response.getEntity(), t);
} else if (response.getStatus() == Response.Status.NOT_ACCEPTABLE.getStatusCode() && LOG.isDebugEnabled()) {
LOG.debug("Not acceptable: Status: " + response.getStatus() + " Message: " + response.getEntity(), t);
} else {
LOG.error("An exception was caught by the JAX-RS framework: Status: " + response.getStatus() + " Message: " + response.getEntity(), t);
}
} else {
LOG.error("An exception was caught by the JAX-RS framework: ", t);
}
if (response != null) {
Object msg = response.getEntity();
if (msg == null) {
msg = "An error occurred";
}
return Response.status(response.getStatus()).type(MediaType.TEXT_PLAIN).entity(msg).build();
}
return Response.status(500).type(MediaType.TEXT_PLAIN).entity("An unknown or unreported error has occured. If the problem persists, please contact the administrator.").build();
}
@Override
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_BroadleafRestExceptionMapper.java |
1,424 | public final class HazelcastInstanceFactory {
private final static String HZ_CLIENT_LOADER_CLASSNAME = "com.hazelcast.hibernate.instance.HazelcastClientLoader";
private final static String HZ_INSTANCE_LOADER_CLASSNAME = "com.hazelcast.hibernate.instance.HazelcastInstanceLoader";
private HazelcastInstanceFactory() {
}
public static HazelcastInstance createInstance(Properties props) throws CacheException {
return createInstanceLoader(props).loadInstance();
}
public static IHazelcastInstanceLoader createInstanceLoader(Properties props) throws CacheException {
boolean useNativeClient = false;
if (props != null) {
useNativeClient = CacheEnvironment.isNativeClient(props);
}
IHazelcastInstanceLoader loader = null;
Class loaderClass = null;
ClassLoader cl = HazelcastInstanceFactory.class.getClassLoader();
try {
if (useNativeClient) {
loaderClass = cl.loadClass(HZ_CLIENT_LOADER_CLASSNAME);
} else {
loaderClass = cl.loadClass(HZ_INSTANCE_LOADER_CLASSNAME);
}
loader = (IHazelcastInstanceLoader) loaderClass.newInstance();
} catch (Exception e) {
throw new CacheException(e);
}
loader.configure(props);
return loader;
}
} | 0true
| hazelcast-hibernate_hazelcast-hibernate4_src_main_java_com_hazelcast_hibernate_instance_HazelcastInstanceFactory.java |
2,151 | public final class AllTokenStream extends TokenFilter {
public static TokenStream allTokenStream(String allFieldName, AllEntries allEntries, Analyzer analyzer) throws IOException {
return new AllTokenStream(analyzer.tokenStream(allFieldName, allEntries), allEntries);
}
private final BytesRef payloadSpare = new BytesRef(new byte[4]);
private final AllEntries allEntries;
private final OffsetAttribute offsetAttribute;
private final PayloadAttribute payloadAttribute;
AllTokenStream(TokenStream input, AllEntries allEntries) {
super(input);
this.allEntries = allEntries;
offsetAttribute = addAttribute(OffsetAttribute.class);
payloadAttribute = addAttribute(PayloadAttribute.class);
}
public AllEntries allEntries() {
return allEntries;
}
@Override
public final boolean incrementToken() throws IOException {
if (!input.incrementToken()) {
return false;
}
final float boost = allEntries.boost(offsetAttribute.startOffset());
if (boost != 1.0f) {
encodeFloat(boost, payloadSpare.bytes, payloadSpare.offset);
payloadAttribute.setPayload(payloadSpare);
} else {
payloadAttribute.setPayload(null);
}
return true;
}
@Override
public String toString() {
return allEntries.toString();
}
} | 0true
| src_main_java_org_elasticsearch_common_lucene_all_AllTokenStream.java |
2,459 | @SuppressWarnings("serial")
private final static class KeyLock extends ReentrantLock {
private final AtomicInteger count = new AtomicInteger(1);
} | 0true
| src_main_java_org_elasticsearch_common_util_concurrent_KeyedLock.java |
82 | @SuppressWarnings("serial")
static final class MapReduceValuesToDoubleTask<K,V>
extends BulkTask<K,V,Double> {
final ObjectToDouble<? super V> transformer;
final DoubleByDoubleToDouble reducer;
final double basis;
double result;
MapReduceValuesToDoubleTask<K,V> rights, nextRight;
MapReduceValuesToDoubleTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceValuesToDoubleTask<K,V> nextRight,
ObjectToDouble<? super V> transformer,
double basis,
DoubleByDoubleToDouble reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Double getRawResult() { return result; }
public final void compute() {
final ObjectToDouble<? super V> transformer;
final DoubleByDoubleToDouble reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
double r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceValuesToDoubleTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
rights, transformer, r, reducer)).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
r = reducer.apply(r, transformer.apply(p.val));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked") MapReduceValuesToDoubleTask<K,V>
t = (MapReduceValuesToDoubleTask<K,V>)c,
s = t.rights;
while (s != null) {
t.result = reducer.apply(t.result, s.result);
s = t.rights = s.nextRight;
}
}
}
}
} | 0true
| src_main_java_jsr166e_ConcurrentHashMapV8.java |
724 | preFetchedValues.add(new Map.Entry<K, V>() {
@Override
public K getKey() {
return entry.getKey();
}
@Override
public V getValue() {
return resultValue;
}
@Override
public V setValue(V v) {
throw new UnsupportedOperationException("setValue");
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_sbtree_OSBTreeMapEntryIterator.java |
545 | deleteByQueryAction.execute(Requests.deleteByQueryRequest(request.indices()).source(querySourceBuilder), new ActionListener<DeleteByQueryResponse>() {
@Override
public void onResponse(DeleteByQueryResponse deleteByQueryResponse) {
refreshAction.execute(Requests.refreshRequest(request.indices()), new ActionListener<RefreshResponse>() {
@Override
public void onResponse(RefreshResponse refreshResponse) {
removeMapping();
}
@Override
public void onFailure(Throwable e) {
removeMapping();
}
protected void removeMapping() {
DeleteMappingClusterStateUpdateRequest clusterStateUpdateRequest = new DeleteMappingClusterStateUpdateRequest()
.indices(request.indices()).types(request.types())
.ackTimeout(request.timeout())
.masterNodeTimeout(request.masterNodeTimeout());
metaDataMappingService.removeMapping(clusterStateUpdateRequest, new ClusterStateUpdateListener() {
@Override
public void onResponse(ClusterStateUpdateResponse response) {
listener.onResponse(new DeleteMappingResponse(response.isAcknowledged()));
}
@Override
public void onFailure(Throwable t) {
listener.onFailure(t);
}
});
}
});
}
@Override
public void onFailure(Throwable t) {
listener.onFailure(t);
}
}); | 1no label
| src_main_java_org_elasticsearch_action_admin_indices_mapping_delete_TransportDeleteMappingAction.java |
2,052 | return new Provider<T>() {
public T get() {
checkState(delegate != null,
"This Provider cannot be used until the Injector has been created.");
return delegate.get();
}
@Override
public String toString() {
return "Provider<" + key.getTypeLiteral() + ">";
}
}; | 0true
| src_main_java_org_elasticsearch_common_inject_spi_ProviderLookup.java |
1,327 | @Service("blSearchService")
public class DatabaseSearchServiceImpl implements SearchService {
@Resource(name = "blCatalogService")
protected CatalogService catalogService;
@Resource(name = "blSearchFacetDao")
protected SearchFacetDao searchFacetDao;
@Resource(name = "blFieldDao")
protected FieldDao fieldDao;
protected static String CACHE_NAME = "blStandardElements";
protected static String CACHE_KEY_PREFIX = "facet:";
protected Cache cache = CacheManager.getInstance().getCache(CACHE_NAME);
@Override
public ProductSearchResult findExplicitProductsByCategory(Category category, ProductSearchCriteria searchCriteria) throws ServiceException {
throw new UnsupportedOperationException("See findProductsByCategory or use the SolrSearchService implementation");
}
@Override
public ProductSearchResult findProductsByCategoryAndQuery(Category category, String query, ProductSearchCriteria searchCriteria) throws ServiceException {
throw new UnsupportedOperationException("This operation is only supported by the SolrSearchService by default");
}
@Override
public ProductSearchResult findProductsByCategory(Category category, ProductSearchCriteria searchCriteria) {
ProductSearchResult result = new ProductSearchResult();
setQualifiedKeys(searchCriteria);
List<Product> products = catalogService.findFilteredActiveProductsByCategory(category, searchCriteria);
List<SearchFacetDTO> facets = getCategoryFacets(category);
setActiveFacets(facets, searchCriteria);
result.setProducts(products);
result.setFacets(facets);
result.setTotalResults(products.size());
result.setPage(1);
result.setPageSize(products.size());
return result;
}
@Override
public ProductSearchResult findProductsByQuery(String query, ProductSearchCriteria searchCriteria) {
ProductSearchResult result = new ProductSearchResult();
setQualifiedKeys(searchCriteria);
List<Product> products = catalogService.findFilteredActiveProductsByQuery(query, searchCriteria);
List<SearchFacetDTO> facets = getSearchFacets();
setActiveFacets(facets, searchCriteria);
result.setProducts(products);
result.setFacets(facets);
result.setTotalResults(products.size());
result.setPage(1);
result.setPageSize(products.size());
return result;
}
@Override
@SuppressWarnings("unchecked")
public List<SearchFacetDTO> getSearchFacets() {
List<SearchFacetDTO> facets = null;
String cacheKey = CACHE_KEY_PREFIX + "blc-search";
Element element = cache.get(cacheKey);
if (element != null) {
facets = (List<SearchFacetDTO>) element.getValue();
}
if (facets == null) {
facets = buildSearchFacetDtos(searchFacetDao.readAllSearchFacets());
element = new Element(cacheKey, facets);
cache.put(element);
}
return facets;
}
@Override
@SuppressWarnings("unchecked")
public List<SearchFacetDTO> getCategoryFacets(Category category) {
List<SearchFacetDTO> facets = null;
String cacheKey = CACHE_KEY_PREFIX + "category:" + category.getId();
Element element = cache.get(cacheKey);
if (element != null) {
facets = (List<SearchFacetDTO>) element.getValue();
}
if (facets == null) {
List<CategorySearchFacet> categorySearchFacets = category.getCumulativeSearchFacets();
List<SearchFacet> searchFacets = new ArrayList<SearchFacet>();
for (CategorySearchFacet categorySearchFacet : categorySearchFacets) {
searchFacets.add(categorySearchFacet.getSearchFacet());
}
facets = buildSearchFacetDtos(searchFacets);
element = new Element(cacheKey, facets);
cache.put(element);
}
return facets;
}
/**
* Perform any necessary conversion of the key to be used by the search service
* @param criteria
*/
protected void setQualifiedKeys(ProductSearchCriteria criteria) {
// Convert the filter criteria url keys
Map<String, String[]> convertedFilterCriteria = new HashMap<String, String[]>();
for (Entry<String, String[]> entry : criteria.getFilterCriteria().entrySet()) {
Field field = fieldDao.readFieldByAbbreviation(entry.getKey());
String qualifiedFieldName = getDatabaseQualifiedFieldName(field.getQualifiedFieldName());
convertedFilterCriteria.put(qualifiedFieldName, entry.getValue());
}
criteria.setFilterCriteria(convertedFilterCriteria);
// Convert the sort criteria url keys
if (StringUtils.isNotBlank(criteria.getSortQuery())) {
StringBuilder convertedSortQuery = new StringBuilder();
for (String sortQuery : criteria.getSortQuery().split(",")) {
String[] sort = sortQuery.split(" ");
if (sort.length == 2) {
String key = sort[0];
Field field = fieldDao.readFieldByAbbreviation(key);
String qualifiedFieldName = getDatabaseQualifiedFieldName(field.getQualifiedFieldName());
if (convertedSortQuery.length() > 0) {
convertedSortQuery.append(",");
}
convertedSortQuery.append(qualifiedFieldName).append(" ").append(sort[1]);
}
}
criteria.setSortQuery(convertedSortQuery.toString());
}
}
/**
* From the Field's qualifiedName, build out the qualified name to be used by the ProductDao
* to find the requested products.
*
* @param qualifiedFieldName
* @return the database qualified name
*/
protected String getDatabaseQualifiedFieldName(String qualifiedFieldName) {
if (qualifiedFieldName.contains("productAttributes")) {
return qualifiedFieldName.replace("product.", "");
} else if (qualifiedFieldName.contains("defaultSku")) {
return qualifiedFieldName.replace("product.", "");
} else {
return qualifiedFieldName;
}
}
protected void setActiveFacets(List<SearchFacetDTO> facets, ProductSearchCriteria searchCriteria) {
for (SearchFacetDTO facet : facets) {
String qualifiedFieldName = getDatabaseQualifiedFieldName(facet.getFacet().getField().getQualifiedFieldName());
for (Entry<String, String[]> entry : searchCriteria.getFilterCriteria().entrySet()) {
if (qualifiedFieldName.equals(entry.getKey())) {
facet.setActive(true);
}
}
}
}
/**
* Create the wrapper DTO around the SearchFacet
* @param categoryFacets
* @return the wrapper DTO
*/
protected List<SearchFacetDTO> buildSearchFacetDtos(List<SearchFacet> categoryFacets) {
List<SearchFacetDTO> facets = new ArrayList<SearchFacetDTO>();
for (SearchFacet facet : categoryFacets) {
SearchFacetDTO dto = new SearchFacetDTO();
dto.setFacet(facet);
dto.setShowQuantity(false);
dto.setFacetValues(getFacetValues(facet));
dto.setActive(false);
facets.add(dto);
}
return facets;
}
protected List<SearchFacetResultDTO> getFacetValues(SearchFacet facet) {
if (facet.getSearchFacetRanges().size() > 0) {
return getRangeFacetValues(facet);
} else {
return getMatchFacetValues(facet);
}
}
protected List<SearchFacetResultDTO> getRangeFacetValues(SearchFacet facet) {
List<SearchFacetResultDTO> results = new ArrayList<SearchFacetResultDTO>();
List<SearchFacetRange> ranges = facet.getSearchFacetRanges();
Collections.sort(ranges, new Comparator<SearchFacetRange>() {
public int compare(SearchFacetRange o1, SearchFacetRange o2) {
return o1.getMinValue().compareTo(o2.getMinValue());
}
});
for (SearchFacetRange range : ranges) {
SearchFacetResultDTO dto = new SearchFacetResultDTO();
dto.setMinValue(range.getMinValue());
dto.setMaxValue(range.getMaxValue());
dto.setFacet(facet);
results.add(dto);
}
return results;
}
protected List<SearchFacetResultDTO> getMatchFacetValues(SearchFacet facet) {
List<SearchFacetResultDTO> results = new ArrayList<SearchFacetResultDTO>();
String qualifiedFieldName = facet.getField().getQualifiedFieldName();
qualifiedFieldName = getDatabaseQualifiedFieldName(qualifiedFieldName);
List<String> values = searchFacetDao.readDistinctValuesForField(qualifiedFieldName, String.class);
Collections.sort(values);
for (String value : values) {
SearchFacetResultDTO dto = new SearchFacetResultDTO();
dto.setValue(value);
dto.setFacet(facet);
results.add(dto);
}
return results;
}
@Override
public void rebuildIndex() {
throw new UnsupportedOperationException("Indexes are not supported by this implementation");
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_service_DatabaseSearchServiceImpl.java |
931 | while (makeDbCall(iMyDb, new ODbRelatedCall<Boolean>() {
public Boolean call() {
return myEntryIterator.hasNext();
}
})) { | 0true
| core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocumentHelper.java |
443 | class NotSerializableDocument extends ODocument {
private static final long serialVersionUID = 1L;
private void writeObject(ObjectOutputStream oos) throws IOException {
throw new NotSerializableException();
}
} | 0true
| core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedSetTest.java |
208 | private class ClusterAuthenticator implements Authenticator {
@Override
public void auth(ClientConnection connection) throws AuthenticationException, IOException {
authenticate(connection, credentials, principal, false, false);
}
} | 1no label
| hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientConnectionManagerImpl.java |
438 | map.addChangeListener(new OMultiValueChangeListener<Object, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) {
changed.value = true;
}
}); | 0true
| core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedMapTest.java |
1,072 | public class CartTest extends OrderBaseTest {
@Resource(name="blMergeCartService")
private MergeCartService mergeCartService;
protected boolean cartContainsOnlyTheseItems(Order cart, List<OrderItem> orderItems) {
List<OrderItem> cartOrderItems = new ArrayList<OrderItem>(cart.getOrderItems());
for (OrderItem item : orderItems) {
ListIterator<OrderItem> it = cartOrderItems.listIterator();
while (it.hasNext()) {
OrderItem otherItem = it.next();
if (orderItemsSemanticallyEqual((DiscreteOrderItem) item, (DiscreteOrderItem) otherItem)) {
it.remove();
break;
}
}
}
return cartOrderItems.size() == 0;
}
protected boolean orderItemsSemanticallyEqual(DiscreteOrderItem one, DiscreteOrderItem two) {
if ((one == null && two != null) || (one != null && two == null)) {
return false;
}
if (!one.getClass().equals(two.getClass())) {
return false;
}
if (!one.getSku().getId().equals(two.getSku().getId())) {
return false;
}
if (one.getQuantity() != two.getQuantity()) {
return false;
}
if (((one.getProduct() == null && two.getProduct() != null) ||
(one.getProduct() != null && two.getProduct() == null)) &&
!one.getProduct().getId().equals(two.getProduct().getId())) {
return false;
}
if (((one.getCategory() == null && two.getCategory() != null) ||
(one.getCategory() != null && two.getCategory() == null)) &&
!one.getCategory().getId().equals(two.getCategory().getId())) {
return false;
}
return true;
}
@Test(groups = { "testCartAndNamedOrder" })
@Transactional
public void testMoveAllItemsToCartFromNamedOrder() throws RemoveFromCartException, AddToCartException {
Order namedOrder = setUpNamedOrder();
List<OrderItem> namedOrderItems = new ArrayList<OrderItem>();
namedOrderItems.addAll(namedOrder.getOrderItems());
Order cart = orderService.createNewCartForCustomer(namedOrder.getCustomer());
cart = orderService.addAllItemsFromNamedOrder(namedOrder, true);
assert cartContainsOnlyTheseItems(cart, namedOrderItems);
assert namedOrder.getOrderItems().size() == 0;
}
@Test(groups = { "testCartAndNamedOrder" })
@Transactional
public void testAddAllItemsToCartFromNamedOrder() throws RemoveFromCartException, AddToCartException {
Order namedOrder = setUpNamedOrder();
List<OrderItem> namedOrderItems = new ArrayList<OrderItem>();
namedOrderItems.addAll(namedOrder.getOrderItems());
Order cart = orderService.createNewCartForCustomer(namedOrder.getCustomer());
orderService.setMoveNamedOrderItems(false);
cart = orderService.addAllItemsFromNamedOrder(namedOrder, true);
orderService.setMoveNamedOrderItems(true);
assert cartContainsOnlyTheseItems(cart, namedOrderItems);
}
@Test(groups = { "testCartAndNamedOrder" })
@Transactional
public void testAddAllItemsToCartFromNamedOrderWithoutExistingCart() throws RemoveFromCartException, AddToCartException {
Order namedOrder = setUpNamedOrder();
List<OrderItem> namedOrderItems = new ArrayList<OrderItem>();
namedOrderItems.addAll(namedOrder.getOrderItems());
orderService.setMoveNamedOrderItems(false);
Order cart = orderService.addAllItemsFromNamedOrder(namedOrder, true);
orderService.setMoveNamedOrderItems(true);
assert cartContainsOnlyTheseItems(cart, namedOrderItems);
}
@Test(groups = { "testCartAndNamedOrder" })
@Transactional
public void testAddItemToCartFromNamedOrder() throws RemoveFromCartException, AddToCartException {
Order namedOrder = setUpNamedOrder();
List<OrderItem> namedOrderItems = new ArrayList<OrderItem>();
namedOrderItems.addAll(namedOrder.getOrderItems());
List<OrderItem> movedOrderItems = new ArrayList<OrderItem>();
movedOrderItems.add(namedOrderItems.get(0));
Order cart = orderService.createNewCartForCustomer(namedOrder.getCustomer());
orderService.setMoveNamedOrderItems(false);
cart = orderService.addItemFromNamedOrder(namedOrder, movedOrderItems.get(0), true);
orderService.setMoveNamedOrderItems(true);
assert cartContainsOnlyTheseItems(cart, movedOrderItems);
}
@Test(groups = { "testCartAndNamedOrder" })
@Transactional
public void testMoveItemToCartFromNamedOrder() throws RemoveFromCartException, AddToCartException {
Order namedOrder = setUpNamedOrder();
List<OrderItem> namedOrderItems = new ArrayList<OrderItem>();
namedOrderItems.addAll(namedOrder.getOrderItems());
List<OrderItem> movedOrderItems = new ArrayList<OrderItem>();
movedOrderItems.add(namedOrderItems.get(0));
Order cart = orderService.createNewCartForCustomer(namedOrder.getCustomer());
cart = orderService.addItemFromNamedOrder(namedOrder, movedOrderItems.get(0), true);
List<Order> customerNamedOrders = orderService.findOrdersForCustomer(namedOrder.getCustomer(), OrderStatus.NAMED);
assert customerNamedOrders.size() == 0;
assert cart.getOrderItems().size() == 1;
assert namedOrder.getOrderItems().size() == 0;
assert cartContainsOnlyTheseItems(cart, movedOrderItems);
}
@Test(groups = { "testCartAndNamedOrder" })
@Transactional
public void testMoveItemToCartFromNamedOrderWithoutExistingCart() throws RemoveFromCartException, AddToCartException {
Order namedOrder = setUpNamedOrder();
List<OrderItem> namedOrderItems = new ArrayList<OrderItem>();
namedOrderItems.addAll(namedOrder.getOrderItems());
List<OrderItem> movedOrderItems = new ArrayList<OrderItem>();
movedOrderItems.add(namedOrderItems.get(0));
Order cart = orderService.addItemFromNamedOrder(namedOrder, movedOrderItems.get(0), true);
List<Order> customerNamedOrders = orderService.findOrdersForCustomer(namedOrder.getCustomer(), OrderStatus.NAMED);
assert customerNamedOrders.size() == 0;
assert cart.getOrderItems().size() == 1;
assert namedOrder.getOrderItems().size() == 0;
assert cartContainsOnlyTheseItems(cart, movedOrderItems);
}
@Transactional
@Test(groups = { "testMergeCart" })
public void testMergeWithNoAnonymousCart() throws PricingException, RemoveFromCartException, AddToCartException {
Order anonymousCart = null;
Order customerCart = setUpCartWithActiveSku();
Customer customer = customerCart.getCustomer();
MergeCartResponse response = mergeCartService.mergeCart(customer, anonymousCart);
assert response.getOrder().getOrderItems().size() == 1;
assert response.getOrder().getId().equals(customerCart.getId());
assert response.isMerged() == false;
}
@Transactional
@Test(groups = { "testMergeCart" })
public void testMergeWithNoCustomerCart() throws PricingException, RemoveFromCartException, AddToCartException {
Order anonymousCart = setUpCartWithActiveSku();
Order customerCart = null;
Customer customer = customerService.saveCustomer(createNamedCustomer());
MergeCartResponse response = mergeCartService.mergeCart(customer, anonymousCart);
assert response.getOrder().getOrderItems().size() == 1;
assert response.getOrder().getId().equals(anonymousCart.getId());
assert response.isMerged() == false;
}
@Transactional
@Test(groups = { "testMergeCart" })
public void testMergeWithBothCarts() throws PricingException, RemoveFromCartException, AddToCartException {
Order anonymousCart = setUpCartWithActiveSku();
Order customerCart = setUpCartWithActiveSku();
Customer customer = customerCart.getCustomer();
MergeCartResponse response = mergeCartService.mergeCart(customer, anonymousCart);
assert response.getOrder().getOrderItems().size() == 1;
assert response.getOrder().getId().equals(anonymousCart.getId());
assert response.isMerged() == false;
}
@Transactional
@Test(groups = { "testMergeCart" })
public void testMergeWithInactiveAnonymousCart() throws PricingException, RemoveFromCartException, AddToCartException {
Order anonymousCart = null;
Order customerCart = setUpCartWithInactiveSku();
Customer customer = customerCart.getCustomer();
MergeCartResponse response = mergeCartService.mergeCart(customer, anonymousCart);
assert response.getOrder().getOrderItems().size() == 0;
assert response.getOrder().getId().equals(customerCart.getId());
assert response.isMerged() == false;
}
/*
@Transactional
@Test(groups = { "testMergeCartLegacy" })
public void testMergeToExistingCart() throws PricingException {
//sets up anonymous cart with a DiscreteOrderItem, inactive DiscreteOrderItem, BundleOrderItem, and inactive BundleOrderItem
Order anonymousCart = setUpAnonymousCartWithInactiveSku();
Customer customer = customerService.saveCustomer(createNamedCustomer());
//sets up existing cart with a DiscreteOrderItem, inactive DiscreteOrderItem, BundleOrderItem, and inactive BundleOrderItem
initializeExistingCartWithInactiveSkuAndInactiveBundle(customer);
MergeCartResponse response = cartService.mergeCart(customer, anonymousCart);
assert response.getAddedItems().size() == 2;
assert response.getOrder().getOrderItems().size() == 4;
assert response.isMerged();
assert response.getRemovedItems().size() == 4;
}
@Transactional
@Test(groups = { "testMergeCartLegacy" })
public void testMergeToExistingCartWithGiftWrapOrderItems() throws PricingException {
//sets up anonymous cart with two DiscreteOrderItems, and a GiftWrapOrderItem
Order anonymousCart = setUpAnonymousCartWithGiftWrap();
Customer customer = customerService.saveCustomer(createNamedCustomer());
//sets up existing cart with two active DiscreteOrderItems
initializeExistingCart(customer);
MergeCartResponse response = cartService.mergeCart(customer, anonymousCart);
assert response.getAddedItems().size() == 3;
assert response.getOrder().getOrderItems().size() == 5;
assert response.isMerged();
assert response.getRemovedItems().size() == 0;
//sets up anonymous cart with a DiscreteOrderItem, inactive DiscreteOrderItem and inactive GiftWrapOrderItem (due to inactive wrapped item)
anonymousCart = setUpAnonymousCartWithInactiveGiftWrap();
customer = customerService.saveCustomer(createNamedCustomer());
//sets up existing cart with two active DiscreteOrderItems
initializeExistingCart(customer);
response = cartService.mergeCart(customer, anonymousCart);
assert response.getAddedItems().size() == 1;
assert response.getOrder().getOrderItems().size() == 3;
assert response.isMerged();
assert response.getRemovedItems().size() == 2;
//sets up anonymous cart with a DiscreteOrderItem, inactive DiscreteOrderItem and inactive GiftWrapOrderItem (due to inactive wrapped item) inside a BundleOrderItem
anonymousCart = setUpAnonymousCartWithInactiveBundleGiftWrap();
customer = customerService.saveCustomer(createNamedCustomer());
//sets up existing cart with two active DiscreteOrderItems
initializeExistingCart(customer);
response = cartService.mergeCart(customer, anonymousCart);
assert response.getAddedItems().size() == 0;
assert response.getOrder().getOrderItems().size() == 2;
assert response.isMerged();
assert response.getRemovedItems().size() == 1;
//sets up anonymous cart with active DiscreteOrderItems, and active GiftWrapOrderItem inside a BundleOrderItem
anonymousCart = setUpAnonymousCartWithBundleGiftWrap();
customer = customerService.saveCustomer(createNamedCustomer());
//sets up existing cart with two active DiscreteOrderItems
initializeExistingCart(customer);
response = cartService.mergeCart(customer, anonymousCart);
assert response.getAddedItems().size() == 1;
assert response.getOrder().getOrderItems().size() == 3;
assert response.isMerged();
assert response.getRemovedItems().size() == 0;
//sets up anonymous cart with active DiscreteOrderItems, and active GiftWrapOrderItem inside a BundleOrderItem. Active OrderItems are also in the root of the order and the bundled GiftWrapOrderItem wraps the root OrderItems
anonymousCart = setUpAnonymousCartWithBundleGiftWrapReferringToRootItems();
customer = customerService.saveCustomer(createNamedCustomer());
//sets up existing cart with two active DiscreteOrderItems
initializeExistingCart(customer);
response = cartService.mergeCart(customer, anonymousCart);
assert response.getAddedItems().size() == 3;
assert response.getOrder().getOrderItems().size() == 5;
assert response.isMerged();
assert response.getRemovedItems().size() == 0;
//sets up anonymous cart with two BundleOrderItems, one of which has a GiftWrapOrderItem. The GiftWrapOrderItem wraps the DiscreteOrderItems from the other bundle, which makes its bundle inactive.
anonymousCart = setUpAnonymousCartWithBundleGiftWrapReferringItemsInAnotherBundle();
customer = customerService.saveCustomer(createNamedCustomer());
//sets up existing cart with two active DiscreteOrderItems
initializeExistingCart(customer);
response = cartService.mergeCart(customer, anonymousCart);
assert response.getAddedItems().size() == 1;
assert response.getOrder().getOrderItems().size() == 3;
assert response.isMerged();
assert response.getRemovedItems().size() == 1;
}
*/
} | 0true
| integration_src_test_java_org_broadleafcommerce_core_order_service_CartTest.java |
2,980 | public class SimpleDocSetCache extends AbstractIndexComponent implements DocSetCache, SegmentReader.CoreClosedListener {
private final ConcurrentMap<Object, Queue<FixedBitSet>> cache;
@Inject
public SimpleDocSetCache(Index index, @IndexSettings Settings indexSettings) {
super(index, indexSettings);
this.cache = ConcurrentCollections.newConcurrentMap();
}
@Override
public void onClose(Object coreCacheKey) {
cache.remove(coreCacheKey);
}
@Override
public void clear(String reason) {
cache.clear();
}
@Override
public void clear(IndexReader reader) {
cache.remove(reader.getCoreCacheKey());
}
@Override
public ContextDocIdSet obtain(AtomicReaderContext context) {
Queue<FixedBitSet> docIdSets = cache.get(context.reader().getCoreCacheKey());
if (docIdSets == null) {
if (context.reader() instanceof SegmentReader) {
((SegmentReader) context.reader()).addCoreClosedListener(this);
}
cache.put(context.reader().getCoreCacheKey(), ConcurrentCollections.<FixedBitSet>newQueue());
return new ContextDocIdSet(context, new FixedBitSet(context.reader().maxDoc()));
}
FixedBitSet docIdSet = docIdSets.poll();
if (docIdSet == null) {
docIdSet = new FixedBitSet(context.reader().maxDoc());
} else {
docIdSet.clear(0, docIdSet.length());
}
return new ContextDocIdSet(context, docIdSet);
}
@Override
public void release(ContextDocIdSet docSet) {
Queue<FixedBitSet> docIdSets = cache.get(docSet.context.reader().getCoreCacheKey());
if (docIdSets != null) {
docIdSets.add((FixedBitSet) docSet.docSet);
}
}
} | 0true
| src_main_java_org_elasticsearch_index_cache_docset_simple_SimpleDocSetCache.java |
330 | Iterables.filter(config.getKeys(prefix),new Predicate<String>() {
@Override
public boolean apply(@Nullable String s) {
return !writtenValues.containsKey(s);
}
})); | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_TransactionalConfiguration.java |
614 | public class BroadleafThymeleafMessageResolver extends AbstractMessageResolver {
protected static final Log LOG = LogFactory.getLog(BroadleafThymeleafMessageResolver.class);
protected static final String I18N_VALUE_KEY = "translate";
@Resource(name = "blTranslationService")
protected TranslationService translationService;
/**
* Resolve a translated value of an object's property.
*
* @param args
* @param key
* @param messageParams
* @return the resolved message
*/
public MessageResolution resolveMessage(final Arguments args, final String key, final Object[] messageParams) {
Validate.notNull(args, "args cannot be null");
Validate.notNull(args.getContext().getLocale(), "Locale in context cannot be null");
Validate.notNull(key, "Message key cannot be null");
if (I18N_VALUE_KEY.equals(key)) {
Object entity = messageParams[0];
String property = (String) messageParams[1];
Locale locale = args.getContext().getLocale();
if (LOG.isTraceEnabled()) {
LOG.trace(String.format("Attempting to resolve translated value for object %s, property %s, locale %s",
entity, property, locale));
}
String resolvedMessage = translationService.getTranslatedValue(entity, property, locale);
if (StringUtils.isNotBlank(resolvedMessage)) {
return new MessageResolution(resolvedMessage);
}
}
return null;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_web_BroadleafThymeleafMessageResolver.java |
1,274 | private static class ChatMessage implements Serializable {
private String username;
private String message;
public ChatMessage(String username, String message) {
this.username = username;
this.message = message;
}
public String toString() {
return username + ": " + message;
}
public void send(IMap<String, ChatMessage> map) {
map.put(username, this);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_examples_ChatApplication.java |
958 | public abstract class AbstractUnlockRequest extends KeyBasedClientRequest
implements Portable, SecureRequest {
protected Data key;
private long threadId;
private boolean force;
public AbstractUnlockRequest() {
}
public AbstractUnlockRequest(Data key, long threadId) {
this.key = key;
this.threadId = threadId;
}
protected AbstractUnlockRequest(Data key, long threadId, boolean force) {
this.key = key;
this.threadId = threadId;
this.force = force;
}
protected String getName() {
return (String) getClientEngine().toObject(key);
}
@Override
protected final Object getKey() {
return key;
}
@Override
protected final Operation prepareOperation() {
return new UnlockOperation(getNamespace(), key, threadId, force);
}
protected abstract ObjectNamespace getNamespace();
@Override
public final String getServiceName() {
return LockService.SERVICE_NAME;
}
@Override
public void write(PortableWriter writer) throws IOException {
writer.writeLong("tid", threadId);
writer.writeBoolean("force", force);
ObjectDataOutput out = writer.getRawDataOutput();
key.writeData(out);
}
@Override
public void read(PortableReader reader) throws IOException {
threadId = reader.readLong("tid");
force = reader.readBoolean("force");
ObjectDataInput in = reader.getRawDataInput();
key = new Data();
key.readData(in);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_lock_client_AbstractUnlockRequest.java |
762 | public class TransportMultiGetAction extends TransportAction<MultiGetRequest, MultiGetResponse> {
private final ClusterService clusterService;
private final TransportShardMultiGetAction shardAction;
@Inject
public TransportMultiGetAction(Settings settings, ThreadPool threadPool, TransportService transportService, ClusterService clusterService, TransportShardMultiGetAction shardAction) {
super(settings, threadPool);
this.clusterService = clusterService;
this.shardAction = shardAction;
transportService.registerHandler(MultiGetAction.NAME, new TransportHandler());
}
@Override
protected void doExecute(final MultiGetRequest request, final ActionListener<MultiGetResponse> listener) {
ClusterState clusterState = clusterService.state();
clusterState.blocks().globalBlockedRaiseException(ClusterBlockLevel.READ);
final AtomicArray<MultiGetItemResponse> responses = new AtomicArray<MultiGetItemResponse>(request.items.size());
Map<ShardId, MultiGetShardRequest> shardRequests = new HashMap<ShardId, MultiGetShardRequest>();
for (int i = 0; i < request.items.size(); i++) {
MultiGetRequest.Item item = request.items.get(i);
if (!clusterState.metaData().hasConcreteIndex(item.index())) {
responses.set(i, new MultiGetItemResponse(null, new MultiGetResponse.Failure(item.index(), item.type(), item.id(), "[" + item.index() + "] missing")));
continue;
}
if (item.routing() == null && clusterState.getMetaData().routingRequired(item.index(), item.type())) {
responses.set(i, new MultiGetItemResponse(null, new MultiGetResponse.Failure(item.index(), item.type(), item.id(), "routing is required, but hasn't been specified")));
continue;
}
item.routing(clusterState.metaData().resolveIndexRouting(item.routing(), item.index()));
item.index(clusterState.metaData().concreteIndex(item.index()));
ShardId shardId = clusterService.operationRouting()
.getShards(clusterState, item.index(), item.type(), item.id(), item.routing(), null).shardId();
MultiGetShardRequest shardRequest = shardRequests.get(shardId);
if (shardRequest == null) {
shardRequest = new MultiGetShardRequest(shardId.index().name(), shardId.id());
shardRequest.preference(request.preference);
shardRequest.realtime(request.realtime);
shardRequest.refresh(request.refresh);
shardRequests.put(shardId, shardRequest);
}
shardRequest.add(i, item.type(), item.id(), item.fields(), item.version(), item.versionType(), item.fetchSourceContext());
}
if (shardRequests.size() == 0) {
// only failures..
listener.onResponse(new MultiGetResponse(responses.toArray(new MultiGetItemResponse[responses.length()])));
}
final AtomicInteger counter = new AtomicInteger(shardRequests.size());
for (final MultiGetShardRequest shardRequest : shardRequests.values()) {
shardAction.execute(shardRequest, new ActionListener<MultiGetShardResponse>() {
@Override
public void onResponse(MultiGetShardResponse response) {
for (int i = 0; i < response.locations.size(); i++) {
responses.set(response.locations.get(i), new MultiGetItemResponse(response.responses.get(i), response.failures.get(i)));
}
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
@Override
public void onFailure(Throwable e) {
// create failures for all relevant requests
String message = ExceptionsHelper.detailedMessage(e);
for (int i = 0; i < shardRequest.locations.size(); i++) {
responses.set(shardRequest.locations.get(i), new MultiGetItemResponse(null,
new MultiGetResponse.Failure(shardRequest.index(), shardRequest.types.get(i), shardRequest.ids.get(i), message)));
}
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
private void finishHim() {
listener.onResponse(new MultiGetResponse(responses.toArray(new MultiGetItemResponse[responses.length()])));
}
});
}
}
class TransportHandler extends BaseTransportRequestHandler<MultiGetRequest> {
@Override
public MultiGetRequest newInstance() {
return new MultiGetRequest();
}
@Override
public void messageReceived(final MultiGetRequest 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<MultiGetResponse>() {
@Override
public void onResponse(MultiGetResponse response) {
try {
channel.sendResponse(response);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send error response for action [" + MultiGetAction.NAME + "] and request [" + request + "]", e1);
}
}
});
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
} | 1no label
| src_main_java_org_elasticsearch_action_get_TransportMultiGetAction.java |
239 | public interface OCacheLevelOneLocator {
public OCache threadLocalCache();
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_cache_OCacheLevelOneLocator.java |
285 | public class ActionRequestValidationException extends ElasticsearchException {
private final List<String> validationErrors = new ArrayList<String>();
public ActionRequestValidationException() {
super(null);
}
public void addValidationError(String error) {
validationErrors.add(error);
}
public void addValidationErrors(Iterable<String> errors) {
for (String error : errors) {
validationErrors.add(error);
}
}
public List<String> validationErrors() {
return validationErrors;
}
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder();
sb.append("Validation Failed: ");
int index = 0;
for (String error : validationErrors) {
sb.append(++index).append(": ").append(error).append(";");
}
return sb.toString();
}
} | 0true
| src_main_java_org_elasticsearch_action_ActionRequestValidationException.java |
207 | public static class Done extends LogEntry
{
Done( int identifier )
{
super( identifier );
}
@Override
public String toString()
{
return "Done[" + getIdentifier() + "]";
}
} | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogEntry.java |
831 | public class SearchRequestBuilder extends ActionRequestBuilder<SearchRequest, SearchResponse, SearchRequestBuilder> {
private SearchSourceBuilder sourceBuilder;
public SearchRequestBuilder(Client client) {
super((InternalClient) client, new SearchRequest());
}
/**
* Sets the indices the search will be executed on.
*/
public SearchRequestBuilder setIndices(String... indices) {
request.indices(indices);
return this;
}
/**
* The document types to execute the search against. Defaults to be executed against
* all types.
*/
public SearchRequestBuilder setTypes(String... types) {
request.types(types);
return this;
}
/**
* The search type to execute, defaults to {@link org.elasticsearch.action.search.SearchType#DEFAULT}.
*/
public SearchRequestBuilder setSearchType(SearchType searchType) {
request.searchType(searchType);
return this;
}
/**
* The a string representation search type to execute, defaults to {@link SearchType#DEFAULT}. Can be
* one of "dfs_query_then_fetch"/"dfsQueryThenFetch", "dfs_query_and_fetch"/"dfsQueryAndFetch",
* "query_then_fetch"/"queryThenFetch", and "query_and_fetch"/"queryAndFetch".
*/
public SearchRequestBuilder setSearchType(String searchType) throws ElasticsearchIllegalArgumentException {
request.searchType(searchType);
return this;
}
/**
* If set, will enable scrolling of the search request.
*/
public SearchRequestBuilder setScroll(Scroll scroll) {
request.scroll(scroll);
return this;
}
/**
* If set, will enable scrolling of the search request for the specified timeout.
*/
public SearchRequestBuilder setScroll(TimeValue keepAlive) {
request.scroll(keepAlive);
return this;
}
/**
* If set, will enable scrolling of the search request for the specified timeout.
*/
public SearchRequestBuilder setScroll(String keepAlive) {
request.scroll(keepAlive);
return this;
}
/**
* An optional timeout to control how long search is allowed to take.
*/
public SearchRequestBuilder setTimeout(TimeValue timeout) {
sourceBuilder().timeout(timeout);
return this;
}
/**
* An optional timeout to control how long search is allowed to take.
*/
public SearchRequestBuilder setTimeout(String timeout) {
sourceBuilder().timeout(timeout);
return this;
}
/**
* A comma separated list of routing values to control the shards the search will be executed on.
*/
public SearchRequestBuilder setRouting(String routing) {
request.routing(routing);
return this;
}
/**
* The routing values to control the shards that the search will be executed on.
*/
public SearchRequestBuilder 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, or
* a custom value, which guarantees that the same order will be used across different requests.
*/
public SearchRequestBuilder setPreference(String preference) {
request.preference(preference);
return this;
}
/**
* Controls the the search operation threading model.
*/
public SearchRequestBuilder setOperationThreading(SearchOperationThreading operationThreading) {
request.operationThreading(operationThreading);
return this;
}
/**
* Sets the string representation of the operation threading model. Can be one of
* "no_threads", "single_thread" and "thread_per_shard".
*/
public SearchRequestBuilder setOperationThreading(String operationThreading) {
request.operationThreading(operationThreading);
return this;
}
/**
* Specifies what type of requested indices to ignore and wildcard indices expressions.
*
* For example indices that don't exist.
*/
public SearchRequestBuilder setIndicesOptions(IndicesOptions indicesOptions) {
request().indicesOptions(indicesOptions);
return this;
}
/**
* Constructs a new search source builder with a search query.
*
* @see org.elasticsearch.index.query.QueryBuilders
*/
public SearchRequestBuilder setQuery(QueryBuilder queryBuilder) {
sourceBuilder().query(queryBuilder);
return this;
}
/**
* Constructs a new search source builder with a raw search query.
*/
public SearchRequestBuilder setQuery(String query) {
sourceBuilder().query(query);
return this;
}
/**
* Constructs a new search source builder with a raw search query.
*/
public SearchRequestBuilder setQuery(BytesReference queryBinary) {
sourceBuilder().query(queryBinary);
return this;
}
/**
* Constructs a new search source builder with a raw search query.
*/
public SearchRequestBuilder setQuery(byte[] queryBinary) {
sourceBuilder().query(queryBinary);
return this;
}
/**
* Constructs a new search source builder with a raw search query.
*/
public SearchRequestBuilder setQuery(byte[] queryBinary, int queryBinaryOffset, int queryBinaryLength) {
sourceBuilder().query(queryBinary, queryBinaryOffset, queryBinaryLength);
return this;
}
/**
* Constructs a new search source builder with a raw search query.
*/
public SearchRequestBuilder setQuery(XContentBuilder query) {
sourceBuilder().query(query);
return this;
}
/**
* Constructs a new search source builder with a raw search query.
*/
public SearchRequestBuilder setQuery(Map query) {
sourceBuilder().query(query);
return this;
}
/**
* Sets a filter that will be executed after the query has been executed and only has affect on the search hits
* (not aggregations or facets). This filter is always executed as last filtering mechanism.
*/
public SearchRequestBuilder setPostFilter(FilterBuilder postFilter) {
sourceBuilder().postFilter(postFilter);
return this;
}
/**
* Sets a filter on the query executed that only applies to the search query
* (and not facets for example).
*/
public SearchRequestBuilder setPostFilter(String postFilter) {
sourceBuilder().postFilter(postFilter);
return this;
}
/**
* Sets a filter on the query executed that only applies to the search query
* (and not facets for example).
*/
public SearchRequestBuilder setPostFilter(BytesReference postFilter) {
sourceBuilder().postFilter(postFilter);
return this;
}
/**
* Sets a filter on the query executed that only applies to the search query
* (and not facets for example).
*/
public SearchRequestBuilder setPostFilter(byte[] postFilter) {
sourceBuilder().postFilter(postFilter);
return this;
}
/**
* Sets a filter on the query executed that only applies to the search query
* (and not facets for example).
*/
public SearchRequestBuilder setPostFilter(byte[] postFilter, int postFilterOffset, int postFilterLength) {
sourceBuilder().postFilter(postFilter, postFilterOffset, postFilterLength);
return this;
}
/**
* Sets a filter on the query executed that only applies to the search query
* (and not facets for example).
*/
public SearchRequestBuilder setPostFilter(XContentBuilder postFilter) {
sourceBuilder().postFilter(postFilter);
return this;
}
/**
* Sets a filter on the query executed that only applies to the search query
* (and not facets for example).
*/
public SearchRequestBuilder setPostFilter(Map postFilter) {
sourceBuilder().postFilter(postFilter);
return this;
}
/**
* Sets the minimum score below which docs will be filtered out.
*/
public SearchRequestBuilder setMinScore(float minScore) {
sourceBuilder().minScore(minScore);
return this;
}
/**
* From index to start the search from. Defaults to <tt>0</tt>.
*/
public SearchRequestBuilder setFrom(int from) {
sourceBuilder().from(from);
return this;
}
/**
* The number of search hits to return. Defaults to <tt>10</tt>.
*/
public SearchRequestBuilder setSize(int size) {
sourceBuilder().size(size);
return this;
}
/**
* Should each {@link org.elasticsearch.search.SearchHit} be returned with an
* explanation of the hit (ranking).
*/
public SearchRequestBuilder setExplain(boolean explain) {
sourceBuilder().explain(explain);
return this;
}
/**
* Should each {@link org.elasticsearch.search.SearchHit} be returned with its
* version.
*/
public SearchRequestBuilder setVersion(boolean version) {
sourceBuilder().version(version);
return this;
}
/**
* Sets the boost a specific index will receive when the query is executeed against it.
*
* @param index The index to apply the boost against
* @param indexBoost The boost to apply to the index
*/
public SearchRequestBuilder addIndexBoost(String index, float indexBoost) {
sourceBuilder().indexBoost(index, indexBoost);
return this;
}
/**
* The stats groups this request will be aggregated under.
*/
public SearchRequestBuilder setStats(String... statsGroups) {
sourceBuilder().stats(statsGroups);
return this;
}
/**
* Sets no fields to be loaded, resulting in only id and type to be returned per field.
*/
public SearchRequestBuilder setNoFields() {
sourceBuilder().noFields();
return this;
}
/**
* Indicates whether the response should contain the stored _source for every hit
*
* @param fetch
* @return
*/
public SearchRequestBuilder setFetchSource(boolean fetch) {
sourceBuilder().fetchSource(fetch);
return this;
}
/**
* Indicate that _source should be returned with every hit, with an "include" and/or "exclude" set which can include simple wildcard
* elements.
*
* @param include An optional include (optionally wildcarded) pattern to filter the returned _source
* @param exclude An optional exclude (optionally wildcarded) pattern to filter the returned _source
*/
public SearchRequestBuilder setFetchSource(@Nullable String include, @Nullable String exclude) {
sourceBuilder().fetchSource(include, exclude);
return this;
}
/**
* Indicate that _source should be returned with every hit, with an "include" and/or "exclude" set which can include simple wildcard
* elements.
*
* @param includes An optional list of include (optionally wildcarded) pattern to filter the returned _source
* @param excludes An optional list of exclude (optionally wildcarded) pattern to filter the returned _source
*/
public SearchRequestBuilder setFetchSource(@Nullable String[] includes, @Nullable String[] excludes) {
sourceBuilder().fetchSource(includes, excludes);
return this;
}
/**
* Adds a field to load and return (note, it must be stored) as part of the search request.
* If none are specified, the source of the document will be return.
*/
public SearchRequestBuilder addField(String field) {
sourceBuilder().field(field);
return this;
}
/**
* Adds a field data based field to load and return. The field does not have to be stored,
* but its recommended to use non analyzed or numeric fields.
*
* @param name The field to get from the field data cache
*/
public SearchRequestBuilder addFieldDataField(String name) {
sourceBuilder().fieldDataField(name);
return this;
}
/**
* Adds a script based field to load and return. The field does not have to be stored,
* but its recommended to use non analyzed or numeric fields.
*
* @param name The name that will represent this value in the return hit
* @param script The script to use
*/
public SearchRequestBuilder addScriptField(String name, String script) {
sourceBuilder().scriptField(name, script);
return this;
}
/**
* Adds a script based field to load and return. The field does not have to be stored,
* but its recommended to use non analyzed or numeric fields.
*
* @param name The name that will represent this value in the return hit
* @param script The script to use
* @param params Parameters that the script can use.
*/
public SearchRequestBuilder addScriptField(String name, String script, Map<String, Object> params) {
sourceBuilder().scriptField(name, script, params);
return this;
}
/**
* Adds a partial field based on _source, with an "include" and/or "exclude" set which can include simple wildcard
* elements.
*
* @deprecated since 1.0.0
* use {@link org.elasticsearch.action.search.SearchRequestBuilder#setFetchSource(String, String)} instead
*
* @param name The name of the field
* @param include An optional include (optionally wildcarded) pattern from _source
* @param exclude An optional exclude (optionally wildcarded) pattern from _source
*/
@Deprecated
public SearchRequestBuilder addPartialField(String name, @Nullable String include, @Nullable String exclude) {
sourceBuilder().partialField(name, include, exclude);
return this;
}
/**
* Adds a partial field based on _source, with an "includes" and/or "excludes set which can include simple wildcard
* elements.
*
* @deprecated since 1.0.0
* use {@link org.elasticsearch.action.search.SearchRequestBuilder#setFetchSource(String[], String[])} instead
*
* @param name The name of the field
* @param includes An optional list of includes (optionally wildcarded) patterns from _source
* @param excludes An optional list of excludes (optionally wildcarded) patterns from _source
*/
@Deprecated
public SearchRequestBuilder addPartialField(String name, @Nullable String[] includes, @Nullable String[] excludes) {
sourceBuilder().partialField(name, includes, excludes);
return this;
}
/**
* Adds a script based field to load and return. The field does not have to be stored,
* but its recommended to use non analyzed or numeric fields.
*
* @param name The name that will represent this value in the return hit
* @param lang The language of the script
* @param script The script to use
* @param params Parameters that the script can use (can be <tt>null</tt>).
*/
public SearchRequestBuilder addScriptField(String name, String lang, String script, Map<String, Object> params) {
sourceBuilder().scriptField(name, lang, script, params);
return this;
}
/**
* Adds a sort against the given field name and the sort ordering.
*
* @param field The name of the field
* @param order The sort ordering
*/
public SearchRequestBuilder addSort(String field, SortOrder order) {
sourceBuilder().sort(field, order);
return this;
}
/**
* Adds a generic sort builder.
*
* @see org.elasticsearch.search.sort.SortBuilders
*/
public SearchRequestBuilder addSort(SortBuilder sort) {
sourceBuilder().sort(sort);
return this;
}
/**
* Applies when sorting, and controls if scores will be tracked as well. Defaults to
* <tt>false</tt>.
*/
public SearchRequestBuilder setTrackScores(boolean trackScores) {
sourceBuilder().trackScores(trackScores);
return this;
}
/**
* Adds the fields to load and return as part of the search request. If none are specified,
* the source of the document will be returned.
*/
public SearchRequestBuilder addFields(String... fields) {
sourceBuilder().fields(fields);
return this;
}
/**
* Adds a facet to the search operation.
*/
public SearchRequestBuilder addFacet(FacetBuilder facet) {
sourceBuilder().facet(facet);
return this;
}
/**
* Sets a raw (xcontent) binary representation of facets to use.
*/
public SearchRequestBuilder setFacets(BytesReference facets) {
sourceBuilder().facets(facets);
return this;
}
/**
* Sets a raw (xcontent) binary representation of facets to use.
*/
public SearchRequestBuilder setFacets(byte[] facets) {
sourceBuilder().facets(facets);
return this;
}
/**
* Sets a raw (xcontent) binary representation of facets to use.
*/
public SearchRequestBuilder setFacets(byte[] facets, int facetsOffset, int facetsLength) {
sourceBuilder().facets(facets, facetsOffset, facetsLength);
return this;
}
/**
* Sets a raw (xcontent) binary representation of facets to use.
*/
public SearchRequestBuilder setFacets(XContentBuilder facets) {
sourceBuilder().facets(facets);
return this;
}
/**
* Sets a raw (xcontent) binary representation of facets to use.
*/
public SearchRequestBuilder setFacets(Map facets) {
sourceBuilder().facets(facets);
return this;
}
/**
* Adds an get to the search operation.
*/
public SearchRequestBuilder addAggregation(AbstractAggregationBuilder aggregation) {
sourceBuilder().aggregation(aggregation);
return this;
}
/**
* Sets a raw (xcontent) binary representation of addAggregation to use.
*/
public SearchRequestBuilder setAggregations(BytesReference aggregations) {
sourceBuilder().aggregations(aggregations);
return this;
}
/**
* Sets a raw (xcontent) binary representation of addAggregation to use.
*/
public SearchRequestBuilder setAggregations(byte[] aggregations) {
sourceBuilder().aggregations(aggregations);
return this;
}
/**
* Sets a raw (xcontent) binary representation of addAggregation to use.
*/
public SearchRequestBuilder setAggregations(byte[] aggregations, int aggregationsOffset, int aggregationsLength) {
sourceBuilder().facets(aggregations, aggregationsOffset, aggregationsLength);
return this;
}
/**
* Sets a raw (xcontent) binary representation of addAggregation to use.
*/
public SearchRequestBuilder setAggregations(XContentBuilder aggregations) {
sourceBuilder().aggregations(aggregations);
return this;
}
/**
* Sets a raw (xcontent) binary representation of addAggregation to use.
*/
public SearchRequestBuilder setAggregations(Map aggregations) {
sourceBuilder().aggregations(aggregations);
return this;
}
/**
* Adds a field to be highlighted with default fragment size of 100 characters, and
* default number of fragments of 5.
*
* @param name The field to highlight
*/
public SearchRequestBuilder addHighlightedField(String name) {
highlightBuilder().field(name);
return this;
}
/**
* Adds a field to be highlighted with a provided fragment size (in characters), and
* default number of fragments of 5.
*
* @param name The field to highlight
* @param fragmentSize The size of a fragment in characters
*/
public SearchRequestBuilder addHighlightedField(String name, int fragmentSize) {
highlightBuilder().field(name, fragmentSize);
return this;
}
/**
* Adds a field to be highlighted with a provided fragment size (in characters), and
* a provided (maximum) number of fragments.
*
* @param name The field to highlight
* @param fragmentSize The size of a fragment in characters
* @param numberOfFragments The (maximum) number of fragments
*/
public SearchRequestBuilder addHighlightedField(String name, int fragmentSize, int numberOfFragments) {
highlightBuilder().field(name, fragmentSize, numberOfFragments);
return this;
}
/**
* Adds a field to be highlighted with a provided fragment size (in characters),
* a provided (maximum) number of fragments and an offset for the highlight.
*
* @param name The field to highlight
* @param fragmentSize The size of a fragment in characters
* @param numberOfFragments The (maximum) number of fragments
*/
public SearchRequestBuilder addHighlightedField(String name, int fragmentSize, int numberOfFragments,
int fragmentOffset) {
highlightBuilder().field(name, fragmentSize, numberOfFragments, fragmentOffset);
return this;
}
/**
* Adds a highlighted field.
*/
public SearchRequestBuilder addHighlightedField(HighlightBuilder.Field field) {
highlightBuilder().field(field);
return this;
}
/**
* Set a tag scheme that encapsulates a built in pre and post tags. The allows schemes
* are <tt>styled</tt> and <tt>default</tt>.
*
* @param schemaName The tag scheme name
*/
public SearchRequestBuilder setHighlighterTagsSchema(String schemaName) {
highlightBuilder().tagsSchema(schemaName);
return this;
}
/**
* Explicitly set the pre tags that will be used for highlighting.
*/
public SearchRequestBuilder setHighlighterPreTags(String... preTags) {
highlightBuilder().preTags(preTags);
return this;
}
/**
* Explicitly set the post tags that will be used for highlighting.
*/
public SearchRequestBuilder setHighlighterPostTags(String... postTags) {
highlightBuilder().postTags(postTags);
return this;
}
/**
* The order of fragments per field. By default, ordered by the order in the
* highlighted text. Can be <tt>score</tt>, which then it will be ordered
* by score of the fragments.
*/
public SearchRequestBuilder setHighlighterOrder(String order) {
highlightBuilder().order(order);
return this;
}
/**
* The encoder to set for highlighting
*/
public SearchRequestBuilder setHighlighterEncoder(String encoder) {
highlightBuilder().encoder(encoder);
return this;
}
/**
* Sets a query to be used for highlighting all fields instead of the search query.
*/
public SearchRequestBuilder setHighlighterQuery(QueryBuilder highlightQuery) {
highlightBuilder().highlightQuery(highlightQuery);
return this;
}
public SearchRequestBuilder setHighlighterRequireFieldMatch(boolean requireFieldMatch) {
highlightBuilder().requireFieldMatch(requireFieldMatch);
return this;
}
/**
* The highlighter type to use.
*/
public SearchRequestBuilder setHighlighterType(String type) {
highlightBuilder().highlighterType(type);
return this;
}
/**
* Sets the size of the fragment to return from the beginning of the field if there are no matches to
* highlight and the field doesn't also define noMatchSize.
* @param noMatchSize integer to set or null to leave out of request. default is null.
* @return this builder for chaining
*/
public SearchRequestBuilder setHighlighterNoMatchSize(Integer noMatchSize) {
highlightBuilder().noMatchSize(noMatchSize);
return this;
}
public SearchRequestBuilder setHighlighterOptions(Map<String, Object> options) {
highlightBuilder().options(options);
return this;
}
/**
* Delegates to {@link org.elasticsearch.search.suggest.SuggestBuilder#setText(String)}.
*/
public SearchRequestBuilder setSuggestText(String globalText) {
suggestBuilder().setText(globalText);
return this;
}
/**
* Delegates to {@link org.elasticsearch.search.suggest.SuggestBuilder#addSuggestion(org.elasticsearch.search.suggest.SuggestBuilder.SuggestionBuilder)}.
*/
public SearchRequestBuilder addSuggestion(SuggestBuilder.SuggestionBuilder<?> suggestion) {
suggestBuilder().addSuggestion(suggestion);
return this;
}
/**
* Clears all rescorers on the builder and sets the first one. To use multiple rescore windows use
* {@link #addRescorer(org.elasticsearch.search.rescore.RescoreBuilder.Rescorer, int)}.
* @param rescorer rescorer configuration
* @return this for chaining
*/
public SearchRequestBuilder setRescorer(RescoreBuilder.Rescorer rescorer) {
sourceBuilder().clearRescorers();
return addRescorer(rescorer);
}
/**
* Clears all rescorers on the builder and sets the first one. To use multiple rescore windows use
* {@link #addRescorer(org.elasticsearch.search.rescore.RescoreBuilder.Rescorer, int)}.
* @param rescorer rescorer configuration
* @param window rescore window
* @return this for chaining
*/
public SearchRequestBuilder setRescorer(RescoreBuilder.Rescorer rescorer, int window) {
sourceBuilder().clearRescorers();
return addRescorer(rescorer, window);
}
/**
* Adds a new rescorer.
* @param rescorer rescorer configuration
* @return this for chaining
*/
public SearchRequestBuilder addRescorer(RescoreBuilder.Rescorer rescorer) {
sourceBuilder().addRescorer(new RescoreBuilder().rescorer(rescorer));
return this;
}
/**
* Adds a new rescorer.
* @param rescorer rescorer configuration
* @param window rescore window
* @return this for chaining
*/
public SearchRequestBuilder addRescorer(RescoreBuilder.Rescorer rescorer, int window) {
sourceBuilder().addRescorer(new RescoreBuilder().rescorer(rescorer).windowSize(window));
return this;
}
/**
* Clears all rescorers from the builder.
* @return this for chaining
*/
public SearchRequestBuilder clearRescorers() {
sourceBuilder().clearRescorers();
return this;
}
/**
* Sets the rescore window for all rescorers that don't specify a window when added.
* @param window rescore window
* @return this for chaining
*/
public SearchRequestBuilder setRescoreWindow(int window) {
sourceBuilder().defaultRescoreWindowSize(window);
return this;
}
/**
* Sets the source of the request as a json string. Note, settings anything other
* than the search type will cause this source to be overridden, consider using
* {@link #setExtraSource(String)}.
*/
public SearchRequestBuilder setSource(String source) {
request.source(source);
return this;
}
/**
* Sets the source of the request as a json string. Allows to set other parameters.
*/
public SearchRequestBuilder setExtraSource(String source) {
request.extraSource(source);
return this;
}
/**
* Sets the source of the request as a json string. Note, settings anything other
* than the search type will cause this source to be overridden, consider using
* {@link #setExtraSource(BytesReference)}.
*/
public SearchRequestBuilder setSource(BytesReference source) {
request.source(source, false);
return this;
}
/**
* Sets the source of the request as a json string. Note, settings anything other
* than the search type will cause this source to be overridden, consider using
* {@link #setExtraSource(BytesReference)}.
*/
public SearchRequestBuilder setSource(BytesReference source, boolean unsafe) {
request.source(source, unsafe);
return this;
}
/**
* Sets the source of the request as a json string. Note, settings anything other
* than the search type will cause this source to be overridden, consider using
* {@link #setExtraSource(byte[])}.
*/
public SearchRequestBuilder setSource(byte[] source) {
request.source(source);
return this;
}
/**
* Sets the source of the request as a json string. Allows to set other parameters.
*/
public SearchRequestBuilder setExtraSource(BytesReference source) {
request.extraSource(source, false);
return this;
}
/**
* Sets the source of the request as a json string. Allows to set other parameters.
*/
public SearchRequestBuilder setExtraSource(BytesReference source, boolean unsafe) {
request.extraSource(source, unsafe);
return this;
}
/**
* Sets the source of the request as a json string. Allows to set other parameters.
*/
public SearchRequestBuilder setExtraSource(byte[] source) {
request.extraSource(source);
return this;
}
/**
* Sets the source of the request as a json string. Note, settings anything other
* than the search type will cause this source to be overridden, consider using
* {@link #setExtraSource(byte[])}.
*/
public SearchRequestBuilder setSource(byte[] source, int offset, int length) {
request.source(source, offset, length);
return this;
}
/**
* Sets the source of the request as a json string. Allows to set other parameters.
*/
public SearchRequestBuilder setExtraSource(byte[] source, int offset, int length) {
request.extraSource(source, offset, length);
return this;
}
/**
* Sets the source of the request as a json string. Note, settings anything other
* than the search type will cause this source to be overridden, consider using
* {@link #setExtraSource(byte[])}.
*/
public SearchRequestBuilder setSource(XContentBuilder builder) {
request.source(builder);
return this;
}
/**
* Sets the source of the request as a json string. Allows to set other parameters.
*/
public SearchRequestBuilder setExtraSource(XContentBuilder builder) {
request.extraSource(builder);
return this;
}
/**
* Sets the source of the request as a map. Note, setting anything other than the
* search type will cause this source to be overridden, consider using
* {@link #setExtraSource(java.util.Map)}.
*/
public SearchRequestBuilder setSource(Map source) {
request.source(source);
return this;
}
public SearchRequestBuilder setExtraSource(Map source) {
request.extraSource(source);
return this;
}
/**
* Sets the source builder to be used with this request. Note, any operations done
* on this require builder before are discarded as this internal builder replaces
* what has been built up until this point.
*/
public SearchRequestBuilder internalBuilder(SearchSourceBuilder sourceBuilder) {
this.sourceBuilder = sourceBuilder;
return this;
}
/**
* Returns the internal search source builder used to construct the request.
*/
public SearchSourceBuilder internalBuilder() {
return sourceBuilder();
}
@Override
public String toString() {
return internalBuilder().toString();
}
@Override
public SearchRequest request() {
if (sourceBuilder != null) {
request.source(sourceBuilder());
}
return request;
}
@Override
protected void doExecute(ActionListener<SearchResponse> listener) {
if (sourceBuilder != null) {
request.source(sourceBuilder());
}
((Client) client).search(request, listener);
}
private SearchSourceBuilder sourceBuilder() {
if (sourceBuilder == null) {
sourceBuilder = new SearchSourceBuilder();
}
return sourceBuilder;
}
private HighlightBuilder highlightBuilder() {
return sourceBuilder().highlighter();
}
private SuggestBuilder suggestBuilder() {
return sourceBuilder().suggest();
}
} | 1no label
| src_main_java_org_elasticsearch_action_search_SearchRequestBuilder.java |
885 | public interface PromotableCandidateOrderOffer extends Serializable {
PromotableOrder getPromotableOrder();
Offer getOffer();
Money getPotentialSavings();
HashMap<OfferItemCriteria, List<PromotableOrderItem>> getCandidateQualifiersMap();
boolean isTotalitarian();
boolean isCombinable();
int getPriority();
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_domain_PromotableCandidateOrderOffer.java |
2,280 | public class ConcurrentRecyclerTests extends AbstractRecyclerTests {
@Override
protected Recycler<byte[]> newRecycler() {
return Recyclers.concurrent(Recyclers.dequeFactory(RECYCLER_C, randomIntBetween(5, 10)), randomIntBetween(1,5));
}
} | 0true
| src_test_java_org_elasticsearch_common_recycler_ConcurrentRecyclerTests.java |
1,431 | public class MetaDataService extends AbstractComponent {
private final Semaphore[] indexMdLocks;
@Inject
public MetaDataService(Settings settings) {
super(settings);
indexMdLocks = new Semaphore[500];
for (int i = 0; i < indexMdLocks.length; i++) {
indexMdLocks[i] = new Semaphore(1);
}
}
public Semaphore indexMetaDataLock(String index) {
return indexMdLocks[Math.abs(DjbHashFunction.DJB_HASH(index) % indexMdLocks.length)];
}
} | 0true
| src_main_java_org_elasticsearch_cluster_metadata_MetaDataService.java |
79 | public static class Presentation {
public static class Tab {
public static class Name {
public static final String File_Details = "StaticAssetImpl_FileDetails_Tab";
public static final String Advanced = "StaticAssetImpl_Advanced_Tab";
}
public static class Order {
public static final int File_Details = 2000;
public static final int Advanced = 3000;
}
}
public static class FieldOrder {
// General Fields
public static final int NAME = 1000;
public static final int URL = 2000;
public static final int TITLE = 3000;
public static final int ALT_TEXT = 4000;
public static final int MIME_TYPE = 5000;
public static final int FILE_EXTENSION = 6000;
public static final int FILE_SIZE = 7000;
// Used by subclasses to know where the last field is.
public static final int LAST = 7000;
}
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_domain_StaticAssetImpl.java |
1,042 | public class GlobalSerializerConfig {
private String className;
private Serializer implementation;
public GlobalSerializerConfig() {
super();
}
public String getClassName() {
return className;
}
public GlobalSerializerConfig setClassName(final String className) {
this.className = className;
return this;
}
public Serializer getImplementation() {
return implementation;
}
public GlobalSerializerConfig setImplementation(final ByteArraySerializer implementation) {
this.implementation = implementation;
return this;
}
public GlobalSerializerConfig setImplementation(final StreamSerializer implementation) {
this.implementation = implementation;
return this;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("GlobalSerializerConfig{");
sb.append("className='").append(className).append('\'');
sb.append(", implementation=").append(implementation);
sb.append('}');
return sb.toString();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_config_GlobalSerializerConfig.java |
2,111 | abstract class MapProxySupport extends AbstractDistributedObject<MapService> implements InitializingObject {
protected static final String NULL_KEY_IS_NOT_ALLOWED = "Null key is not allowed!";
protected static final String NULL_VALUE_IS_NOT_ALLOWED = "Null value is not allowed!";
protected final String name;
protected final MapConfig mapConfig;
protected final LocalMapStatsImpl localMapStats;
protected final LockProxySupport lockSupport;
protected final PartitioningStrategy partitionStrategy;
protected MapProxySupport(final String name, final MapService service, NodeEngine nodeEngine) {
super(nodeEngine, service);
this.name = name;
mapConfig = service.getMapContainer(name).getMapConfig();
partitionStrategy = service.getMapContainer(name).getPartitioningStrategy();
localMapStats = service.getLocalMapStatsImpl(name);
lockSupport = new LockProxySupport(new DefaultObjectNamespace(MapService.SERVICE_NAME, name));
}
@Override
public void initialize() {
initializeListeners();
initializeIndexes();
initializeMapStoreLoad();
}
private void initializeMapStoreLoad() {
MapStoreConfig mapStoreConfig = mapConfig.getMapStoreConfig();
if (mapStoreConfig != null && mapStoreConfig.isEnabled()) {
MapStoreConfig.InitialLoadMode initialLoadMode = mapStoreConfig.getInitialLoadMode();
if (initialLoadMode.equals(MapStoreConfig.InitialLoadMode.EAGER)) {
waitUntilLoaded();
}
}
}
private void initializeIndexes() {
for (MapIndexConfig index : mapConfig.getMapIndexConfigs()) {
if (index.getAttribute() != null) {
addIndex(index.getAttribute(), index.isOrdered());
}
}
}
private void initializeListeners() {
final NodeEngine nodeEngine = getNodeEngine();
List<EntryListenerConfig> listenerConfigs = mapConfig.getEntryListenerConfigs();
for (EntryListenerConfig listenerConfig : listenerConfigs) {
EntryListener listener = null;
if (listenerConfig.getImplementation() != null) {
listener = listenerConfig.getImplementation();
} else if (listenerConfig.getClassName() != null) {
try {
listener = ClassLoaderUtil
.newInstance(nodeEngine.getConfigClassLoader(), listenerConfig.getClassName());
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
if (listener != null) {
if (listener instanceof HazelcastInstanceAware) {
((HazelcastInstanceAware) listener).setHazelcastInstance(nodeEngine.getHazelcastInstance());
}
if (listenerConfig.isLocal()) {
addLocalEntryListener(listener);
} else {
addEntryListenerInternal(listener, null, listenerConfig.isIncludeValue());
}
}
}
}
// this operation returns the object in data format except it is got from near-cache and near-cache memory format is object.
protected Object getInternal(Data key) {
final MapService mapService = getService();
final boolean nearCacheEnabled = mapConfig.isNearCacheEnabled();
if (nearCacheEnabled) {
Object cached = mapService.getFromNearCache(name, key);
if (cached != null) {
if (NearCache.NULL_OBJECT.equals(cached)) {
cached = null;
}
mapService.interceptAfterGet(name, cached);
return cached;
}
}
NodeEngine nodeEngine = getNodeEngine();
// todo action for read-backup true is not well tested.
if (mapConfig.isReadBackupData()) {
int backupCount = mapConfig.getTotalBackupCount();
InternalPartitionService partitionService = mapService.getNodeEngine().getPartitionService();
for (int i = 0; i <= backupCount; i++) {
int partitionId = partitionService.getPartitionId(key);
InternalPartition partition = partitionService.getPartition(partitionId);
if (nodeEngine.getThisAddress().equals(partition.getReplicaAddress(i))) {
Object val = mapService.getPartitionContainer(partitionId).getRecordStore(name).get(key);
if (val != null) {
mapService.interceptAfterGet(name, val);
// this serialization step is needed not to expose the object, see issue 1292
return mapService.toData(val);
}
}
}
}
GetOperation operation = new GetOperation(name, key);
Data result = (Data) invokeOperation(key, operation);
if (nearCacheEnabled) {
int partitionId = nodeEngine.getPartitionService().getPartitionId(key);
if (!nodeEngine.getPartitionService().getPartitionOwner(partitionId)
.equals(nodeEngine.getClusterService().getThisAddress()) || mapConfig.getNearCacheConfig().isCacheLocalEntries()) {
return mapService.putNearCache(name, key, result);
}
}
return result;
}
protected ICompletableFuture<Data> getAsyncInternal(final Data key) {
final NodeEngine nodeEngine = getNodeEngine();
final MapService mapService = getService();
int partitionId = nodeEngine.getPartitionService().getPartitionId(key);
final boolean nearCacheEnabled = mapConfig.isNearCacheEnabled();
if (nearCacheEnabled) {
Object cached = mapService.getFromNearCache(name, key);
if (cached != null) {
if (NearCache.NULL_OBJECT.equals(cached)) {
cached = null;
}
return new CompletedFuture<Data>(
nodeEngine.getSerializationService(),
cached,
nodeEngine.getExecutionService().getExecutor(ExecutionService.ASYNC_EXECUTOR));
}
}
GetOperation operation = new GetOperation(name, key);
try {
final OperationService operationService = nodeEngine.getOperationService();
final InvocationBuilder invocationBuilder = operationService.createInvocationBuilder(SERVICE_NAME, operation, partitionId).setResultDeserialized(false);
final InternalCompletableFuture<Data> future = invocationBuilder.invoke();
future.andThen(new ExecutionCallback<Data>() {
@Override
public void onResponse(Data response) {
if (nearCacheEnabled) {
int partitionId = nodeEngine.getPartitionService().getPartitionId(key);
if (!nodeEngine.getPartitionService().getPartitionOwner(partitionId)
.equals(nodeEngine.getClusterService().getThisAddress()) || mapConfig.getNearCacheConfig().isCacheLocalEntries()) {
mapService.putNearCache(name, key, response);
}
}
}
@Override
public void onFailure(Throwable t) {
}
});
return future;
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
protected Data putInternal(final Data key, final Data value, final long ttl, final TimeUnit timeunit) {
PutOperation operation = new PutOperation(name, key, value, getTimeInMillis(ttl, timeunit));
Data previousValue = (Data) invokeOperation(key, operation);
invalidateNearCache(key);
return previousValue;
}
protected boolean tryPutInternal(final Data key, final Data value, final long timeout, final TimeUnit timeunit) {
TryPutOperation operation = new TryPutOperation(name, key, value, getTimeInMillis(timeout, timeunit));
boolean putSuccessful = (Boolean) invokeOperation(key, operation);
invalidateNearCache(key);
return putSuccessful;
}
protected Data putIfAbsentInternal(final Data key, final Data value, final long ttl, final TimeUnit timeunit) {
PutIfAbsentOperation operation = new PutIfAbsentOperation(name, key, value, getTimeInMillis(ttl, timeunit));
Data previousValue = (Data) invokeOperation(key, operation);
invalidateNearCache(key);
return previousValue;
}
protected void putTransientInternal(final Data key, final Data value, final long ttl, final TimeUnit timeunit) {
PutTransientOperation operation = new PutTransientOperation(name, key, value, getTimeInMillis(ttl, timeunit));
invokeOperation(key, operation);
invalidateNearCache(key);
}
private Object invokeOperation(Data key, KeyBasedMapOperation operation) {
final NodeEngine nodeEngine = getNodeEngine();
int partitionId = nodeEngine.getPartitionService().getPartitionId(key);
operation.setThreadId(ThreadUtil.getThreadId());
try {
Future f;
Object o;
OperationService operationService = nodeEngine.getOperationService();
if (mapConfig.isStatisticsEnabled()) {
long time = System.currentTimeMillis();
f = operationService
.createInvocationBuilder(SERVICE_NAME, operation, partitionId)
.setResultDeserialized(false)
.invoke();
o = f.get();
if (operation instanceof BasePutOperation)
localMapStats.incrementPuts(System.currentTimeMillis() - time);
else if (operation instanceof BaseRemoveOperation)
localMapStats.incrementRemoves(System.currentTimeMillis() - time);
else if (operation instanceof GetOperation)
localMapStats.incrementGets(System.currentTimeMillis() - time);
} else {
f = operationService.createInvocationBuilder(SERVICE_NAME, operation, partitionId)
.setResultDeserialized(false).invoke();
o = f.get();
}
return o;
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
protected ICompletableFuture<Data> putAsyncInternal(final Data key, final Data value, final long ttl, final TimeUnit timeunit) {
final NodeEngine nodeEngine = getNodeEngine();
int partitionId = nodeEngine.getPartitionService().getPartitionId(key);
PutOperation operation = new PutOperation(name, key, value, getTimeInMillis(ttl, timeunit));
operation.setThreadId(ThreadUtil.getThreadId());
try {
ICompletableFuture<Data> future = nodeEngine.getOperationService().invokeOnPartition(SERVICE_NAME, operation, partitionId);
invalidateNearCache(key);
return future;
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
protected boolean replaceInternal(final Data key, final Data oldValue, final Data newValue) {
ReplaceIfSameOperation operation = new ReplaceIfSameOperation(name, key, oldValue, newValue);
boolean replaceSuccessful = (Boolean) invokeOperation(key, operation);
invalidateNearCache(key);
return replaceSuccessful;
}
protected Data replaceInternal(final Data key, final Data value) {
ReplaceOperation operation = new ReplaceOperation(name, key, value);
final Data result = (Data) invokeOperation(key, operation);
invalidateNearCache(key);
return result;
}
protected void setInternal(final Data key, final Data value, final long ttl, final TimeUnit timeunit) {
SetOperation operation = new SetOperation(name, key, value, timeunit.toMillis(ttl));
invokeOperation(key, operation);
invalidateNearCache(key);
}
protected boolean evictInternal(final Data key) {
EvictOperation operation = new EvictOperation(name, key, false);
final boolean evictSuccess = (Boolean) invokeOperation(key, operation);
invalidateNearCache(key);
return evictSuccess;
}
protected Data removeInternal(Data key) {
RemoveOperation operation = new RemoveOperation(name, key);
Data previousValue = (Data) invokeOperation(key, operation);
invalidateNearCache(key);
return previousValue;
}
protected void deleteInternal(Data key) {
RemoveOperation operation = new RemoveOperation(name, key);
invokeOperation(key, operation);
invalidateNearCache(key);
}
protected boolean removeInternal(final Data key, final Data value) {
RemoveIfSameOperation operation = new RemoveIfSameOperation(name, key, value);
boolean removed = (Boolean) invokeOperation(key, operation);
invalidateNearCache(key);
return removed;
}
protected boolean tryRemoveInternal(final Data key, final long timeout, final TimeUnit timeunit) {
TryRemoveOperation operation = new TryRemoveOperation(name, key, getTimeInMillis(timeout, timeunit));
boolean removed = (Boolean) invokeOperation(key, operation);
invalidateNearCache(key);
return removed;
}
protected ICompletableFuture<Data> removeAsyncInternal(final Data key) {
final NodeEngine nodeEngine = getNodeEngine();
int partitionId = nodeEngine.getPartitionService().getPartitionId(key);
RemoveOperation operation = new RemoveOperation(name, key);
operation.setThreadId(ThreadUtil.getThreadId());
try {
ICompletableFuture<Data> future = nodeEngine.getOperationService().invokeOnPartition(SERVICE_NAME, operation, partitionId);
invalidateNearCache(key);
return future;
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
protected boolean containsKeyInternal(Data key) {
if (isKeyInNearCache(key)) {
return true;
}
final NodeEngine nodeEngine = getNodeEngine();
int partitionId = nodeEngine.getPartitionService().getPartitionId(key);
ContainsKeyOperation containsKeyOperation = new ContainsKeyOperation(name, key);
containsKeyOperation.setServiceName(SERVICE_NAME);
try {
Future f = nodeEngine.getOperationService().invokeOnPartition(SERVICE_NAME, containsKeyOperation,
partitionId);
return (Boolean) getService().toObject(f.get());
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
public void waitUntilLoaded() {
final NodeEngine nodeEngine = getNodeEngine();
try {
Map<Integer, Object> results = nodeEngine.getOperationService()
.invokeOnAllPartitions(SERVICE_NAME, new PartitionCheckIfLoadedOperationFactory(name));
Iterator<Entry<Integer, Object>> iterator = results.entrySet().iterator();
boolean isFinished = false;
final Set<Integer> retrySet = new HashSet<Integer>();
while (!isFinished) {
while (iterator.hasNext()) {
final Entry<Integer, Object> entry = iterator.next();
if (Boolean.TRUE.equals(entry.getValue())) {
iterator.remove();
} else {
retrySet.add(entry.getKey());
}
}
if (retrySet.size() > 0) {
results = retryPartitions(retrySet);
iterator = results.entrySet().iterator();
Thread.sleep(1000);
retrySet.clear();
} else {
isFinished = true;
}
}
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
private Map<Integer, Object> retryPartitions(Collection partitions) {
final NodeEngine nodeEngine = getNodeEngine();
try {
final Map<Integer, Object> results = nodeEngine.getOperationService()
.invokeOnPartitions(SERVICE_NAME, new PartitionCheckIfLoadedOperationFactory(name), partitions);
return results;
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
public int size() {
final NodeEngine nodeEngine = getNodeEngine();
try {
Map<Integer, Object> results = nodeEngine.getOperationService()
.invokeOnAllPartitions(SERVICE_NAME, new SizeOperationFactory(name));
int total = 0;
for (Object result : results.values()) {
Integer size = (Integer) getService().toObject(result);
total += size;
}
return total;
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
public boolean containsValueInternal(Data dataValue) {
final NodeEngine nodeEngine = getNodeEngine();
try {
Map<Integer, Object> results = nodeEngine.getOperationService()
.invokeOnAllPartitions(SERVICE_NAME, new ContainsValueOperationFactory(name, dataValue));
for (Object result : results.values()) {
Boolean contains = (Boolean) getService().toObject(result);
if (contains)
return true;
}
return false;
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
public boolean isEmpty() {
final NodeEngine nodeEngine = getNodeEngine();
try {
Map<Integer, Object> results = nodeEngine.getOperationService()
.invokeOnAllPartitions(SERVICE_NAME,
new BinaryOperationFactory(new MapIsEmptyOperation(name), nodeEngine));
for (Object result : results.values()) {
if (!(Boolean) getService().toObject(result))
return false;
}
return true;
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
protected Map<Object, Object> getAllObjectInternal(final Set<Data> keys) {
final NodeEngine nodeEngine = getNodeEngine();
final MapService mapService = getService();
Map<Object, Object> result = new HashMap<Object, Object>();
final boolean nearCacheEnabled = mapConfig.isNearCacheEnabled();
if (nearCacheEnabled) {
final Iterator<Data> iterator = keys.iterator();
while (iterator.hasNext()) {
Data key = iterator.next();
Object cachedValue = mapService.getFromNearCache(name, key);
if (cachedValue != null) {
if (!NearCache.NULL_OBJECT.equals(cachedValue)) {
result.put(mapService.toObject(key), mapService.toObject(cachedValue));
}
iterator.remove();
}
}
}
if (keys.isEmpty()) {
return result;
}
Collection<Integer> partitions = getPartitionsForKeys(keys);
Map<Integer, Object> responses;
try {
responses = nodeEngine.getOperationService()
.invokeOnPartitions(SERVICE_NAME, new MapGetAllOperationFactory(name, keys), partitions);
for (Object response : responses.values()) {
Set<Map.Entry<Data, Data>> entries = ((MapEntrySet) mapService.toObject(response)).getEntrySet();
for (Entry<Data, Data> entry : entries) {
result.put(mapService.toObject(entry.getKey()), mapService.toObject(entry.getValue()));
if (nearCacheEnabled) {
int partitionId = nodeEngine.getPartitionService().getPartitionId(entry.getKey());
if (!nodeEngine.getPartitionService().getPartitionOwner(partitionId)
.equals(nodeEngine.getClusterService().getThisAddress()) || mapConfig.getNearCacheConfig().isCacheLocalEntries()) {
mapService.putNearCache(name, entry.getKey(), entry.getValue());
}
}
}
}
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
return result;
}
private Collection<Integer> getPartitionsForKeys(Set<Data> keys) {
InternalPartitionService partitionService = getNodeEngine().getPartitionService();
int partitions = partitionService.getPartitionCount();
int capacity = Math.min(partitions, keys.size()); //todo: is there better way to estimate size?
Set<Integer> partitionIds = new HashSet<Integer>(capacity);
Iterator<Data> iterator = keys.iterator();
while (iterator.hasNext() && partitionIds.size() < partitions) {
Data key = iterator.next();
partitionIds.add(partitionService.getPartitionId(key));
}
return partitionIds;
}
protected void putAllInternal(final Map<? extends Object, ? extends Object> entries) {
final NodeEngine nodeEngine = getNodeEngine();
final MapService mapService = getService();
int factor = 3;
InternalPartitionService partitionService = nodeEngine.getPartitionService();
OperationService operationService = nodeEngine.getOperationService();
int partitionCount = partitionService.getPartitionCount();
boolean tooManyEntries = entries.size() > (partitionCount * factor);
try {
if (tooManyEntries) {
List<Future> futures = new LinkedList<Future>();
Map<Integer, MapEntrySet> entryMap = new HashMap<Integer, MapEntrySet>(nodeEngine.getPartitionService().getPartitionCount());
for (Entry entry : entries.entrySet()) {
if (entry.getKey() == null) {
throw new NullPointerException(NULL_KEY_IS_NOT_ALLOWED);
}
if (entry.getValue() == null) {
throw new NullPointerException(NULL_VALUE_IS_NOT_ALLOWED);
}
int partitionId = partitionService.getPartitionId(entry.getKey());
if (!entryMap.containsKey(partitionId)) {
entryMap.put(partitionId, new MapEntrySet());
}
entryMap.get(partitionId).add(new AbstractMap.SimpleImmutableEntry<Data, Data>(mapService.toData(
entry.getKey(),
partitionStrategy),
mapService
.toData(entry.getValue())
));
}
for (final Map.Entry<Integer, MapEntrySet> entry : entryMap.entrySet()) {
final Integer partitionId = entry.getKey();
final PutAllOperation op = new PutAllOperation(name, entry.getValue());
op.setPartitionId(partitionId);
futures.add(operationService.invokeOnPartition(SERVICE_NAME, op, partitionId));
}
for (Future future : futures) {
future.get();
}
} else {
for (Entry entry : entries.entrySet()) {
if (entry.getKey() == null) {
throw new NullPointerException(NULL_KEY_IS_NOT_ALLOWED);
}
if (entry.getValue() == null) {
throw new NullPointerException(NULL_VALUE_IS_NOT_ALLOWED);
}
putInternal(mapService.toData(entry.getKey(), partitionStrategy),
mapService.toData(entry.getValue()),
-1,
TimeUnit.SECONDS);
}
}
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
protected Set<Data> keySetInternal() {
final NodeEngine nodeEngine = getNodeEngine();
try {
// todo you can optimize keyset by taking keys without lock then re-fetch missing ones. see localKeySet
Map<Integer, Object> results = nodeEngine.getOperationService()
.invokeOnAllPartitions(SERVICE_NAME,
new BinaryOperationFactory(new MapKeySetOperation(name), nodeEngine));
Set<Data> keySet = new HashSet<Data>();
for (Object result : results.values()) {
Set keys = ((MapKeySet) getService().toObject(result)).getKeySet();
keySet.addAll(keys);
}
return keySet;
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
protected Set<Data> localKeySetInternal() {
final NodeEngine nodeEngine = getNodeEngine();
final MapService mapService = getService();
Set<Data> keySet = new HashSet<Data>();
try {
List<Integer> memberPartitions =
nodeEngine.getPartitionService().getMemberPartitions(nodeEngine.getThisAddress());
for (Integer memberPartition : memberPartitions) {
RecordStore recordStore = mapService.getRecordStore(memberPartition, name);
keySet.addAll(recordStore.getReadonlyRecordMap().keySet());
}
return keySet;
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
public void flush() {
final NodeEngine nodeEngine = getNodeEngine();
try {
// todo add a feature to mancenter to sync cache to db completely
nodeEngine.getOperationService()
.invokeOnAllPartitions(SERVICE_NAME,
new BinaryOperationFactory(new MapFlushOperation(name), nodeEngine));
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
protected Collection<Data> valuesInternal() {
final NodeEngine nodeEngine = getNodeEngine();
try {
Map<Integer, Object> results = nodeEngine.getOperationService()
.invokeOnAllPartitions(SERVICE_NAME,
new BinaryOperationFactory(new MapValuesOperation(name), nodeEngine));
List<Data> values = new ArrayList<Data>();
for (Object result : results.values()) {
values.addAll(((MapValueCollection) getService().toObject(result)).getValues());
}
return values;
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
public void clearInternal() {
final String mapName = name;
final NodeEngine nodeEngine = getNodeEngine();
try {
ClearOperation clearOperation = new ClearOperation(mapName);
clearOperation.setServiceName(SERVICE_NAME);
nodeEngine.getOperationService()
.invokeOnAllPartitions(SERVICE_NAME, new BinaryOperationFactory(clearOperation, nodeEngine));
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
public String addMapInterceptorInternal(MapInterceptor interceptor) {
final NodeEngine nodeEngine = getNodeEngine();
final MapService mapService = getService();
if (interceptor instanceof HazelcastInstanceAware) {
((HazelcastInstanceAware) interceptor).setHazelcastInstance(nodeEngine.getHazelcastInstance());
}
String id = mapService.addInterceptor(name, interceptor);
Collection<MemberImpl> members = nodeEngine.getClusterService().getMemberList();
for (MemberImpl member : members) {
try {
if (member.localMember())
continue;
Future f = nodeEngine.getOperationService()
.invokeOnTarget(SERVICE_NAME, new AddInterceptorOperation(id, interceptor, name),
member.getAddress());
f.get();
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
return id;
}
public void removeMapInterceptorInternal(String id) {
final NodeEngine nodeEngine = getNodeEngine();
final MapService mapService = getService();
mapService.removeInterceptor(name, id);
Collection<MemberImpl> members = nodeEngine.getClusterService().getMemberList();
for (Member member : members) {
try {
if (member.localMember())
continue;
MemberImpl memberImpl = (MemberImpl) member;
Future f = nodeEngine.getOperationService()
.invokeOnTarget(SERVICE_NAME, new RemoveInterceptorOperation(name, id), memberImpl.getAddress());
f.get();
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
}
public String addLocalEntryListener(final EntryListener listener) {
final MapService mapService = getService();
return mapService.addLocalEventListener(listener, name);
}
public String addLocalEntryListenerInternal(EntryListener listener, Predicate predicate, final Data key, boolean includeValue) {
final MapService mapService = getService();
EventFilter eventFilter = new QueryEventFilter(includeValue, key, predicate);
return mapService.addLocalEventListener(listener, eventFilter, name);
}
protected String addEntryListenerInternal(
final EntryListener listener, final Data key, final boolean includeValue) {
EventFilter eventFilter = new EntryEventFilter(includeValue, key);
final MapService mapService = getService();
return mapService.addEventListener(listener, eventFilter, name);
}
protected String addEntryListenerInternal(
EntryListener listener, Predicate predicate, final Data key, final boolean includeValue) {
EventFilter eventFilter = new QueryEventFilter(includeValue, key, predicate);
final MapService mapService = getService();
return mapService.addEventListener(listener, eventFilter, name);
}
protected boolean removeEntryListenerInternal(String id) {
final MapService mapService = getService();
return mapService.removeEventListener(name, id);
}
protected EntryView getEntryViewInternal(final Data key) {
final NodeEngine nodeEngine = getNodeEngine();
int partitionId = nodeEngine.getPartitionService().getPartitionId(key);
GetEntryViewOperation getEntryViewOperation = new GetEntryViewOperation(name, key);
getEntryViewOperation.setServiceName(SERVICE_NAME);
try {
Future f = nodeEngine.getOperationService().invokeOnPartition(SERVICE_NAME, getEntryViewOperation, partitionId);
Object o = getService().toObject(f.get());
return (EntryView) o;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
protected Set<Entry<Data, Data>> entrySetInternal() {
final NodeEngine nodeEngine = getNodeEngine();
try {
Map<Integer, Object> results = nodeEngine.getOperationService()
.invokeOnAllPartitions(SERVICE_NAME,
new BinaryOperationFactory(new MapEntrySetOperation(name), nodeEngine));
Set<Entry<Data, Data>> entrySet = new HashSet<Entry<Data, Data>>();
for (Object result : results.values()) {
Set entries = ((MapEntrySet) getService().toObject(result)).getEntrySet();
if (entries != null)
entrySet.addAll(entries);
}
return entrySet;
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
public Data executeOnKeyInternal(Data key, EntryProcessor entryProcessor) {
final NodeEngine nodeEngine = getNodeEngine();
int partitionId = nodeEngine.getPartitionService().getPartitionId(key);
EntryOperation operation = new EntryOperation(name, key, entryProcessor);
operation.setThreadId(ThreadUtil.getThreadId());
try {
Future future = nodeEngine.getOperationService()
.createInvocationBuilder(SERVICE_NAME, operation, partitionId)
.setResultDeserialized(false)
.invoke();
final Data data = (Data) future.get();
invalidateNearCache(key);
return data;
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
public Map executeOnKeysInternal(Set<Data> keys, EntryProcessor entryProcessor) {
Map result = new HashMap();
final NodeEngine nodeEngine = getNodeEngine();
final Collection<Integer> partitionsForKeys = getPartitionsForKeys(keys);
try {
MultipleEntryOperationFactory operationFactory = new MultipleEntryOperationFactory(name, keys, entryProcessor);
Map<Integer, Object> results = nodeEngine.getOperationService()
.invokeOnPartitions(SERVICE_NAME, operationFactory, partitionsForKeys);
for (Object o : results.values()) {
if (o != null) {
final MapService service = getService();
final MapEntrySet mapEntrySet = (MapEntrySet) o;
for (Entry<Data, Data> entry : mapEntrySet.getEntrySet()) {
result.put(service.toObject(entry.getKey()), service.toObject(entry.getValue()));
}
}
}
invalidateNearCache(keys);
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
return result;
}
public ICompletableFuture executeOnKeyInternal(Data key, EntryProcessor entryProcessor, ExecutionCallback callback) {
final NodeEngine nodeEngine = getNodeEngine();
int partitionId = nodeEngine.getPartitionService().getPartitionId(key);
EntryOperation operation = new EntryOperation(name, key, entryProcessor);
operation.setThreadId(ThreadUtil.getThreadId());
try {
if (callback == null) {
return nodeEngine.getOperationService().invokeOnPartition(SERVICE_NAME, operation, partitionId);
} else {
ICompletableFuture future = nodeEngine.getOperationService()
.createInvocationBuilder(SERVICE_NAME, operation, partitionId)
.setCallback(new MapExecutionCallbackAdapter(callback))
.invoke();
invalidateNearCache(key);
return future;
}
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
/**
* {@link IMap#executeOnEntries(EntryProcessor)}
*/
public Map executeOnEntries(EntryProcessor entryProcessor) {
Map result = new HashMap();
try {
NodeEngine nodeEngine = getNodeEngine();
Map<Integer, Object> results = nodeEngine.getOperationService()
.invokeOnAllPartitions(SERVICE_NAME, new PartitionWideEntryOperationFactory(name, entryProcessor));
for (Object o : results.values()) {
if (o != null) {
final MapService service = getService();
final MapEntrySet mapEntrySet = (MapEntrySet) o;
for (Entry<Data, Data> entry : mapEntrySet.getEntrySet()) {
final Data key = entry.getKey();
result.put(service.toObject(entry.getKey()), service.toObject(entry.getValue()));
invalidateNearCache(key);
}
}
}
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
return result;
}
/**
* {@link IMap#executeOnEntries(EntryProcessor, Predicate)}
*/
public Map executeOnEntries(EntryProcessor entryProcessor, Predicate predicate) {
Map result = new HashMap();
try {
NodeEngine nodeEngine = getNodeEngine();
Map<Integer, Object> results = nodeEngine.getOperationService()
.invokeOnAllPartitions(SERVICE_NAME,
new PartitionWideEntryWithPredicateOperationFactory(name,
entryProcessor,
predicate)
);
for (Object o : results.values()) {
if (o != null) {
final MapService service = getService();
final MapEntrySet mapEntrySet = (MapEntrySet) o;
for (Entry<Data, Data> entry : mapEntrySet.getEntrySet()) {
final Data key = entry.getKey();
result.put(service.toObject(key), service.toObject(entry.getValue()));
invalidateNearCache(key);
}
}
}
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
return result;
}
protected Set queryLocal(final Predicate predicate, final IterationType iterationType, final boolean dataResult) {
final NodeEngine nodeEngine = getNodeEngine();
OperationService operationService = nodeEngine.getOperationService();
final SerializationService ss = nodeEngine.getSerializationService();
List<Integer> partitionIds = nodeEngine.getPartitionService().getMemberPartitions(nodeEngine.getThisAddress());
PagingPredicate pagingPredicate = null;
if (predicate instanceof PagingPredicate) {
pagingPredicate = (PagingPredicate) predicate;
pagingPredicate.setIterationType(iterationType);
if (pagingPredicate.getPage() > 0 && pagingPredicate.getAnchor() == null) {
pagingPredicate.previousPage();
query(pagingPredicate, iterationType, dataResult);
pagingPredicate.nextPage();
}
}
Set result;
if (pagingPredicate == null) {
result = new QueryResultSet(ss, iterationType, dataResult);
} else {
result = new SortedQueryResultSet(pagingPredicate.getComparator(), iterationType, pagingPredicate.getPageSize());
}
List<Integer> returnedPartitionIds = new ArrayList<Integer>();
try {
Future future = operationService
.invokeOnTarget(SERVICE_NAME,
new QueryOperation(name, predicate),
nodeEngine.getThisAddress());
QueryResult queryResult = (QueryResult) future.get();
if (queryResult != null) {
returnedPartitionIds = queryResult.getPartitionIds();
if (pagingPredicate == null) {
result.addAll(queryResult.getResult());
} else {
for (QueryResultEntry queryResultEntry : queryResult.getResult()) {
Object key = ss.toObject(queryResultEntry.getKeyData());
Object value = ss.toObject(queryResultEntry.getValueData());
result.add(new AbstractMap.SimpleImmutableEntry(key, value));
}
}
}
if (returnedPartitionIds.size() == partitionIds.size()) {
if (pagingPredicate != null) {
PagingPredicateAccessor.setPagingPredicateAnchor(pagingPredicate, ((SortedQueryResultSet) result).last());
}
return result;
}
List<Integer> missingList = new ArrayList<Integer>();
for (Integer partitionId : partitionIds) {
if (!returnedPartitionIds.contains(partitionId))
missingList.add(partitionId);
}
List<Future> futures = new ArrayList<Future>(missingList.size());
for (Integer pid : missingList) {
QueryPartitionOperation queryPartitionOperation = new QueryPartitionOperation(name, predicate);
queryPartitionOperation.setPartitionId(pid);
try {
Future f =
operationService.invokeOnPartition(SERVICE_NAME, queryPartitionOperation, pid);
futures.add(f);
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
for (Future f : futures) {
QueryResult qResult = (QueryResult) f.get();
if (pagingPredicate == null) {
result.addAll(qResult.getResult());
} else {
for (QueryResultEntry queryResultEntry : qResult.getResult()) {
Object key = ss.toObject(queryResultEntry.getKeyData());
Object value = ss.toObject(queryResultEntry.getValueData());
result.add(new AbstractMap.SimpleImmutableEntry(key, value));
}
}
}
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
return result;
}
protected Set query(final Predicate predicate, final IterationType iterationType, final boolean dataResult) {
final NodeEngine nodeEngine = getNodeEngine();
OperationService operationService = nodeEngine.getOperationService();
final SerializationService ss = nodeEngine.getSerializationService();
Collection<MemberImpl> members = nodeEngine.getClusterService().getMemberList();
int partitionCount = nodeEngine.getPartitionService().getPartitionCount();
Set<Integer> plist = new HashSet<Integer>(partitionCount);
PagingPredicate pagingPredicate = null;
if (predicate instanceof PagingPredicate) {
pagingPredicate = (PagingPredicate) predicate;
pagingPredicate.setIterationType(iterationType);
if (pagingPredicate.getPage() > 0 && pagingPredicate.getAnchor() == null) {
pagingPredicate.previousPage();
query(pagingPredicate, iterationType, dataResult);
pagingPredicate.nextPage();
}
}
Set result;
if (pagingPredicate == null) {
result = new QueryResultSet(ss, iterationType, dataResult);
} else {
result = new SortedQueryResultSet(pagingPredicate.getComparator(), iterationType, pagingPredicate.getPageSize());
}
List<Integer> missingList = new ArrayList<Integer>();
try {
List<Future> flist = new ArrayList<Future>();
for (MemberImpl member : members) {
Future future = operationService
.invokeOnTarget(SERVICE_NAME, new QueryOperation(name, predicate), member.getAddress());
flist.add(future);
}
for (Future future : flist) {
QueryResult queryResult = (QueryResult) future.get();
if (queryResult != null) {
final List<Integer> partitionIds = queryResult.getPartitionIds();
if (partitionIds != null) {
plist.addAll(partitionIds);
if (pagingPredicate == null) {
result.addAll(queryResult.getResult());
} else {
for (QueryResultEntry queryResultEntry : queryResult.getResult()) {
Object key = ss.toObject(queryResultEntry.getKeyData());
Object value = ss.toObject(queryResultEntry.getValueData());
result.add(new AbstractMap.SimpleImmutableEntry(key, value));
}
}
}
}
}
if (plist.size() == partitionCount) {
if (pagingPredicate != null) {
PagingPredicateAccessor.setPagingPredicateAnchor(pagingPredicate, ((SortedQueryResultSet) result).last());
}
return result;
}
for (int i = 0; i < partitionCount; i++) {
if (!plist.contains(i)) {
missingList.add(i);
}
}
} catch (Throwable t) {
missingList.clear();
for (int i = 0; i < partitionCount; i++) {
if (!plist.contains(i)) {
missingList.add(i);
}
}
}
try {
List<Future> futures = new ArrayList<Future>(missingList.size());
for (Integer pid : missingList) {
QueryPartitionOperation queryPartitionOperation = new QueryPartitionOperation(name, predicate);
queryPartitionOperation.setPartitionId(pid);
try {
Future f =
operationService.invokeOnPartition(SERVICE_NAME, queryPartitionOperation, pid);
futures.add(f);
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
for (Future future : futures) {
QueryResult queryResult = (QueryResult) future.get();
if (pagingPredicate == null) {
result.addAll(queryResult.getResult());
} else {
for (QueryResultEntry queryResultEntry : queryResult.getResult()) {
Object key = ss.toObject(queryResultEntry.getKeyData());
Object value = ss.toObject(queryResultEntry.getValueData());
result.add(new AbstractMap.SimpleImmutableEntry(key, value));
}
}
}
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
if (pagingPredicate != null) {
PagingPredicateAccessor.setPagingPredicateAnchor(pagingPredicate, ((SortedQueryResultSet) result).last());
}
return result;
}
public void addIndex(final String attribute, final boolean ordered) {
final NodeEngine nodeEngine = getNodeEngine();
if (attribute == null) throw new IllegalArgumentException("Attribute name cannot be null");
try {
AddIndexOperation addIndexOperation = new AddIndexOperation(name, attribute, ordered);
nodeEngine.getOperationService()
.invokeOnAllPartitions(SERVICE_NAME, new BinaryOperationFactory(addIndexOperation, nodeEngine));
} catch (Throwable t) {
throw ExceptionUtil.rethrow(t);
}
}
public LocalMapStats getLocalMapStats() {
return getService().createLocalMapStats(name);
}
private boolean isKeyInNearCache(Data key) {
final MapService mapService = getService();
final boolean nearCacheEnabled = mapConfig.isNearCacheEnabled();
if (nearCacheEnabled) {
Object cached = mapService.getFromNearCache(name, key);
if (cached != null && !cached.equals(NearCache.NULL_OBJECT)) {
return true;
}
}
return false;
}
private void invalidateNearCache(Data key) {
if (key == null) {
return;
}
getService().invalidateNearCache(name, key);
}
private void invalidateNearCache(Set<Data> keys) {
if (keys == null || keys.isEmpty()) {
return;
}
getService().invalidateNearCache(name, keys);
}
protected long getTimeInMillis(final long time, final TimeUnit timeunit) {
return timeunit != null ? timeunit.toMillis(time) : time;
}
public final String getName() {
return name;
}
public final String getServiceName() {
return SERVICE_NAME;
}
private class MapExecutionCallbackAdapter implements Callback {
private final ExecutionCallback executionCallback;
public MapExecutionCallbackAdapter(ExecutionCallback executionCallback) {
this.executionCallback = executionCallback;
}
@Override
public void notify(Object response) {
if (response instanceof Throwable) {
executionCallback.onFailure((Throwable) response);
} else {
executionCallback.onResponse(getService().toObject(response));
}
}
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_map_proxy_MapProxySupport.java |
405 | add(store, "expiring-doc4", new HashMap<String, Object>() {{
put(NAME, "fourth");
put(TIME, 3L);
put(WEIGHT, 7.7d);
}}, true, 7); // bigger ttl then one recycle interval, should still show up in the results | 0true
| titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexProviderTest.java |
142 | public static class Tab {
public static class Name {
public static final String Rules = "StructuredContentImpl_Rules_Tab";
}
public static class Order {
public static final int Rules = 1000;
}
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContentImpl.java |
466 | final long indexTwoSize = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<Long>() {
public Long call() {
return indexTwo.getSize();
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java |
140 | public static class FileSizePruneStrategy extends AbstractPruneStrategy
{
private final int maxSize;
public FileSizePruneStrategy( FileSystemAbstraction fileystem, int maxSizeBytes )
{
super( fileystem );
this.maxSize = maxSizeBytes;
}
@Override
protected Threshold newThreshold()
{
return new Threshold()
{
private int size;
@Override
public boolean reached( File file, long version, LogLoader source )
{
size += fileSystem.getFileSize( file );
return size >= maxSize;
}
};
}
} | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogPruneStrategies.java |
1,320 | private static final class AddEntryResult {
private final long pageIndex;
private final int pagePosition;
private final ORecordVersion recordVersion;
private final int recordsSizeDiff;
public AddEntryResult(long pageIndex, int pagePosition, ORecordVersion recordVersion, int recordsSizeDiff) {
this.pageIndex = pageIndex;
this.pagePosition = pagePosition;
this.recordVersion = recordVersion;
this.recordsSizeDiff = recordsSizeDiff;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_OPaginatedCluster.java |
1,856 | static class TxnIncrementor implements Runnable {
int count = 0;
HazelcastInstance instance;
final String key = "count";
final CountDownLatch latch;
TxnIncrementor(int count, HazelcastInstance instance, CountDownLatch latch) {
this.count = count;
this.instance = instance;
this.latch = latch;
}
@Override
public void run() {
for (int i = 0; i < count; i++) {
instance.executeTransaction(new TransactionalTask<Boolean>() {
public Boolean execute(TransactionalTaskContext context) throws TransactionException {
final TransactionalMap<String, Integer> txMap = context.getMap("default");
Integer value = txMap.getForUpdate(key);
txMap.put(key, value + 1);
return true;
}
});
latch.countDown();
}
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_map_MapTransactionStressTest.java |
880 | new Thread() {
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
return;
}
latch.destroy();
}
}.start(); | 0true
| hazelcast_src_test_java_com_hazelcast_concurrent_countdownlatch_CountDownLatchTest.java |
1,488 | public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> {
private boolean isVertex;
private ElementChecker startChecker;
private ElementChecker endChecker;
@Override
public void setup(final Mapper.Context context) throws IOException, InterruptedException {
this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class);
final String key = context.getConfiguration().get(KEY);
final Class valueClass = context.getConfiguration().getClass(VALUE_CLASS, String.class);
final Object startValue;
final Object endValue;
if (valueClass.equals(String.class)) {
startValue = context.getConfiguration().get(START_VALUE);
endValue = context.getConfiguration().get(END_VALUE);
} else if (Number.class.isAssignableFrom((valueClass))) {
startValue = context.getConfiguration().getFloat(START_VALUE, Float.MIN_VALUE);
endValue = context.getConfiguration().getFloat(END_VALUE, Float.MAX_VALUE);
} else {
throw new IOException("Class " + valueClass + " is an unsupported value class");
}
this.startChecker = new ElementChecker(key, Compare.GREATER_THAN_EQUAL, startValue);
this.endChecker = new ElementChecker(key, Compare.LESS_THAN, endValue);
}
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException {
if (this.isVertex) {
if (value.hasPaths() && !(this.startChecker.isLegal(value) && this.endChecker.isLegal(value))) {
value.clearPaths();
DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_FILTERED, 1L);
}
} else {
long counter = 0;
for (final Edge e : value.getEdges(Direction.BOTH)) {
final StandardFaunusEdge edge = (StandardFaunusEdge) e;
if (edge.hasPaths() && !(this.startChecker.isLegal(edge) && this.endChecker.isLegal(edge))) {
edge.clearPaths();
counter++;
}
}
DEFAULT_COMPAT.incrementContextCounter(context, Counters.EDGES_FILTERED, counter);
}
context.write(NullWritable.get(), value);
}
} | 1no label
| titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_filter_IntervalFilterMap.java |
1,949 | public class MapPutRequest extends KeyBasedClientRequest implements Portable, SecureRequest {
protected Data key;
protected Data value;
protected String name;
protected long threadId;
protected long ttl;
protected transient long startTime;
public MapPutRequest() {
}
public MapPutRequest(String name, Data key, Data value, long threadId, long ttl) {
this.name = name;
this.key = key;
this.value = value;
this.threadId = threadId;
this.ttl = ttl;
}
public MapPutRequest(String name, Data key, Data value, long threadId) {
this.name = name;
this.key = key;
this.value = value;
this.threadId = threadId;
this.ttl = -1;
}
public int getFactoryId() {
return MapPortableHook.F_ID;
}
public int getClassId() {
return MapPortableHook.PUT;
}
protected Object getKey() {
return key;
}
@Override
protected void beforeProcess() {
startTime = System.currentTimeMillis();
}
@Override
protected void afterResponse() {
final long latency = System.currentTimeMillis() - startTime;
final MapService mapService = getService();
MapContainer mapContainer = mapService.getMapContainer(name);
if (mapContainer.getMapConfig().isStatisticsEnabled()) {
mapService.getLocalMapStatsImpl(name).incrementPuts(latency);
}
}
@Override
protected Operation prepareOperation() {
PutOperation op = new PutOperation(name, key, value, ttl);
op.setThreadId(threadId);
return op;
}
public String getServiceName() {
return MapService.SERVICE_NAME;
}
public void write(PortableWriter writer) throws IOException {
writer.writeUTF("n", name);
writer.writeLong("t", threadId);
writer.writeLong("ttl", ttl);
final ObjectDataOutput out = writer.getRawDataOutput();
key.writeData(out);
value.writeData(out);
}
public void read(PortableReader reader) throws IOException {
name = reader.readUTF("n");
threadId = reader.readLong("t");
ttl = reader.readLong("ttl");
final ObjectDataInput in = reader.getRawDataInput();
key = new Data();
key.readData(in);
value = new Data();
value.readData(in);
}
public Permission getRequiredPermission() {
return new MapPermission(name, ActionConstants.ACTION_PUT);
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_map_client_MapPutRequest.java |
5,124 | public abstract class Aggregator implements Releasable, ReaderContextAware {
/**
* Defines the nature of the aggregator's aggregation execution when nested in other aggregators and the buckets they create.
*/
public static enum BucketAggregationMode {
/**
* In this mode, a new aggregator instance will be created per bucket (created by the parent aggregator)
*/
PER_BUCKET,
/**
* In this mode, a single aggregator instance will be created per parent aggregator, that will handle the aggregations of all its buckets.
*/
MULTI_BUCKETS
}
protected final String name;
protected final Aggregator parent;
protected final AggregationContext context;
protected final int depth;
protected final long estimatedBucketCount;
protected final BucketAggregationMode bucketAggregationMode;
protected final AggregatorFactories factories;
protected final Aggregator[] subAggregators;
/**
* Constructs a new Aggregator.
*
* @param name The name of the aggregation
* @param bucketAggregationMode The nature of execution as a sub-aggregator (see {@link BucketAggregationMode})
* @param factories The factories for all the sub-aggregators under this aggregator
* @param estimatedBucketsCount When served as a sub-aggregator, indicate how many buckets the parent aggregator will generate.
* @param context The aggregation context
* @param parent The parent aggregator (may be {@code null} for top level aggregators)
*/
protected Aggregator(String name, BucketAggregationMode bucketAggregationMode, AggregatorFactories factories, long estimatedBucketsCount, AggregationContext context, Aggregator parent) {
this.name = name;
this.parent = parent;
this.estimatedBucketCount = estimatedBucketsCount;
this.context = context;
this.depth = parent == null ? 0 : 1 + parent.depth();
this.bucketAggregationMode = bucketAggregationMode;
assert factories != null : "sub-factories provided to BucketAggregator must not be null, use AggragatorFactories.EMPTY instead";
this.factories = factories;
this.subAggregators = factories.createSubAggregators(this, estimatedBucketsCount);
}
/**
* @return The name of the aggregation.
*/
public String name() {
return name;
}
/** Return the estimated number of buckets. */
public final long estimatedBucketCount() {
return estimatedBucketCount;
}
/** Return the depth of this aggregator in the aggregation tree. */
public final int depth() {
return depth;
}
/**
* @return The parent aggregator of this aggregator. The addAggregation are hierarchical in the sense that some can
* be composed out of others (more specifically, bucket addAggregation can define other addAggregation that will
* be aggregated per bucket). This method returns the direct parent aggregator that contains this aggregator, or
* {@code null} if there is none (meaning, this aggregator is a top level one)
*/
public Aggregator parent() {
return parent;
}
public Aggregator[] subAggregators() {
return subAggregators;
}
/**
* @return The current aggregation context.
*/
public AggregationContext context() {
return context;
}
/**
* @return The bucket aggregation mode of this aggregator. This mode defines the nature in which the aggregation is executed
* @see BucketAggregationMode
*/
public BucketAggregationMode bucketAggregationMode() {
return bucketAggregationMode;
}
/**
* @return Whether this aggregator is in the state where it can collect documents. Some aggregators can do their aggregations without
* actually collecting documents, for example, an aggregator that computes stats over unmapped fields doesn't need to collect
* anything as it knows to just return "empty" stats as the aggregation result.
*/
public abstract boolean shouldCollect();
/**
* Called during the query phase, to collect & aggregate the given document.
*
* @param doc The document to be collected/aggregated
* @param owningBucketOrdinal The ordinal of the bucket this aggregator belongs to, assuming this aggregator is not a top level aggregator.
* Typically, aggregators with {@code #bucketAggregationMode} set to {@link BucketAggregationMode#MULTI_BUCKETS}
* will heavily depend on this ordinal. Other aggregators may or may not use it and can see this ordinal as just
* an extra information for the aggregation context. For top level aggregators, the ordinal will always be
* equal to 0.
* @throws IOException
*/
public abstract void collect(int doc, long owningBucketOrdinal) throws IOException;
/**
* Called after collection of all document is done.
*/
public final void postCollection() {
for (int i = 0; i < subAggregators.length; i++) {
subAggregators[i].postCollection();
}
doPostCollection();
}
/** Called upon release of the aggregator. */
@Override
public boolean release() {
boolean success = false;
try {
doRelease();
success = true;
} finally {
Releasables.release(success, subAggregators);
}
return true;
}
/** Release instance-specific data. */
protected void doRelease() {}
/**
* Can be overriden by aggregator implementation to be called back when the collection phase ends.
*/
protected void doPostCollection() {
}
/**
* @return The aggregated & built aggregation
*/
public abstract InternalAggregation buildAggregation(long owningBucketOrdinal);
public abstract InternalAggregation buildEmptyAggregation();
protected final InternalAggregations buildEmptySubAggregations() {
List<InternalAggregation> aggs = new ArrayList<InternalAggregation>();
for (Aggregator aggregator : subAggregators) {
aggs.add(aggregator.buildEmptyAggregation());
}
return new InternalAggregations(aggs);
}
/**
* Parses the aggregation request and creates the appropriate aggregator factory for it.
*
* @see {@link AggregatorFactory}
*/
public static interface Parser {
/**
* @return The aggregation type this parser is associated with.
*/
String type();
/**
* Returns the aggregator factory with which this parser is associated, may return {@code null} indicating the
* aggregation should be skipped (e.g. when trying to aggregate on unmapped fields).
*
* @param aggregationName The name of the aggregation
* @param parser The xcontent parser
* @param context The search context
* @return The resolved aggregator factory or {@code null} in case the aggregation should be skipped
* @throws java.io.IOException When parsing fails
*/
AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException;
}
} | 1no label
| src_main_java_org_elasticsearch_search_aggregations_Aggregator.java |
1,663 | public class SandBoxOperationType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, SandBoxOperationType> TYPES = new LinkedHashMap<String, SandBoxOperationType>();
public static final SandBoxOperationType ADD = new SandBoxOperationType("ADD", "Add");
public static final SandBoxOperationType UPDATE = new SandBoxOperationType("UPDATE", "Update");
public static final SandBoxOperationType DELETE = new SandBoxOperationType("DELETE", "Delete");
public static SandBoxOperationType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public SandBoxOperationType() {
//do nothing
}
public SandBoxOperationType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
public String getType() {
return type;
}
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
} else {
throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName());
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SandBoxOperationType other = (SandBoxOperationType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
} | 0true
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_domain_SandBoxOperationType.java |
2,526 | static interface MapFactory {
Map<String, Object> newMap();
} | 0true
| src_main_java_org_elasticsearch_common_xcontent_support_AbstractXContentParser.java |
1,852 | 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);
}
}
}); | 1no label
| hazelcast_src_main_java_com_hazelcast_map_MapService.java |
1,224 | public class OStorageOperationResult<RET> implements Externalizable {
private RET result;
private boolean isMoved;
public OStorageOperationResult(RET result) {
this(result, false);
}
public OStorageOperationResult(RET result, boolean moved) {
this.result = result;
isMoved = moved;
}
public boolean isMoved() {
return isMoved;
}
public RET getResult() {
return result;
}
@Override
public void writeExternal(final ObjectOutput out) throws IOException {
out.writeObject(result);
out.writeBoolean(isMoved);
}
@SuppressWarnings("unchecked")
@Override
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
result = (RET) in.readObject();
isMoved = in.readBoolean();
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_OStorageOperationResult.java |
1,172 | public interface IdGenerator extends DistributedObject {
/**
* Try to initialize this IdGenerator instance with given id. The first
* generated id will be 1 bigger than id.
*
* @return true if initialization success. If id is equal or smaller
* than 0, then false is returned.
*/
boolean init(long id);
/**
* Generates and returns cluster-wide unique id.
* Generated ids are guaranteed to be unique for the entire cluster
* as long as the cluster is live. If the cluster restarts then
* id generation will start from 0.
*
* @return cluster-wide new unique id
*/
long newId();
} | 0true
| hazelcast_src_main_java_com_hazelcast_core_IdGenerator.java |
666 | constructors[COLLECTION_RESERVE_ADD] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new CollectionReserveAddOperation();
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java |
3,499 | public static abstract class Builder<T extends Builder, Y extends Mapper> {
public String name;
protected T builder;
protected Builder(String name) {
this.name = name;
}
public String name() {
return this.name;
}
public abstract Y build(BuilderContext context);
} | 0true
| src_main_java_org_elasticsearch_index_mapper_Mapper.java |
247 | class ResourceAcquisitionFailedException extends RuntimeException
{
ResourceAcquisitionFailedException( XAResource resource )
{
super( "Unable to enlist '" + resource + "' in " + "transaction" );
}
ResourceAcquisitionFailedException( RollbackException cause )
{
super( "The transaction is marked for rollback only.", cause );
}
ResourceAcquisitionFailedException( Throwable cause )
{
super( "TM encountered an unexpected error condition.", cause );
}
} | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_persistence_ResourceAcquisitionFailedException.java |
124 | public interface PageRuleProcessor {
/**
* Returns true if the passed in <code>Page</code> is valid according
* to this rule processor.
*
* @param page
* @return
*/
public boolean checkForMatch(PageDTO page, Map<String,Object> valueMap);
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_service_PageRuleProcessor.java |
2,225 | MIN {
@Override
public float combine(double queryBoost, double queryScore, double funcScore, double maxBoost) {
return toFloat(queryBoost * Math.min(queryScore, Math.min(funcScore, maxBoost)));
}
@Override
public String getName() {
return "min";
}
@Override
public ComplexExplanation explain(float queryBoost, Explanation queryExpl, Explanation funcExpl, float maxBoost) {
float score = toFloat(queryBoost * Math.min(queryExpl.getValue(), Math.min(funcExpl.getValue(), maxBoost)));
ComplexExplanation res = new ComplexExplanation(true, score, "function score, product of:");
ComplexExplanation innerMinExpl = new ComplexExplanation(true, Math.min(funcExpl.getValue(), maxBoost), "Math.min of");
innerMinExpl.addDetail(funcExpl);
innerMinExpl.addDetail(new Explanation(maxBoost, "maxBoost"));
ComplexExplanation outerMinExpl = new ComplexExplanation(true, Math.min(Math.min(funcExpl.getValue(), maxBoost),
queryExpl.getValue()), "min of");
outerMinExpl.addDetail(queryExpl);
outerMinExpl.addDetail(innerMinExpl);
res.addDetail(outerMinExpl);
res.addDetail(new Explanation(queryBoost, "queryBoost"));
return res;
}
}, | 0true
| src_main_java_org_elasticsearch_common_lucene_search_function_CombineFunction.java |
3,620 | public static class Defaults extends IntegerFieldMapper.Defaults {
} | 0true
| src_main_java_org_elasticsearch_index_mapper_core_TokenCountFieldMapper.java |
3,115 | public class AddListenerRequest extends CallableClientRequest implements SecureRequest, RetryableRequest {
private String name;
private boolean includeValue;
public AddListenerRequest() {
}
public AddListenerRequest(String name, boolean includeValue) {
this.name = name;
this.includeValue = includeValue;
}
@Override
public String getServiceName() {
return QueueService.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return QueuePortableHook.F_ID;
}
@Override
public int getClassId() {
return QueuePortableHook.ADD_LISTENER;
}
@Override
public void write(PortableWriter writer) throws IOException {
writer.writeUTF("n", name);
writer.writeBoolean("i", includeValue);
}
@Override
public void read(PortableReader reader) throws IOException {
name = reader.readUTF("n");
includeValue = reader.readBoolean("i");
}
@Override
public Object call() throws Exception {
final ClientEndpoint endpoint = getEndpoint();
final ClientEngine clientEngine = getClientEngine();
final QueueService service = getService();
ItemListener listener = new ItemListener() {
@Override
public void itemAdded(ItemEvent item) {
send(item);
}
@Override
public void itemRemoved(ItemEvent item) {
send(item);
}
private void send(ItemEvent event) {
if (endpoint.live()) {
Data item = clientEngine.toData(event.getItem());
PortableItemEvent portableItemEvent = new PortableItemEvent(
item, event.getEventType(), event.getMember().getUuid());
endpoint.sendEvent(portableItemEvent, getCallId());
}
}
};
String registrationId = service.addItemListener(name, listener, includeValue);
endpoint.setListenerRegistration(QueueService.SERVICE_NAME, name, registrationId);
return registrationId;
}
@Override
public Permission getRequiredPermission() {
return new QueuePermission(name, ActionConstants.ACTION_LISTEN);
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_queue_client_AddListenerRequest.java |
1,529 | @Component("blToggleFacetLinkProcessor")
public class ToggleFacetLinkProcessor extends AbstractAttributeModifierAttrProcessor {
@Resource(name = "blSearchFacetDTOService")
protected SearchFacetDTOService facetService;
/**
* Sets the name of this processor to be used in Thymeleaf template
*/
public ToggleFacetLinkProcessor() {
super("togglefacetlink");
}
@Override
public int getPrecedence() {
return 10000;
}
@Override
@SuppressWarnings("unchecked")
protected Map<String, String> getModifiedAttributeValues(Arguments arguments, Element element, String attributeName) {
Map<String, String> attrs = new HashMap<String, String>();
BroadleafRequestContext blcContext = BroadleafRequestContext.getBroadleafRequestContext();
HttpServletRequest request = blcContext.getRequest();
String baseUrl = request.getRequestURL().toString();
Map<String, String[]> params = new HashMap<String, String[]>(request.getParameterMap());
SearchFacetResultDTO result = (SearchFacetResultDTO) StandardExpressionProcessor.processExpression(arguments, element.getAttributeValue(attributeName));
String key = facetService.getUrlKey(result);
String value = facetService.getValue(result);
String[] paramValues = params.get(key);
if (ArrayUtils.contains(paramValues, facetService.getValue(result))) {
paramValues = (String[]) ArrayUtils.removeElement(paramValues, facetService.getValue(result));
} else {
paramValues = (String[]) ArrayUtils.add(paramValues, value);
}
params.remove(ProductSearchCriteria.PAGE_NUMBER);
params.put(key, paramValues);
String url = ProcessorUtils.getUrl(baseUrl, params);
attrs.put("href", url);
return attrs;
}
@Override
protected ModificationType getModificationType(Arguments arguments, Element element, String attributeName, String newAttributeName) {
return ModificationType.SUBSTITUTION;
}
@Override
protected boolean removeAttributeIfEmpty(Arguments arguments, Element element, String attributeName, String newAttributeName) {
return true;
}
@Override
protected boolean recomputeProcessorsAfterExecution(Arguments arguments, Element element, String attributeName) {
return false;
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_processor_ToggleFacetLinkProcessor.java |
309 | public class ConfigOption<O> extends ConfigElement {
public enum Type {
/**
* Once the database has been opened, these configuration options cannot
* be changed for the entire life of the database
*/
FIXED,
/**
* These options can only be changed for the entire database cluster at
* once when all instances are shut down
*/
GLOBAL_OFFLINE,
/**
* These options can only be changed globally across the entire database
* cluster
*/
GLOBAL,
/**
* These options are global but can be overwritten by a local
* configuration file
*/
MASKABLE,
/**
* These options can ONLY be provided through a local configuration file
*/
LOCAL;
}
private static final EnumSet<Type> managedTypes = EnumSet.of(Type.FIXED, Type.GLOBAL_OFFLINE, Type.GLOBAL);
private final Type type;
private final Class<O> datatype;
private final O defaultValue;
private final Predicate<O> verificationFct;
private boolean isHidden = false;
private ConfigOption<?> supersededBy;
public ConfigOption(ConfigNamespace parent, String name, String description, Type type, O defaultValue) {
this(parent,name,description,type,defaultValue, disallowEmpty((Class<O>) defaultValue.getClass()));
}
public ConfigOption(ConfigNamespace parent, String name, String description, Type type, O defaultValue, Predicate<O> verificationFct) {
this(parent,name,description,type,(Class<O>)defaultValue.getClass(),defaultValue,verificationFct);
}
public ConfigOption(ConfigNamespace parent, String name, String description, Type type, Class<O> datatype) {
this(parent,name,description,type,datatype, disallowEmpty(datatype));
}
public ConfigOption(ConfigNamespace parent, String name, String description, Type type, Class<O> datatype, Predicate<O> verificationFct) {
this(parent,name,description,type,datatype,null,verificationFct);
}
public ConfigOption(ConfigNamespace parent, String name, String description, Type type, Class<O> datatype, O defaultValue) {
this(parent,name,description,type,datatype,defaultValue,disallowEmpty(datatype));
}
public ConfigOption(ConfigNamespace parent, String name, String description, Type type, Class<O> datatype, O defaultValue, Predicate<O> verificationFct) {
this(parent, name, description, type, datatype, defaultValue, verificationFct, null);
}
public ConfigOption(ConfigNamespace parent, String name, String description, Type type, Class<O> datatype, O defaultValue, Predicate<O> verificationFct, ConfigOption<?> supersededBy) {
super(parent, name, description);
Preconditions.checkNotNull(type);
Preconditions.checkNotNull(datatype);
Preconditions.checkNotNull(verificationFct);
this.type = type;
this.datatype = datatype;
this.defaultValue = defaultValue;
this.verificationFct = verificationFct;
this.supersededBy = supersededBy;
}
public ConfigOption<O> hide() {
this.isHidden = true;
return this;
}
public boolean isHidden() {
return isHidden;
}
public Type getType() {
return type;
}
public Class<O> getDatatype() {
return datatype;
}
public O getDefaultValue() {
return defaultValue;
}
public boolean isFixed() {
return type==Type.FIXED;
}
public boolean isGlobal() {
return type==Type.FIXED || type==Type.GLOBAL_OFFLINE || type==Type.GLOBAL || type==Type.MASKABLE;
}
/**
* Returns true on config options whose values are not local or maskable, that is,
* cluster-wide options that are either fixed or which can be changed only by using
* the {@link com.thinkaurelius.titan.graphdb.database.management.ManagementSystem}
* (and not by editing the local config).
*
* @return true for managed options, false otherwise
*/
public boolean isManaged() {
return managedTypes.contains(type);
}
public static EnumSet<Type> getManagedTypes() {
return EnumSet.copyOf(managedTypes);
}
public boolean isLocal() {
return type==Type.MASKABLE || type==Type.LOCAL;
}
public boolean isDeprecated() {
return null != supersededBy;
}
public ConfigOption<?> getDeprecationReplacement() {
return supersededBy;
}
@Override
public boolean isOption() {
return true;
}
public O get(Object input) {
if (input==null) {
input=defaultValue;
}
if (input==null) {
Preconditions.checkState(verificationFct.apply((O) input), "Need to set configuration value: %s", this.toString());
return null;
} else {
return verify(input);
}
}
public O verify(Object input) {
Preconditions.checkNotNull(input);
Preconditions.checkArgument(datatype.isInstance(input),"Invalid class for configuration value [%s]. Expected [%s] but given [%s]",this.toString(),datatype,input.getClass());
O result = (O)input;
Preconditions.checkArgument(verificationFct.apply(result),"Invalid configuration value for [%s]: %s",this.toString(),input);
return result;
}
//########### HELPER METHODS ##################
public static final<O> Predicate<O> disallowEmpty(Class<O> clazz) {
return new Predicate<O>() {
@Override
public boolean apply(@Nullable O o) {
if (o==null) return false;
if (o.getClass().isArray() && (Array.getLength(o)==0 || Array.get(o,0)==null)) return false;
if (o instanceof Collection && (((Collection)o).isEmpty() || ((Collection)o).iterator().next()==null)) return false;
return true;
}
};
}
public static final Predicate<Integer> positiveInt() {
return new Predicate<Integer>() {
@Override
public boolean apply(@Nullable Integer num) {
return num!=null && num>0;
}
};
}
public static final Predicate<Integer> nonnegativeInt() {
return new Predicate<Integer>() {
@Override
public boolean apply(@Nullable Integer num) {
return num!=null && num>=0;
}
};
}
public static final Predicate<Long> positiveLong() {
return new Predicate<Long>() {
@Override
public boolean apply(@Nullable Long num) {
return num!=null && num>0;
}
};
}
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_ConfigOption.java |
3,549 | public class BinaryFieldMapper extends AbstractFieldMapper<BytesReference> {
public static final String CONTENT_TYPE = "binary";
public static class Defaults extends AbstractFieldMapper.Defaults {
public static final long COMPRESS_THRESHOLD = -1;
public static final FieldType FIELD_TYPE = new FieldType(AbstractFieldMapper.Defaults.FIELD_TYPE);
static {
FIELD_TYPE.setIndexed(false);
FIELD_TYPE.freeze();
}
}
public static class Builder extends AbstractFieldMapper.Builder<Builder, BinaryFieldMapper> {
private Boolean compress = null;
private long compressThreshold = Defaults.COMPRESS_THRESHOLD;
public Builder(String name) {
super(name, new FieldType(Defaults.FIELD_TYPE));
builder = this;
}
public Builder compress(boolean compress) {
this.compress = compress;
return this;
}
public Builder compressThreshold(long compressThreshold) {
this.compressThreshold = compressThreshold;
return this;
}
@Override
public BinaryFieldMapper build(BuilderContext context) {
return new BinaryFieldMapper(buildNames(context), fieldType, compress, compressThreshold, postingsProvider,
docValuesProvider, multiFieldsBuilder.build(this, context), copyTo);
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
BinaryFieldMapper.Builder builder = binaryField(name);
parseField(builder, name, node, parserContext);
for (Map.Entry<String, Object> entry : node.entrySet()) {
String fieldName = Strings.toUnderscoreCase(entry.getKey());
Object fieldNode = entry.getValue();
if (fieldName.equals("compress") && fieldNode != null) {
builder.compress(nodeBooleanValue(fieldNode));
} else if (fieldName.equals("compress_threshold") && fieldNode != null) {
if (fieldNode instanceof Number) {
builder.compressThreshold(((Number) fieldNode).longValue());
builder.compress(true);
} else {
builder.compressThreshold(ByteSizeValue.parseBytesSizeValue(fieldNode.toString()).bytes());
builder.compress(true);
}
}
}
return builder;
}
}
private Boolean compress;
private long compressThreshold;
protected BinaryFieldMapper(Names names, FieldType fieldType, Boolean compress, long compressThreshold,
PostingsFormatProvider postingsProvider, DocValuesFormatProvider docValuesProvider,
MultiFields multiFields, CopyTo copyTo) {
super(names, 1.0f, fieldType, null, null, null, postingsProvider, docValuesProvider, null, null, null, null, multiFields, copyTo);
this.compress = compress;
this.compressThreshold = compressThreshold;
}
@Override
public FieldType defaultFieldType() {
return Defaults.FIELD_TYPE;
}
@Override
public FieldDataType defaultFieldDataType() {
return null;
}
@Override
public Object valueForSearch(Object value) {
return value(value);
}
@Override
public BytesReference value(Object value) {
if (value == null) {
return null;
}
BytesReference bytes;
if (value instanceof BytesRef) {
bytes = new BytesArray((BytesRef) value);
} else if (value instanceof BytesReference) {
bytes = (BytesReference) value;
} else if (value instanceof byte[]) {
bytes = new BytesArray((byte[]) value);
} else {
try {
bytes = new BytesArray(Base64.decode(value.toString()));
} catch (IOException e) {
throw new ElasticsearchParseException("failed to convert bytes", e);
}
}
try {
return CompressorFactory.uncompressIfNeeded(bytes);
} catch (IOException e) {
throw new ElasticsearchParseException("failed to decompress source", e);
}
}
@Override
protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException {
if (!fieldType().stored()) {
return;
}
byte[] value;
if (context.parser().currentToken() == XContentParser.Token.VALUE_NULL) {
return;
} else {
value = context.parser().binaryValue();
if (compress != null && compress && !CompressorFactory.isCompressed(value, 0, value.length)) {
if (compressThreshold == -1 || value.length > compressThreshold) {
BytesStreamOutput bStream = new BytesStreamOutput();
StreamOutput stream = CompressorFactory.defaultCompressor().streamOutput(bStream);
stream.writeBytes(value, 0, value.length);
stream.close();
value = bStream.bytes().toBytes();
}
}
}
if (value == null) {
return;
}
fields.add(new Field(names.indexName(), value, fieldType));
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
@Override
protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException {
builder.field("type", contentType());
if (includeDefaults || !names.name().equals(names.indexNameClean())) {
builder.field("index_name", names.indexNameClean());
}
if (compress != null) {
builder.field("compress", compress);
} else if (includeDefaults) {
builder.field("compress", false);
}
if (compressThreshold != -1) {
builder.field("compress_threshold", new ByteSizeValue(compressThreshold).toString());
} else if (includeDefaults) {
builder.field("compress_threshold", -1);
}
if (includeDefaults || fieldType.stored() != defaultFieldType().stored()) {
builder.field("store", fieldType.stored());
}
}
@Override
public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException {
BinaryFieldMapper sourceMergeWith = (BinaryFieldMapper) mergeWith;
if (!mergeContext.mergeFlags().simulate()) {
if (sourceMergeWith.compress != null) {
this.compress = sourceMergeWith.compress;
}
if (sourceMergeWith.compressThreshold != -1) {
this.compressThreshold = sourceMergeWith.compressThreshold;
}
}
}
@Override
public boolean hasDocValues() {
return false;
}
} | 1no label
| src_main_java_org_elasticsearch_index_mapper_core_BinaryFieldMapper.java |
771 | public abstract class OIdentifiableIterator<REC extends OIdentifiable> implements Iterator<REC>, Iterable<REC> {
protected final ODatabaseRecord database;
private final ODatabaseRecord lowLevelDatabase;
private final OStorage dbStorage;
protected boolean liveUpdated = false;
protected long limit = -1;
protected long browsedRecords = 0;
private String fetchPlan;
private ORecordInternal<?> reusedRecord = null; // DEFAULT = NOT
// REUSE IT
private Boolean directionForward;
protected final ORecordId current = new ORecordId();
protected long totalAvailableRecords;
protected List<ORecordOperation> txEntries;
protected int currentTxEntryPosition = -1;
protected OClusterPosition firstClusterEntry = OClusterPositionFactory.INSTANCE.valueOf(0);
protected OClusterPosition lastClusterEntry = OClusterPositionFactory.INSTANCE.getMaxValue();
private OClusterPosition currentEntry = OClusterPosition.INVALID_POSITION;
private int currentEntryPosition = -1;
private OPhysicalPosition[] positionsToProcess = null;
private final boolean useCache;
private final boolean iterateThroughTombstones;
public OIdentifiableIterator(final ODatabaseRecord iDatabase, final ODatabaseRecord iLowLevelDatabase, final boolean useCache,
final boolean iterateThroughTombstones) {
database = iDatabase;
lowLevelDatabase = iLowLevelDatabase;
this.iterateThroughTombstones = iterateThroughTombstones;
this.useCache = useCache;
dbStorage = lowLevelDatabase.getStorage();
current.clusterPosition = OClusterPosition.INVALID_POSITION; // DEFAULT = START FROM THE BEGIN
}
public boolean isIterateThroughTombstones() {
return iterateThroughTombstones;
}
public abstract boolean hasPrevious();
public abstract OIdentifiable previous();
public abstract OIdentifiableIterator<REC> begin();
public abstract OIdentifiableIterator<REC> last();
public ORecordInternal<?> current() {
return readCurrentRecord(getRecord(), 0);
}
protected ORecordInternal<?> getTransactionEntry() {
boolean noPhysicalRecordToBrowse;
if (current.clusterPosition.isTemporary())
noPhysicalRecordToBrowse = true;
else if (directionForward)
noPhysicalRecordToBrowse = lastClusterEntry.compareTo(currentEntry) <= 0;
else
noPhysicalRecordToBrowse = currentEntry.compareTo(firstClusterEntry) <= 0;
if (!noPhysicalRecordToBrowse && positionsToProcess.length == 0)
noPhysicalRecordToBrowse = true;
if (noPhysicalRecordToBrowse && txEntries != null) {
// IN TX
currentTxEntryPosition++;
if (currentTxEntryPosition >= txEntries.size())
throw new NoSuchElementException();
else
return txEntries.get(currentTxEntryPosition).getRecord();
}
return null;
}
public String getFetchPlan() {
return fetchPlan;
}
public void setFetchPlan(String fetchPlan) {
this.fetchPlan = fetchPlan;
}
public void remove() {
throw new UnsupportedOperationException("remove");
}
/**
* Tells if the iterator is using the same record for browsing.
*
* @see #setReuseSameRecord(boolean)
*/
public boolean isReuseSameRecord() {
return reusedRecord != null;
}
public OClusterPosition getCurrentEntry() {
return currentEntry;
}
/**
* Tell to the iterator to use the same record for browsing. The record will be reset before every use. This improve the
* performance and reduce memory utilization since it does not create a new one for each operation, but pay attention to copy the
* data of the record once read otherwise they will be reset to the next operation.
*
* @param reuseSameRecord
* if true the same record will be used for iteration. If false new record will be created each time iterator retrieves
* record from db.
* @return @see #isReuseSameRecord()
*/
public OIdentifiableIterator<REC> setReuseSameRecord(final boolean reuseSameRecord) {
reusedRecord = (ORecordInternal<?>) (reuseSameRecord ? database.newInstance() : null);
return this;
}
/**
* Return the record to use for the operation.
*
* @return the record to use for the operation.
*/
protected ORecordInternal<?> getRecord() {
final ORecordInternal<?> record;
if (reusedRecord != null) {
// REUSE THE SAME RECORD AFTER HAVING RESETTED IT
record = reusedRecord;
record.reset();
} else
record = null;
return record;
}
/**
* Return the iterator to be used in Java5+ constructs<br/>
* <br/>
* <code>
* for( ORecordDocument rec : database.browseCluster( "Animal" ) ){<br/>
* ...<br/>
* }<br/>
* </code>
*/
public Iterator<REC> iterator() {
return this;
}
/**
* Return the current limit on browsing record. -1 means no limits (default).
*
* @return The limit if setted, otherwise -1
* @see #setLimit(long)
*/
public long getLimit() {
return limit;
}
/**
* Set the limit on browsing record. -1 means no limits. You can set the limit even while you're browsing.
*
* @param limit
* The current limit on browsing record. -1 means no limits (default).
* @see #getLimit()
*/
public OIdentifiableIterator<REC> setLimit(long limit) {
this.limit = limit;
return this;
}
/**
* Return current configuration of live updates.
*
* @return True to activate it, otherwise false (default)
* @see #setLiveUpdated(boolean)
*/
public boolean isLiveUpdated() {
return liveUpdated;
}
/**
* Tell to the iterator that the upper limit must be checked at every cycle. Useful when concurrent deletes or additions change
* the size of the cluster while you're browsing it. Default is false.
*
* @param liveUpdated
* True to activate it, otherwise false (default)
* @see #isLiveUpdated()
*/
public OIdentifiableIterator<REC> setLiveUpdated(boolean liveUpdated) {
this.liveUpdated = liveUpdated;
return this;
}
protected void checkDirection(final boolean iForward) {
if (directionForward == null)
// SET THE DIRECTION
directionForward = iForward;
else if (directionForward != iForward)
throw new OIterationException("Iterator cannot change direction while browsing");
}
/**
* Read the current record and increment the counter if the record was found.
*
* @param iRecord
* to read value from database inside it. If record is null link will be created and stored in it.
* @return record which was read from db.
*/
protected ORecordInternal<?> readCurrentRecord(ORecordInternal<?> iRecord, final int iMovement) {
if (limit > -1 && browsedRecords >= limit)
// LIMIT REACHED
return null;
do {
final boolean moveResult;
switch (iMovement) {
case 1:
moveResult = nextPosition();
break;
case -1:
moveResult = prevPosition();
break;
case 0:
moveResult = checkCurrentPosition();
break;
default:
throw new IllegalStateException("Invalid movement value : " + iMovement);
}
if (!moveResult)
return null;
try {
if (iRecord != null) {
iRecord.setIdentity(new ORecordId(current.clusterId, current.clusterPosition));
iRecord = lowLevelDatabase.load(iRecord, fetchPlan, !useCache, iterateThroughTombstones);
} else
iRecord = lowLevelDatabase.load(current, fetchPlan, !useCache, iterateThroughTombstones);
} catch (ODatabaseException e) {
if (Thread.interrupted())
// THREAD INTERRUPTED: RETURN
throw e;
OLogManager.instance().error(this, "Error on fetching record during browsing. The record has been skipped", e);
}
if (iRecord != null) {
browsedRecords++;
return iRecord;
}
} while (iMovement != 0);
return null;
}
protected boolean nextPosition() {
if (positionsToProcess == null) {
positionsToProcess = dbStorage.ceilingPhysicalPositions(current.clusterId, new OPhysicalPosition(firstClusterEntry));
if (positionsToProcess == null)
return false;
} else {
if (currentEntry.compareTo(lastClusterEntry) >= 0)
return false;
}
incrementEntreePosition();
while (positionsToProcess.length > 0 && currentEntryPosition >= positionsToProcess.length) {
positionsToProcess = dbStorage.higherPhysicalPositions(current.clusterId, positionsToProcess[positionsToProcess.length - 1]);
currentEntryPosition = -1;
incrementEntreePosition();
}
if (positionsToProcess.length == 0)
return false;
currentEntry = positionsToProcess[currentEntryPosition].clusterPosition;
if (currentEntry.compareTo(lastClusterEntry) > 0 || currentEntry.equals(OClusterPosition.INVALID_POSITION))
return false;
current.clusterPosition = currentEntry;
return true;
}
protected boolean checkCurrentPosition() {
if (currentEntry == null || currentEntry.equals(OClusterPosition.INVALID_POSITION)
|| firstClusterEntry.compareTo(currentEntry) > 0 || lastClusterEntry.compareTo(currentEntry) < 0)
return false;
current.clusterPosition = currentEntry;
return true;
}
protected boolean prevPosition() {
if (positionsToProcess == null) {
positionsToProcess = dbStorage.floorPhysicalPositions(current.clusterId, new OPhysicalPosition(lastClusterEntry));
if (positionsToProcess == null)
return false;
if (positionsToProcess.length == 0)
return false;
currentEntryPosition = positionsToProcess.length;
} else {
if (currentEntry.compareTo(firstClusterEntry) < 0)
return false;
}
decrementEntreePosition();
while (positionsToProcess.length > 0 && currentEntryPosition < 0) {
positionsToProcess = dbStorage.lowerPhysicalPositions(current.clusterId, positionsToProcess[0]);
currentEntryPosition = positionsToProcess.length;
decrementEntreePosition();
}
if (positionsToProcess.length == 0)
return false;
currentEntry = positionsToProcess[currentEntryPosition].clusterPosition;
if (currentEntry.compareTo(firstClusterEntry) < 0)
return false;
current.clusterPosition = currentEntry;
return true;
}
private void decrementEntreePosition() {
if (positionsToProcess.length > 0)
if (iterateThroughTombstones)
currentEntryPosition--;
else
do {
currentEntryPosition--;
} while (currentEntryPosition >= 0 && positionsToProcess[currentEntryPosition].recordVersion.isTombstone());
}
private void incrementEntreePosition() {
if (positionsToProcess.length > 0)
if (iterateThroughTombstones)
currentEntryPosition++;
else
do {
currentEntryPosition++;
} while (currentEntryPosition < positionsToProcess.length
&& positionsToProcess[currentEntryPosition].recordVersion.isTombstone());
}
protected void resetCurrentPosition() {
currentEntry = OClusterPosition.INVALID_POSITION;
positionsToProcess = null;
currentEntryPosition = -1;
}
protected OClusterPosition currentPosition() {
return currentEntry;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_iterator_OIdentifiableIterator.java |
972 | abstract class BaseSignalOperation extends BaseLockOperation {
protected boolean all;
protected String conditionId;
protected transient int awaitCount;
public BaseSignalOperation() {
}
public BaseSignalOperation(ObjectNamespace namespace, Data key, long threadId, String conditionId, boolean all) {
super(namespace, key, threadId);
this.conditionId = conditionId;
this.all = all;
}
@Override
public void run() throws Exception {
LockStoreImpl lockStore = getLockStore();
awaitCount = lockStore.getAwaitCount(key, conditionId);
int signalCount;
if (awaitCount > 0) {
if (all) {
signalCount = awaitCount;
} else {
signalCount = 1;
}
} else {
signalCount = 0;
}
ConditionKey notifiedKey = new ConditionKey(namespace.getObjectName(), key, conditionId);
for (int i = 0; i < signalCount; i++) {
lockStore.registerSignalKey(notifiedKey);
}
response = true;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeBoolean(all);
out.writeUTF(conditionId);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
all = in.readBoolean();
conditionId = in.readUTF();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_lock_operations_BaseSignalOperation.java |
52 | public interface RelationType extends TitanVertex, TitanSchemaType {
/**
* Checks if this relation type is a property key
*
* @return true, if this relation type is a property key, else false.
* @see PropertyKey
*/
public boolean isPropertyKey();
/**
* Checks if this relation type is an edge label
*
* @return true, if this relation type is a edge label, else false.
* @see EdgeLabel
*/
public boolean isEdgeLabel();
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_RelationType.java |
139 | public interface TitanSchemaElement extends Namifiable {
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_schema_TitanSchemaElement.java |
870 | public abstract class OAbstractBlock implements OProcessorBlock {
protected OProcessorBlock parentBlock;
protected abstract Object processBlock(OComposableProcessor iManager, OCommandContext iContext, ODocument iConfig,
ODocument iOutput, boolean iReadOnly);
@Override
public Object process(OComposableProcessor iManager, OCommandContext iContext, ODocument iConfig, ODocument iOutput,
boolean iReadOnly) {
if (!checkForCondition(iContext, iConfig))
return null;
Boolean enabled = getFieldOfClass(iContext, iConfig, "enabled", Boolean.class);
if (enabled != null && !enabled)
return null;
String returnVariable = getFieldOfClass(iContext, iConfig, "return", String.class);
debug(iContext, "Executing {%s} block...", iConfig.field("type"));
final Object result = processBlock(iManager, iContext, iConfig, iOutput, iReadOnly);
printReturn(iContext, result);
if (returnVariable != null)
assignVariable(iContext, returnVariable, result);
return result;
}
protected void printReturn(OCommandContext iContext, final Object result) {
if (result != null && !(result instanceof OCommandRequest) && result instanceof Iterable<?>)
debug(iContext, "Returned %s", OCollections.toString((Iterable<?>) result));
else
debug(iContext, "Returned %s", result);
}
protected Object delegate(final String iElementName, final OComposableProcessor iManager, final Object iContent,
final OCommandContext iContext, ODocument iOutput, final boolean iReadOnly) {
try {
return iManager.process(this, iContent, iContext, iOutput, iReadOnly);
} catch (Exception e) {
throw new OProcessException("Error on processing '" + iElementName + "' field of '" + getName() + "' block", e);
}
}
protected Object delegate(final String iElementName, final OComposableProcessor iManager, final String iType,
final ODocument iContent, final OCommandContext iContext, ODocument iOutput, final boolean iReadOnly) {
try {
return iManager.process(this, iType, iContent, iContext, iOutput, iReadOnly);
} catch (Exception e) {
throw new OProcessException("Error on processing '" + iElementName + "' field of '" + getName() + "' block", e);
}
}
public boolean checkForCondition(final OCommandContext iContext, final ODocument iConfig) {
Object condition = getField(iContext, iConfig, "if");
if (condition instanceof Boolean)
return (Boolean) condition;
else if (condition != null) {
Object result = evaluate(iContext, (String) condition);
return result != null && (Boolean) result;
}
return true;
}
public Object evaluate(final OCommandContext iContext, final String iExpression) {
if (iExpression == null)
throw new OProcessException("Null expression");
final OSQLPredicate predicate = new OSQLPredicate((String) resolveValue(iContext, iExpression, true));
final Object result = predicate.evaluate(iContext);
debug(iContext, "Evaluated expression '" + iExpression + "' = " + result);
return result;
}
public void assignVariable(final OCommandContext iContext, final String iName, final Object iValue) {
if (iName != null) {
iContext.setVariable(iName, iValue);
debug(iContext, "Assigned context variable %s=%s", iName, iValue);
}
}
protected void debug(final OCommandContext iContext, final String iText, Object... iArgs) {
if (isDebug(iContext)) {
final Integer depthLevel = (Integer) iContext.getVariable("depthLevel");
final StringBuilder text = new StringBuilder();
for (int i = 0; i < depthLevel; ++i)
text.append('-');
text.append('>');
text.append('{');
text.append(getName());
text.append("} ");
text.append(iText);
OLogManager.instance().info(this, text.toString(), iArgs);
}
}
@SuppressWarnings("unchecked")
protected <T> T getRawField(final ODocument iConfig, final String iFieldName) {
return (T) iConfig.field(iFieldName);
}
@SuppressWarnings("unchecked")
protected <T> T getField(final OCommandContext iContext, final ODocument iConfig, final String iFieldName) {
return (T) resolveValue(iContext, iConfig.field(iFieldName), true);
}
@SuppressWarnings("unchecked")
protected <T> T getField(final OCommandContext iContext, final ODocument iConfig, final String iFieldName, final boolean iCopy) {
return (T) resolveValue(iContext, iConfig.field(iFieldName), iCopy);
}
@SuppressWarnings("unchecked")
protected <T> T getFieldOrDefault(final OCommandContext iContext, final ODocument iConfig, final String iFieldName,
final T iDefaultValue) {
final Object f = iConfig.field(iFieldName);
if (f == null)
return iDefaultValue;
return (T) resolveValue(iContext, f, true);
}
protected <T> T getFieldOfClass(final OCommandContext iContext, final ODocument iConfig, final String iFieldName,
Class<? extends T> iExpectedClass) {
return getFieldOfClass(iContext, iConfig, iFieldName, iExpectedClass, true);
}
@SuppressWarnings("unchecked")
protected <T> T getFieldOfClass(final OCommandContext iContext, final ODocument iConfig, final String iFieldName,
Class<? extends T> iExpectedClass, final boolean iCopy) {
final Object f = resolveValue(iContext, iConfig.field(iFieldName), iCopy);
if (f != null)
if (!iExpectedClass.isAssignableFrom(f.getClass()))
throw new OProcessException("Block '" + getName() + "' defines the field '" + iFieldName + "' of type '" + f.getClass()
+ "' that is not compatible with the expected type '" + iExpectedClass + "'");
return (T) f;
}
@SuppressWarnings("unchecked")
protected <T> T getRequiredField(final OCommandContext iContext, final ODocument iConfig, final String iFieldName) {
final Object f = iConfig.field(iFieldName);
if (f == null)
throw new OProcessException("Block '" + getName() + "' must define the field '" + iFieldName + "'");
return (T) resolveValue(iContext, f, true);
}
@SuppressWarnings("unchecked")
protected <T> T getRequiredFieldOfClass(final OCommandContext iContext, final ODocument iConfig, final String iFieldName,
Class<? extends T> iExpectedClass) {
final Object f = getFieldOfClass(iContext, iConfig, iFieldName, iExpectedClass);
if (f == null)
throw new OProcessException("Block '" + getName() + "' must define the field '" + iFieldName + "'");
return (T) resolveValue(iContext, f, true);
}
public void checkForBlock(final Object iValue) {
if (!isBlock(iValue))
throw new OProcessException("Block '" + getName() + "' was expecting a block but found object of type " + iValue.getClass());
}
public boolean isDebug(final OCommandContext iContext) {
final Object debug = iContext.getVariable("debugMode");
if (debug != null) {
if (debug instanceof Boolean)
return (Boolean) debug;
else
return Boolean.parseBoolean((String) debug);
}
return false;
}
public static boolean isBlock(final Object iValue) {
return iValue instanceof ODocument && ((ODocument) iValue).containsField(("type"));
}
public static Object resolve(final OCommandContext iContext, final Object iContent) {
Object value = null;
if (iContent instanceof String)
value = OVariableParser.resolveVariables((String) iContent, OSystemVariableResolver.VAR_BEGIN,
OSystemVariableResolver.VAR_END, new OVariableParserListener() {
@Override
public Object resolve(final String iVariable) {
return iContext.getVariable(iVariable);
}
});
else
value = iContent;
if (value instanceof String)
value = OVariableParser.resolveVariables((String) value, "={", "}", new OVariableParserListener() {
@Override
public Object resolve(final String iVariable) {
return new OSQLPredicate(iVariable).evaluate(iContext);
}
});
return value;
}
@SuppressWarnings("unchecked")
protected Object resolveValue(final OCommandContext iContext, final Object iValue, final boolean iClone) {
if (iValue == null)
return null;
if (iValue instanceof String)
// STRING
return resolve(iContext, iValue);
else if (iValue instanceof ODocument) {
// DOCUMENT
final ODocument sourceDoc = ((ODocument) iValue);
final ODocument destDoc = iClone ? new ODocument().setOrdered(true) : sourceDoc;
for (String fieldName : sourceDoc.fieldNames()) {
Object fieldValue = resolveValue(iContext, sourceDoc.field(fieldName), iClone);
// PUT IN CONTEXT
destDoc.field(fieldName, fieldValue);
}
return destDoc;
} else if (iValue instanceof Map<?, ?>) {
// MAP
final Map<Object, Object> sourceMap = (Map<Object, Object>) iValue;
final Map<Object, Object> destMap = iClone ? new HashMap<Object, Object>() : sourceMap;
for (Entry<Object, Object> entry : sourceMap.entrySet())
destMap.put(entry.getKey(), resolveValue(iContext, entry.getValue(), iClone));
return destMap;
} else if (iValue instanceof List<?>) {
final List<Object> sourceList = (List<Object>) iValue;
final List<Object> destList = iClone ? new ArrayList<Object>() : sourceList;
for (int i = 0; i < sourceList.size(); ++i)
if (iClone)
destList.add(i, resolve(iContext, sourceList.get(i)));
else
destList.set(i, resolve(iContext, sourceList.get(i)));
return destList;
}
// ANY OTHER OBJECT
return iValue;
}
@SuppressWarnings("unchecked")
protected Object getValue(final Object iValue, final Boolean iCopy) {
if (iValue != null && iCopy != null && iCopy) {
// COPY THE VALUE
if (iValue instanceof ODocument)
return ((ODocument) iValue).copy();
else if (iValue instanceof List)
return new ArrayList<Object>((Collection<Object>) iValue);
else if (iValue instanceof Set)
return new HashSet<Object>((Collection<Object>) iValue);
else if (iValue instanceof Map)
return new LinkedHashMap<Object, Object>((Map<Object, Object>) iValue);
else
throw new OProcessException("Copy of value '" + iValue + "' of class '" + iValue.getClass() + "' is not supported");
}
return iValue;
}
protected Object flatMultivalues(final OCommandContext iContext, final Boolean copy, final Boolean flatMultivalues,
final Object value) {
if (OMultiValue.isMultiValue(value) && flatMultivalues != null && flatMultivalues) {
Collection<Object> newColl;
if (value instanceof Set<?>)
newColl = new HashSet<Object>();
else
newColl = new ArrayList<Object>();
for (Object entry : OMultiValue.getMultiValueIterable(value)) {
if (entry instanceof ODocument) {
// DOCUMENT
for (String fieldName : ((ODocument) entry).fieldNames())
newColl.add(((ODocument) entry).field(fieldName));
} else
OMultiValue.add(newColl, resolveValue(iContext, getValue(entry, copy), false));
}
return newColl;
}
return value;
}
public OProcessorBlock getParentBlock() {
return parentBlock;
}
public void setParentBlock(OProcessorBlock parentBlock) {
this.parentBlock = parentBlock;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_processor_block_OAbstractBlock.java |
198 | final class GetSelection implements Runnable {
ITextSelection selection;
@Override
public void run() {
ISelectionProvider sp =
CeylonEditor.this.getSelectionProvider();
selection = sp==null ?
null : (ITextSelection) sp.getSelection();
}
ITextSelection getSelection() {
Display.getDefault().syncExec(this);
return selection;
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonEditor.java |
106 | public class OFileUtils {
private static final int KILOBYTE = 1024;
private static final int MEGABYTE = 1048576;
private static final int GIGABYTE = 1073741824;
private static final long TERABYTE = 1099511627776L;
public static long getSizeAsNumber(final Object iSize) {
if (iSize == null)
throw new IllegalArgumentException("Size is null");
if (iSize instanceof Number)
return ((Number) iSize).longValue();
String size = iSize.toString();
boolean number = true;
for (int i = size.length() - 1; i >= 0; --i) {
if (!Character.isDigit(size.charAt(i))) {
number = false;
break;
}
}
if (number)
return string2number(size).longValue();
else {
size = size.toUpperCase(Locale.ENGLISH);
int pos = size.indexOf("KB");
if (pos > -1)
return (long) (string2number(size.substring(0, pos)).floatValue() * KILOBYTE);
pos = size.indexOf("MB");
if (pos > -1)
return (long) (string2number(size.substring(0, pos)).floatValue() * MEGABYTE);
pos = size.indexOf("GB");
if (pos > -1)
return (long) (string2number(size.substring(0, pos)).floatValue() * GIGABYTE);
pos = size.indexOf("TB");
if (pos > -1)
return (long) (string2number(size.substring(0, pos)).floatValue() * TERABYTE);
pos = size.indexOf('B');
if (pos > -1)
return (long) string2number(size.substring(0, pos)).floatValue();
pos = size.indexOf('%');
if (pos > -1)
return (long) (-1 * string2number(size.substring(0, pos)).floatValue());
// RE-THROW THE EXCEPTION
throw new IllegalArgumentException("Size " + size + " has a unrecognizable format");
}
}
public static Number string2number(final String iText) {
if (iText.indexOf('.') > -1)
return Double.parseDouble(iText);
else
return Long.parseLong(iText);
}
public static String getSizeAsString(final long iSize) {
if (iSize > TERABYTE)
return String.format("%2.2fTb", (float) iSize / TERABYTE);
if (iSize > GIGABYTE)
return String.format("%2.2fGb", (float) iSize / GIGABYTE);
if (iSize > MEGABYTE)
return String.format("%2.2fMb", (float) iSize / MEGABYTE);
if (iSize > KILOBYTE)
return String.format("%2.2fKb", (float) iSize / KILOBYTE);
return String.valueOf(iSize) + "b";
}
public static String getDirectory(String iPath) {
iPath = getPath(iPath);
int pos = iPath.lastIndexOf("/");
if (pos == -1)
return "";
return iPath.substring(0, pos);
}
public static void createDirectoryTree(final String iFileName) {
final String[] fileDirectories = iFileName.split("/");
for (int i = 0; i < fileDirectories.length - 1; ++i)
new File(fileDirectories[i]).mkdir();
}
public static String getPath(final String iPath) {
if (iPath == null)
return null;
return iPath.replace('\\', '/');
}
public static void checkValidName(final String iFileName) throws IOException {
if (iFileName.contains("..") || iFileName.contains("/") || iFileName.contains("\\"))
throw new IOException("Invalid file name '" + iFileName + "'");
}
public static void deleteRecursively(final File iRootFile) {
if (iRootFile.exists()) {
if (iRootFile.isDirectory()) {
for (File f : iRootFile.listFiles()) {
if (f.isFile())
f.delete();
else
deleteRecursively(f);
}
}
iRootFile.delete();
}
}
@SuppressWarnings("resource")
public static final void copyFile(final File source, final File destination) throws IOException {
FileChannel sourceChannel = new FileInputStream(source).getChannel();
FileChannel targetChannel = new FileOutputStream(destination).getChannel();
sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
sourceChannel.close();
targetChannel.close();
}
public static final void copyDirectory(final File source, final File destination) throws IOException {
if (!destination.exists())
destination.mkdirs();
for (File f : source.listFiles()) {
final File target = new File(destination.getAbsolutePath() + "/" + f.getName());
if (f.isFile())
copyFile(f, target);
else
copyDirectory(f, target);
}
}
} | 1no label
| commons_src_main_java_com_orientechnologies_common_io_OFileUtils.java |
1,686 | public interface AdminSection extends Serializable {
public Long getId();
public String getName();
public void setName(String name);
public String getSectionKey();
public void setSectionKey(String sectionKey);
public String getUrl();
public void setUrl(String url);
public List<AdminPermission> getPermissions();
public void setPermissions(List<AdminPermission> permissions);
public void setDisplayController(String displayController);
public String getDisplayController();
public AdminModule getModule();
public void setModule(AdminModule module);
public Boolean getUseDefaultHandler();
public void setUseDefaultHandler(Boolean useDefaultHandler);
public String getCeilingEntity();
public void setCeilingEntity(String ceilingEntity);
public Integer getDisplayOrder();
public void setDisplayOrder(Integer displayOrder);
} | 0true
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_security_domain_AdminSection.java |
417 | @Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface AdminPresentationMapField {
/**
* <p>Represents the field name for this field.</p>
*
* @return the name for this field
*/
String fieldName();
/**
* <p>Represents the metadata for this field. The <tt>AdminPresentation</tt> properties will be used
* by the system to determine how this field should be treated in the admin tool (e.g. date fields get
* a date picker in the UI)</p>
*
* @return the descriptive metadata for this field
*/
AdminPresentation fieldPresentation();
/**
* <p>Optional - if the Map structure is using generics, then the system can usually infer the concrete
* type for the Map value. However, if not using generics for the Map, or if the value cannot be clearly
* inferred, you can explicitly set the Map structure value type here. Map fields can only understand
* maps whose values are basic types (String, Long, Date, etc...). Complex types require additional
* support. Support is provided out-of-the-box for complex types <tt>ValueAssignable</tt>,
* <tt>Searchable</tt> and <tt>SimpleRule</tt>.</p>
*
* @return the concrete type for the Map structure value
*/
Class<?> targetClass() default Void.class;
/**
* <p>Optional - if the map field value contains searchable information and should be included in Broadleaf
* search engine indexing and searching. If set, the map value class must implement the <tt>Searchable</tt> interface.
* Note, support for indexing and searching this field must be explicitly added to the Broadleaf search service
* as well.</p>
*
* @return Whether or not this field is searchable with the Broadleaf search engine
*/
CustomFieldSearchableTypes searchable() default CustomFieldSearchableTypes.NOT_SPECIFIED;
/**
* <p>Optional - if the value is not primitive and contains a bi-directional reference back to the entity containing
* this map structure, you can declare the field name in the value class for this reference. Note, if the map
* uses the JPA mappedBy property, the system will try to infer the manyToField value so you don't have to set
* it here.</p>
*
* @return the parent entity referring field name
*/
String manyToField() default "";
} | 0true
| common_src_main_java_org_broadleafcommerce_common_presentation_AdminPresentationMapField.java |
455 | public static class AdminPresentationMap {
public static final String FRIENDLYNAME = "friendlyName";
public static final String SECURITYLEVEL = "securityLevel";
public static final String EXCLUDED = "excluded";
public static final String READONLY = "readOnly";
public static final String USESERVERSIDEINSPECTIONCACHE = "useServerSideInspectionCache";
public static final String ORDER = "order";
public static final String TAB = "tab";
public static final String TABORDER = "tabOrder";
public static final String KEYCLASS = "keyClass";
public static final String MAPKEYVALUEPROPERTY = "mapKeyValueProperty";
public static final String KEYPROPERTYFRIENDLYNAME = "keyPropertyFriendlyName";
public static final String VALUECLASS = "valueClass";
public static final String DELETEENTITYUPONREMOVE = "deleteEntityUponRemove";
public static final String VALUEPROPERTYFRIENDLYNAME = "valuePropertyFriendlyName";
public static final String ISSIMPLEVALUE = "isSimpleValue";
public static final String MEDIAFIELD = "mediaField";
public static final String KEYS = "keys";
public static final String FORCEFREEFORMKEYS = "forceFreeFormKeys";
public static final String MANYTOFIELD = "manyToField";
public static final String MAPKEYOPTIONENTITYCLASS = "mapKeyOptionEntityClass";
public static final String MAPKEYOPTIONENTITYDISPLAYFIELD = "mapKeyOptionEntityDisplayField";
public static final String MAPKEYOPTIONENTITYVALUEFIELD = "mapKeyOptionEntityValueField";
public static final String CUSTOMCRITERIA = "customCriteria";
public static final String OPERATIONTYPES = "operationTypes";
public static final String SHOWIFPROPERTY = "showIfProperty";
public static final String CURRENCYCODEFIELD = "currencyCodeField";
} | 0true
| common_src_main_java_org_broadleafcommerce_common_presentation_override_PropertyType.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.