Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
680
public class PutWarmerRequest extends AcknowledgedRequest<PutWarmerRequest> { private String name; private SearchRequest searchRequest; PutWarmerRequest() { } /** * Constructs a new warmer. * * @param name The name of the warmer. */ public PutWarmerRequest(String name) { this.name = name; } /** * Sets the name of the warmer. */ public PutWarmerRequest name(String name) { this.name = name; return this; } String name() { return this.name; } /** * Sets the search request to warm. */ public PutWarmerRequest searchRequest(SearchRequest searchRequest) { this.searchRequest = searchRequest; return this; } /** * Sets the search request to warm. */ public PutWarmerRequest searchRequest(SearchRequestBuilder searchRequest) { this.searchRequest = searchRequest.request(); return this; } SearchRequest searchRequest() { return this.searchRequest; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; if (searchRequest == null) { validationException = addValidationError("search request is missing", validationException); } else { validationException = searchRequest.validate(); } if (name == null) { validationException = addValidationError("name is missing", validationException); } return validationException; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); name = in.readString(); if (in.readBoolean()) { searchRequest = new SearchRequest(); searchRequest.readFrom(in); } readTimeout(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(name); if (searchRequest == null) { out.writeBoolean(false); } else { out.writeBoolean(true); searchRequest.writeTo(out); } writeTimeout(out); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_warmer_put_PutWarmerRequest.java
269
public interface OCommandOutputListener { public void onMessage(String iText); }
0true
core_src_main_java_com_orientechnologies_orient_core_command_OCommandOutputListener.java
28
public class FastDiskDataBufferHelper implements DataBufferHelper { public final PartitionDataBuffer newPartitionBuffer(int partitionNo) { return new PartitionFastDiskBuffer(partitionNo); } public final PartitionDataBuffer newPartitionBuffer(DataBufferEnv env) { assert env instanceof FastDiskBufferEnv; return new PartitionFastDiskBuffer((FastDiskBufferEnv)env); } @Override public MetaDataBuffer newMetaDataBuffer(DataBufferEnv env) { if (env == null) { return new MetaDiskBuffer(); } assert env instanceof FastDiskBufferEnv; return new MetaDiskBuffer((FastDiskBufferEnv)env); } @Override public DataBufferEnv newMetaDataBufferEnv(Properties prop) { return new FastDiskBufferEnv(prop); } }
0true
timeSequenceFeedAggregator_src_main_java_gov_nasa_arc_mct_buffer_disk_internal_FastDiskDataBufferHelper.java
100
{ @Override public void beforeCompletion() { throw firstException; } @Override public void afterCompletion( int status ) { } };
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestTransactionImpl.java
826
return getDatabase().getStorage().callInLock(new Callable<OClass>() { @Override public OClass call() throws Exception { if (classes.containsKey(key)) throw new OSchemaException("Class " + iClassName + " already exists in current database"); final OClassImpl cls = new OClassImpl(me, iClassName, clusterIds); classes.put(key, cls); if (cls.getShortName() != null) // BIND SHORT NAME TOO classes.put(cls.getShortName().toLowerCase(), cls); if (superClass != null) { cls.setSuperClassInternal(superClass); // UPDATE INDEXES final int[] clustersToIndex = superClass.getPolymorphicClusterIds(); final String[] clusterNames = new String[clustersToIndex.length]; for (int i = 0; i < clustersToIndex.length; i++) clusterNames[i] = database.getClusterNameById(clustersToIndex[i]); for (OIndex<?> index : superClass.getIndexes()) for (String clusterName : clusterNames) if (clusterName != null) database.getMetadata().getIndexManager().addClusterToIndex(clusterName, index.getName()); } return cls; } }, true);
0true
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OSchemaShared.java
893
declareRecordType(ODocument.RECORD_TYPE, "document", ODocument.class, new ORecordFactory() { public ORecord<?> newRecord() { return new ODocument(); } });
0true
core_src_main_java_com_orientechnologies_orient_core_record_ORecordFactoryManager.java
310
new OConfigurationChangeCallback() { public void change(final Object iCurrentValue, final Object iNewValue) { if ((Boolean) iNewValue) Orient.instance().getProfiler().startRecording(); else Orient.instance().getProfiler().stopRecording(); } }),
0true
core_src_main_java_com_orientechnologies_orient_core_config_OGlobalConfiguration.java
1,141
static class StatsResult { final String name; final long took; StatsResult(String name, long took) { this.name = name; this.took = took; } }
0true
src_test_java_org_elasticsearch_benchmark_search_aggregations_TermsAggregationSearchBenchmark.java
1,446
public class SnapshotMetaData implements MetaData.Custom { public static final String TYPE = "snapshots"; public static final Factory FACTORY = new Factory(); @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SnapshotMetaData that = (SnapshotMetaData) o; if (!entries.equals(that.entries)) return false; return true; } @Override public int hashCode() { return entries.hashCode(); } public static class Entry { private final State state; private final SnapshotId snapshotId; private final boolean includeGlobalState; private final ImmutableMap<ShardId, ShardSnapshotStatus> shards; private final ImmutableList<String> indices; public Entry(SnapshotId snapshotId, boolean includeGlobalState, State state, ImmutableList<String> indices, ImmutableMap<ShardId, ShardSnapshotStatus> shards) { this.state = state; this.snapshotId = snapshotId; this.includeGlobalState = includeGlobalState; this.indices = indices; if (shards == null) { this.shards = ImmutableMap.of(); } else { this.shards = shards; } } public SnapshotId snapshotId() { return this.snapshotId; } public ImmutableMap<ShardId, ShardSnapshotStatus> shards() { return this.shards; } public State state() { return state; } public ImmutableList<String> indices() { return indices; } public boolean includeGlobalState() { return includeGlobalState; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Entry entry = (Entry) o; if (includeGlobalState != entry.includeGlobalState) return false; if (!indices.equals(entry.indices)) return false; if (!shards.equals(entry.shards)) return false; if (!snapshotId.equals(entry.snapshotId)) return false; if (state != entry.state) return false; return true; } @Override public int hashCode() { int result = state.hashCode(); result = 31 * result + snapshotId.hashCode(); result = 31 * result + (includeGlobalState ? 1 : 0); result = 31 * result + shards.hashCode(); result = 31 * result + indices.hashCode(); return result; } } public static class ShardSnapshotStatus { private State state; private String nodeId; private String reason; private ShardSnapshotStatus() { } public ShardSnapshotStatus(String nodeId) { this(nodeId, State.INIT); } public ShardSnapshotStatus(String nodeId, State state) { this(nodeId, state, null); } public ShardSnapshotStatus(String nodeId, State state, String reason) { this.nodeId = nodeId; this.state = state; this.reason = reason; } public State state() { return state; } public String nodeId() { return nodeId; } public String reason() { return reason; } public static ShardSnapshotStatus readShardSnapshotStatus(StreamInput in) throws IOException { ShardSnapshotStatus shardSnapshotStatus = new ShardSnapshotStatus(); shardSnapshotStatus.readFrom(in); return shardSnapshotStatus; } public void readFrom(StreamInput in) throws IOException { nodeId = in.readOptionalString(); state = State.fromValue(in.readByte()); reason = in.readOptionalString(); } public void writeTo(StreamOutput out) throws IOException { out.writeOptionalString(nodeId); out.writeByte(state.value); out.writeOptionalString(reason); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ShardSnapshotStatus status = (ShardSnapshotStatus) o; if (nodeId != null ? !nodeId.equals(status.nodeId) : status.nodeId != null) return false; if (reason != null ? !reason.equals(status.reason) : status.reason != null) return false; if (state != status.state) return false; return true; } @Override public int hashCode() { int result = state != null ? state.hashCode() : 0; result = 31 * result + (nodeId != null ? nodeId.hashCode() : 0); result = 31 * result + (reason != null ? reason.hashCode() : 0); return result; } } public static enum State { INIT((byte) 0), STARTED((byte) 1), SUCCESS((byte) 2), FAILED((byte) 3), ABORTED((byte) 4), MISSING((byte) 5); private byte value; State(byte value) { this.value = value; } public byte value() { return value; } public boolean completed() { switch (this) { case INIT: return false; case STARTED: return false; case SUCCESS: return true; case FAILED: return true; case ABORTED: return false; case MISSING: return true; default: assert false; return true; } } public boolean failed() { switch (this) { case INIT: return false; case STARTED: return false; case SUCCESS: return false; case FAILED: return true; case ABORTED: return true; case MISSING: return true; default: assert false; return false; } } public static State fromValue(byte value) { switch (value) { case 0: return INIT; case 1: return STARTED; case 2: return SUCCESS; case 3: return FAILED; case 4: return ABORTED; case 5: return MISSING; default: throw new ElasticsearchIllegalArgumentException("No snapshot state for value [" + value + "]"); } } } private final ImmutableList<Entry> entries; public SnapshotMetaData(ImmutableList<Entry> entries) { this.entries = entries; } public SnapshotMetaData(Entry... entries) { this.entries = ImmutableList.copyOf(entries); } public ImmutableList<Entry> entries() { return this.entries; } public Entry snapshot(SnapshotId snapshotId) { for (Entry entry : entries) { if (snapshotId.equals(entry.snapshotId())) { return entry; } } return null; } public static class Factory implements MetaData.Custom.Factory<SnapshotMetaData> { @Override public String type() { return TYPE; //To change body of implemented methods use File | Settings | File Templates. } @Override public SnapshotMetaData readFrom(StreamInput in) throws IOException { Entry[] entries = new Entry[in.readVInt()]; for (int i = 0; i < entries.length; i++) { SnapshotId snapshotId = SnapshotId.readSnapshotId(in); boolean includeGlobalState = in.readBoolean(); State state = State.fromValue(in.readByte()); int indices = in.readVInt(); ImmutableList.Builder<String> indexBuilder = ImmutableList.builder(); for (int j = 0; j < indices; j++) { indexBuilder.add(in.readString()); } ImmutableMap.Builder<ShardId, ShardSnapshotStatus> builder = ImmutableMap.<ShardId, ShardSnapshotStatus>builder(); int shards = in.readVInt(); for (int j = 0; j < shards; j++) { ShardId shardId = ShardId.readShardId(in); String nodeId = in.readOptionalString(); State shardState = State.fromValue(in.readByte()); builder.put(shardId, new ShardSnapshotStatus(nodeId, shardState)); } entries[i] = new Entry(snapshotId, includeGlobalState, state, indexBuilder.build(), builder.build()); } return new SnapshotMetaData(entries); } @Override public void writeTo(SnapshotMetaData repositories, StreamOutput out) throws IOException { out.writeVInt(repositories.entries().size()); for (Entry entry : repositories.entries()) { entry.snapshotId().writeTo(out); out.writeBoolean(entry.includeGlobalState()); out.writeByte(entry.state().value()); out.writeVInt(entry.indices().size()); for (String index : entry.indices()) { out.writeString(index); } out.writeVInt(entry.shards().size()); for (Map.Entry<ShardId, ShardSnapshotStatus> shardEntry : entry.shards().entrySet()) { shardEntry.getKey().writeTo(out); out.writeOptionalString(shardEntry.getValue().nodeId()); out.writeByte(shardEntry.getValue().state().value()); } } } @Override public SnapshotMetaData fromXContent(XContentParser parser) throws IOException { throw new UnsupportedOperationException(); } @Override public void toXContent(SnapshotMetaData customIndexMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startArray("snapshots"); for (Entry entry : customIndexMetaData.entries()) { toXContent(entry, builder, params); } builder.endArray(); } public void toXContent(Entry entry, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(); builder.field("repository", entry.snapshotId().getRepository()); builder.field("snapshot", entry.snapshotId().getSnapshot()); builder.field("include_global_state", entry.includeGlobalState()); builder.field("state", entry.state()); builder.startArray("indices"); { for (String index : entry.indices()) { builder.value(index); } } builder.endArray(); builder.startArray("shards"); { for (Map.Entry<ShardId, ShardSnapshotStatus> shardEntry : entry.shards.entrySet()) { ShardId shardId = shardEntry.getKey(); ShardSnapshotStatus status = shardEntry.getValue(); builder.startObject(); { builder.field("index", shardId.getIndex()); builder.field("shard", shardId.getId()); builder.field("state", status.state()); builder.field("node", status.nodeId()); } builder.endObject(); } } builder.endArray(); builder.endObject(); } public boolean isPersistent() { return false; } } }
1no label
src_main_java_org_elasticsearch_cluster_metadata_SnapshotMetaData.java
1,894
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class MigrationTest extends HazelcastTestSupport { @Test public void testMapMigration() throws InterruptedException { TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(3); Config cfg = new Config(); HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(cfg); int size = 1000; Map map = instance1.getMap("testMapMigration"); for (int i = 0; i < size; i++) { map.put(i, i); } HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(cfg); Thread.sleep(1000); for (int i = 0; i < size; i++) { assertEquals(map.get(i), i); } HazelcastInstance instance3 = nodeFactory.newHazelcastInstance(cfg); Thread.sleep(1000); for (int i = 0; i < size; i++) { assertEquals(map.get(i), i); } } @Test public void testMigration_failure_when_statistics_disabled() { final int noOfRecords = 100; final int nodeCount = 3; final Config config = new Config().addMapConfig(new MapConfig("myMap").setStatisticsEnabled(false)); TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(nodeCount); final HazelcastInstance instance1 = nodeFactory.newHazelcastInstance(config); final HazelcastInstance instance2 = nodeFactory.newHazelcastInstance(config); final HazelcastInstance instance3 = nodeFactory.newHazelcastInstance(config); IMap<Integer, Integer> myMap = instance1.getMap("myMap"); for (int i = 0; i < noOfRecords; i++) { myMap.put(i, i); } instance2.shutdown(); instance3.shutdown(); assertEquals("Some records have been lost.", noOfRecords, myMap.values().size()); } }
0true
hazelcast_src_test_java_com_hazelcast_map_MigrationTest.java
763
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()]))); } });
0true
src_main_java_org_elasticsearch_action_get_TransportMultiGetAction.java
568
public class OpenIndexAction extends IndicesAction<OpenIndexRequest, OpenIndexResponse, OpenIndexRequestBuilder> { public static final OpenIndexAction INSTANCE = new OpenIndexAction(); public static final String NAME = "indices/open"; private OpenIndexAction() { super(NAME); } @Override public OpenIndexResponse newResponse() { return new OpenIndexResponse(); } @Override public OpenIndexRequestBuilder newRequestBuilder(IndicesAdminClient client) { return new OpenIndexRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_open_OpenIndexAction.java
1,348
private class NodeIndexDeletedTransportHandler extends BaseTransportRequestHandler<NodeIndexDeletedMessage> { static final String ACTION = "cluster/nodeIndexDeleted"; @Override public NodeIndexDeletedMessage newInstance() { return new NodeIndexDeletedMessage(); } @Override public void messageReceived(NodeIndexDeletedMessage message, TransportChannel channel) throws Exception { innerNodeIndexDeleted(message.index, message.nodeId); channel.sendResponse(TransportResponse.Empty.INSTANCE); } @Override public String executor() { return ThreadPool.Names.SAME; } }
0true
src_main_java_org_elasticsearch_cluster_action_index_NodeIndexDeletedAction.java
2,521
public class SmileXContentParser extends JsonXContentParser { public SmileXContentParser(JsonParser parser) { super(parser); } @Override public XContentType contentType() { return XContentType.SMILE; } }
0true
src_main_java_org_elasticsearch_common_xcontent_smile_SmileXContentParser.java
356
public class NodesStatsAction extends ClusterAction<NodesStatsRequest, NodesStatsResponse, NodesStatsRequestBuilder> { public static final NodesStatsAction INSTANCE = new NodesStatsAction(); public static final String NAME = "cluster/nodes/stats"; private NodesStatsAction() { super(NAME); } @Override public NodesStatsResponse newResponse() { return new NodesStatsResponse(); } @Override public NodesStatsRequestBuilder newRequestBuilder(ClusterAdminClient client) { return new NodesStatsRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_stats_NodesStatsAction.java
1,630
public class UpdateMapConfigOperation extends Operation { private String mapName; private MapConfig mapConfig; public UpdateMapConfigOperation() { } public UpdateMapConfigOperation(String mapName, MapConfig mapConfig) { this.mapName = mapName; this.mapConfig = mapConfig; } @Override public void beforeRun() throws Exception { } @Override public void run() throws Exception { MapService service = getService(); MapConfig oldConfig = service.getMapContainer(mapName).getMapConfig(); MapConfig newConfig = new MapConfig(oldConfig); newConfig.setTimeToLiveSeconds(mapConfig.getTimeToLiveSeconds()); newConfig.setMaxIdleSeconds(mapConfig.getMaxIdleSeconds()); newConfig.setEvictionPolicy(mapConfig.getEvictionPolicy()); newConfig.setEvictionPercentage(mapConfig.getEvictionPercentage()); newConfig.setReadBackupData(mapConfig.isReadBackupData()); newConfig.setBackupCount(mapConfig.getTotalBackupCount()); newConfig.setAsyncBackupCount(mapConfig.getAsyncBackupCount()); newConfig.setMaxSizeConfig(mapConfig.getMaxSizeConfig()); service.getMapContainer(mapName).setMapConfig(newConfig.getAsReadOnly()); } @Override public void afterRun() throws Exception { } @Override public boolean returnsResponse() { return true; } @Override public Object getResponse() { return null; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { out.writeUTF(mapName); new MapConfigAdapter(mapConfig).writeData(out); } @Override protected void readInternal(ObjectDataInput in) throws IOException { mapName = in.readUTF(); MapConfigAdapter adapter = new MapConfigAdapter(); adapter.readData(in); mapConfig = adapter.getMapConfig(); } }
0true
hazelcast_src_main_java_com_hazelcast_management_operation_UpdateMapConfigOperation.java
383
public class TransportClusterRerouteAction extends TransportMasterNodeOperationAction<ClusterRerouteRequest, ClusterRerouteResponse> { private final AllocationService allocationService; @Inject public TransportClusterRerouteAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool, AllocationService allocationService) { super(settings, transportService, clusterService, threadPool); this.allocationService = allocationService; } @Override protected String executor() { // we go async right away return ThreadPool.Names.SAME; } @Override protected String transportAction() { return ClusterRerouteAction.NAME; } @Override protected ClusterRerouteRequest newRequest() { return new ClusterRerouteRequest(); } @Override protected ClusterRerouteResponse newResponse() { return new ClusterRerouteResponse(); } @Override protected void masterOperation(final ClusterRerouteRequest request, final ClusterState state, final ActionListener<ClusterRerouteResponse> listener) throws ElasticsearchException { clusterService.submitStateUpdateTask("cluster_reroute (api)", Priority.URGENT, new AckedClusterStateUpdateTask() { private volatile ClusterState clusterStateToSend; @Override public boolean mustAck(DiscoveryNode discoveryNode) { return true; } @Override public void onAllNodesAcked(@Nullable Throwable t) { listener.onResponse(new ClusterRerouteResponse(true, clusterStateToSend)); } @Override public void onAckTimeout() { listener.onResponse(new ClusterRerouteResponse(false, clusterStateToSend)); } @Override public TimeValue ackTimeout() { return request.timeout(); } @Override public TimeValue timeout() { return request.masterNodeTimeout(); } @Override public void onFailure(String source, Throwable t) { logger.debug("failed to perform [{}]", t, source); listener.onFailure(t); } @Override public ClusterState execute(ClusterState currentState) { RoutingAllocation.Result routingResult = allocationService.reroute(currentState, request.commands, true); ClusterState newState = ClusterState.builder(currentState).routingResult(routingResult).build(); clusterStateToSend = newState; if (request.dryRun) { return currentState; } return newState; } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { } }); } }
1no label
src_main_java_org_elasticsearch_action_admin_cluster_reroute_TransportClusterRerouteAction.java
656
new OProfiler.OProfilerHookValue() { public Object getValue() { return map != null ? map.getEntryPointSize() : "-"; } }, profilerMetadataPrefix + "items");
0true
core_src_main_java_com_orientechnologies_orient_core_index_engine_OMVRBTreeIndexEngine.java
6,452
clusterService.submitStateUpdateTask("cluster event from " + tribeName + ", " + event.source(), new ClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) throws Exception { ClusterState tribeState = event.state(); DiscoveryNodes.Builder nodes = DiscoveryNodes.builder(currentState.nodes()); // -- merge nodes // go over existing nodes, and see if they need to be removed for (DiscoveryNode discoNode : currentState.nodes()) { String markedTribeName = discoNode.attributes().get(TRIBE_NAME); if (markedTribeName != null && markedTribeName.equals(tribeName)) { if (tribeState.nodes().get(discoNode.id()) == null) { logger.info("[{}] removing node [{}]", tribeName, discoNode); nodes.remove(discoNode.id()); } } } // go over tribe nodes, and see if they need to be added for (DiscoveryNode tribe : tribeState.nodes()) { if (currentState.nodes().get(tribe.id()) == null) { // a new node, add it, but also add the tribe name to the attributes ImmutableMap<String, String> tribeAttr = MapBuilder.newMapBuilder(tribe.attributes()).put(TRIBE_NAME, tribeName).immutableMap(); DiscoveryNode discoNode = new DiscoveryNode(tribe.name(), tribe.id(), tribe.getHostName(), tribe.getHostAddress(), tribe.address(), tribeAttr, tribe.version()); logger.info("[{}] adding node [{}]", tribeName, discoNode); nodes.put(discoNode); } } // -- merge metadata MetaData.Builder metaData = MetaData.builder(currentState.metaData()); RoutingTable.Builder routingTable = RoutingTable.builder(currentState.routingTable()); // go over existing indices, and see if they need to be removed for (IndexMetaData index : currentState.metaData()) { String markedTribeName = index.settings().get(TRIBE_NAME); if (markedTribeName != null && markedTribeName.equals(tribeName)) { IndexMetaData tribeIndex = tribeState.metaData().index(index.index()); if (tribeIndex == null) { logger.info("[{}] removing index [{}]", tribeName, index.index()); metaData.remove(index.index()); routingTable.remove(index.index()); } else { // always make sure to update the metadata and routing table, in case // there are changes in them (new mapping, shards moving from initializing to started) routingTable.add(tribeState.routingTable().index(index.index())); Settings tribeSettings = ImmutableSettings.builder().put(tribeIndex.settings()).put(TRIBE_NAME, tribeName).build(); metaData.put(IndexMetaData.builder(tribeIndex).settings(tribeSettings)); } } } // go over tribe one, and see if they need to be added for (IndexMetaData tribeIndex : tribeState.metaData()) { if (!currentState.metaData().hasIndex(tribeIndex.index())) { // a new index, add it, and add the tribe name as a setting logger.info("[{}] adding index [{}]", tribeName, tribeIndex.index()); Settings tribeSettings = ImmutableSettings.builder().put(tribeIndex.settings()).put(TRIBE_NAME, tribeName).build(); metaData.put(IndexMetaData.builder(tribeIndex).settings(tribeSettings)); routingTable.add(tribeState.routingTable().index(tribeIndex.index())); } } return ClusterState.builder(currentState).nodes(nodes).metaData(metaData).routingTable(routingTable).build(); } @Override public void onFailure(String source, Throwable t) { logger.warn("failed to process [{}]", t, source); } });
1no label
src_main_java_org_elasticsearch_tribe_TribeService.java
202
{ private final Map<Long, File> activeLogFiles = getActiveLogs( storeDir ); private final long highestLogVersion = max( getHighestHistoryLogVersion( fileSystem, storeDir, LOGICAL_LOG_DEFAULT_NAME ), maxKey( activeLogFiles ) ); @Override public ReadableByteChannel getLogicalLogOrMyselfCommitted( long version, long position ) throws IOException { File name = getFileName( version ); if ( !fileSystem.fileExists( name ) ) { name = activeLogFiles.get( version ); if ( name == null ) throw new NoSuchLogVersionException( version ); } StoreChannel channel = fileSystem.open( name, "r" ); channel.position( position ); return new BufferedFileChannel( channel, monitor ); } private long maxKey( Map<Long, File> activeLogFiles ) { long max = 0; for ( Long key : activeLogFiles.keySet() ) max = max( max, key ); return max; } private Map<Long, File> getActiveLogs( File storeDir ) throws IOException { Map<Long, File> result = new HashMap<Long, File>(); for ( String postfix : ACTIVE_POSTFIXES ) { File candidateFile = new File( storeDir, LOGICAL_LOG_DEFAULT_NAME + postfix ); if ( !fileSystem.fileExists( candidateFile ) ) continue; long[] header = LogIoUtils.readLogHeader( fileSystem, candidateFile ); result.put( header[0], candidateFile ); } return result; } @Override public File getFileName( long version ) { return new File( storeDir, LOGICAL_LOG_DEFAULT_NAME + ".v" + version ); } @Override public long getHighestLogVersion() { return highestLogVersion; } @Override public Long getFirstCommittedTxId( long version ) { throw new UnsupportedOperationException(); } @Override public Long getFirstStartRecordTimestamp( long version ) { throw new UnsupportedOperationException(); } @Override public long getLastCommittedTxId() { throw new UnsupportedOperationException(); } @Override public String toString() { return getClass().getSimpleName() + "[" + storeDir + "]"; } };
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogExtractor.java
498
public class CloseIndexResponse extends AcknowledgedResponse { CloseIndexResponse() { } CloseIndexResponse(boolean acknowledged) { super(acknowledged); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); readAcknowledged(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); writeAcknowledged(out); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_close_CloseIndexResponse.java
46
@Component("blRequestDTOCustomPersistenceHandler") public class RequestDTOCustomPersistenceHandler extends TimeDTOCustomPersistenceHandler { private static final Log LOG = LogFactory.getLog(RequestDTOCustomPersistenceHandler.class); @Override public Boolean canHandleInspect(PersistencePackage persistencePackage) { String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname(); return RequestDTOImpl.class.getName().equals(ceilingEntityFullyQualifiedClassname); } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_admin_server_handler_RequestDTOCustomPersistenceHandler.java
1,487
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class HibernateSerializationHookAvailableTest { private static final Field ORIGINAL; private static final Field TYPE_MAP; static { try { ORIGINAL = HazelcastInstanceProxy.class.getDeclaredField("original"); ORIGINAL.setAccessible(true); TYPE_MAP = SerializationServiceImpl.class.getDeclaredField("typeMap"); TYPE_MAP.setAccessible(true); } catch (Exception e) { throw new RuntimeException(e); } } @After public void teardown() { Hazelcast.shutdownAll(); } @Test public void testAutoregistrationOnHibernate3Available() throws Exception { HazelcastInstance hz = Hazelcast.newHazelcastInstance(); HazelcastInstanceImpl impl = (HazelcastInstanceImpl) ORIGINAL.get(hz); SerializationService ss = impl.getSerializationService(); ConcurrentMap<Class, ?> typeMap = (ConcurrentMap<Class, ?>) TYPE_MAP.get(ss); boolean cacheKeySerializerFound = false; boolean cacheEntrySerializerFound = false; for (Class clazz : typeMap.keySet()) { if (clazz == CacheKey.class) { cacheKeySerializerFound = true; } else if (clazz == CacheEntry.class) { cacheEntrySerializerFound = true; } } assertTrue("CacheKey serializer not found", cacheKeySerializerFound); assertTrue("CacheEntry serializer not found", cacheEntrySerializerFound); } }
0true
hazelcast-hibernate_hazelcast-hibernate3_src_test_java_com_hazelcast_hibernate_serialization_HibernateSerializationHookAvailableTest.java
1,777
public class MultiLineStringBuilder extends ShapeBuilder { public static final GeoShapeType TYPE = GeoShapeType.MULTILINESTRING; private final ArrayList<BaseLineStringBuilder<?>> lines = new ArrayList<BaseLineStringBuilder<?>>(); public InternalLineStringBuilder linestring() { InternalLineStringBuilder line = new InternalLineStringBuilder(this); this.lines.add(line); return line; } public MultiLineStringBuilder linestring(BaseLineStringBuilder<?> line) { this.lines.add(line); return this; } public Coordinate[][] coordinates() { Coordinate[][] result = new Coordinate[lines.size()][]; for (int i = 0; i < result.length; i++) { result[i] = lines.get(i).coordinates(false); } return result; } @Override public GeoShapeType type() { return TYPE; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(FIELD_TYPE, TYPE.shapename); builder.field(FIELD_COORDINATES); builder.startArray(); for(BaseLineStringBuilder<?> line : lines) { line.coordinatesToXcontent(builder, false); } builder.endArray(); builder.endObject(); return builder; } @Override public Shape build() { final Geometry geometry; if(wrapdateline) { ArrayList<LineString> parts = new ArrayList<LineString>(); for (BaseLineStringBuilder<?> line : lines) { BaseLineStringBuilder.decompose(FACTORY, line.coordinates(false), parts); } if(parts.size() == 1) { geometry = parts.get(0); } else { LineString[] lineStrings = parts.toArray(new LineString[parts.size()]); geometry = FACTORY.createMultiLineString(lineStrings); } } else { LineString[] lineStrings = new LineString[lines.size()]; Iterator<BaseLineStringBuilder<?>> iterator = lines.iterator(); for (int i = 0; iterator.hasNext(); i++) { lineStrings[i] = FACTORY.createLineString(iterator.next().coordinates(false)); } geometry = FACTORY.createMultiLineString(lineStrings); } return new JtsGeometry(geometry, SPATIAL_CONTEXT, true); } public static class InternalLineStringBuilder extends BaseLineStringBuilder<InternalLineStringBuilder> { private final MultiLineStringBuilder collection; public InternalLineStringBuilder(MultiLineStringBuilder collection) { super(); this.collection = collection; } public MultiLineStringBuilder end() { return collection; } public Coordinate[] coordinates() { return super.coordinates(false); } @Override public GeoShapeType type() { return null; } } }
0true
src_main_java_org_elasticsearch_common_geo_builders_MultiLineStringBuilder.java
128
return new CorrectionProposal(description, change, null, IMPORT) { @Override public StyledString getStyledDisplayString() { return Highlights.styleProposal(getDisplayString(), true); } };
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ImportProposals.java
1,069
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_FULFILLMENT_WEIGHT_BAND") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blStandardElements") public class FulfillmentWeightBandImpl extends FulfillmentBandImpl implements FulfillmentWeightBand { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator= "FulfillmentWeightBandId") @GenericGenerator( name="FulfillmentWeightBandId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="FulfillmentWeightBandImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.order.fulfillment.domain.FulfillmentWeightBandImpl") } ) @Column(name = "FULFILLMENT_WEIGHT_BAND_ID") protected Long id; @Column(name = "MINIMUM_WEIGHT", precision = 19, scale = 5) @AdminPresentation(friendlyName = "FulfillmentWeightBandImpl_Weight") protected BigDecimal minimumWeight; @Column(name = "WEIGHT_UNIT_OF_MEASURE") @AdminPresentation(friendlyName = "FulfillmentWeightBandImpl_Weight_Units", fieldType= SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration="org.broadleafcommerce.common.util.WeightUnitOfMeasureType") protected String weightUnitOfMeasure; @ManyToOne(targetEntity=BandedWeightFulfillmentOptionImpl.class) @JoinColumn(name="FULFILLMENT_OPTION_ID") protected BandedWeightFulfillmentOption option; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public BigDecimal getMinimumWeight() { return minimumWeight; } @Override public void setMinimumWeight(BigDecimal minimumWeight) { this.minimumWeight = minimumWeight; } @Override public BandedWeightFulfillmentOption getOption() { return option; } @Override public void setOption(BandedWeightFulfillmentOption option) { this.option = option; } @Override public WeightUnitOfMeasureType getWeightUnitOfMeasure() { return WeightUnitOfMeasureType.getInstance(weightUnitOfMeasure); } @Override public void setWeightUnitOfMeasure(WeightUnitOfMeasureType weightUnitOfMeasure) { if (weightUnitOfMeasure != null) { this.weightUnitOfMeasure = weightUnitOfMeasure.getType(); } } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_fulfillment_domain_FulfillmentWeightBandImpl.java
1,956
public class MapReplaceIfSameRequest extends MapPutRequest { private Data testValue; public MapReplaceIfSameRequest() { } public MapReplaceIfSameRequest(String name, Data key, Data testValue, Data value, long threadId) { super(name, key, value, threadId); this.testValue = testValue; } public int getClassId() { return MapPortableHook.REPLACE_IF_SAME; } protected Operation prepareOperation() { ReplaceIfSameOperation op = new ReplaceIfSameOperation(name, key, testValue, value); op.setThreadId(threadId); return op; } @Override public void write(PortableWriter writer) throws IOException { super.write(writer); final ObjectDataOutput out = writer.getRawDataOutput(); testValue.writeData(out); } @Override public void read(PortableReader reader) throws IOException { super.read(reader); final ObjectDataInput in = reader.getRawDataInput(); testValue = new Data(); testValue.readData(in); } }
0true
hazelcast_src_main_java_com_hazelcast_map_client_MapReplaceIfSameRequest.java
895
public interface PromotableOrderAdjustment extends Serializable { /** * Returns the associated promotableOrder * @return */ public PromotableOrder getPromotableOrder(); /** * Returns the associated promotableCandidateOrderOffer * @return */ public Offer getOffer(); /** * Returns the value of this adjustment * @return */ public Money getAdjustmentValue(); /** * Returns true if this adjustment represents a combinable offer. */ boolean isCombinable(); /** * Returns true if this adjustment represents a totalitarian offer. */ boolean isTotalitarian(); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_domain_PromotableOrderAdjustment.java
2,221
MULT { @Override public float combine(double queryBoost, double queryScore, double funcScore, double maxBoost) { return toFloat(queryBoost * queryScore * Math.min(funcScore, maxBoost)); } @Override public String getName() { return "multiply"; } @Override public ComplexExplanation explain(float queryBoost, Explanation queryExpl, Explanation funcExpl, float maxBoost) { float score = queryBoost * Math.min(funcExpl.getValue(), maxBoost) * queryExpl.getValue(); ComplexExplanation res = new ComplexExplanation(true, score, "function score, product of:"); res.addDetail(queryExpl); ComplexExplanation minExpl = new ComplexExplanation(true, Math.min(funcExpl.getValue(), maxBoost), "Math.min of"); minExpl.addDetail(funcExpl); minExpl.addDetail(new Explanation(maxBoost, "maxBoost")); res.addDetail(minExpl); res.addDetail(new Explanation(queryBoost, "queryBoost")); return res; } },
0true
src_main_java_org_elasticsearch_common_lucene_search_function_CombineFunction.java
1,309
public class EmptyClusterInfoService extends AbstractComponent implements ClusterInfoService { private final static class Holder { private final static EmptyClusterInfoService instance = new EmptyClusterInfoService(); } private final ClusterInfo emptyClusterInfo; private EmptyClusterInfoService() { super(ImmutableSettings.EMPTY); emptyClusterInfo = new ClusterInfo(ImmutableMap.<String, DiskUsage>of(), ImmutableMap.<String, Long>of()); } public static EmptyClusterInfoService getInstance() { return Holder.instance; } @Override public ClusterInfo getClusterInfo() { return emptyClusterInfo; } }
0true
src_main_java_org_elasticsearch_cluster_EmptyClusterInfoService.java
1,665
@Service("blPersistencePackageFactory") public class PersistencePackageFactoryImpl implements PersistencePackageFactory { @Override public PersistencePackage create(PersistencePackageRequest request) { PersistencePerspective persistencePerspective = new PersistencePerspective(); persistencePerspective.setAdditionalForeignKeys(request.getAdditionalForeignKeys()); persistencePerspective.setAdditionalNonPersistentProperties(new String[] {}); if (request.getForeignKey() != null) { persistencePerspective.addPersistencePerspectiveItem(PersistencePerspectiveItemType.FOREIGNKEY, request.getForeignKey()); } switch (request.getType()) { case STANDARD: persistencePerspective.setOperationTypes(getDefaultOperationTypes()); break; case ADORNED: if (request.getAdornedList() == null) { throw new IllegalArgumentException("ADORNED type requires the adornedList to be set"); } persistencePerspective.setOperationTypes(getOperationTypes(OperationType.ADORNEDTARGETLIST)); persistencePerspective.addPersistencePerspectiveItem(PersistencePerspectiveItemType.ADORNEDTARGETLIST, request.getAdornedList()); break; case MAP: if (request.getMapStructure() == null) { throw new IllegalArgumentException("MAP type requires the mapStructure to be set"); } persistencePerspective.setOperationTypes(getOperationTypes(OperationType.MAP)); persistencePerspective.addPersistencePerspectiveItem(PersistencePerspectiveItemType.MAPSTRUCTURE, request.getMapStructure()); break; } if (request.getOperationTypesOverride() != null) { persistencePerspective.setOperationTypes(request.getOperationTypesOverride()); } PersistencePackage pp = new PersistencePackage(); pp.setCeilingEntityFullyQualifiedClassname(request.getCeilingEntityClassname()); pp.setFetchTypeFullyQualifiedClassname(null); pp.setPersistencePerspective(persistencePerspective); pp.setCustomCriteria(request.getCustomCriteria()); pp.setCsrfToken(null); pp.setValidateUnsubmittedProperties(request.isValidateUnsubmittedProperties()); if (request.getEntity() != null) { pp.setEntity(request.getEntity()); } for (Map.Entry<String, PersistencePackageRequest> subRequest : request.getSubRequests().entrySet()) { pp.getSubPackages().put(subRequest.getKey(), create(subRequest.getValue())); } return pp; } protected OperationTypes getDefaultOperationTypes() { OperationTypes operationTypes = new OperationTypes(); operationTypes.setFetchType(OperationType.BASIC); operationTypes.setRemoveType(OperationType.BASIC); operationTypes.setAddType(OperationType.BASIC); operationTypes.setUpdateType(OperationType.BASIC); operationTypes.setInspectType(OperationType.BASIC); return operationTypes; } protected OperationTypes getOperationTypes(OperationType nonInspectOperationType) { OperationTypes operationTypes = new OperationTypes(); operationTypes.setFetchType(nonInspectOperationType); operationTypes.setRemoveType(nonInspectOperationType); operationTypes.setAddType(nonInspectOperationType); operationTypes.setUpdateType(nonInspectOperationType); operationTypes.setInspectType(OperationType.BASIC); return operationTypes; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_factory_PersistencePackageFactoryImpl.java
818
public abstract class AtomicLongBackupAwareOperation extends AtomicLongBaseOperation implements BackupAwareOperation { protected boolean shouldBackup = true; public AtomicLongBackupAwareOperation() { } public AtomicLongBackupAwareOperation(String name) { super(name); } @Override public boolean shouldBackup() { return shouldBackup; } @Override public int getSyncBackupCount() { return 1; } @Override public int getAsyncBackupCount() { return 0; } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_operations_AtomicLongBackupAwareOperation.java
1,382
public class IndexTemplateMetaData { private final String name; private final int order; private final String template; private final Settings settings; // the mapping source should always include the type as top level private final ImmutableOpenMap<String, CompressedString> mappings; private final ImmutableOpenMap<String, IndexMetaData.Custom> customs; public IndexTemplateMetaData(String name, int order, String template, Settings settings, ImmutableOpenMap<String, CompressedString> mappings, ImmutableOpenMap<String, IndexMetaData.Custom> customs) { this.name = name; this.order = order; this.template = template; this.settings = settings; this.mappings = mappings; this.customs = customs; } public String name() { return this.name; } public int order() { return this.order; } public int getOrder() { return order(); } public String getName() { return this.name; } public String template() { return this.template; } public String getTemplate() { return this.template; } public Settings settings() { return this.settings; } public Settings getSettings() { return settings(); } public ImmutableOpenMap<String, CompressedString> mappings() { return this.mappings; } public ImmutableOpenMap<String, CompressedString> getMappings() { return this.mappings; } public ImmutableOpenMap<String, IndexMetaData.Custom> customs() { return this.customs; } public ImmutableOpenMap<String, IndexMetaData.Custom> getCustoms() { return this.customs; } public <T extends IndexMetaData.Custom> T custom(String type) { return (T) customs.get(type); } public static Builder builder(String name) { return new Builder(name); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IndexTemplateMetaData that = (IndexTemplateMetaData) o; if (order != that.order) return false; if (!mappings.equals(that.mappings)) return false; if (!name.equals(that.name)) return false; if (!settings.equals(that.settings)) return false; if (!template.equals(that.template)) return false; return true; } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + order; result = 31 * result + template.hashCode(); result = 31 * result + settings.hashCode(); result = 31 * result + mappings.hashCode(); return result; } public static class Builder { private static final Set<String> VALID_FIELDS = Sets.newHashSet("template", "order", "mappings", "settings"); static { VALID_FIELDS.addAll(IndexMetaData.customFactories.keySet()); } private String name; private int order; private String template; private Settings settings = ImmutableSettings.Builder.EMPTY_SETTINGS; private final ImmutableOpenMap.Builder<String, CompressedString> mappings; private final ImmutableOpenMap.Builder<String, IndexMetaData.Custom> customs; public Builder(String name) { this.name = name; mappings = ImmutableOpenMap.builder(); customs = ImmutableOpenMap.builder(); } public Builder(IndexTemplateMetaData indexTemplateMetaData) { this.name = indexTemplateMetaData.name(); order(indexTemplateMetaData.order()); template(indexTemplateMetaData.template()); settings(indexTemplateMetaData.settings()); mappings = ImmutableOpenMap.builder(indexTemplateMetaData.mappings()); customs = ImmutableOpenMap.builder(indexTemplateMetaData.customs()); } public Builder order(int order) { this.order = order; return this; } public Builder template(String template) { this.template = template; return this; } public String template() { return template; } public Builder settings(Settings.Builder settings) { this.settings = settings.build(); return this; } public Builder settings(Settings settings) { this.settings = settings; return this; } public Builder removeMapping(String mappingType) { mappings.remove(mappingType); return this; } public Builder putMapping(String mappingType, CompressedString mappingSource) throws IOException { mappings.put(mappingType, mappingSource); return this; } public Builder putMapping(String mappingType, String mappingSource) throws IOException { mappings.put(mappingType, new CompressedString(mappingSource)); return this; } public Builder putCustom(String type, IndexMetaData.Custom customIndexMetaData) { this.customs.put(type, customIndexMetaData); return this; } public Builder removeCustom(String type) { this.customs.remove(type); return this; } public IndexMetaData.Custom getCustom(String type) { return this.customs.get(type); } public IndexTemplateMetaData build() { return new IndexTemplateMetaData(name, order, template, settings, mappings.build(), customs.build()); } public static void toXContent(IndexTemplateMetaData indexTemplateMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(indexTemplateMetaData.name(), XContentBuilder.FieldCaseConversion.NONE); builder.field("order", indexTemplateMetaData.order()); builder.field("template", indexTemplateMetaData.template()); builder.startObject("settings"); for (Map.Entry<String, String> entry : indexTemplateMetaData.settings().getAsMap().entrySet()) { builder.field(entry.getKey(), entry.getValue()); } builder.endObject(); if (params.paramAsBoolean("reduce_mappings", false)) { builder.startObject("mappings"); for (ObjectObjectCursor<String, CompressedString> cursor : indexTemplateMetaData.mappings()) { byte[] mappingSource = cursor.value.uncompressed(); XContentParser parser = XContentFactory.xContent(mappingSource).createParser(mappingSource); Map<String, Object> mapping = parser.map(); if (mapping.size() == 1 && mapping.containsKey(cursor.key)) { // the type name is the root value, reduce it mapping = (Map<String, Object>) mapping.get(cursor.key); } builder.field(cursor.key); builder.map(mapping); } builder.endObject(); } else { builder.startArray("mappings"); for (ObjectObjectCursor<String, CompressedString> cursor : indexTemplateMetaData.mappings()) { byte[] data = cursor.value.uncompressed(); XContentParser parser = XContentFactory.xContent(data).createParser(data); Map<String, Object> mapping = parser.mapOrderedAndClose(); builder.map(mapping); } builder.endArray(); } for (ObjectObjectCursor<String, IndexMetaData.Custom> cursor : indexTemplateMetaData.customs()) { builder.startObject(cursor.key, XContentBuilder.FieldCaseConversion.NONE); IndexMetaData.lookupFactorySafe(cursor.key).toXContent(cursor.value, builder, params); builder.endObject(); } builder.endObject(); } public static IndexTemplateMetaData fromXContentStandalone(XContentParser parser) throws IOException { XContentParser.Token token = parser.nextToken(); if (token == null) { throw new IOException("no data"); } if (token != XContentParser.Token.START_OBJECT) { throw new IOException("should start object"); } token = parser.nextToken(); if (token != XContentParser.Token.FIELD_NAME) { throw new IOException("the first field should be the template name"); } return fromXContent(parser); } public static IndexTemplateMetaData fromXContent(XContentParser parser) throws IOException { Builder builder = new Builder(parser.currentName()); String currentFieldName = skipTemplateName(parser); XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { if ("settings".equals(currentFieldName)) { ImmutableSettings.Builder templateSettingsBuilder = ImmutableSettings.settingsBuilder(); for (Map.Entry<String, String> entry : SettingsLoader.Helper.loadNestedFromMap(parser.mapOrdered()).entrySet()) { if (!entry.getKey().startsWith("index.")) { templateSettingsBuilder.put("index." + entry.getKey(), entry.getValue()); } else { templateSettingsBuilder.put(entry.getKey(), entry.getValue()); } } builder.settings(templateSettingsBuilder.build()); } else if ("mappings".equals(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.START_OBJECT) { String mappingType = currentFieldName; Map<String, Object> mappingSource = MapBuilder.<String, Object>newMapBuilder().put(mappingType, parser.mapOrdered()).map(); builder.putMapping(mappingType, XContentFactory.jsonBuilder().map(mappingSource).string()); } } } else { // check if its a custom index metadata IndexMetaData.Custom.Factory<IndexMetaData.Custom> factory = IndexMetaData.lookupFactory(currentFieldName); if (factory == null) { //TODO warn parser.skipChildren(); } else { builder.putCustom(factory.type(), factory.fromXContent(parser)); } } } else if (token == XContentParser.Token.START_ARRAY) { if ("mappings".equals(currentFieldName)) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { Map<String, Object> mapping = parser.mapOrdered(); if (mapping.size() == 1) { String mappingType = mapping.keySet().iterator().next(); String mappingSource = XContentFactory.jsonBuilder().map(mapping).string(); if (mappingSource == null) { // crap, no mapping source, warn? } else { builder.putMapping(mappingType, mappingSource); } } } } } else if (token.isValue()) { if ("template".equals(currentFieldName)) { builder.template(parser.text()); } else if ("order".equals(currentFieldName)) { builder.order(parser.intValue()); } } } return builder.build(); } private static String skipTemplateName(XContentParser parser) throws IOException { XContentParser.Token token = parser.nextToken(); if (token != null && token == XContentParser.Token.START_OBJECT) { token = parser.nextToken(); if (token == XContentParser.Token.FIELD_NAME) { String currentFieldName = parser.currentName(); if (VALID_FIELDS.contains(currentFieldName)) { return currentFieldName; } else { // we just hit the template name, which should be ignored and we move on parser.nextToken(); } } } return null; } public static IndexTemplateMetaData readFrom(StreamInput in) throws IOException { Builder builder = new Builder(in.readString()); builder.order(in.readInt()); builder.template(in.readString()); builder.settings(ImmutableSettings.readSettingsFromStream(in)); int mappingsSize = in.readVInt(); for (int i = 0; i < mappingsSize; i++) { builder.putMapping(in.readString(), CompressedString.readCompressedString(in)); } int customSize = in.readVInt(); for (int i = 0; i < customSize; i++) { String type = in.readString(); IndexMetaData.Custom customIndexMetaData = IndexMetaData.lookupFactorySafe(type).readFrom(in); builder.putCustom(type, customIndexMetaData); } return builder.build(); } public static void writeTo(IndexTemplateMetaData indexTemplateMetaData, StreamOutput out) throws IOException { out.writeString(indexTemplateMetaData.name()); out.writeInt(indexTemplateMetaData.order()); out.writeString(indexTemplateMetaData.template()); ImmutableSettings.writeSettingsToStream(indexTemplateMetaData.settings(), out); out.writeVInt(indexTemplateMetaData.mappings().size()); for (ObjectObjectCursor<String, CompressedString> cursor : indexTemplateMetaData.mappings()) { out.writeString(cursor.key); cursor.value.writeTo(out); } out.writeVInt(indexTemplateMetaData.customs().size()); for (ObjectObjectCursor<String, IndexMetaData.Custom> cursor : indexTemplateMetaData.customs()) { out.writeString(cursor.key); IndexMetaData.lookupFactorySafe(cursor.key).writeTo(cursor.value, out); } } } }
1no label
src_main_java_org_elasticsearch_cluster_metadata_IndexTemplateMetaData.java
21
public class FastDiskBufferEnv implements DataBufferEnv, Cloneable { private static final Logger LOGGER = LoggerFactory.getLogger(FastDiskBufferEnv.class); private static final String META_DATABASE_PATH = "metaBuffer"; private static final String META_DATABASE_NAME = "meta"; private static enum STATE { unInitialized, initializing, initialized; } private Environment dbufferEnv; private STATE state = STATE.unInitialized; private final Properties prop; private volatile long bufferTimeMills; private long evictorRecurrMills; private File envHome; private final int concurrency; private final int bufferWriteThreadPoolSize; private final int numOfBufferPartitions; private final int currentBufferPartition; private final long partitionOverlapMillis; private final long metaRefreshMillis; private TransactionConfig txnConfig; private CursorConfig cursorConfig; private List<EntityStore> openStores = new LinkedList<EntityStore>(); private DiskQuotaHelper diskQuotaHelper; private static Properties loadDefaultPropertyFile() { Properties prop = new Properties(); InputStream is = null; try { is = ClassLoader.getSystemResourceAsStream("properties/feed.properties"); prop.load(is); } catch (Exception e) { LOGGER.error("Cannot initialized DataBufferEnv properties", e); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // ignore exception } } } return prop; } public FastDiskBufferEnv(Properties prop) { if (prop == null) { prop = loadDefaultPropertyFile(); } this.prop = prop; this.currentBufferPartition = 0; File bufferHome = new File(FilepathReplacer.substitute(getPropertyWithPrecedence(prop, "buffer.disk.loc"))); if (!bufferHome.exists()) { bufferHome.mkdirs(); } envHome = new File(bufferHome, META_DATABASE_PATH); if (!envHome.exists()) { envHome.mkdirs(); } concurrency = Integer.parseInt(prop.getProperty("buffer.concurrency")); evictorRecurrMills = Long.parseLong(prop.getProperty("buffer.evictor.recurrMills")); bufferWriteThreadPoolSize = Integer.parseInt(prop.getProperty("buffer.write.threadPool.size")); numOfBufferPartitions = Integer.parseInt(prop.getProperty("buffer.partitions")); bufferTimeMills = Long.parseLong(prop.getProperty("buffer.time.millis")); metaRefreshMillis = Long.parseLong(prop.getProperty("meta.buffer.refresh.millis")); if (bufferTimeMills > numOfBufferPartitions) { bufferTimeMills = bufferTimeMills / numOfBufferPartitions; } partitionOverlapMillis = Long.parseLong(prop.getProperty("buffer.partition.overlap.millis")); diskQuotaHelper = new DiskQuotaHelper(prop, bufferHome); this.state = STATE.initializing; setup(false); } public FastDiskBufferEnv(Properties prop, int currentBufferPartition) { if (prop == null) { prop = loadDefaultPropertyFile(); } this.prop = prop; this.currentBufferPartition = currentBufferPartition; File bufferHome = new File(FilepathReplacer.substitute(getPropertyWithPrecedence(prop, "buffer.disk.loc"))); if (!bufferHome.exists()) { bufferHome.mkdirs(); } envHome = new File(bufferHome, String.valueOf(currentBufferPartition)); if (!envHome.exists()) { envHome.mkdirs(); } concurrency = Integer.parseInt(prop.getProperty("buffer.concurrency")); evictorRecurrMills = Long.parseLong(prop.getProperty("buffer.evictor.recurrMills")); bufferWriteThreadPoolSize = Integer.parseInt(prop.getProperty("buffer.write.threadPool.size")); numOfBufferPartitions = Integer.parseInt(prop.getProperty("buffer.partitions")); bufferTimeMills = Long.parseLong(prop.getProperty("buffer.time.millis")); bufferTimeMills = bufferTimeMills / numOfBufferPartitions; partitionOverlapMillis = Long.parseLong(prop.getProperty("buffer.partition.overlap.millis")); metaRefreshMillis = Long.parseLong(prop.getProperty("meta.buffer.refresh.millis")); diskQuotaHelper = new DiskQuotaHelper(prop, bufferHome); this.state = STATE.initializing; setup(false); } private void setup(boolean readOnly) { assertState(STATE.initializing); // Instantiate an environment configuration object EnvironmentConfig envConfig = new EnvironmentConfig(); envConfig.setSharedCache(true); String cachePercent = prop.getProperty("bdb.cache.percent"); if (cachePercent != null) { envConfig.setCachePercent(Integer.parseInt(cachePercent)); } // Configure the environment for the read-only state as identified by // the readOnly parameter on this method call. envConfig.setReadOnly(readOnly); // If the environment is opened for write, then we want to be able to // create the environment if it does not exist. envConfig.setAllowCreate(!readOnly); envConfig.setConfigParam(EnvironmentConfig.CHECKPOINTER_BYTES_INTERVAL, "40000000"); envConfig.setTransactional(false); envConfig.setDurability(Durability.COMMIT_NO_SYNC); envConfig.setConfigParam(EnvironmentConfig.ENV_RUN_CLEANER, Boolean.FALSE.toString()); envConfig.setConfigParam(EnvironmentConfig.ENV_IS_LOCKING, Boolean.FALSE.toString()); setupConfig(); // Instantiate the Environment. This opens it and also possibly // creates it. try { dbufferEnv = new Environment(envHome, envConfig); state = STATE.initialized; } catch (DatabaseException de) { LOGGER.error("DatabaseException in setup", de); state = STATE.unInitialized; } } private void setupConfig() { txnConfig = new TransactionConfig(); txnConfig.setReadUncommitted(true); txnConfig.setDurability(Durability.COMMIT_NO_SYNC); cursorConfig = new CursorConfig(); cursorConfig.setReadUncommitted(true); } public boolean isDiskBufferFull() { return diskQuotaHelper.isDiskBufferFull(); } public String getErrorMsg() { return diskQuotaHelper.getErrorMsg(); } private String getPropertyWithPrecedence(Properties localProps, String key) { String systemProp = System.getProperty(key); return systemProp != null ? systemProp.trim() : localProps.getProperty(key, "unset").trim(); } public EntityStore openMetaDiskStore() throws DatabaseException { assertState(STATE.initialized); StoreConfig storeConfig = new StoreConfig(); storeConfig.setAllowCreate(true); storeConfig.setDeferredWrite(true); storeConfig.setTransactional(false); ClassLoader originalClassloader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); return new EntityStore(dbufferEnv, META_DATABASE_NAME, storeConfig); } finally { Thread.currentThread().setContextClassLoader(originalClassloader); } } public EntityStore openDiskStore(String dbName) throws DatabaseException { assertState(STATE.initialized); StoreConfig storeConfig = new StoreConfig(); storeConfig.setAllowCreate(true); storeConfig.setDeferredWrite(true); storeConfig.setTransactional(false); EntityStore store = new EntityStore(dbufferEnv, dbName, storeConfig); openStores.add(store); return store; } public void removeEnvironment() throws DatabaseException { dbufferEnv.cleanLog(); dbufferEnv.close(); deleteDatabaseFile(currentBufferPartition); this.state = STATE.unInitialized; } public void closeEnvironment() throws DatabaseException { dbufferEnv.cleanLog(); dbufferEnv.close(); this.state = STATE.unInitialized; } public void removeAndCloseAllDiskStores() throws DatabaseException { for (EntityStore store: openStores) { store.close(); } openStores.clear(); removeEnvironment(); } public void closeDatabase(EntityStore store) throws DatabaseException { if (store == null) { return; } store.close(); openStores.remove(store); } public void closeAndRestartEnvironment() throws DatabaseException { boolean isReadOnly = dbufferEnv.getConfig().getReadOnly(); removeAndCloseAllDiskStores(); restartEnvironment(isReadOnly); } public void restartEnvironment(boolean isReadOnly) throws DatabaseException { state = STATE.initializing; setup(isReadOnly); } public int getConcurrencyDegree() { return concurrency; } public int getBufferWriteThreadPoolSize() { return bufferWriteThreadPoolSize; } public long getBufferTime() { return bufferTimeMills; } public long getEvictorRecurr() { return evictorRecurrMills; } public int getNumOfBufferPartitions() { return numOfBufferPartitions; } public void setBufferTime(long bufferTimeMills) { this.bufferTimeMills = bufferTimeMills; } public long getBufferPartitionOverlap() { return partitionOverlapMillis; } public int getCurrentBufferPartition() { return currentBufferPartition; } public DataBufferEnv advanceBufferPartition() { int nextBufferPartition = nextBufferPartition(); deleteDatabaseFile(nextBufferPartition); FastDiskBufferEnv newBufferEnv = new FastDiskBufferEnv(prop, (this.currentBufferPartition + 1) % numOfBufferPartitions); return newBufferEnv; } private void deleteDatabaseFile(int partitionNo) { File parentDir = this.envHome.getParentFile(); File nextBufferPartitionDir = new File(parentDir, String.valueOf(partitionNo)); if (nextBufferPartitionDir.exists()) { if (nextBufferPartitionDir.isDirectory()) { File[] files = nextBufferPartitionDir.listFiles(); for (File f: files) { f.delete(); } } nextBufferPartitionDir.delete(); } } public int nextBufferPartition() { return (this.currentBufferPartition+1)%numOfBufferPartitions; } public int previousBufferPartition(int currentPartition) { int i = currentPartition; if (i == 0) { i = this.numOfBufferPartitions-1; } else { i--; } return i; } public long getMetaRefresh() { return this.metaRefreshMillis; } @Override public Object clone() { return new FastDiskBufferEnv(prop, 0); } @Override public Object cloneMetaBuffer() { return new FastDiskBufferEnv(prop); } private void assertState(STATE expectedState) { assert this.state == expectedState; } @Override public Properties getConfigProperties() { return this.prop; } public void flush() { this.dbufferEnv.sync(); } @Override public LOS getLOS() { return LOS.medium; } }
0true
timeSequenceFeedAggregator_src_main_java_gov_nasa_arc_mct_buffer_config_FastDiskBufferEnv.java
636
public final class OIndexes { private static Set<OIndexFactory> FACTORIES = null; private static ClassLoader orientClassLoader = OIndexes.class.getClassLoader(); private OIndexes() { } /** * Cache a set of all factories. we do not use the service loader directly since it is not concurrent. * * @return Set<OIndexFactory> */ private static synchronized Set<OIndexFactory> getFactories() { if (FACTORIES == null) { final Iterator<OIndexFactory> ite = lookupProviderWithOrientClassLoader(OIndexFactory.class, orientClassLoader); final Set<OIndexFactory> factories = new HashSet<OIndexFactory>(); while (ite.hasNext()) { factories.add(ite.next()); } FACTORIES = Collections.unmodifiableSet(factories); } return FACTORIES; } /** * @return Iterator of all index factories */ public static Iterator<OIndexFactory> getAllFactories() { return getFactories().iterator(); } /** * Iterates on all factories and append all index types. * * @return Set of all index types. */ public static Set<String> getIndexTypes() { final Set<String> types = new HashSet<String>(); final Iterator<OIndexFactory> ite = getAllFactories(); while (ite.hasNext()) { types.addAll(ite.next().getTypes()); } return types; } /** * * * * @param database * @param indexType * index type * @param algorithm * @param valueContainerAlgorithm * @return OIndexInternal * @throws OConfigurationException * if index creation failed * @throws OIndexException * if index type does not exist */ public static OIndexInternal<?> createIndex(ODatabaseRecord database, String indexType, String algorithm, String valueContainerAlgorithm) throws OConfigurationException, OIndexException { final Iterator<OIndexFactory> ite = getAllFactories(); while (ite.hasNext()) { final OIndexFactory factory = ite.next(); if (factory.getTypes().contains(indexType)) { return factory.createIndex(database, indexType, algorithm, valueContainerAlgorithm); } } throw new OIndexException("Index type : " + indexType + " is not supported. " + "Types are " + OCollections.toString(getIndexTypes())); } /** * Scans for factory plug-ins on the application class path. This method is needed because the application class path can * theoretically change, or additional plug-ins may become available. Rather than re-scanning the classpath on every invocation of * the API, the class path is scanned automatically only on the first invocation. Clients can call this method to prompt a * re-scan. Thus this method need only be invoked by sophisticated applications which dynamically make new plug-ins available at * runtime. */ public static synchronized void scanForPlugins() { // clear cache, will cause a rescan on next getFactories call FACTORIES = null; } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_OIndexes.java
1,833
public class MapKeySet implements IdentifiedDataSerializable { Set<Data> keySet; public MapKeySet(Set<Data> keySet) { this.keySet = keySet; } public MapKeySet() { } public Set<Data> getKeySet() { return keySet; } public void writeData(ObjectDataOutput out) throws IOException { int size = keySet.size(); out.writeInt(size); for (Data o : keySet) { o.writeData(out); } } public void readData(ObjectDataInput in) throws IOException { int size = in.readInt(); keySet = new HashSet<Data>(size); for (int i = 0; i < size; i++) { Data data = new Data(); data.readData(in); keySet.add(data); } } @Override public int getFactoryId() { return MapDataSerializerHook.F_ID; } @Override public int getId() { return MapDataSerializerHook.KEY_SET; } }
0true
hazelcast_src_main_java_com_hazelcast_map_MapKeySet.java
409
public class ClientAtomicReferenceProxy<E> extends ClientProxy implements IAtomicReference<E> { private final String name; private volatile Data key; public ClientAtomicReferenceProxy(String instanceName, String serviceName, String objectId) { super(instanceName, serviceName, objectId); this.name = objectId; } @Override public <R> R apply(IFunction<E, R> function) { isNotNull(function, "function"); return invoke(new ApplyRequest(name, toData(function))); } @Override public void alter(IFunction<E, E> function) { isNotNull(function, "function"); invoke(new AlterRequest(name, toData(function))); } @Override public E alterAndGet(IFunction<E, E> function) { isNotNull(function, "function"); return invoke(new AlterAndGetRequest(name, toData(function))); } @Override public E getAndAlter(IFunction<E, E> function) { isNotNull(function, "function"); return invoke(new GetAndAlterRequest(name, toData(function))); } @Override public boolean compareAndSet(E expect, E update) { return (Boolean) invoke(new CompareAndSetRequest(name, toData(expect), toData(update))); } @Override public boolean contains(E expected) { return (Boolean) invoke(new ContainsRequest(name, toData(expected))); } @Override public E get() { return invoke(new GetRequest(name)); } @Override public void set(E newValue) { invoke(new SetRequest(name, toData(newValue))); } @Override public void clear() { set(null); } @Override public E getAndSet(E newValue) { return invoke(new GetAndSetRequest(name, toData(newValue))); } @Override public E setAndGet(E update) { invoke(new SetRequest(name, toData(update))); return update; } @Override public boolean isNull() { return (Boolean) invoke(new IsNullRequest(name)); } @Override protected void onDestroy() { } protected <T> T invoke(ClientRequest req) { return super.invoke(req, getKey()); } private Data getKey() { if (key == null) { key = toData(name); } return key; } @Override public String toString() { return "IAtomicReference{" + "name='" + name + '\'' + '}'; } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientAtomicReferenceProxy.java
1,746
private static class FetchSerializedCount implements EntryProcessor<String, MyObject> { @Override public Object process(Map.Entry<String, MyObject> entry) { return entry.getValue().serializedCount; } @Override public EntryBackupProcessor<String, MyObject> getBackupProcessor() { return null; } }
0true
hazelcast_src_test_java_com_hazelcast_map_EntryProcessorTest.java
751
public class TxnSetAddRequest extends TxnCollectionRequest { public TxnSetAddRequest() { } public TxnSetAddRequest(String name, Data value) { super(name, value); } @Override public Object innerCall() throws Exception { return getEndpoint().getTransactionContext(txnId).getSet(name).add(value); } @Override public String getServiceName() { return SetService.SERVICE_NAME; } @Override public int getClassId() { return CollectionPortableHook.TXN_SET_ADD; } @Override public Permission getRequiredPermission() { return new SetPermission(name, ActionConstants.ACTION_ADD); } }
0true
hazelcast_src_main_java_com_hazelcast_collection_client_TxnSetAddRequest.java
96
public static class GeoshapeSerializer implements AttributeSerializer<Geoshape> { @Override public void verifyAttribute(Geoshape value) { //All values of Geoshape are valid } @Override public Geoshape convert(Object value) { if (value.getClass().isArray() && (value.getClass().getComponentType().isPrimitive() || Number.class.isAssignableFrom(value.getClass().getComponentType())) ) { Geoshape shape = null; int len= Array.getLength(value); double[] arr = new double[len]; for (int i=0;i<len;i++) arr[i]=((Number)Array.get(value,i)).doubleValue(); if (len==2) shape= point(arr[0],arr[1]); else if (len==3) shape= circle(arr[0],arr[1],arr[2]); else if (len==4) shape= box(arr[0],arr[1],arr[2],arr[3]); else throw new IllegalArgumentException("Expected 2-4 coordinates to create Geoshape, but given: " + value); return shape; } else if (value instanceof String) { String[] components=null; for (String delimiter : new String[]{",",";"}) { components = ((String)value).split(delimiter); if (components.length>=2 && components.length<=4) break; else components=null; } Preconditions.checkArgument(components!=null,"Could not parse coordinates from string: %s",value); double[] coords = new double[components.length]; try { for (int i=0;i<components.length;i++) { coords[i]=Double.parseDouble(components[i]); } } catch (NumberFormatException e) { throw new IllegalArgumentException("Could not parse coordinates from string: " + value, e); } return convert(coords); } else return null; } @Override public Geoshape read(ScanBuffer buffer) { long l = VariableLong.readPositive(buffer); assert l>0 && l<Integer.MAX_VALUE; int length = (int)l; float[][] coordinates = new float[2][]; for (int i = 0; i < 2; i++) { coordinates[i]=buffer.getFloats(length); } return new Geoshape(coordinates); } @Override public void write(WriteBuffer buffer, Geoshape attribute) { float[][] coordinates = attribute.coordinates; assert (coordinates.length==2); assert (coordinates[0].length==coordinates[1].length && coordinates[0].length>0); int length = coordinates[0].length; VariableLong.writePositive(buffer,length); for (int i = 0; i < 2; i++) { for (int j = 0; j < length; j++) { buffer.putFloat(coordinates[i][j]); } } } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Geoshape.java
475
public class LocalRedirectStrategy implements RedirectStrategy { private boolean contextRelative = false; private Logger logger = Logger.getLogger(this.getClass()); private boolean enforcePortMatch = false; /* * (non-Javadoc) * * @see * org.springframework.security.web.RedirectStrategy#sendRedirect(javax. * servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, * java.lang.String) */ public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException { if (!url.startsWith("/")) { if (StringUtils.equals(request.getParameter("successUrl"), url) || StringUtils.equals(request.getParameter("failureUrl"), url)) { validateRedirectUrl(request.getContextPath(), url, request.getServerName(), request.getServerPort()); } } String redirectUrl = calculateRedirectUrl(request.getContextPath(), url); redirectUrl = response.encodeRedirectURL(redirectUrl); if (logger.isDebugEnabled()) { logger.debug("Redirecting to '" + url + "'"); } response.sendRedirect(redirectUrl); } /** * Create the redirect url * * @param contextPath * @param url * @return */ protected String calculateRedirectUrl(String contextPath, String url) { if ((!(url.startsWith("http://"))) && (!(url.startsWith("https://")))) { if (this.contextRelative) { return url; } return contextPath + url; } if (!(this.contextRelative)) { return url; } url = url.substring(url.indexOf("://") + 3); url = url.substring(url.indexOf(contextPath) + contextPath.length()); if ((url.length() > 1) && (url.charAt(0) == '/')) { url = url.substring(1); } return url; } /** * Insure the url is valid (must begin with http or https) and local to the * application * * @param contextPath * the application context path * @param url * the url to validate * @param requestServerName * the server name of the request * @param requestServerPort * the port of the request * @throws MalformedURLException * if the url is invalid */ private void validateRedirectUrl(String contextPath, String url, String requestServerName, int requestServerPort) throws MalformedURLException { URL urlObject = new URL(url); if (urlObject.getProtocol().equals("http") || urlObject.getProtocol().equals("https")) { if (StringUtils.equals(requestServerName, urlObject.getHost())) { if (!enforcePortMatch || requestServerPort == urlObject.getPort()) { if (StringUtils.isEmpty(contextPath) || urlObject.getPath().startsWith("/" + contextPath)) { return; } } } } String errorMessage = "Invalid redirect url specified. Must be of the form /<relative view> or http[s]://<server name>[:<server port>][/<context path>]/..."; logger.warn(errorMessage + ": " + url); throw new MalformedURLException(errorMessage + ": " + url); } /** * This forces the redirect url port to match the request port. This could * be problematic when switching between secure and non-secure (e.g. * http://localhost:8080 to https://localhost:8443) * * @param enforcePortMatch */ public void setEnforcePortMatch(boolean enforcePortMatch) { this.enforcePortMatch = enforcePortMatch; } /** * Set whether or not the context should be included in the redirect path. If true, the context * is excluded from the generated path, otherwise it is included. * * @param contextRelative */ public void setContextRelative(boolean contextRelative) { this.contextRelative = contextRelative; } }
0true
common_src_main_java_org_broadleafcommerce_common_security_LocalRedirectStrategy.java
1,593
public class ShardsLimitAllocationDecider extends AllocationDecider { /** * Controls the maximum number of shards per index on a single elastic * search node. Negative values are interpreted as unlimited. */ public static final String INDEX_TOTAL_SHARDS_PER_NODE = "index.routing.allocation.total_shards_per_node"; @Inject public ShardsLimitAllocationDecider(Settings settings) { super(settings); } @Override public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { IndexMetaData indexMd = allocation.routingNodes().metaData().index(shardRouting.index()); int totalShardsPerNode = indexMd.settings().getAsInt(INDEX_TOTAL_SHARDS_PER_NODE, -1); if (totalShardsPerNode <= 0) { return allocation.decision(Decision.YES, "total shard limit disabled: [%d] <= 0", totalShardsPerNode); } int nodeCount = 0; for (MutableShardRouting nodeShard : node) { if (!nodeShard.index().equals(shardRouting.index())) { continue; } // don't count relocating shards... if (nodeShard.relocating()) { continue; } nodeCount++; } if (nodeCount >= totalShardsPerNode) { return allocation.decision(Decision.NO, "too many shards for this index on node [%d], limit: [%d]", nodeCount, totalShardsPerNode); } return allocation.decision(Decision.YES, "shard count under limit [%d] of total shards per node", totalShardsPerNode); } @Override public Decision canRemain(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { IndexMetaData indexMd = allocation.routingNodes().metaData().index(shardRouting.index()); int totalShardsPerNode = indexMd.settings().getAsInt(INDEX_TOTAL_SHARDS_PER_NODE, -1); if (totalShardsPerNode <= 0) { return allocation.decision(Decision.YES, "total shard limit disabled: [%d] <= 0", totalShardsPerNode); } int nodeCount = 0; for (MutableShardRouting nodeShard : node) {; if (!nodeShard.index().equals(shardRouting.index())) { continue; } // don't count relocating shards... if (nodeShard.relocating()) { continue; } nodeCount++; } if (nodeCount > totalShardsPerNode) { return allocation.decision(Decision.NO, "too many shards for this index on node [%d], limit: [%d]", nodeCount, totalShardsPerNode); } return allocation.decision(Decision.YES, "shard count under limit [%d] of total shards per node", totalShardsPerNode); } }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_decider_ShardsLimitAllocationDecider.java
292
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name="BLC_DATA_DRVN_ENUM_VAL") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @AdminPresentationClass(friendlyName = "DataDrivenEnumerationValueImpl_friendyName") public class DataDrivenEnumerationValueImpl implements DataDrivenEnumerationValue { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "DataDrivenEnumerationValueId") @GenericGenerator( name="DataDrivenEnumerationValueId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="DataDrivenEnumerationValueImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.common.enumeration.domain.DataDrivenEnumerationValueImpl") } ) @Column(name = "ENUM_VAL_ID") protected Long id; @ManyToOne(targetEntity = DataDrivenEnumerationImpl.class) @JoinColumn(name = "ENUM_TYPE") protected DataDrivenEnumeration type; @Column(name = "ENUM_KEY") @Index(name = "ENUM_VAL_KEY_INDEX", columnNames = {"ENUM_KEY"}) @AdminPresentation(friendlyName = "DataDrivenEnumerationValueImpl_Key", order = 1, gridOrder = 1, prominent = true) protected String key; @Column(name = "DISPLAY") @AdminPresentation(friendlyName = "DataDrivenEnumerationValueImpl_Display", order = 2, gridOrder = 2, prominent = true) protected String display; @Column(name = "HIDDEN") @Index(name = "HIDDEN_INDEX", columnNames = {"HIDDEN"}) @AdminPresentation(friendlyName = "DataDrivenEnumerationValueImpl_Hidden", order = 3, gridOrder = 3, prominent = true) protected Boolean hidden = false; @Override public String getDisplay() { return display; } @Override public void setDisplay(String display) { this.display = display; } @Override public Boolean getHidden() { if (hidden == null) { return Boolean.FALSE; } else { return hidden; } } @Override public void setHidden(Boolean hidden) { this.hidden = hidden; } @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getKey() { return key; } @Override public void setKey(String key) { this.key = key; } @Override public DataDrivenEnumeration getType() { return type; } @Override public void setType(DataDrivenEnumeration type) { this.type = type; } }
0true
common_src_main_java_org_broadleafcommerce_common_enumeration_domain_DataDrivenEnumerationValueImpl.java
213
private class NavigateQuickAccessAction extends QuickMenuAction { public NavigateQuickAccessAction() { super(NAVIGATE_MENU_ID); } protected void fillMenu(IMenuManager menu) { IContributionItem[] cis = new NavigateMenuItems().getContributionItems(); for (IContributionItem ci: cis) { menu.add(ci); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonEditor.java
401
public enum ClientNearCacheType { /** * java.util.concurrent.ConcurrentMap implementation */ Map, /** * com.hazelcast.core.ReplicatedMap implementation */ ReplicatedMap }
0true
hazelcast-client_src_main_java_com_hazelcast_client_nearcache_ClientNearCacheType.java
274
public class PortableHelpersFactory implements PortableFactory { public static final int ID = 666; public Portable create(int classId) { if (classId == SimpleClientInterceptor.ID){ return new SimpleClientInterceptor(); } return null; } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_helpers_PortableHelpersFactory.java
1,017
public class ReleaseBackupOperation extends SemaphoreBackupOperation implements IdentifiedDataSerializable { public ReleaseBackupOperation() { } public ReleaseBackupOperation(String name, int permitCount, String firstCaller) { super(name, permitCount, firstCaller); } @Override public void run() throws Exception { Permit permit = getPermit(); permit.release(permitCount, firstCaller); response = true; } @Override public int getFactoryId() { return SemaphoreDataSerializerHook.F_ID; } @Override public int getId() { return SemaphoreDataSerializerHook.RELEASE_BACKUP_OPERATION; } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_semaphore_operations_ReleaseBackupOperation.java
1,835
Runnable runnable = new Runnable() { public void run() { for (int i = 0; i < size; i++) { map1.lock(i); try { Thread.sleep(100); } catch (InterruptedException e) { } latch.countDown(); } for (int i = 0; i < size; i++) { assertTrue(map1.isLocked(i)); } for (int i = 0; i < size; i++) { map1.unlock(i); } for (int i = 0; i < size; i++) { assertFalse(map1.isLocked(i)); } latch.countDown(); } };
0true
hazelcast_src_test_java_com_hazelcast_map_MapLockTest.java
259
class FindBodyVisitor extends Visitor { Node result; private void handle(Node that) { if (ts.getOffset()>=that.getStartIndex() && ts.getOffset()+ts.getLength()<=that.getStopIndex()+1) { result = that; } } @Override public void visit(Tree.Body that) { handle(that); super.visit(that); } @Override public void visit(Tree.NamedArgumentList that) { handle(that); super.visit(that); } @Override public void visit(Tree.ImportMemberOrTypeList that) { handle(that); super.visit(that); } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_FormatBlockAction.java
1,135
public class HistogramAggregationSearchBenchmark { static final long COUNT = SizeValue.parseSizeValue("20m").singles(); static final int BATCH = 1000; static final int QUERY_WARMUP = 5; static final int QUERY_COUNT = 20; static final int NUMBER_OF_TERMS = 1000; public static void main(String[] args) throws Exception { Settings settings = settingsBuilder() .put("refresh_interval", "-1") .put("gateway.type", "local") .put(SETTING_NUMBER_OF_SHARDS, 1) .put(SETTING_NUMBER_OF_REPLICAS, 0) .build(); String clusterName = HistogramAggregationSearchBenchmark.class.getSimpleName(); Node node1 = nodeBuilder() .clusterName(clusterName) .settings(settingsBuilder().put(settings).put("name", "node1")).node(); //Node clientNode = nodeBuilder().clusterName(clusterName).settings(settingsBuilder().put(settings).put("name", "client")).client(true).node(); Client client = node1.client(); long[] lValues = new long[NUMBER_OF_TERMS]; for (int i = 0; i < NUMBER_OF_TERMS; i++) { lValues[i] = i; } Random r = new Random(); try { client.admin().indices().prepareCreate("test") .setSettings(settingsBuilder().put(settings)) .addMapping("type1", jsonBuilder() .startObject() .startObject("type1") .startObject("properties") .startObject("l_value") .field("type", "long") .endObject() .startObject("i_value") .field("type", "integer") .endObject() .startObject("s_value") .field("type", "short") .endObject() .startObject("b_value") .field("type", "byte") .endObject() .endObject() .endObject() .endObject()) .execute().actionGet(); StopWatch stopWatch = new StopWatch().start(); System.out.println("--> Indexing [" + COUNT + "] ..."); long iters = COUNT / BATCH; long i = 1; int counter = 0; for (; i <= iters; i++) { BulkRequestBuilder request = client.prepareBulk(); for (int j = 0; j < BATCH; j++) { counter++; final long value = lValues[r.nextInt(lValues.length)]; XContentBuilder source = jsonBuilder().startObject() .field("id", Integer.valueOf(counter)) .field("l_value", value) .field("i_value", (int) value) .field("s_value", (short) value) .field("b_value", (byte) value) .field("date", new Date()) .endObject(); request.add(Requests.indexRequest("test").type("type1").id(Integer.toString(counter)) .source(source)); } BulkResponse response = request.execute().actionGet(); if (response.hasFailures()) { System.err.println("--> failures..."); } if (((i * BATCH) % 10000) == 0) { System.out.println("--> Indexed " + (i * BATCH) + " took " + stopWatch.stop().lastTaskTime()); stopWatch.start(); } } client.admin().indices().prepareFlush("test").execute().actionGet(); System.out.println("--> Indexing took " + stopWatch.totalTime() + ", TPS " + (((double) (COUNT)) / stopWatch.totalTime().secondsFrac())); } catch (Exception e) { System.out.println("--> Index already exists, ignoring indexing phase, waiting for green"); ClusterHealthResponse clusterHealthResponse = client.admin().cluster().prepareHealth().setWaitForGreenStatus().setTimeout("10m").execute().actionGet(); if (clusterHealthResponse.isTimedOut()) { System.err.println("--> Timed out waiting for cluster health"); } } if (client.prepareCount().setQuery(matchAllQuery()).execute().actionGet().getCount() != COUNT) { throw new Error(); } System.out.println("--> Number of docs in index: " + COUNT); System.out.println("--> Warmup..."); // run just the child query, warm up first for (int j = 0; j < QUERY_WARMUP; j++) { SearchResponse searchResponse = client.prepareSearch() .setQuery(matchAllQuery()) .addFacet(histogramFacet("l_value").field("l_value").interval(4)) .addFacet(histogramFacet("i_value").field("i_value").interval(4)) .addFacet(histogramFacet("s_value").field("s_value").interval(4)) .addFacet(histogramFacet("b_value").field("b_value").interval(4)) .addFacet(histogramFacet("date").field("date").interval(1000)) .addAggregation(histogram("l_value").field("l_value").interval(4)) .addAggregation(histogram("i_value").field("i_value").interval(4)) .addAggregation(histogram("s_value").field("s_value").interval(4)) .addAggregation(histogram("b_value").field("b_value").interval(4)) .addAggregation(histogram("date").field("date").interval(1000)) .execute().actionGet(); if (j == 0) { System.out.println("--> Warmup took: " + searchResponse.getTook()); } if (searchResponse.getHits().totalHits() != COUNT) { System.err.println("--> mismatch on hits"); } } System.out.println("--> Warmup DONE"); long totalQueryTime = 0; for (String field : new String[] {"b_value", "s_value", "i_value", "l_value"}) { totalQueryTime = 0; for (int j = 0; j < QUERY_COUNT; j++) { SearchResponse searchResponse = client.prepareSearch() .setQuery(matchAllQuery()) .addFacet(histogramFacet(field).field(field).interval(4)) .execute().actionGet(); if (searchResponse.getHits().totalHits() != COUNT) { System.err.println("--> mismatch on hits"); } totalQueryTime += searchResponse.getTookInMillis(); } System.out.println("--> Histogram Facet (" + field + ") " + (totalQueryTime / QUERY_COUNT) + "ms"); totalQueryTime = 0; for (int j = 0; j < QUERY_COUNT; j++) { SearchResponse searchResponse = client.prepareSearch() .setQuery(matchAllQuery()) .addAggregation(histogram(field).field(field).interval(4)) .execute().actionGet(); if (searchResponse.getHits().totalHits() != COUNT) { System.err.println("--> mismatch on hits"); } totalQueryTime += searchResponse.getTookInMillis(); } System.out.println("--> Histogram Aggregation (" + field + ") " + (totalQueryTime / QUERY_COUNT) + "ms"); totalQueryTime = 0; for (int j = 0; j < QUERY_COUNT; j++) { SearchResponse searchResponse = client.prepareSearch() .setQuery(matchAllQuery()) .addFacet(histogramFacet(field).field(field).valueField(field).interval(4)) .execute().actionGet(); if (searchResponse.getHits().totalHits() != COUNT) { System.err.println("--> mismatch on hits"); } totalQueryTime += searchResponse.getTookInMillis(); } System.out.println("--> Histogram Facet (" + field + "/" + field + ") " + (totalQueryTime / QUERY_COUNT) + "ms"); totalQueryTime = 0; for (int j = 0; j < QUERY_COUNT; j++) { SearchResponse searchResponse = client.prepareSearch() .setQuery(matchAllQuery()) .addAggregation(histogram(field).field(field).subAggregation(stats(field).field(field)).interval(4)) .execute().actionGet(); if (searchResponse.getHits().totalHits() != COUNT) { System.err.println("--> mismatch on hits"); } totalQueryTime += searchResponse.getTookInMillis(); } System.out.println("--> Histogram Aggregation (" + field + "/" + field + ") " + (totalQueryTime / QUERY_COUNT) + "ms"); } totalQueryTime = 0; for (int j = 0; j < QUERY_COUNT; j++) { SearchResponse searchResponse = client.prepareSearch() .setQuery(matchAllQuery()) .addFacet(histogramFacet("date").field("date").interval(1000)) .execute().actionGet(); if (searchResponse.getHits().totalHits() != COUNT) { System.err.println("--> mismatch on hits"); } totalQueryTime += searchResponse.getTookInMillis(); } System.out.println("--> Histogram Facet (date) " + (totalQueryTime / QUERY_COUNT) + "ms"); totalQueryTime = 0; for (int j = 0; j < QUERY_COUNT; j++) { SearchResponse searchResponse = client.prepareSearch() .setQuery(matchAllQuery()) .addAggregation(dateHistogram("date").field("date").interval(1000)) .execute().actionGet(); if (searchResponse.getHits().totalHits() != COUNT) { System.err.println("--> mismatch on hits"); } totalQueryTime += searchResponse.getTookInMillis(); } System.out.println("--> Histogram Aggregation (date) " + (totalQueryTime / QUERY_COUNT) + "ms"); totalQueryTime = 0; for (int j = 0; j < QUERY_COUNT; j++) { SearchResponse searchResponse = client.prepareSearch() .setQuery(matchAllQuery()) .addFacet(histogramFacet("date").field("date").valueField("l_value").interval(1000)) .execute().actionGet(); if (searchResponse.getHits().totalHits() != COUNT) { System.err.println("--> mismatch on hits"); } totalQueryTime += searchResponse.getTookInMillis(); } System.out.println("--> Histogram Facet (date/l_value) " + (totalQueryTime / QUERY_COUNT) + "ms"); totalQueryTime = 0; for (int j = 0; j < QUERY_COUNT; j++) { SearchResponse searchResponse = client.prepareSearch() .setQuery(matchAllQuery()) .addAggregation(dateHistogram("date").field("date").interval(1000).subAggregation(stats("stats").field("l_value"))) .execute().actionGet(); if (searchResponse.getHits().totalHits() != COUNT) { System.err.println("--> mismatch on hits"); } totalQueryTime += searchResponse.getTookInMillis(); } System.out.println("--> Histogram Aggregation (date/l_value) " + (totalQueryTime / QUERY_COUNT) + "ms"); totalQueryTime = 0; for (int j = 0; j < QUERY_COUNT; j++) { SearchResponse searchResponse = client.prepareSearch() .setQuery(matchAllQuery()) .addFacet(dateHistogramFacet("date").field("date").interval("day").mode(FacetBuilder.Mode.COLLECTOR)) .execute().actionGet(); if (searchResponse.getHits().totalHits() != COUNT) { System.err.println("--> mismatch on hits"); } totalQueryTime += searchResponse.getTookInMillis(); } System.out.println("--> Date Histogram Facet (mode/collector) (date) " + (totalQueryTime / QUERY_COUNT) + "ms"); totalQueryTime = 0; for (int j = 0; j < QUERY_COUNT; j++) { SearchResponse searchResponse = client.prepareSearch() .setQuery(matchAllQuery()) .addFacet(dateHistogramFacet("date").field("date").interval("day").mode(FacetBuilder.Mode.POST)) .execute().actionGet(); if (searchResponse.getHits().totalHits() != COUNT) { System.err.println("--> mismatch on hits"); } totalQueryTime += searchResponse.getTookInMillis(); } System.out.println("--> Date Histogram Facet (mode/post) (date) " + (totalQueryTime / QUERY_COUNT) + "ms"); node1.close(); } }
0true
src_test_java_org_elasticsearch_benchmark_search_aggregations_HistogramAggregationSearchBenchmark.java
4,103
public class IncludeNestedDocsQuery extends Query { private final Filter parentFilter; private final Query parentQuery; // If we are rewritten, this is the original childQuery we // were passed; we use this for .equals() and // .hashCode(). This makes rewritten query equal the // original, so that user does not have to .rewrite() their // query before searching: private final Query origParentQuery; public IncludeNestedDocsQuery(Query parentQuery, Filter parentFilter) { this.origParentQuery = parentQuery; this.parentQuery = parentQuery; this.parentFilter = parentFilter; } // For rewritting IncludeNestedDocsQuery(Query rewrite, Query originalQuery, IncludeNestedDocsQuery previousInstance) { this.origParentQuery = originalQuery; this.parentQuery = rewrite; this.parentFilter = previousInstance.parentFilter; setBoost(previousInstance.getBoost()); } // For cloning IncludeNestedDocsQuery(Query originalQuery, IncludeNestedDocsQuery previousInstance) { this.origParentQuery = originalQuery; this.parentQuery = originalQuery; this.parentFilter = previousInstance.parentFilter; } @Override public Weight createWeight(IndexSearcher searcher) throws IOException { return new IncludeNestedDocsWeight(parentQuery, parentQuery.createWeight(searcher), parentFilter); } static class IncludeNestedDocsWeight extends Weight { private final Query parentQuery; private final Weight parentWeight; private final Filter parentsFilter; IncludeNestedDocsWeight(Query parentQuery, Weight parentWeight, Filter parentsFilter) { this.parentQuery = parentQuery; this.parentWeight = parentWeight; this.parentsFilter = parentsFilter; } @Override public Query getQuery() { return parentQuery; } @Override public void normalize(float norm, float topLevelBoost) { parentWeight.normalize(norm, topLevelBoost); } @Override public float getValueForNormalization() throws IOException { return parentWeight.getValueForNormalization(); // this query is never boosted so just delegate... } @Override public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException { final Scorer parentScorer = parentWeight.scorer(context, true, false, acceptDocs); // no matches if (parentScorer == null) { return null; } DocIdSet parents = parentsFilter.getDocIdSet(context, acceptDocs); if (parents == null) { // No matches return null; } if (!(parents instanceof FixedBitSet)) { throw new IllegalStateException("parentFilter must return FixedBitSet; got " + parents); } int firstParentDoc = parentScorer.nextDoc(); if (firstParentDoc == DocIdSetIterator.NO_MORE_DOCS) { // No matches return null; } return new IncludeNestedDocsScorer(this, parentScorer, (FixedBitSet) parents, firstParentDoc); } @Override public Explanation explain(AtomicReaderContext context, int doc) throws IOException { return null; //Query is used internally and not by users, so explain can be empty } @Override public boolean scoresDocsOutOfOrder() { return false; } } static class IncludeNestedDocsScorer extends Scorer { final Scorer parentScorer; final FixedBitSet parentBits; int currentChildPointer = -1; int currentParentPointer = -1; int currentDoc = -1; IncludeNestedDocsScorer(Weight weight, Scorer parentScorer, FixedBitSet parentBits, int currentParentPointer) { super(weight); this.parentScorer = parentScorer; this.parentBits = parentBits; this.currentParentPointer = currentParentPointer; if (currentParentPointer == 0) { currentChildPointer = 0; } else { this.currentChildPointer = parentBits.prevSetBit(currentParentPointer - 1); if (currentChildPointer == -1) { // no previous set parent, we delete from doc 0 currentChildPointer = 0; } else { currentChildPointer++; // we only care about children } } currentDoc = currentChildPointer; } @Override public Collection<ChildScorer> getChildren() { return parentScorer.getChildren(); } public int nextDoc() throws IOException { if (currentParentPointer == NO_MORE_DOCS) { return (currentDoc = NO_MORE_DOCS); } if (currentChildPointer == currentParentPointer) { // we need to return the current parent as well, but prepare to return // the next set of children currentDoc = currentParentPointer; currentParentPointer = parentScorer.nextDoc(); if (currentParentPointer != NO_MORE_DOCS) { currentChildPointer = parentBits.prevSetBit(currentParentPointer - 1); if (currentChildPointer == -1) { // no previous set parent, just set the child to the current parent currentChildPointer = currentParentPointer; } else { currentChildPointer++; // we only care about children } } } else { currentDoc = currentChildPointer++; } assert currentDoc != -1; return currentDoc; } public int advance(int target) throws IOException { if (target == NO_MORE_DOCS) { return (currentDoc = NO_MORE_DOCS); } if (target == 0) { return nextDoc(); } if (target < currentParentPointer) { currentDoc = currentParentPointer = parentScorer.advance(target); if (currentParentPointer == NO_MORE_DOCS) { return (currentDoc = NO_MORE_DOCS); } if (currentParentPointer == 0) { currentChildPointer = 0; } else { currentChildPointer = parentBits.prevSetBit(currentParentPointer - 1); if (currentChildPointer == -1) { // no previous set parent, just set the child to 0 to delete all up to the parent currentChildPointer = 0; } else { currentChildPointer++; // we only care about children } } } else { currentDoc = currentChildPointer++; } return currentDoc; } public float score() throws IOException { return parentScorer.score(); } public int freq() throws IOException { return parentScorer.freq(); } public int docID() { return currentDoc; } @Override public long cost() { return parentScorer.cost(); } } @Override public void extractTerms(Set<Term> terms) { parentQuery.extractTerms(terms); } @Override public Query rewrite(IndexReader reader) throws IOException { final Query parentRewrite = parentQuery.rewrite(reader); if (parentRewrite != parentQuery) { return new IncludeNestedDocsQuery(parentRewrite, parentQuery, this); } else { return this; } } @Override public String toString(String field) { return "IncludeNestedDocsQuery (" + parentQuery.toString() + ")"; } @Override public boolean equals(Object _other) { if (_other instanceof IncludeNestedDocsQuery) { final IncludeNestedDocsQuery other = (IncludeNestedDocsQuery) _other; return origParentQuery.equals(other.origParentQuery) && parentFilter.equals(other.parentFilter); } else { return false; } } @Override public int hashCode() { final int prime = 31; int hash = 1; hash = prime * hash + origParentQuery.hashCode(); hash = prime * hash + parentFilter.hashCode(); return hash; } @Override public Query clone() { Query clonedQuery = origParentQuery.clone(); return new IncludeNestedDocsQuery(clonedQuery, this); } }
1no label
src_main_java_org_elasticsearch_index_search_nested_IncludeNestedDocsQuery.java
608
public class MemberInfoUpdateOperation extends AbstractClusterOperation implements JoinOperation { private Collection<MemberInfo> memberInfos; private long masterTime = Clock.currentTimeMillis(); private boolean sendResponse; public MemberInfoUpdateOperation() { memberInfos = new ArrayList<MemberInfo>(); } public MemberInfoUpdateOperation(Collection<MemberInfo> memberInfos, long masterTime, boolean sendResponse) { this.masterTime = masterTime; this.memberInfos = memberInfos; this.sendResponse = sendResponse; } @Override public void run() throws Exception { processMemberUpdate(); } protected final void processMemberUpdate() { if (isValid()) { final ClusterServiceImpl clusterService = getService(); clusterService.setMasterTime(masterTime); clusterService.updateMembers(memberInfos); } } protected final boolean isValid() { final ClusterServiceImpl clusterService = getService(); final Connection conn = getConnection(); final Address masterAddress = conn != null ? conn.getEndPoint() : null; boolean isLocal = conn == null; return isLocal || (masterAddress != null && masterAddress.equals(clusterService.getMasterAddress())); } @Override public final boolean returnsResponse() { return sendResponse; } @Override protected void readInternal(ObjectDataInput in) throws IOException { masterTime = in.readLong(); int size = in.readInt(); memberInfos = new ArrayList<MemberInfo>(size); while (size-- > 0) { MemberInfo memberInfo = new MemberInfo(); memberInfo.readData(in); memberInfos.add(memberInfo); } sendResponse = in.readBoolean(); } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { out.writeLong(masterTime); out.writeInt(memberInfos.size()); for (MemberInfo memberInfo : memberInfos) { memberInfo.writeData(out); } out.writeBoolean(sendResponse); } @Override public String toString() { StringBuilder sb = new StringBuilder("MembersUpdateCall {\n"); for (MemberInfo address : memberInfos) { sb.append(address).append('\n'); } sb.append('}'); return sb.toString(); } }
0true
hazelcast_src_main_java_com_hazelcast_cluster_MemberInfoUpdateOperation.java
1,969
class IdleReachabilityHandler extends AbstractReachabilityHandler { private final long idleTimeOutInNanos; public IdleReachabilityHandler(long idleTimeOutInNanos) { assert idleTimeOutInNanos > 0L : String.format("Not valid idleTimeOutInNanos %d", idleTimeOutInNanos); this.idleTimeOutInNanos = idleTimeOutInNanos; } @Override public Record handle(Record record, long criteria, long timeInNanos) { if (record == null) { return null; } boolean result; // lastAccessTime : updates on every touch (put/get). final long lastAccessTime = record.getLastAccessTime(); assert lastAccessTime > 0L; assert timeInNanos > 0L; assert timeInNanos >= lastAccessTime; result = timeInNanos - lastAccessTime >= idleTimeOutInNanos; log("%s is asked for check and said %s", this.getClass().getName(), result); return result ? null : record; } @Override public short niceNumber() { return 1; } }
0true
hazelcast_src_main_java_com_hazelcast_map_eviction_IdleReachabilityHandler.java
2,239
public class ChecksumIndexOutput extends IndexOutput { private final IndexOutput out; private final Checksum digest; public ChecksumIndexOutput(IndexOutput out, Checksum digest) { this.out = out; this.digest = digest; } public Checksum digest() { return digest; } @Override public void writeByte(byte b) throws IOException { out.writeByte(b); digest.update(b); } @Override public void setLength(long length) throws IOException { out.setLength(length); } // don't override copyBytes, since we need to read it and compute it // @Override // public void copyBytes(DataInput input, long numBytes) throws IOException { // super.copyBytes(input, numBytes); // } @Override public String toString() { return out.toString(); } @Override public void writeBytes(byte[] b, int offset, int length) throws IOException { out.writeBytes(b, offset, length); digest.update(b, offset, length); } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { out.close(); } @Override public long getFilePointer() { return out.getFilePointer(); } @Override public void seek(long pos) throws IOException { out.seek(pos); } @Override public long length() throws IOException { return out.length(); } }
0true
src_main_java_org_elasticsearch_common_lucene_store_ChecksumIndexOutput.java
507
createIndexService.createIndex(updateRequest, new ClusterStateUpdateListener() { @Override public void onResponse(ClusterStateUpdateResponse response) { listener.onResponse(new CreateIndexResponse(response.isAcknowledged())); } @Override public void onFailure(Throwable t) { if (t instanceof IndexAlreadyExistsException) { logger.trace("[{}] failed to create", t, request.index()); } else { logger.debug("[{}] failed to create", t, request.index()); } listener.onFailure(t); } });
0true
src_main_java_org_elasticsearch_action_admin_indices_create_TransportCreateIndexAction.java
2,032
new AssertTask() { @Override public void run() { assertEquals("Invalidation is not working on putAll()", 0, nearCache.size()); } }
0true
hazelcast_src_test_java_com_hazelcast_map_nearcache_NearCacheTest.java
218
new InPlaceMergeSorter() { @Override protected void swap(int i, int j) { String tmp = fields[i]; fields[i] = fields[j]; fields[j] = tmp; int tmp2 = maxPassages[i]; maxPassages[i] = maxPassages[j]; maxPassages[j] = tmp2; } @Override protected int compare(int i, int j) { return fields[i].compareTo(fields[j]); } }.sort(0, fields.length);
0true
src_main_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighter.java
717
@Test public class WOWCacheTest { private int systemOffset = 2 * (OIntegerSerializer.INT_SIZE + OLongSerializer.LONG_SIZE); private int pageSize = systemOffset + 8; private OLocalPaginatedStorage storageLocal; private String fileName; private OWriteAheadLog writeAheadLog; private OWOWCache wowCache; @BeforeClass public void beforeClass() throws IOException { OGlobalConfiguration.FILE_LOCK.setValue(Boolean.FALSE); String buildDirectory = System.getProperty("buildDirectory"); if (buildDirectory == null) buildDirectory = "."; storageLocal = (OLocalPaginatedStorage) Orient.instance().loadStorage("plocal:" + buildDirectory + "/WOWCacheTest"); fileName = "wowCacheTest.tst"; OWALRecordsFactory.INSTANCE.registerNewRecord((byte) 128, WriteAheadLogTest.TestRecord.class); } @BeforeMethod public void beforeMethod() throws IOException { closeCacheAndDeleteFile(); initBuffer(); } private void closeCacheAndDeleteFile() throws IOException { if (wowCache != null) { wowCache.close(); wowCache = null; } if (writeAheadLog != null) { writeAheadLog.delete(); writeAheadLog = null; } File testFile = new File(storageLocal.getConfiguration().getDirectory() + File.separator + fileName); if (testFile.exists()) { Assert.assertTrue(testFile.delete()); } File nameIdMapFile = new File(storageLocal.getConfiguration().getDirectory() + File.separator + "name_id_map.cm"); if (nameIdMapFile.exists()) { Assert.assertTrue(nameIdMapFile.delete()); } } @AfterClass public void afterClass() throws IOException { closeCacheAndDeleteFile(); File file = new File(storageLocal.getConfiguration().getDirectory()); Assert.assertTrue(file.delete()); } private void initBuffer() throws IOException { wowCache = new OWOWCache(true, pageSize, 10000, writeAheadLog, 10, 100, storageLocal, false); } public void testLoadStore() throws IOException { Random random = new Random(); byte[][] pageData = new byte[200][]; long fileId = wowCache.openFile(fileName); for (int i = 0; i < pageData.length; i++) { byte[] data = new byte[8]; random.nextBytes(data); pageData[i] = data; final OCachePointer cachePointer = wowCache.load(fileId, i); cachePointer.acquireExclusiveLock(); cachePointer.getDataPointer().set(systemOffset, data, 0, data.length); cachePointer.releaseExclusiveLock(); wowCache.store(fileId, i, cachePointer); cachePointer.decrementReferrer(); } for (int i = 0; i < pageData.length; i++) { byte[] dataOne = pageData[i]; OCachePointer cachePointer = wowCache.load(fileId, i); byte[] dataTwo = cachePointer.getDataPointer().get(systemOffset, 8); cachePointer.decrementReferrer(); Assert.assertEquals(dataTwo, dataOne); } wowCache.flush(); for (int i = 0; i < pageData.length; i++) { byte[] dataContent = pageData[i]; assertFile(i, dataContent, new OLogSequenceNumber(0, 0)); } } public void testDataUpdate() throws Exception { final NavigableMap<Long, byte[]> pageIndexDataMap = new TreeMap<Long, byte[]>(); long fileId = wowCache.openFile(fileName); Random random = new Random(); for (int i = 0; i < 600; i++) { long pageIndex = random.nextInt(2048); byte[] data = new byte[8]; random.nextBytes(data); pageIndexDataMap.put(pageIndex, data); final OCachePointer cachePointer = wowCache.load(fileId, pageIndex); cachePointer.acquireExclusiveLock(); cachePointer.getDataPointer().set(systemOffset, data, 0, data.length); cachePointer.releaseExclusiveLock(); wowCache.store(fileId, pageIndex, cachePointer); cachePointer.decrementReferrer(); } for (Map.Entry<Long, byte[]> entry : pageIndexDataMap.entrySet()) { long pageIndex = entry.getKey(); byte[] dataOne = entry.getValue(); OCachePointer cachePointer = wowCache.load(fileId, pageIndex); byte[] dataTwo = cachePointer.getDataPointer().get(systemOffset, 8); cachePointer.decrementReferrer(); Assert.assertEquals(dataTwo, dataOne); } for (int i = 0; i < 300; i++) { long desiredIndex = random.nextInt(2048); Long pageIndex = pageIndexDataMap.ceilingKey(desiredIndex); if (pageIndex == null) pageIndex = pageIndexDataMap.floorKey(desiredIndex); byte[] data = new byte[8]; random.nextBytes(data); pageIndexDataMap.put(pageIndex, data); final OCachePointer cachePointer = wowCache.load(fileId, pageIndex); cachePointer.acquireExclusiveLock(); cachePointer.getDataPointer().set(systemOffset, data, 0, data.length); cachePointer.releaseExclusiveLock(); wowCache.store(fileId, pageIndex, cachePointer); cachePointer.decrementReferrer(); } for (Map.Entry<Long, byte[]> entry : pageIndexDataMap.entrySet()) { long pageIndex = entry.getKey(); byte[] dataOne = entry.getValue(); OCachePointer cachePointer = wowCache.load(fileId, pageIndex); byte[] dataTwo = cachePointer.getDataPointer().get(systemOffset, 8); cachePointer.decrementReferrer(); Assert.assertEquals(dataTwo, dataOne); } wowCache.flush(); for (Map.Entry<Long, byte[]> entry : pageIndexDataMap.entrySet()) { assertFile(entry.getKey(), entry.getValue(), new OLogSequenceNumber(0, 0)); } } public void testFlushAllContentEventually() throws Exception { Random random = new Random(); byte[][] pageData = new byte[200][]; long fileId = wowCache.openFile(fileName); for (int i = 0; i < pageData.length; i++) { byte[] data = new byte[8]; random.nextBytes(data); pageData[i] = data; final OCachePointer cachePointer = wowCache.load(fileId, i); cachePointer.acquireExclusiveLock(); cachePointer.getDataPointer().set(systemOffset, data, 0, data.length); cachePointer.releaseExclusiveLock(); wowCache.store(fileId, i, cachePointer); cachePointer.decrementReferrer(); } for (int i = 0; i < pageData.length; i++) { byte[] dataOne = pageData[i]; OCachePointer cachePointer = wowCache.load(fileId, i); byte[] dataTwo = cachePointer.getDataPointer().get(systemOffset, 8); cachePointer.decrementReferrer(); Assert.assertEquals(dataTwo, dataOne); } Thread.sleep(5000); for (int i = 0; i < pageData.length; i++) { byte[] dataContent = pageData[i]; assertFile(i, dataContent, new OLogSequenceNumber(0, 0)); } } private void assertFile(long pageIndex, byte[] value, OLogSequenceNumber lsn) throws IOException { String path = storageLocal.getConfiguration().getDirectory() + File.separator + fileName; OFileClassic fileClassic = new OFileClassic(); fileClassic.init(path, "r"); fileClassic.open(); byte[] content = new byte[8 + systemOffset]; fileClassic.read(pageIndex * (8 + systemOffset), content, 8 + systemOffset); Assert.assertEquals(Arrays.copyOfRange(content, systemOffset, 8 + systemOffset), value); long magicNumber = OLongSerializer.INSTANCE.deserializeNative(content, 0); Assert.assertEquals(magicNumber, OWOWCache.MAGIC_NUMBER); CRC32 crc32 = new CRC32(); crc32.update(content, OIntegerSerializer.INT_SIZE + OLongSerializer.LONG_SIZE, content.length - OIntegerSerializer.INT_SIZE - OLongSerializer.LONG_SIZE); int crc = OIntegerSerializer.INSTANCE.deserializeNative(content, OLongSerializer.LONG_SIZE); Assert.assertEquals(crc, (int) crc32.getValue()); int segment = OIntegerSerializer.INSTANCE.deserializeNative(content, OLongSerializer.LONG_SIZE + OIntegerSerializer.INT_SIZE); long position = OLongSerializer.INSTANCE .deserializeNative(content, OLongSerializer.LONG_SIZE + 2 * OIntegerSerializer.INT_SIZE); OLogSequenceNumber readLsn = new OLogSequenceNumber(segment, position); Assert.assertEquals(readLsn, lsn); fileClassic.close(); } }
0true
core_src_test_java_com_orientechnologies_orient_core_index_hashindex_local_cache_WOWCacheTest.java
1,152
private class VertexConstructor implements Retriever<Long, InternalVertex> { private final boolean verifyExistence; private VertexConstructor(boolean verifyExistence) { this.verifyExistence = verifyExistence; } @Override public InternalVertex get(Long vertexid) { Preconditions.checkNotNull(vertexid); Preconditions.checkArgument(vertexid > 0); Preconditions.checkArgument(idInspector.isSchemaVertexId(vertexid) || idInspector.isUserVertexId(vertexid), "Not a valid vertex id: %s", vertexid); byte lifecycle = ElementLifeCycle.Loaded; long canonicalVertexId = idInspector.isPartitionedVertex(vertexid)?idManager.getCanonicalVertexId(vertexid):vertexid; if (verifyExistence) { if (graph.edgeQuery(canonicalVertexId, graph.vertexExistenceQuery, txHandle).isEmpty()) lifecycle = ElementLifeCycle.Removed; } if (canonicalVertexId!=vertexid) { //Take lifecycle from canonical representative lifecycle = getExistingVertex(canonicalVertexId).getLifeCycle(); } InternalVertex vertex = null; if (idInspector.isRelationTypeId(vertexid)) { if (idInspector.isPropertyKeyId(vertexid)) { if (idInspector.isSystemRelationTypeId(vertexid)) { vertex = SystemTypeManager.getSystemType(vertexid); } else { vertex = new PropertyKeyVertex(StandardTitanTx.this, vertexid, lifecycle); } } else { assert idInspector.isEdgeLabelId(vertexid); if (idInspector.isSystemRelationTypeId(vertexid)) { vertex = SystemTypeManager.getSystemType(vertexid); } else { vertex = new EdgeLabelVertex(StandardTitanTx.this, vertexid, lifecycle); } } } else if (idInspector.isVertexLabelVertexId(vertexid)) { vertex = new VertexLabelVertex(StandardTitanTx.this,vertexid, lifecycle); } else if (idInspector.isGenericSchemaVertexId(vertexid)) { vertex = new TitanSchemaVertex(StandardTitanTx.this,vertexid, lifecycle); } else if (idInspector.isUserVertexId(vertexid)) { vertex = new CacheVertex(StandardTitanTx.this, vertexid, lifecycle); } else throw new IllegalArgumentException("ID could not be recognized"); return vertex; } }
1no label
titan-core_src_main_java_com_thinkaurelius_titan_graphdb_transaction_StandardTitanTx.java
1,123
public class OSQLFunctionFormat extends OSQLFunctionAbstract { public static final String NAME = "format"; public OSQLFunctionFormat() { super(NAME, 2, -1); } public Object execute(OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParameters, OCommandContext iContext) { final Object[] args = new Object[iParameters.length - 1]; for (int i = 0; i < args.length; ++i) args[i] = iParameters[i + 1]; return String.format((String) iParameters[0], args); } public String getSyntax() { return "Syntax error: format(<format>, <arg1> [,<argN>]*)"; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_functions_misc_OSQLFunctionFormat.java
36
private static final ThreadFactory tf = new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = Executors.defaultThreadFactory().newThread(r); t.setContextClassLoader(getClass().getClassLoader()); return t; } };
0true
timeSequenceFeedAggregator_src_main_java_gov_nasa_arc_mct_buffer_disk_internal_PartitionFastDiskBuffer.java
1,153
public interface PaymentInfoDao { public PaymentInfo readPaymentInfoById(Long paymentId); public PaymentInfo save(PaymentInfo paymentInfo); public PaymentResponseItem save(PaymentResponseItem paymentResponseItem); public PaymentLog save(PaymentLog log); public List<PaymentInfo> readPaymentInfosForOrder(Order order); public PaymentInfo create(); public void delete(PaymentInfo paymentInfo); public PaymentResponseItem createResponseItem(); public PaymentLog createLog(); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_dao_PaymentInfoDao.java
1,003
public class OStreamSerializerLiteral implements OStreamSerializer { public static final String NAME = "li"; public static final OStreamSerializerLiteral INSTANCE = new OStreamSerializerLiteral(); public String getName() { return NAME; } public Object fromStream(final byte[] iStream) throws IOException { return ORecordSerializerStringAbstract.getTypeValue(OBinaryProtocol.bytes2string(iStream)); } public byte[] toStream(final Object iObject) throws IOException { if (iObject == null) return null; final StringBuilder buffer = new StringBuilder(); ORecordSerializerStringAbstract.fieldTypeToString(buffer, OType.getTypeByClass(iObject.getClass()), iObject); return OBinaryProtocol.string2bytes(buffer.toString()); } }
0true
core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_stream_OStreamSerializerLiteral.java
539
public class DeleteMappingClusterStateUpdateRequest extends IndicesClusterStateUpdateRequest<DeleteMappingClusterStateUpdateRequest> { private String[] types; DeleteMappingClusterStateUpdateRequest() { } /** * Returns the type to be removed */ public String[] types() { return types; } /** * Sets the type to be removed */ public DeleteMappingClusterStateUpdateRequest types(String[] types) { this.types = types; return this; } }
0true
src_main_java_org_elasticsearch_action_admin_indices_mapping_delete_DeleteMappingClusterStateUpdateRequest.java
101
static final class TableStack<K,V> { int length; int index; Node<K,V>[] tab; TableStack<K,V> next; }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
1,273
private class ChatCallback implements EntryListener { public ChatCallback() { } public void entryAdded(EntryEvent event) { if (!username.equals(event.getKey())) { System.out.println(event.getValue()); } } public void entryRemoved(EntryEvent event) { if (!username.equals(event.getKey())) { System.out.println(event.getKey() + " left"); } } public void entryUpdated(EntryEvent event) { if (!username.equals(event.getKey())) { System.out.println(event.getValue().toString()); } } public void entryEvicted(EntryEvent event) { } }
0true
hazelcast_src_main_java_com_hazelcast_examples_ChatApplication.java
253
private static abstract class PreferenceAction extends ResourceAction implements IUpdate { PreferenceAction(ResourceBundle bundle, String prefix, int style) { super(bundle, prefix, style); } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_FoldingActionGroup.java
1,079
public class CacheProperty extends AbstractProperty { public CacheProperty(long id, PropertyKey key, InternalVertex start, Object value, Entry data) { super(id, key, start.it(), value); this.data = data; } //############## Similar code as CacheEdge but be careful when copying ############################# private final Entry data; @Override public InternalRelation it() { InternalRelation it = null; InternalVertex startVertex = getVertex(0); if (startVertex.hasAddedRelations() && startVertex.hasRemovedRelations()) { //Test whether this relation has been replaced final long id = super.getLongId(); it = Iterables.getOnlyElement(startVertex.getAddedRelations(new Predicate<InternalRelation>() { @Override public boolean apply(@Nullable InternalRelation internalRelation) { return (internalRelation instanceof StandardProperty) && ((StandardProperty) internalRelation).getPreviousID() == id; } }), null); } return (it != null) ? it : super.it(); } private void copyProperties(InternalRelation to) { for (LongObjectCursor<Object> entry : getPropertyMap()) { to.setPropertyDirect(tx().getExistingRelationType(entry.key), entry.value); } } private synchronized InternalRelation update() { StandardProperty copy = new StandardProperty(super.getLongId(), getPropertyKey(), getVertex(0), getValue(), ElementLifeCycle.Loaded); copyProperties(copy); copy.remove(); StandardProperty u = (StandardProperty) tx().addProperty(getVertex(0), getPropertyKey(), getValue()); if (type.getConsistencyModifier()!= ConsistencyModifier.FORK) u.setId(super.getLongId()); u.setPreviousID(super.getLongId()); copyProperties(u); return u; } @Override public long getLongId() { InternalRelation it = it(); return (it == this) ? super.getLongId() : it.getLongId(); } private RelationCache getPropertyMap() { RelationCache map = data.getCache(); if (map == null || !map.hasProperties()) { map = RelationConstructor.readRelationCache(data, tx()); } return map; } @Override public <O> O getPropertyDirect(RelationType type) { return getPropertyMap().get(type.getLongId()); } @Override public Iterable<RelationType> getPropertyKeysDirect() { RelationCache map = getPropertyMap(); List<RelationType> types = new ArrayList<RelationType>(map.numProperties()); for (LongObjectCursor<Object> entry : map) { types.add(tx().getExistingRelationType(entry.key)); } return types; } @Override public void setPropertyDirect(RelationType type, Object value) { update().setPropertyDirect(type, value); } @Override public <O> O removePropertyDirect(RelationType type) { return update().removePropertyDirect(type); } @Override public byte getLifeCycle() { if ((getVertex(0).hasRemovedRelations() || getVertex(0).isRemoved()) && tx().isRemovedRelation(super.getLongId())) return ElementLifeCycle.Removed; else return ElementLifeCycle.Loaded; } @Override public void remove() { if (!tx().isRemovedRelation(super.getLongId())) { tx().removeRelation(this); }// else throw InvalidElementException.removedException(this); } }
1no label
titan-core_src_main_java_com_thinkaurelius_titan_graphdb_relations_CacheProperty.java
3,728
public class NullValueObjectMappingTests extends ElasticsearchTestCase { @Test public void testNullValueObject() throws IOException { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("obj1").field("type", "object").endObject().endObject() .endObject().endObject().string(); DocumentMapper defaultMapper = MapperTestUtils.newParser().parse(mapping); ParsedDocument doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder() .startObject() .startObject("obj1").endObject() .field("value1", "test1") .endObject() .bytes()); assertThat(doc.rootDoc().get("value1"), equalTo("test1")); doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder() .startObject() .nullField("obj1") .field("value1", "test1") .endObject() .bytes()); assertThat(doc.rootDoc().get("value1"), equalTo("test1")); doc = defaultMapper.parse("type", "1", XContentFactory.jsonBuilder() .startObject() .startObject("obj1").field("field", "value").endObject() .field("value1", "test1") .endObject() .bytes()); assertThat(doc.rootDoc().get("obj1.field"), equalTo("value")); assertThat(doc.rootDoc().get("value1"), equalTo("test1")); } }
0true
src_test_java_org_elasticsearch_index_mapper_object_NullValueObjectMappingTests.java
949
public class LockTestUtils { public static void lockByOtherThread(final ILock lock) { Thread t = new Thread() { public void run() { lock.lock(); } }; t.start(); try { t.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
0true
hazelcast_src_test_java_com_hazelcast_concurrent_lock_LockTestUtils.java
735
public class IndexDeleteByQueryRequest extends IndexReplicationOperationRequest<IndexDeleteByQueryRequest> { private BytesReference source; private String[] types = Strings.EMPTY_ARRAY; @Nullable private Set<String> routing; @Nullable private String[] filteringAliases; IndexDeleteByQueryRequest(DeleteByQueryRequest request, String index, @Nullable Set<String> routing, @Nullable String[] filteringAliases) { this.index = index; this.timeout = request.timeout(); this.source = request.source(); this.types = request.types(); this.replicationType = request.replicationType(); this.consistencyLevel = request.consistencyLevel(); this.routing = routing; this.filteringAliases = filteringAliases; } IndexDeleteByQueryRequest() { } BytesReference source() { return source; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = super.validate(); if (source == null) { validationException = addValidationError("source is missing", validationException); } return validationException; } Set<String> routing() { return this.routing; } String[] types() { return this.types; } String[] filteringAliases() { return filteringAliases; } public IndexDeleteByQueryRequest timeout(TimeValue timeout) { this.timeout = timeout; return this; } public void readFrom(StreamInput in) throws IOException { super.readFrom(in); source = in.readBytesReference(); int typesSize = in.readVInt(); if (typesSize > 0) { types = new String[typesSize]; for (int i = 0; i < typesSize; i++) { types[i] = in.readString(); } } int routingSize = in.readVInt(); if (routingSize > 0) { routing = new HashSet<String>(routingSize); for (int i = 0; i < routingSize; i++) { routing.add(in.readString()); } } int aliasesSize = in.readVInt(); if (aliasesSize > 0) { filteringAliases = new String[aliasesSize]; for (int i = 0; i < aliasesSize; i++) { filteringAliases[i] = in.readString(); } } } public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeBytesReference(source); out.writeVInt(types.length); for (String type : types) { out.writeString(type); } if (routing != null) { out.writeVInt(routing.size()); for (String r : routing) { out.writeString(r); } } else { out.writeVInt(0); } if (filteringAliases != null) { out.writeVInt(filteringAliases.length); for (String alias : filteringAliases) { out.writeString(alias); } } else { out.writeVInt(0); } } }
0true
src_main_java_org_elasticsearch_action_deletebyquery_IndexDeleteByQueryRequest.java
1,143
public class DuplicateInstanceNameException extends HazelcastException { public DuplicateInstanceNameException() { super(); } public DuplicateInstanceNameException(String message) { super(message); } }
0true
hazelcast_src_main_java_com_hazelcast_core_DuplicateInstanceNameException.java
1,085
@Service("blOrderMultishipOptionService") public class OrderMultishipOptionServiceImpl implements OrderMultishipOptionService { @Resource(name = "blOrderMultishipOptionDao") OrderMultishipOptionDao orderMultishipOptionDao; @Resource(name = "blAddressService") protected AddressService addressService; @Resource(name = "blOrderItemService") protected OrderItemService orderItemService; @Resource(name = "blFulfillmentOptionService") protected FulfillmentOptionService fulfillmentOptionService; @Override public OrderMultishipOption save(OrderMultishipOption orderMultishipOption) { return orderMultishipOptionDao.save(orderMultishipOption); } @Override public List<OrderMultishipOption> findOrderMultishipOptions(Long orderId) { return orderMultishipOptionDao.readOrderMultishipOptions(orderId); } @Override public List<OrderMultishipOption> findOrderItemOrderMultishipOptions(Long orderItemId) { return orderMultishipOptionDao.readOrderItemOrderMultishipOptions(orderItemId); } @Override public OrderMultishipOption create() { return orderMultishipOptionDao.create(); } @Override public void deleteOrderItemOrderMultishipOptions(Long orderItemId) { List<OrderMultishipOption> options = findOrderItemOrderMultishipOptions(orderItemId); orderMultishipOptionDao.deleteAll(options); } @Override public void deleteOrderItemOrderMultishipOptions(Long orderItemId, int numToDelete) { List<OrderMultishipOption> options = findOrderItemOrderMultishipOptions(orderItemId); numToDelete = (numToDelete > options.size()) ? options.size() : numToDelete; options = options.subList(0, numToDelete); orderMultishipOptionDao.deleteAll(options); } @Override public void deleteAllOrderMultishipOptions(Order order) { List<OrderMultishipOption> options = findOrderMultishipOptions(order.getId()); orderMultishipOptionDao.deleteAll(options); } @Override public void saveOrderMultishipOptions(Order order, List<OrderMultishipOptionDTO> optionDTOs) { Map<Long, OrderMultishipOption> currentOptions = new HashMap<Long, OrderMultishipOption>(); for (OrderMultishipOption option : findOrderMultishipOptions(order.getId())) { currentOptions.put(option.getId(), option); } List<OrderMultishipOption> orderMultishipOptions = new ArrayList<OrderMultishipOption>(); for (OrderMultishipOptionDTO dto: optionDTOs) { OrderMultishipOption option = currentOptions.get(dto.getId()); if (option == null) { option = orderMultishipOptionDao.create(); } option.setOrder(order); option.setOrderItem(orderItemService.readOrderItemById(dto.getOrderItemId())); if (dto.getAddressId() != null) { option.setAddress(addressService.readAddressById(dto.getAddressId())); } else { option.setAddress(null); } if (dto.getFulfillmentOptionId() != null) { option.setFulfillmentOption(fulfillmentOptionService.readFulfillmentOptionById(dto.getFulfillmentOptionId())); } else { option.setFulfillmentOption(null); } orderMultishipOptions.add(option); } for (OrderMultishipOption option : orderMultishipOptions) { save(option); } } @Override public List<OrderMultishipOption> getOrGenerateOrderMultishipOptions(Order order) { List<OrderMultishipOption> orderMultishipOptions = findOrderMultishipOptions(order.getId()); if (orderMultishipOptions == null || orderMultishipOptions.size() == 0) { orderMultishipOptions = generateOrderMultishipOptions(order); } // Create a map representing the current discrete order item counts for the order Map<Long, Integer> orderDiscreteOrderItemCounts = new HashMap<Long, Integer>(); for (DiscreteOrderItem item : order.getDiscreteOrderItems()) { orderDiscreteOrderItemCounts.put(item.getId(), item.getQuantity()); } List<OrderMultishipOption> optionsToRemove = new ArrayList<OrderMultishipOption>(); for (OrderMultishipOption option : orderMultishipOptions) { Integer count = orderDiscreteOrderItemCounts.get(option.getOrderItem().getId()); if (count == null || count == 0) { optionsToRemove.add(option); } else { count--; orderDiscreteOrderItemCounts.put(option.getOrderItem().getId(), count); } } for (Entry<Long, Integer> entry : orderDiscreteOrderItemCounts.entrySet()) { DiscreteOrderItem item = (DiscreteOrderItem) orderItemService.readOrderItemById(entry.getKey()); orderMultishipOptions.addAll(createPopulatedOrderMultishipOption(order, item, entry.getValue())); } orderMultishipOptions.removeAll(optionsToRemove); orderMultishipOptionDao.deleteAll(optionsToRemove); return orderMultishipOptions; } @Override public List<OrderMultishipOption> getOrderMultishipOptionsFromDTOs(Order order, List<OrderMultishipOptionDTO> optionDtos) { List<OrderMultishipOption> orderMultishipOptions = new ArrayList<OrderMultishipOption>(); for (OrderMultishipOptionDTO optionDto : optionDtos) { OrderMultishipOption option = new OrderMultishipOptionImpl(); if (optionDto.getAddressId() != null) { option.setAddress(addressService.readAddressById(optionDto.getAddressId())); } if (optionDto.getFulfillmentOptionId() != null) { option.setFulfillmentOption(fulfillmentOptionService.readFulfillmentOptionById(optionDto.getFulfillmentOptionId())); } option.setId(optionDto.getId()); option.setOrder(order); option.setOrderItem(orderItemService.readOrderItemById(optionDto.getOrderItemId())); orderMultishipOptions.add(option); } return orderMultishipOptions; } @Override public List<OrderMultishipOption> generateOrderMultishipOptions(Order order) { List<OrderMultishipOption> orderMultishipOptions = new ArrayList<OrderMultishipOption>(); for (DiscreteOrderItem discreteOrderItem : order.getDiscreteOrderItems()) { orderMultishipOptions.addAll(createPopulatedOrderMultishipOption(order, discreteOrderItem, discreteOrderItem.getQuantity())); } return orderMultishipOptions; } protected List<OrderMultishipOption> createPopulatedOrderMultishipOption(Order order, DiscreteOrderItem item, Integer quantity) { List<OrderMultishipOption> orderMultishipOptions = new ArrayList<OrderMultishipOption>(); for (int i = 0; i < quantity; i++) { OrderMultishipOption orderMultishipOption = new OrderMultishipOptionImpl(); orderMultishipOption.setOrder(order); orderMultishipOption.setOrderItem(item); orderMultishipOptions.add(orderMultishipOption); } return orderMultishipOptions; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_OrderMultishipOptionServiceImpl.java
114
{ @Override public Object doWork( Void state ) { try { tm.rollback(); } catch ( Exception e ) { throw new RuntimeException( e ); } return null; } };
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestJtaCompliance.java
1,478
public class RoutingNodesIterator implements Iterator<RoutingNode>, Iterable<MutableShardRouting> { private RoutingNode current; private final Iterator<RoutingNode> delegate; public RoutingNodesIterator(Iterator<RoutingNode> iterator) { delegate = iterator; } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public RoutingNode next() { return current = delegate.next(); } public RoutingNodeIterator nodeShards() { return new RoutingNodeIterator(current); } @Override public void remove() { delegate.remove(); } @Override public Iterator<MutableShardRouting> iterator() { return nodeShards(); } }
0true
src_main_java_org_elasticsearch_cluster_routing_RoutingNodes.java
1,447
static private class EvictionEntry implements Comparable<EvictionEntry> { final Object key; final Value value; private EvictionEntry(final Object key, final Value value) { this.key = key; this.value = value; } public int compareTo(final EvictionEntry o) { final long thisVal = this.value.getCreationTime(); final long anotherVal = o.value.getCreationTime(); return (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EvictionEntry that = (EvictionEntry) o; if (key != null ? !key.equals(that.key) : that.key != null) return false; if (value != null ? !value.equals(that.value) : that.value != null) return false; return true; } @Override public int hashCode() { return key != null ? key.hashCode() : 0; } }
1no label
hazelcast-hibernate_hazelcast-hibernate3_src_main_java_com_hazelcast_hibernate_local_LocalRegionCache.java
156
public static final Map<String,String> REGISTERED_LOG_MANAGERS = new HashMap<String, String>() {{ put("default","com.thinkaurelius.titan.diskstorage.log.kcvs.KCVSLogManager"); }};
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_Backend.java
1,096
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class QueueConfigTest { /** * Test method for {@link com.hazelcast.config.QueueConfig#getName()}. */ @Test public void testGetName() { QueueConfig queueConfig = new QueueConfig(); assertNull(null, queueConfig.getName()); } /** * Test method for {@link com.hazelcast.config.QueueConfig#setName(java.lang.String)}. */ @Test public void testSetName() { String name = "a test name"; QueueConfig queueConfig = new QueueConfig().setName(name); assertEquals(name, queueConfig.getName()); } }
0true
hazelcast_src_test_java_com_hazelcast_config_QueueConfigTest.java
1,448
new OResourcePoolListener<ODatabaseDocumentTx, OrientBaseGraph>() { @Override public OrientGraph createNewResource(final ODatabaseDocumentTx iKey, final Object... iAdditionalArgs) { return new OrientGraph(iKey); } @Override public boolean reuseResource(final ODatabaseDocumentTx iKey, final Object[] iAdditionalArgs, final OrientBaseGraph iReusedGraph) { iReusedGraph.reuse(iKey); return true; } });
0true
graphdb_src_main_java_com_orientechnologies_orient_graph_gremlin_OGremlinHelper.java
1,847
lockService.registerLockStoreConstructor(SERVICE_NAME, new ConstructorFunction<ObjectNamespace, LockStoreInfo>() { public LockStoreInfo createNew(final ObjectNamespace key) { final MapContainer mapContainer = getMapContainer(key.getObjectName()); return new LockStoreInfo() { public int getBackupCount() { return mapContainer.getBackupCount(); } public int getAsyncBackupCount() { return mapContainer.getAsyncBackupCount(); } }; } });
0true
hazelcast_src_main_java_com_hazelcast_map_MapService.java
161
@Test public class ShortSerializerTest { private static final int FIELD_SIZE = 2; private static final Short OBJECT = 1; private OShortSerializer shortSerializer; byte[] stream = new byte[FIELD_SIZE]; @BeforeClass public void beforeClass() { shortSerializer = new OShortSerializer(); } public void testFieldSize() { Assert.assertEquals(shortSerializer.getObjectSize(null), FIELD_SIZE); } public void testSerialize() { shortSerializer.serialize(OBJECT, stream, 0); Assert.assertEquals(shortSerializer.deserialize(stream, 0), OBJECT); } public void testSerializeNative() { shortSerializer.serializeNative(OBJECT, stream, 0); Assert.assertEquals(shortSerializer.deserializeNative(stream, 0), OBJECT); } public void testNativeDirectMemoryCompatibility() { shortSerializer.serializeNative(OBJECT, stream, 0); ODirectMemoryPointer pointer = new ODirectMemoryPointer(stream); try { Assert.assertEquals(shortSerializer.deserializeFromDirectMemory(pointer, 0), OBJECT); } finally { pointer.free(); } } }
0true
commons_src_test_java_com_orientechnologies_common_serialization_types_ShortSerializerTest.java
553
public final class OClusterPositionNodeId extends OClusterPosition { private static final ONodeId INVALID_NODE_ID = ONodeId.valueOf(-1); private final ONodeId nodeId; public ONodeId getNodeId() { return nodeId; } public OClusterPositionNodeId(ONodeId nodeId) { this.nodeId = nodeId; } @Override public OClusterPosition inc() { return new OClusterPositionNodeId(nodeId.add(ONodeId.ONE)); } @Override public OClusterPosition dec() { return new OClusterPositionNodeId(nodeId.subtract(ONodeId.ONE)); } @Override public boolean isValid() { return !nodeId.equals(INVALID_NODE_ID); } @Override public boolean isPersistent() { return nodeId.compareTo(INVALID_NODE_ID) > 0; } @Override public boolean isNew() { return nodeId.compareTo(ONodeId.ZERO) < 0; } @Override public boolean isTemporary() { return nodeId.compareTo(INVALID_NODE_ID) < 0; } @Override public byte[] toStream() { return nodeId.toStream(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OClusterPositionNodeId that = (OClusterPositionNodeId) o; return nodeId.equals(that.nodeId); } @Override public int hashCode() { return nodeId.hashCode(); } @Override public String toString() { return nodeId.toString(); } @Override public int compareTo(OClusterPosition o) { final OClusterPositionNodeId clusterPositionNodeId = (OClusterPositionNodeId) o; return nodeId.compareTo(clusterPositionNodeId.getNodeId()); } @Override public int intValue() { return nodeId.intValue(); } @Override public long longValue() { return nodeId.longValue(); } /** * This method return first part of NodeId content. * @return high long value from NodeId. */ @Override public long longValueHigh() { return nodeId.longValueHigh(); } @Override public float floatValue() { return nodeId.floatValue(); } @Override public double doubleValue() { return nodeId.doubleValue(); } }
0true
core_src_main_java_com_orientechnologies_orient_core_id_OClusterPositionNodeId.java
1,788
public class FilterMapping { public static final String RANGE_SPECIFIER_REGEX = "->"; protected String fullPropertyName; protected List<String> filterValues = new ArrayList<String>(); protected List directFilterValues = new ArrayList(); protected SortDirection sortDirection; protected Restriction restriction; protected FieldPath fieldPath; protected Class<?> inheritedFromClass; public FilterMapping withFullPropertyName(String fullPropertyName) { setFullPropertyName(fullPropertyName); return this; } public FilterMapping withFilterValues(List<String> filterValues) { setFilterValues(filterValues); return this; } public FilterMapping withDirectFilterValues(List directFilterValues) { setDirectFilterValues(directFilterValues); return this; } public FilterMapping withSortDirection(SortDirection sortDirection) { setSortDirection(sortDirection); return this; } public FilterMapping withRestriction(Restriction restriction) { setRestriction(restriction); return this; } public FilterMapping withFieldPath(FieldPath fieldPath) { setFieldPath(fieldPath); return this; } public FilterMapping withInheritedFromClass(Class<?> inheritedFromClass) { setInheritedFromClass(inheritedFromClass); return this; } public String getFullPropertyName() { return fullPropertyName; } public void setFullPropertyName(String fullPropertyName) { this.fullPropertyName = fullPropertyName; } public List<String> getFilterValues() { return filterValues; } public void setFilterValues(List<String> filterValues) { if (CollectionUtils.isNotEmpty(directFilterValues)) { throw new IllegalArgumentException("Cannot set both filter values and direct filter values"); } List<String> parsedValues = new ArrayList<String>(); for (String unfiltered : filterValues) { parsedValues.addAll(Arrays.asList(parseFilterValue(unfiltered))); } this.filterValues.addAll(parsedValues); } public SortDirection getSortDirection() { return sortDirection; } public void setSortDirection(SortDirection sortDirection) { this.sortDirection = sortDirection; } public Restriction getRestriction() { return restriction; } public void setRestriction(Restriction restriction) { this.restriction = restriction; } public FieldPath getFieldPath() { return fieldPath; } public void setFieldPath(FieldPath fieldPath) { this.fieldPath = fieldPath; } public List getDirectFilterValues() { return directFilterValues; } public void setDirectFilterValues(List directFilterValues) { if (CollectionUtils.isNotEmpty(filterValues)) { throw new IllegalArgumentException("Cannot set both filter values and direct filter values"); } this.directFilterValues = directFilterValues; } public Class<?> getInheritedFromClass() { return inheritedFromClass; } public void setInheritedFromClass(Class<?> inheritedFromClass) { this.inheritedFromClass = inheritedFromClass; } protected String[] parseFilterValue(String filterValue) { //We do it this way because the String.split() method will return only a single array member //when there is nothing on one side of the delimiter. We want to have two array members (one empty) //in this case. String[] vals; if (filterValue.contains(RANGE_SPECIFIER_REGEX)) { vals = new String[]{filterValue.substring(0, filterValue.indexOf(RANGE_SPECIFIER_REGEX)), filterValue.substring(filterValue.indexOf(RANGE_SPECIFIER_REGEX) + RANGE_SPECIFIER_REGEX.length(), filterValue.length())}; } else { vals = new String[]{filterValue}; } for (int j=0;j<vals.length;j++) { vals[j] = vals[j].trim(); } return vals; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_criteria_FilterMapping.java
324
public class FakeXAResource implements XAResource { private String name = null; private int transactionTimeout = 0; private ArrayList<MethodCall> methodCalls = new ArrayList<MethodCall>(); public FakeXAResource( String name ) { this.name = name; } public String getName() { return name; } @Override public String toString() { return name; } synchronized MethodCall[] getAndRemoveMethodCalls() { if ( methodCalls.size() > 0 ) { MethodCall methodCallArray[] = new MethodCall[methodCalls.size()]; methodCallArray = methodCalls.toArray( methodCallArray ); methodCalls = new ArrayList<MethodCall>(); return methodCallArray; } return new MethodCall[0]; } private synchronized void addMethodCall( MethodCall methodCall ) { methodCalls.add( methodCall ); } @Override public void commit( Xid xid, boolean onePhase ) { addMethodCall( new MethodCall( "commit", new Object[] { xid, new Boolean( onePhase ) }, new String[] { "javax.transaction.xa.Xid", "java.lang.Boolean" } ) ); } @Override public void end( Xid xid, int flags ) { addMethodCall( new MethodCall( "end", new Object[] { xid, new Integer( flags ) }, new String[] { "javax.transaction.xa.Xid", "java.lang.Integer" } ) ); } @Override public void forget( Xid xid ) { addMethodCall( new MethodCall( "forget", new Object[] { xid }, new String[] { "javax.transaction.xa.Xid" } ) ); } @Override public int getTransactionTimeout() { return transactionTimeout; } @Override public boolean setTransactionTimeout( int timeout ) { transactionTimeout = timeout; return true; } @Override public boolean isSameRM( XAResource xares ) { if ( xares instanceof FakeXAResource ) { if ( this.name.equals( ((FakeXAResource) xares).getName() ) ) { return true; } } return false; } @Override public int prepare( Xid xid ) { addMethodCall( new MethodCall( "prepare", new Object[] { xid }, new String[] { "javax.transaction.xa.Xid" } ) ); return XAResource.XA_OK; } @Override public Xid[] recover( int flag ) { addMethodCall( new MethodCall( "recover", new Object[] { new Integer( flag ) }, new String[] { "java.lang.Integer" } ) ); return new Xid[0]; } @Override public void rollback( Xid xid ) { addMethodCall( new MethodCall( "rollback", new Object[] { xid }, new String[] { "javax.transaction.xa.Xid" } ) ); } @Override public void start( Xid xid, int flags ) { addMethodCall( new MethodCall( "start", new Object[] { xid, new Integer( flags ) }, new String[] { "javax.transaction.xa.Xid", "java.lang.Integer" } ) ); } public static class FailingFakeXAResource extends FakeXAResource { private boolean failInCommit; public FailingFakeXAResource( String name, boolean failInCommit ) { super( name ); this.failInCommit = failInCommit; } @Override public void commit( Xid xid, boolean onePhase ) { if ( failInCommit ) { throw new RuntimeException( "I was told to fail" ); } super.commit( xid, onePhase ); } } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_FakeXAResource.java
24
final class DescendingSubMapKeyIterator extends SubMapIterator<K> { DescendingSubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) { super(last, fence); } public K next() { return prevEntry().getKey(); } public void remove() { removeDescending(); } }
0true
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
1,594
public class OSkippedOperationException extends OException { private static final long serialVersionUID = 1L; private final OAbstractRemoteTask task; public OSkippedOperationException(OAbstractRemoteTask iTask) { task = iTask; } public OAbstractRemoteTask getTask() { return task; } @Override public String toString() { return "OSkippedOperationException task=" + task; } }
0true
server_src_main_java_com_orientechnologies_orient_server_distributed_OSkippedOperationException.java
1,969
public class Nullability { private Nullability() { } public static boolean allowsNull(Annotation[] annotations) { for (Annotation a : annotations) { if ("Nullable".equals(a.annotationType().getSimpleName())) { return true; } } return false; } }
0true
src_main_java_org_elasticsearch_common_inject_internal_Nullability.java
1,324
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class ExecutorServiceTest extends HazelcastTestSupport { public static final int simpleTestNodeCount = 3; public static final int COUNT = 1000; private IExecutorService createSingleNodeExecutorService(String name) { return createSingleNodeExecutorService(name, ExecutorConfig.DEFAULT_POOL_SIZE); } private IExecutorService createSingleNodeExecutorService(String name, int poolSize) { final Config config = new Config(); config.addExecutorConfig(new ExecutorConfig(name, poolSize)); final HazelcastInstance instance = createHazelcastInstance(config); return instance.getExecutorService(name); } @Test public void testManagedContextAndLocal() throws Exception { final Config config = new Config(); config.addExecutorConfig(new ExecutorConfig("test", 1)); config.setManagedContext(new ManagedContext() { @Override public Object initialize(Object obj) { if (obj instanceof RunnableWithManagedContext) { RunnableWithManagedContext task = (RunnableWithManagedContext) obj; task.initializeCalled = true; } return obj; } }); final HazelcastInstance instance = createHazelcastInstance(config); IExecutorService executor = instance.getExecutorService("test"); RunnableWithManagedContext task = new RunnableWithManagedContext(); executor.submit(task).get(); assertTrue("The task should have been initialized by the ManagedContext", task.initializeCalled); } static class RunnableWithManagedContext implements Runnable { private volatile boolean initializeCalled = false; @Override public void run() { } } @Test public void hazelcastInstanceAwareAndLocal() throws Exception { final Config config = new Config(); config.addExecutorConfig(new ExecutorConfig("test", 1)); final HazelcastInstance instance = createHazelcastInstance(config); IExecutorService executor = instance.getExecutorService("test"); HazelcastInstanceAwareRunnable task = new HazelcastInstanceAwareRunnable(); executor.submit(task).get(); assertTrue("The setHazelcastInstance should have been called", task.initializeCalled); } static class HazelcastInstanceAwareRunnable implements Runnable, HazelcastInstanceAware { private volatile boolean initializeCalled = false; @Override public void run() { } @Override public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { initializeCalled = true; } } /** * Submit a null task must raise a NullPointerException */ @Test(expected = NullPointerException.class) public void submitNullTask() throws Exception { ExecutorService executor = createSingleNodeExecutorService("submitNullTask"); Callable c = null; executor.submit(c); } /** * Run a basic task */ @Test public void testBasicTask() throws Exception { Callable<String> task = new BasicTestTask(); ExecutorService executor = createSingleNodeExecutorService("testBasicTask"); Future future = executor.submit(task); assertEquals(future.get(), BasicTestTask.RESULT); } @Test public void testExecuteMultipleNode() throws InterruptedException, ExecutionException { final int k = simpleTestNodeCount; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(new Config()); for (int i = 0; i < k; i++) { final IExecutorService service = instances[i].getExecutorService("testExecuteMultipleNode"); final String script = "hazelcast.getAtomicLong('count').incrementAndGet();"; final int rand = new Random().nextInt(100); final Future<Integer> future = service.submit(new ScriptRunnable(script, null), rand); assertEquals(Integer.valueOf(rand), future.get()); } final IAtomicLong count = instances[0].getAtomicLong("count"); assertEquals(k, count.get()); } @Test public void testSubmitToKeyOwnerRunnable() throws InterruptedException { final int k = simpleTestNodeCount; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(new Config()); final AtomicInteger count = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(k); final ExecutionCallback callback = new ExecutionCallback() { public void onResponse(Object response) { if (response == null) count.incrementAndGet(); latch.countDown(); } public void onFailure(Throwable t) { } }; for (int i = 0; i < k; i++) { final HazelcastInstance instance = instances[i]; final IExecutorService service = instance.getExecutorService("testSubmitToKeyOwnerRunnable"); final String script = "if(!hazelcast.getCluster().getLocalMember().equals(member)) " + "hazelcast.getAtomicLong('testSubmitToKeyOwnerRunnable').incrementAndGet();"; final HashMap map = new HashMap(); map.put("member", instance.getCluster().getLocalMember()); int key = 0; while (!instance.getCluster().getLocalMember().equals(instance.getPartitionService().getPartition(++key).getOwner())) { Thread.sleep(1); } service.submitToKeyOwner(new ScriptRunnable(script, map), key, callback); } latch.await(10, TimeUnit.SECONDS); assertEquals(0, instances[0].getAtomicLong("testSubmitToKeyOwnerRunnable").get()); assertEquals(k, count.get()); } @Test public void testSubmitToMemberRunnable() throws InterruptedException { final int k = simpleTestNodeCount; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(new Config()); final AtomicInteger count = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(k); final ExecutionCallback callback = new ExecutionCallback() { public void onResponse(Object response) { if (response == null) { count.incrementAndGet(); } latch.countDown(); } public void onFailure(Throwable t) { } }; for (int i = 0; i < k; i++) { final HazelcastInstance instance = instances[i]; final IExecutorService service = instance.getExecutorService("testSubmitToMemberRunnable"); final String script = "if(!hazelcast.getCluster().getLocalMember().equals(member)) " + "hazelcast.getAtomicLong('testSubmitToMemberRunnable').incrementAndGet();"; final HashMap map = new HashMap(); map.put("member", instance.getCluster().getLocalMember()); service.submitToMember(new ScriptRunnable(script, map), instance.getCluster().getLocalMember(), callback); } latch.await(10, TimeUnit.SECONDS); assertEquals(0, instances[0].getAtomicLong("testSubmitToMemberRunnable").get()); assertEquals(k, count.get()); } @Test public void testSubmitToMembersRunnable() throws InterruptedException { final int k = simpleTestNodeCount; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(new Config()); final AtomicInteger count = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(k); final MultiExecutionCallback callback = new MultiExecutionCallback() { public void onResponse(Member member, Object value) { count.incrementAndGet(); } public void onComplete(Map<Member, Object> values) { latch.countDown(); } }; int sum = 0; final Set<Member> membersSet = instances[0].getCluster().getMembers(); final Member[] members = membersSet.toArray(new Member[membersSet.size()]); final Random random = new Random(); for (int i = 0; i < k; i++) { final IExecutorService service = instances[i].getExecutorService("testSubmitToMembersRunnable"); final String script = "hazelcast.getAtomicLong('testSubmitToMembersRunnable').incrementAndGet();"; final int n = random.nextInt(k) + 1; sum += n; Member[] m = new Member[n]; System.arraycopy(members, 0, m, 0, n); service.submitToMembers(new ScriptRunnable(script, null), Arrays.asList(m), callback); } assertTrue(latch.await(30, TimeUnit.SECONDS)); final IAtomicLong result = instances[0].getAtomicLong("testSubmitToMembersRunnable"); assertEquals(sum, result.get()); assertEquals(sum, count.get()); } @Test public void testSubmitToAllMembersRunnable() throws InterruptedException { final int k = simpleTestNodeCount; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(new Config()); final AtomicInteger count = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(k * k); final MultiExecutionCallback callback = new MultiExecutionCallback() { public void onResponse(Member member, Object value) { if (value == null) count.incrementAndGet(); latch.countDown(); } public void onComplete(Map<Member, Object> values) { } }; for (int i = 0; i < k; i++) { final IExecutorService service = instances[i].getExecutorService("testSubmitToAllMembersRunnable"); final String script = "hazelcast.getAtomicLong('testSubmitToAllMembersRunnable').incrementAndGet();"; service.submitToAllMembers(new ScriptRunnable(script, null), callback); } assertTrue(latch.await(30, TimeUnit.SECONDS)); final IAtomicLong result = instances[0].getAtomicLong("testSubmitToAllMembersRunnable"); assertEquals(k * k, result.get()); assertEquals(k * k, count.get()); } @Test public void testSubmitMultipleNode() throws ExecutionException, InterruptedException { final int k = simpleTestNodeCount; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(new Config()); for (int i = 0; i < k; i++) { final IExecutorService service = instances[i].getExecutorService("testSubmitMultipleNode"); final String script = "hazelcast.getAtomicLong('testSubmitMultipleNode').incrementAndGet();"; final Future future = service.submit(new ScriptCallable(script, null)); assertEquals((long) (i + 1), future.get()); } } @Test @Category(ProblematicTest.class) public void testSubmitToKeyOwnerCallable() throws Exception { final int k = simpleTestNodeCount; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(new Config()); final AtomicInteger count = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(k / 2); final ExecutionCallback callback = new ExecutionCallback() { public void onResponse(Object response) { if ((Boolean) response) count.incrementAndGet(); latch.countDown(); } public void onFailure(Throwable t) { } }; for (int i = 0; i < k; i++) { final HazelcastInstance instance = instances[i]; final IExecutorService service = instance.getExecutorService("testSubmitToKeyOwnerCallable"); final String script = "hazelcast.getCluster().getLocalMember().equals(member)"; final HashMap map = new HashMap(); final Member localMember = instance.getCluster().getLocalMember(); map.put("member", localMember); int key = 0; while (!localMember.equals(instance.getPartitionService().getPartition(++key).getOwner())) ; if (i % 2 == 0) { final Future f = service.submitToKeyOwner(new ScriptCallable(script, map), key); assertTrue((Boolean) f.get(60, TimeUnit.SECONDS)); } else { service.submitToKeyOwner(new ScriptCallable(script, map), key, callback); } } assertOpenEventually(latch); assertEquals(k / 2, count.get()); } @Test @Category(ProblematicTest.class) public void testSubmitToMemberCallable() throws ExecutionException, InterruptedException, TimeoutException { final int k = simpleTestNodeCount; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(new Config()); final AtomicInteger count = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(k / 2); final ExecutionCallback callback = new ExecutionCallback() { public void onResponse(Object response) { if ((Boolean) response) count.incrementAndGet(); latch.countDown(); } public void onFailure(Throwable t) { } }; for (int i = 0; i < k; i++) { final HazelcastInstance instance = instances[i]; final IExecutorService service = instance.getExecutorService("testSubmitToMemberCallable"); final String script = "hazelcast.getCluster().getLocalMember().equals(member); "; final HashMap map = new HashMap(); map.put("member", instance.getCluster().getLocalMember()); if (i % 2 == 0) { final Future f = service.submitToMember(new ScriptCallable(script, map), instance.getCluster().getLocalMember()); assertTrue((Boolean) f.get(5, TimeUnit.SECONDS)); } else { service.submitToMember(new ScriptCallable(script, map), instance.getCluster().getLocalMember(), callback); } } assertTrue(latch.await(30, TimeUnit.SECONDS)); assertEquals(k / 2, count.get()); } @Test public void testSubmitToMembersCallable() throws InterruptedException { final int k = simpleTestNodeCount; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(new Config()); final AtomicInteger count = new AtomicInteger(0); final CountDownLatch latch = new CountDownLatch(k); final MultiExecutionCallback callback = new MultiExecutionCallback() { public void onResponse(Member member, Object value) { count.incrementAndGet(); } public void onComplete(Map<Member, Object> values) { latch.countDown(); } }; int sum = 0; final Set<Member> membersSet = instances[0].getCluster().getMembers(); final Member[] members = membersSet.toArray(new Member[membersSet.size()]); final Random random = new Random(); final String name = "testSubmitToMembersCallable"; for (int i = 0; i < k; i++) { final IExecutorService service = instances[i].getExecutorService(name); final String script = "hazelcast.getAtomicLong('" + name + "').incrementAndGet();"; final int n = random.nextInt(k) + 1; sum += n; Member[] m = new Member[n]; System.arraycopy(members, 0, m, 0, n); service.submitToMembers(new ScriptCallable(script, null), Arrays.asList(m), callback); } assertTrue(latch.await(30, TimeUnit.SECONDS)); final IAtomicLong result = instances[0].getAtomicLong(name); assertEquals(sum, result.get()); assertEquals(sum, count.get()); } @Test public void testSubmitToAllMembersCallable() throws InterruptedException { final int k = simpleTestNodeCount; TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k); final HazelcastInstance[] instances = factory.newInstances(new Config()); final AtomicInteger count = new AtomicInteger(0); final CountDownLatch countDownLatch = new CountDownLatch(k * k); final MultiExecutionCallback callback = new MultiExecutionCallback() { public void onResponse(Member member, Object value) { count.incrementAndGet(); countDownLatch.countDown(); } public void onComplete(Map<Member, Object> values) { } }; for (int i = 0; i < k; i++) { final IExecutorService service = instances[i].getExecutorService("testSubmitToAllMembersCallable"); final String script = "hazelcast.getAtomicLong('testSubmitToAllMembersCallable').incrementAndGet();"; service.submitToAllMembers(new ScriptCallable(script, null), callback); } countDownLatch.await(30, TimeUnit.SECONDS); final IAtomicLong result = instances[0].getAtomicLong("testSubmitToAllMembersCallable"); assertEquals(k * k, result.get()); assertEquals(k * k, count.get()); } @Test public void testIssue292() throws Exception { final BlockingQueue qResponse = new ArrayBlockingQueue(1); createSingleNodeExecutorService("testIssue292").submit(new MemberCheck(), new ExecutionCallback<Member>() { public void onResponse(Member response) { qResponse.offer(response); } public void onFailure(Throwable t) { } }); Object response = qResponse.poll(10, TimeUnit.SECONDS); assertNotNull(response); assertTrue(response instanceof Member); } @Test public void testCancellationAwareTask() throws ExecutionException, InterruptedException { SleepingTask task = new SleepingTask(5000); ExecutorService executor = createSingleNodeExecutorService("testCancellationAwareTask"); Future future = executor.submit(task); try { future.get(2, TimeUnit.SECONDS); fail("Should throw TimeoutException!"); } catch (TimeoutException expected) { } assertFalse(future.isDone()); assertTrue(future.cancel(true)); assertTrue(future.isCancelled()); assertTrue(future.isDone()); try { future.get(); fail("Should not complete the task successfully"); } catch (CancellationException expected) { } catch (Exception e) { fail("Unexpected exception " + e); } } @Test public void testCancellationAwareTask2() { Callable task1 = new SleepingTask(5000); ExecutorService executor = createSingleNodeExecutorService("testCancellationAwareTask", 1); executor.submit(task1); Callable task2 = new BasicTestTask(); Future future = executor.submit(task2); assertFalse(future.isDone()); assertTrue(future.cancel(true)); assertTrue(future.isCancelled()); assertTrue(future.isDone()); try { future.get(); fail("Should not complete the task successfully"); } catch (CancellationException expected) { } catch (Exception e) { fail("Unexpected exception " + e); } } /** * Test the method isDone() */ @Test public void testIsDoneMethod() throws Exception { Callable<String> task = new BasicTestTask(); IExecutorService executor = createSingleNodeExecutorService("isDoneMethod"); Future future = executor.submit(task); if (future.isDone()) { assertTrue(future.isDone()); } assertEquals(future.get(), BasicTestTask.RESULT); assertTrue(future.isDone()); } /** * Test for the issue 129. * Repeatedly runs tasks and check for isDone() status after * get(). */ @Test public void testIsDoneMethod2() throws Exception { ExecutorService executor = createSingleNodeExecutorService("isDoneMethod2"); for (int i = 0; i < COUNT; i++) { Callable<String> task1 = new BasicTestTask(); Callable<String> task2 = new BasicTestTask(); Future future1 = executor.submit(task1); Future future2 = executor.submit(task2); assertEquals(future2.get(), BasicTestTask.RESULT); assertTrue(future2.isDone()); assertEquals(future1.get(), BasicTestTask.RESULT); assertTrue(future1.isDone()); } } /** * Test the Execution Callback */ @Test public void testExecutionCallback() throws Exception { Callable<String> task = new BasicTestTask(); IExecutorService executor = createSingleNodeExecutorService("testExecutionCallback"); final CountDownLatch latch = new CountDownLatch(1); final ExecutionCallback executionCallback = new ExecutionCallback() { public void onResponse(Object response) { latch.countDown(); } public void onFailure(Throwable t) { } }; executor.submit(task, executionCallback); assertTrue(latch.await(2, TimeUnit.SECONDS)); } /** * Execute a task that is executing * something else inside. Nested Execution. */ @Test(timeout = 10000) public void testNestedExecution() throws Exception { Callable<String> task = new NestedExecutorTask(); ExecutorService executor = createSingleNodeExecutorService("testNestedExecution"); Future future = executor.submit(task); future.get(); } /** * Test multiple Future.get() invocation */ @Test public void testMultipleFutureGets() throws Exception { Callable<String> task = new BasicTestTask(); ExecutorService executor = createSingleNodeExecutorService("isTwoGetFromFuture"); Future<String> future = executor.submit(task); String s1 = future.get(); assertEquals(s1, BasicTestTask.RESULT); assertTrue(future.isDone()); String s2 = future.get(); assertEquals(s2, BasicTestTask.RESULT); assertTrue(future.isDone()); String s3 = future.get(); assertEquals(s3, BasicTestTask.RESULT); assertTrue(future.isDone()); String s4 = future.get(); assertEquals(s4, BasicTestTask.RESULT); assertTrue(future.isDone()); } /** * invokeAll tests */ @Test public void testInvokeAll() throws Exception { ExecutorService executor = createSingleNodeExecutorService("testInvokeAll"); assertFalse(executor.isShutdown()); // Only one task ArrayList<Callable<String>> tasks = new ArrayList<Callable<String>>(); tasks.add(new BasicTestTask()); List<Future<String>> futures = executor.invokeAll(tasks); assertEquals(futures.size(), 1); assertEquals(futures.get(0).get(), BasicTestTask.RESULT); // More tasks tasks.clear(); for (int i = 0; i < COUNT; i++) { tasks.add(new BasicTestTask()); } futures = executor.invokeAll(tasks); assertEquals(futures.size(), COUNT); for (int i = 0; i < COUNT; i++) { assertEquals(futures.get(i).get(), BasicTestTask.RESULT); } } @Test public void testInvokeAllTimeoutCancelled() throws Exception { ExecutorService executor = createSingleNodeExecutorService("testInvokeAll"); assertFalse(executor.isShutdown()); // Only one task ArrayList<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>(); tasks.add(new SleepingTask(0)); List<Future<Boolean>> futures = executor.invokeAll(tasks, 5, TimeUnit.SECONDS); assertEquals(futures.size(), 1); assertEquals(futures.get(0).get(), Boolean.TRUE); // More tasks tasks.clear(); for (int i = 0; i < COUNT; i++) { tasks.add(new SleepingTask(i < 2 ? 0 : 20000)); } futures = executor.invokeAll(tasks, 5, TimeUnit.SECONDS); assertEquals(futures.size(), COUNT); for (int i = 0; i < COUNT; i++) { if (i < 2) { assertEquals(futures.get(i).get(), Boolean.TRUE); } else { boolean excepted = false; try { futures.get(i).get(); } catch (CancellationException e) { excepted = true; } assertTrue(excepted); } } } @Test public void testInvokeAllTimeoutSuccess() throws Exception { ExecutorService executor = createSingleNodeExecutorService("testInvokeAll"); assertFalse(executor.isShutdown()); // Only one task ArrayList<Callable<String>> tasks = new ArrayList<Callable<String>>(); tasks.add(new BasicTestTask()); List<Future<String>> futures = executor.invokeAll(tasks, 5, TimeUnit.SECONDS); assertEquals(futures.size(), 1); assertEquals(futures.get(0).get(), BasicTestTask.RESULT); // More tasks tasks.clear(); for (int i = 0; i < COUNT; i++) { tasks.add(new BasicTestTask()); } futures = executor.invokeAll(tasks, 5, TimeUnit.SECONDS); assertEquals(futures.size(), COUNT); for (int i = 0; i < COUNT; i++) { assertEquals(futures.get(i).get(), BasicTestTask.RESULT); } } /** * Shutdown-related method behaviour when the cluster is running */ @Test public void testShutdownBehaviour() throws Exception { ExecutorService executor = createSingleNodeExecutorService("testShutdownBehaviour"); // Fresh instance, is not shutting down assertFalse(executor.isShutdown()); assertFalse(executor.isTerminated()); executor.shutdown(); assertTrue(executor.isShutdown()); assertTrue(executor.isTerminated()); // shutdownNow() should return an empty list and be ignored List<Runnable> pending = executor.shutdownNow(); assertTrue(pending.isEmpty()); assertTrue(executor.isShutdown()); assertTrue(executor.isTerminated()); // awaitTermination() should return immediately false try { boolean terminated = executor.awaitTermination(60L, TimeUnit.SECONDS); assertFalse(terminated); } catch (InterruptedException ie) { fail("InterruptedException"); } assertTrue(executor.isShutdown()); assertTrue(executor.isTerminated()); } /** * Shutting down the cluster should act as the ExecutorService shutdown */ @Test(expected = RejectedExecutionException.class) public void testClusterShutdown() throws Exception { ExecutorService executor = createSingleNodeExecutorService("testClusterShutdown"); shutdownNodeFactory(); Thread.sleep(2000); assertNotNull(executor); assertTrue(executor.isShutdown()); assertTrue(executor.isTerminated()); // New tasks must be rejected Callable<String> task = new BasicTestTask(); executor.submit(task); } @Test public void testStatsIssue2039() throws InterruptedException, ExecutionException, TimeoutException { final Config config = new Config(); final String name = "testStatsIssue2039"; config.addExecutorConfig(new ExecutorConfig(name).setQueueCapacity(1).setPoolSize(1)); final HazelcastInstance instance = createHazelcastInstance(config); final IExecutorService executorService = instance.getExecutorService(name); final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch sleepLatch = new CountDownLatch(1); executorService.execute(new Runnable() { @Override public void run() { startLatch.countDown(); assertOpenEventually(sleepLatch); } }); assertTrue(startLatch.await(30, TimeUnit.SECONDS)); final Future waitingInQueue = executorService.submit(new Runnable() { public void run() { } }); final Future rejected = executorService.submit(new Runnable() { public void run() { } }); try { rejected.get(1, TimeUnit.MINUTES); } catch (Exception e) { boolean isRejected = e.getCause() instanceof RejectedExecutionException; if (!isRejected) { fail(e.toString()); } } finally { sleepLatch.countDown(); } waitingInQueue.get(1, TimeUnit.MINUTES); final LocalExecutorStats stats = executorService.getLocalExecutorStats(); assertEquals(2, stats.getStartedTaskCount()); assertEquals(0, stats.getPendingTaskCount()); } @Test public void testExecutorServiceStats() throws InterruptedException, ExecutionException { final IExecutorService executorService = createSingleNodeExecutorService("testExecutorServiceStats"); final int k = 10; final CountDownLatch latch = new CountDownLatch(k); final int executionTime = 200; for (int i = 0; i < k; i++) { executorService.execute(new Runnable() { public void run() { try { Thread.sleep(executionTime); } catch (InterruptedException e) { e.printStackTrace(); } latch.countDown(); } }); } latch.await(2, TimeUnit.MINUTES); final Future<Boolean> f = executorService.submit(new SleepingTask(10000)); Thread.sleep(1000); f.cancel(true); try { f.get(); } catch (CancellationException e) { } final LocalExecutorStats stats = executorService.getLocalExecutorStats(); assertEquals(k + 1, stats.getStartedTaskCount()); assertEquals(k, stats.getCompletedTaskCount()); assertEquals(0, stats.getPendingTaskCount()); assertEquals(1, stats.getCancelledTaskCount()); } @Test public void testPreregisteredExecutionCallbackCompletableFuture() throws Exception { HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) createHazelcastInstance(); Field originalField = HazelcastInstanceProxy.class.getDeclaredField("original"); originalField.setAccessible(true); HazelcastInstanceImpl hz = (HazelcastInstanceImpl) originalField.get(proxy); NodeEngine nodeEngine = hz.node.nodeEngine; ExecutionService es = nodeEngine.getExecutionService(); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); final ExecutorService executorService = Executors.newSingleThreadExecutor(); try { Future future = executorService.submit(new Callable<String>() { @Override public String call() { try { latch1.await(30, TimeUnit.SECONDS); return "success"; } catch (Exception e) { throw new RuntimeException(e); } } }); final AtomicReference reference = new AtomicReference(); final ICompletableFuture completableFuture = es.asCompletableFuture(future); completableFuture.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { reference.set(response); latch2.countDown(); } @Override public void onFailure(Throwable t) { reference.set(t); latch2.countDown(); } }); latch1.countDown(); latch2.await(30, TimeUnit.SECONDS); assertEquals("success", reference.get()); } finally { executorService.shutdown(); } } @Test public void testMultiPreregisteredExecutionCallbackCompletableFuture() throws Exception { HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) createHazelcastInstance(); Field originalField = HazelcastInstanceProxy.class.getDeclaredField("original"); originalField.setAccessible(true); HazelcastInstanceImpl hz = (HazelcastInstanceImpl) originalField.get(proxy); NodeEngine nodeEngine = hz.node.nodeEngine; ExecutionService es = nodeEngine.getExecutionService(); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(2); final ExecutorService executorService = Executors.newSingleThreadExecutor(); try { Future future = executorService.submit(new Callable<String>() { @Override public String call() { try { latch1.await(30, TimeUnit.SECONDS); return "success"; } catch (Exception e) { throw new RuntimeException(e); } } }); final AtomicReference reference1 = new AtomicReference(); final AtomicReference reference2 = new AtomicReference(); final ICompletableFuture completableFuture = es.asCompletableFuture(future); completableFuture.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { reference1.set(response); latch2.countDown(); } @Override public void onFailure(Throwable t) { reference1.set(t); latch2.countDown(); } }); completableFuture.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { reference2.set(response); latch2.countDown(); } @Override public void onFailure(Throwable t) { reference2.set(t); latch2.countDown(); } }); latch1.countDown(); latch2.await(30, TimeUnit.SECONDS); assertEquals("success", reference1.get()); assertEquals("success", reference2.get()); } finally { executorService.shutdown(); } } @Test public void testPostregisteredExecutionCallbackCompletableFuture() throws Exception { HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) createHazelcastInstance(); Field originalField = HazelcastInstanceProxy.class.getDeclaredField("original"); originalField.setAccessible(true); HazelcastInstanceImpl hz = (HazelcastInstanceImpl) originalField.get(proxy); NodeEngine nodeEngine = hz.node.nodeEngine; ExecutionService es = nodeEngine.getExecutionService(); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); final ExecutorService executorService = Executors.newSingleThreadExecutor(); try { Future future = executorService.submit(new Callable<String>() { @Override public String call() { try { return "success"; } finally { latch1.countDown(); } } }); final ICompletableFuture completableFuture = es.asCompletableFuture(future); latch1.await(30, TimeUnit.SECONDS); final AtomicReference reference = new AtomicReference(); completableFuture.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { reference.set(response); latch2.countDown(); } @Override public void onFailure(Throwable t) { reference.set(t); latch2.countDown(); } }); latch2.await(30, TimeUnit.SECONDS); if (reference.get() instanceof Throwable) { ((Throwable) reference.get()).printStackTrace(); } assertEquals("success", reference.get()); } finally { executorService.shutdown(); } } @Test public void testMultiPostregisteredExecutionCallbackCompletableFuture() throws Exception { HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) createHazelcastInstance(); Field originalField = HazelcastInstanceProxy.class.getDeclaredField("original"); originalField.setAccessible(true); HazelcastInstanceImpl hz = (HazelcastInstanceImpl) originalField.get(proxy); NodeEngine nodeEngine = hz.node.nodeEngine; ExecutionService es = nodeEngine.getExecutionService(); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(2); final ExecutorService executorService = Executors.newSingleThreadExecutor(); try { Future future = executorService.submit(new Callable<String>() { @Override public String call() { try { return "success"; } finally { latch1.countDown(); } } }); latch1.await(30, TimeUnit.SECONDS); final AtomicReference reference1 = new AtomicReference(); final AtomicReference reference2 = new AtomicReference(); final ICompletableFuture completableFuture = es.asCompletableFuture(future); completableFuture.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { reference1.set(response); latch2.countDown(); } @Override public void onFailure(Throwable t) { reference1.set(t); latch2.countDown(); } }); completableFuture.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { reference2.set(response); latch2.countDown(); } @Override public void onFailure(Throwable t) { reference2.set(t); latch2.countDown(); } }); latch2.await(30, TimeUnit.SECONDS); assertEquals("success", reference1.get()); assertEquals("success", reference2.get()); } finally { executorService.shutdown(); } } @Test public void testManagedPreregisteredExecutionCallbackCompletableFuture() throws Exception { HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) createHazelcastInstance(); Field originalField = HazelcastInstanceProxy.class.getDeclaredField("original"); originalField.setAccessible(true); HazelcastInstanceImpl hz = (HazelcastInstanceImpl) originalField.get(proxy); NodeEngine nodeEngine = hz.node.nodeEngine; ExecutionService es = nodeEngine.getExecutionService(); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); Future future = es.submit("default", new Callable<String>() { @Override public String call() { try { latch1.await(30, TimeUnit.SECONDS); return "success"; } catch (Exception e) { throw new RuntimeException(e); } } }); final AtomicReference reference = new AtomicReference(); final ICompletableFuture completableFuture = es.asCompletableFuture(future); completableFuture.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { reference.set(response); latch2.countDown(); } @Override public void onFailure(Throwable t) { reference.set(t); latch2.countDown(); } }); latch1.countDown(); latch2.await(30, TimeUnit.SECONDS); assertEquals("success", reference.get()); } @Test public void testManagedMultiPreregisteredExecutionCallbackCompletableFuture() throws Exception { HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) createHazelcastInstance(); Field originalField = HazelcastInstanceProxy.class.getDeclaredField("original"); originalField.setAccessible(true); HazelcastInstanceImpl hz = (HazelcastInstanceImpl) originalField.get(proxy); NodeEngine nodeEngine = hz.node.nodeEngine; ExecutionService es = nodeEngine.getExecutionService(); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(2); Future future = es.submit("default", new Callable<String>() { @Override public String call() { try { latch1.await(30, TimeUnit.SECONDS); return "success"; } catch (Exception e) { throw new RuntimeException(e); } } }); final AtomicReference reference1 = new AtomicReference(); final AtomicReference reference2 = new AtomicReference(); final ICompletableFuture completableFuture = es.asCompletableFuture(future); completableFuture.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { reference1.set(response); latch2.countDown(); } @Override public void onFailure(Throwable t) { reference1.set(t); latch2.countDown(); } }); completableFuture.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { reference2.set(response); latch2.countDown(); } @Override public void onFailure(Throwable t) { reference2.set(t); latch2.countDown(); } }); latch1.countDown(); latch2.await(30, TimeUnit.SECONDS); assertEquals("success", reference1.get()); assertEquals("success", reference2.get()); } @Test public void testManagedPostregisteredExecutionCallbackCompletableFuture() throws Exception { HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) createHazelcastInstance(); Field originalField = HazelcastInstanceProxy.class.getDeclaredField("original"); originalField.setAccessible(true); HazelcastInstanceImpl hz = (HazelcastInstanceImpl) originalField.get(proxy); NodeEngine nodeEngine = hz.node.nodeEngine; ExecutionService es = nodeEngine.getExecutionService(); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); Future future = es.submit("default", new Callable<String>() { @Override public String call() { try { return "success"; } finally { latch1.countDown(); } } }); latch1.await(30, TimeUnit.SECONDS); final AtomicReference reference = new AtomicReference(); final ICompletableFuture completableFuture = es.asCompletableFuture(future); completableFuture.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { reference.set(response); latch2.countDown(); } @Override public void onFailure(Throwable t) { reference.set(t); latch2.countDown(); } }); latch2.await(30, TimeUnit.SECONDS); assertEquals("success", reference.get()); } @Test public void testManagedMultiPostregisteredExecutionCallbackCompletableFuture() throws Exception { HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) createHazelcastInstance(); Field originalField = HazelcastInstanceProxy.class.getDeclaredField("original"); originalField.setAccessible(true); HazelcastInstanceImpl hz = (HazelcastInstanceImpl) originalField.get(proxy); NodeEngine nodeEngine = hz.node.nodeEngine; ExecutionService es = nodeEngine.getExecutionService(); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(2); Future future = es.submit("default", new Callable<String>() { @Override public String call() { try { return "success"; } finally { latch1.countDown(); } } }); latch1.await(30, TimeUnit.SECONDS); final AtomicReference reference1 = new AtomicReference(); final AtomicReference reference2 = new AtomicReference(); final ICompletableFuture completableFuture = es.asCompletableFuture(future); completableFuture.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { reference1.set(response); latch2.countDown(); } @Override public void onFailure(Throwable t) { reference1.set(t); latch2.countDown(); } }); completableFuture.andThen(new ExecutionCallback() { @Override public void onResponse(Object response) { reference2.set(response); latch2.countDown(); } @Override public void onFailure(Throwable t) { reference2.set(t); latch2.countDown(); } }); latch2.await(30, TimeUnit.SECONDS); assertEquals("success", reference1.get()); assertEquals("success", reference2.get()); } @Test public void testLongRunningCallable() throws ExecutionException, InterruptedException, TimeoutException { TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2); Config config = new Config(); long callTimeout = 3000; config.setProperty(GroupProperties.PROP_OPERATION_CALL_TIMEOUT_MILLIS, String.valueOf(callTimeout)); HazelcastInstance hz1 = factory.newHazelcastInstance(config); HazelcastInstance hz2 = factory.newHazelcastInstance(config); IExecutorService executor = hz1.getExecutorService("test"); Future<Boolean> f = executor .submitToMember(new SleepingTask(callTimeout * 3), hz2.getCluster().getLocalMember()); Boolean result = f.get(1, TimeUnit.MINUTES); assertTrue(result); } private static class ScriptRunnable implements Runnable, Serializable, HazelcastInstanceAware { private final String script; private final Map<String, Object> map; private transient HazelcastInstance hazelcastInstance; ScriptRunnable(String script, Map<String, Object> map) { this.script = script; this.map = map; } public void run() { final ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine e = scriptEngineManager.getEngineByName("javascript"); if (map != null) { for (Map.Entry<String, Object> entry : map.entrySet()) { e.put(entry.getKey(), entry.getValue()); } } e.put("hazelcast", hazelcastInstance); try { // For new JavaScript engine called Nashorn we need the compatibility script if (e.getFactory().getEngineName().toLowerCase().contains("nashorn")) { e.eval("load('nashorn:mozilla_compat.js');"); } e.eval("importPackage(java.lang);"); e.eval("importPackage(java.util);"); e.eval("importPackage(com.hazelcast.core);"); e.eval("importPackage(com.hazelcast.config);"); e.eval("importPackage(java.util.concurrent);"); e.eval("importPackage(org.junit);"); e.eval(script); } catch (ScriptException e1) { e1.printStackTrace(); } } public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { this.hazelcastInstance = hazelcastInstance; } } private static class ScriptCallable implements Callable, Serializable, HazelcastInstanceAware { private final String script; private final Map<String, Object> map; private transient HazelcastInstance hazelcastInstance; ScriptCallable(String script, Map<String, Object> map) { this.script = script; this.map = map; } public Object call() { final ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine e = scriptEngineManager.getEngineByName("javascript"); if (map != null) { for (Map.Entry<String, Object> entry : map.entrySet()) { e.put(entry.getKey(), entry.getValue()); } } e.put("hazelcast", hazelcastInstance); try { // For new JavaScript engine called Nashorn we need the compatibility script if (e.getFactory().getEngineName().toLowerCase().contains("nashorn")) { e.eval("load('nashorn:mozilla_compat.js');"); } e.eval("importPackage(java.lang);"); e.eval("importPackage(java.util);"); e.eval("importPackage(com.hazelcast.core);"); e.eval("importPackage(com.hazelcast.config);"); e.eval("importPackage(java.util.concurrent);"); e.eval("importPackage(org.junit);"); return e.eval(script); } catch (ScriptException e1) { throw new RuntimeException(e1); } } public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { this.hazelcastInstance = hazelcastInstance; } } public static class BasicTestTask implements Callable<String>, Serializable { public static String RESULT = "Task completed"; public String call() throws Exception { return RESULT; } } public static class SleepingTask implements Callable<Boolean>, Serializable { long sleepTime = 10000; public SleepingTask(long sleepTime) { this.sleepTime = sleepTime; } public Boolean call() throws InterruptedException { Thread.sleep(sleepTime); return Boolean.TRUE; } } public static class NestedExecutorTask implements Callable<String>, Serializable, HazelcastInstanceAware { private HazelcastInstance instance; public String call() throws Exception { Future future = instance.getExecutorService("NestedExecutorTask").submit(new BasicTestTask()); return (String) future.get(); } @Override public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { instance = hazelcastInstance; } } public static class MemberCheck implements Callable<Member>, Serializable, HazelcastInstanceAware { private Member localMember; public Member call() throws Exception { return localMember; } @Override public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { localMember = hazelcastInstance.getCluster().getLocalMember(); } } }
0true
hazelcast_src_test_java_com_hazelcast_executor_ExecutorServiceTest.java
2,381
GIGA { @Override public long toSingles(long size) { return x(size, C3 / C0, MAX / (C3 / C0)); } @Override public long toKilo(long size) { return x(size, C3 / C1, MAX / (C3 / C1)); } @Override public long toMega(long size) { return x(size, C3 / C2, MAX / (C3 / C2)); } @Override public long toGiga(long size) { return size; } @Override public long toTera(long size) { return size / (C4 / C3); } @Override public long toPeta(long size) { return size / (C5 / C3); } },
0true
src_main_java_org_elasticsearch_common_unit_SizeUnit.java
166
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { public sun.misc.Unsafe run() throws Exception { Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; for (java.lang.reflect.Field f : k.getDeclaredFields()) { f.setAccessible(true); Object x = f.get(null); if (k.isInstance(x)) return k.cast(x); } throw new NoSuchFieldError("the Unsafe"); }});
0true
src_main_java_jsr166y_ForkJoinPool.java
1,285
public class DataPropagationTask implements Callable<Void> { private ODatabaseDocumentTx baseDB; private ODatabaseDocumentTx testDB; public DataPropagationTask(ODatabaseDocumentTx baseDB, ODatabaseDocumentTx testDocumentTx) { this.baseDB = new ODatabaseDocumentTx(baseDB.getURL()); this.testDB = new ODatabaseDocumentTx(testDocumentTx.getURL()); } @Override public Void call() throws Exception { Random random = new Random(); baseDB.open("admin", "admin"); testDB.open("admin", "admin"); try { while (true) { final ODocument document = new ODocument("TestClass"); document.field("id", idGen.incrementAndGet()); document.field("timestamp", System.currentTimeMillis()); document.field("stringValue", "sfe" + random.nextLong()); saveDoc(document); } } finally { baseDB.close(); testDB.close(); } } private void saveDoc(ODocument document) { ODatabaseRecordThreadLocal.INSTANCE.set(baseDB); ODocument testDoc = new ODocument(); document.copyTo(testDoc); document.save(); ODatabaseRecordThreadLocal.INSTANCE.set(testDB); testDoc.save(); ODatabaseRecordThreadLocal.INSTANCE.set(baseDB); } }
0true
server_src_test_java_com_orientechnologies_orient_core_storage_impl_local_paginated_LocalPaginatedStorageCreateCrashRestore.java
1,326
public interface ProcessedClusterStateUpdateTask extends ClusterStateUpdateTask { /** * Called when the result of the {@link #execute(ClusterState)} have been processed * properly by all listeners. */ void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState); }
0true
src_main_java_org_elasticsearch_cluster_ProcessedClusterStateUpdateTask.java
323
public class MixedConfiguration extends AbstractConfiguration { private final ReadConfiguration global; private final ReadConfiguration local; public MixedConfiguration(ConfigNamespace root, ReadConfiguration global, ReadConfiguration local) { super(root); Preconditions.checkNotNull(global); Preconditions.checkNotNull(local); this.global = global; this.local = local; } @Override public boolean has(ConfigOption option, String... umbrellaElements) { String key = super.getPath(option,umbrellaElements); if (option.isLocal() && local.get(key,option.getDatatype())!=null) return true; if (option.isGlobal() && global.get(key,option.getDatatype())!=null) return true; return false; } @Override public<O> O get(ConfigOption<O> option, String... umbrellaElements) { String key = super.getPath(option,umbrellaElements); Object result = null; if (option.isLocal()) { result = local.get(key,option.getDatatype()); } if (result==null && option.isGlobal()) { result = global.get(key,option.getDatatype()); } return option.get(result); } @Override public Set<String> getContainedNamespaces(ConfigNamespace umbrella, String... umbrellaElements) { Set<String> result = Sets.newHashSet(); for (ReadConfiguration config : new ReadConfiguration[]{global,local}) { result.addAll(super.getContainedNamespaces(config,umbrella,umbrellaElements)); } return result; } public Map<String,Object> getSubset(ConfigNamespace umbrella, String... umbrellaElements) { Map<String,Object> result = Maps.newHashMap(); for (ReadConfiguration config : new ReadConfiguration[]{global,local}) { result.putAll(super.getSubset(config,umbrella,umbrellaElements)); } return result; } @Override public Configuration restrictTo(String... umbrellaElements) { return restrictTo(this,umbrellaElements); } @Override public void close() { global.close(); local.close(); } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_configuration_MixedConfiguration.java
1,234
addOperation(operations, new Runnable() { public void run() { IMap map = hazelcast.getMap("myMap"); int key = random.nextInt(SIZE); boolean locked = map.tryLock(key); if (locked) { try { Thread.sleep(1); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { map.unlock(key); } } } }, 1);
0true
hazelcast_src_main_java_com_hazelcast_examples_AllTest.java
2,905
public class NumericLongTokenizer extends NumericTokenizer { public NumericLongTokenizer(Reader reader, int precisionStep, char[] buffer) throws IOException { super(reader, new NumericTokenStream(precisionStep), buffer, null); } @Override protected void setValue(NumericTokenStream tokenStream, String value) { tokenStream.setLongValue(Long.parseLong(value)); } }
0true
src_main_java_org_elasticsearch_index_analysis_NumericLongTokenizer.java
631
public class IndexShardStatus implements Iterable<ShardStatus> { private final ShardId shardId; private final ShardStatus[] shards; IndexShardStatus(ShardId shardId, ShardStatus[] shards) { this.shardId = shardId; this.shards = shards; } public ShardId getShardId() { return this.shardId; } public ShardStatus[] getShards() { return this.shards; } public ShardStatus getAt(int position) { return shards[position]; } /** * Returns only the primary shards store size in bytes. */ public ByteSizeValue getPrimaryStoreSize() { long bytes = -1; for (ShardStatus shard : getShards()) { if (!shard.getShardRouting().primary()) { // only sum docs for the primaries continue; } if (shard.getStoreSize() != null) { if (bytes == -1) { bytes = 0; } bytes += shard.getStoreSize().bytes(); } } if (bytes == -1) { return null; } return new ByteSizeValue(bytes); } /** * Returns the full store size in bytes, of both primaries and replicas. */ public ByteSizeValue getStoreSize() { long bytes = -1; for (ShardStatus shard : getShards()) { if (shard.getStoreSize() != null) { if (bytes == -1) { bytes = 0; } bytes += shard.getStoreSize().bytes(); } } if (bytes == -1) { return null; } return new ByteSizeValue(bytes); } public long getTranslogOperations() { long translogOperations = -1; for (ShardStatus shard : getShards()) { if (shard.getTranslogOperations() != -1) { if (translogOperations == -1) { translogOperations = 0; } translogOperations += shard.getTranslogOperations(); } } return translogOperations; } private transient DocsStatus docs; public DocsStatus getDocs() { if (docs != null) { return docs; } DocsStatus docs = null; for (ShardStatus shard : getShards()) { if (!shard.getShardRouting().primary()) { // only sum docs for the primaries continue; } if (shard.getDocs() == null) { continue; } if (docs == null) { docs = new DocsStatus(); } docs.numDocs += shard.getDocs().getNumDocs(); docs.maxDoc += shard.getDocs().getMaxDoc(); docs.deletedDocs += shard.getDocs().getDeletedDocs(); } this.docs = docs; return this.docs; } /** * Total merges of this shard replication group. */ public MergeStats getMergeStats() { MergeStats mergeStats = new MergeStats(); for (ShardStatus shard : shards) { mergeStats.add(shard.getMergeStats()); } return mergeStats; } public RefreshStats getRefreshStats() { RefreshStats refreshStats = new RefreshStats(); for (ShardStatus shard : shards) { refreshStats.add(shard.getRefreshStats()); } return refreshStats; } public FlushStats getFlushStats() { FlushStats flushStats = new FlushStats(); for (ShardStatus shard : shards) { flushStats.add(shard.flushStats); } return flushStats; } @Override public Iterator<ShardStatus> iterator() { return Iterators.forArray(shards); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_status_IndexShardStatus.java
1,149
public class GeoDistanceSearchBenchmark { public static void main(String[] args) throws Exception { Node node = NodeBuilder.nodeBuilder().clusterName(GeoDistanceSearchBenchmark.class.getSimpleName()).node(); Client client = node.client(); ClusterHealthResponse clusterHealthResponse = client.admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet(); if (clusterHealthResponse.isTimedOut()) { System.err.println("Failed to wait for green status, bailing"); System.exit(1); } final long NUM_DOCS = SizeValue.parseSizeValue("1m").singles(); final long NUM_WARM = 50; final long NUM_RUNS = 100; if (client.admin().indices().prepareExists("test").execute().actionGet().isExists()) { System.out.println("Found an index, count: " + client.prepareCount("test").setQuery(QueryBuilders.matchAllQuery()).execute().actionGet().getCount()); } else { String mapping = XContentFactory.jsonBuilder().startObject().startObject("type1") .startObject("properties").startObject("location").field("type", "geo_point").field("lat_lon", true).endObject().endObject() .endObject().endObject().string(); client.admin().indices().prepareCreate("test") .setSettings(ImmutableSettings.settingsBuilder().put("index.number_of_shards", 1).put("index.number_of_replicas", 0)) .addMapping("type1", mapping) .execute().actionGet(); System.err.println("--> Indexing [" + NUM_DOCS + "]"); for (long i = 0; i < NUM_DOCS; ) { client.prepareIndex("test", "type1", Long.toString(i++)).setSource(jsonBuilder().startObject() .field("name", "New York") .startObject("location").field("lat", 40.7143528).field("lon", -74.0059731).endObject() .endObject()).execute().actionGet(); // to NY: 5.286 km client.prepareIndex("test", "type1", Long.toString(i++)).setSource(jsonBuilder().startObject() .field("name", "Times Square") .startObject("location").field("lat", 40.759011).field("lon", -73.9844722).endObject() .endObject()).execute().actionGet(); // to NY: 0.4621 km client.prepareIndex("test", "type1", Long.toString(i++)).setSource(jsonBuilder().startObject() .field("name", "Tribeca") .startObject("location").field("lat", 40.718266).field("lon", -74.007819).endObject() .endObject()).execute().actionGet(); // to NY: 1.258 km client.prepareIndex("test", "type1", Long.toString(i++)).setSource(jsonBuilder().startObject() .field("name", "Soho") .startObject("location").field("lat", 40.7247222).field("lon", -74).endObject() .endObject()).execute().actionGet(); // to NY: 8.572 km client.prepareIndex("test", "type1", Long.toString(i++)).setSource(jsonBuilder().startObject() .field("name", "Brooklyn") .startObject("location").field("lat", 40.65).field("lon", -73.95).endObject() .endObject()).execute().actionGet(); if ((i % 10000) == 0) { System.err.println("--> indexed " + i); } } System.err.println("Done indexed"); client.admin().indices().prepareFlush("test").execute().actionGet(); client.admin().indices().prepareRefresh().execute().actionGet(); } System.err.println("--> Warming up (ARC) - optimize_bbox"); long start = System.currentTimeMillis(); for (int i = 0; i < NUM_WARM; i++) { run(client, GeoDistance.ARC, "memory"); } long totalTime = System.currentTimeMillis() - start; System.err.println("--> Warmup (ARC) - optimize_bbox (memory) " + (totalTime / NUM_WARM) + "ms"); System.err.println("--> Perf (ARC) - optimize_bbox (memory)"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_RUNS; i++) { run(client, GeoDistance.ARC, "memory"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Perf (ARC) - optimize_bbox " + (totalTime / NUM_RUNS) + "ms"); System.err.println("--> Warming up (ARC) - optimize_bbox (indexed)"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_WARM; i++) { run(client, GeoDistance.ARC, "indexed"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Warmup (ARC) - optimize_bbox (indexed) " + (totalTime / NUM_WARM) + "ms"); System.err.println("--> Perf (ARC) - optimize_bbox (indexed)"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_RUNS; i++) { run(client, GeoDistance.ARC, "indexed"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Perf (ARC) - optimize_bbox (indexed) " + (totalTime / NUM_RUNS) + "ms"); System.err.println("--> Warming up (ARC) - no optimize_bbox"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_WARM; i++) { run(client, GeoDistance.ARC, "none"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Warmup (ARC) - no optimize_bbox " + (totalTime / NUM_WARM) + "ms"); System.err.println("--> Perf (ARC) - no optimize_bbox"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_RUNS; i++) { run(client, GeoDistance.ARC, "none"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Perf (ARC) - no optimize_bbox " + (totalTime / NUM_RUNS) + "ms"); System.err.println("--> Warming up (SLOPPY_ARC)"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_WARM; i++) { run(client, GeoDistance.SLOPPY_ARC, "memory"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Warmup (SLOPPY_ARC) " + (totalTime / NUM_WARM) + "ms"); System.err.println("--> Perf (SLOPPY_ARC)"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_RUNS; i++) { run(client, GeoDistance.SLOPPY_ARC, "memory"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Perf (SLOPPY_ARC) " + (totalTime / NUM_RUNS) + "ms"); System.err.println("--> Warming up (PLANE)"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_WARM; i++) { run(client, GeoDistance.PLANE, "memory"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Warmup (PLANE) " + (totalTime / NUM_WARM) + "ms"); System.err.println("--> Perf (PLANE)"); start = System.currentTimeMillis(); for (int i = 0; i < NUM_RUNS; i++) { run(client, GeoDistance.PLANE, "memory"); } totalTime = System.currentTimeMillis() - start; System.err.println("--> Perf (PLANE) " + (totalTime / NUM_RUNS) + "ms"); node.close(); } public static void run(Client client, GeoDistance geoDistance, String optimizeBbox) { client.prepareSearch() // from NY .setSearchType(SearchType.COUNT) .setQuery(filteredQuery(matchAllQuery(), geoDistanceFilter("location") .distance("2km") .optimizeBbox(optimizeBbox) .geoDistance(geoDistance) .point(40.7143528, -74.0059731))) .execute().actionGet(); } }
0true
src_test_java_org_elasticsearch_benchmark_search_geo_GeoDistanceSearchBenchmark.java
2,552
public static interface AckListener { void onNodeAck(DiscoveryNode node, @Nullable Throwable t); void onTimeout(); }
0true
src_main_java_org_elasticsearch_discovery_Discovery.java
307
public class ClusterHealthRequestBuilder extends MasterNodeReadOperationRequestBuilder<ClusterHealthRequest, ClusterHealthResponse, ClusterHealthRequestBuilder> { public ClusterHealthRequestBuilder(ClusterAdminClient clusterClient) { super((InternalClusterAdminClient) clusterClient, new ClusterHealthRequest()); } public ClusterHealthRequestBuilder setIndices(String... indices) { request.indices(indices); return this; } public ClusterHealthRequestBuilder setTimeout(TimeValue timeout) { request.timeout(timeout); return this; } public ClusterHealthRequestBuilder setTimeout(String timeout) { request.timeout(timeout); return this; } public ClusterHealthRequestBuilder setWaitForStatus(ClusterHealthStatus waitForStatus) { request.waitForStatus(waitForStatus); return this; } public ClusterHealthRequestBuilder setWaitForGreenStatus() { request.waitForGreenStatus(); return this; } public ClusterHealthRequestBuilder setWaitForYellowStatus() { request.waitForYellowStatus(); return this; } public ClusterHealthRequestBuilder setWaitForRelocatingShards(int waitForRelocatingShards) { request.waitForRelocatingShards(waitForRelocatingShards); return this; } public ClusterHealthRequestBuilder setWaitForActiveShards(int waitForActiveShards) { request.waitForActiveShards(waitForActiveShards); return this; } /** * Waits for N number of nodes. Use "12" for exact mapping, ">12" and "<12" for range. */ public ClusterHealthRequestBuilder setWaitForNodes(String waitForNodes) { request.waitForNodes(waitForNodes); return this; } public ClusterHealthRequestBuilder setWaitForEvents(Priority waitForEvents) { request.waitForEvents(waitForEvents); return this; } @Override protected void doExecute(ActionListener<ClusterHealthResponse> listener) { ((ClusterAdminClient) client).health(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_health_ClusterHealthRequestBuilder.java
1,343
public interface UserConnection { UserConnectionImpl.UserConnectionPK getUserConnectionPK(); void setUserConnectionPK(UserConnectionImpl.UserConnectionPK userConnectionPK); Integer getRank(); void setRank(Integer rank); String getDisplayName(); void setDisplayName(String displayName); String getProfileUrl(); void setProfileUrl(String profileUrl); String getImageUrl(); void setImageUrl(String imageUrl); String getAccessToken(); void setAccessToken(String accessToken); String getSecret(); void setSecret(String secret); String getRefreshToken(); void setRefreshToken(String refreshToken); Long getExpireTime(); void setExpireTime(Long expireTime); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_social_domain_UserConnection.java