Unnamed: 0
int64 0
6.45k
| func
stringlengths 37
161k
| target
class label 2
classes | project
stringlengths 33
167
|
---|---|---|---|
825 |
public class GetOperation extends AtomicLongBaseOperation {
private long returnValue;
public GetOperation() {
}
public GetOperation(String name) {
super(name);
}
@Override
public void run() throws Exception {
LongWrapper number = getNumber();
returnValue = number.get();
}
@Override
public int getId() {
return AtomicLongDataSerializerHook.GET;
}
@Override
public Object getResponse() {
return returnValue;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_operations_GetOperation.java
|
933 |
public abstract class TransportBroadcastOperationAction<Request extends BroadcastOperationRequest, Response extends BroadcastOperationResponse, ShardRequest extends BroadcastShardOperationRequest, ShardResponse extends BroadcastShardOperationResponse>
extends TransportAction<Request, Response> {
protected final ClusterService clusterService;
protected final TransportService transportService;
protected final ThreadPool threadPool;
final String transportAction;
final String transportShardAction;
final String executor;
protected TransportBroadcastOperationAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService) {
super(settings, threadPool);
this.clusterService = clusterService;
this.transportService = transportService;
this.threadPool = threadPool;
this.transportAction = transportAction();
this.transportShardAction = transportAction() + "/s";
this.executor = executor();
transportService.registerHandler(transportAction, new TransportHandler());
transportService.registerHandler(transportShardAction, new ShardTransportHandler());
}
@Override
protected void doExecute(Request request, ActionListener<Response> listener) {
new AsyncBroadcastAction(request, listener).start();
}
protected abstract String transportAction();
protected abstract String executor();
protected abstract Request newRequest();
protected abstract Response newResponse(Request request, AtomicReferenceArray shardsResponses, ClusterState clusterState);
protected abstract ShardRequest newShardRequest();
protected abstract ShardRequest newShardRequest(ShardRouting shard, Request request);
protected abstract ShardResponse newShardResponse();
protected abstract ShardResponse shardOperation(ShardRequest request) throws ElasticsearchException;
protected abstract GroupShardsIterator shards(ClusterState clusterState, Request request, String[] concreteIndices);
protected abstract ClusterBlockException checkGlobalBlock(ClusterState state, Request request);
protected abstract ClusterBlockException checkRequestBlock(ClusterState state, Request request, String[] concreteIndices);
class AsyncBroadcastAction {
private final Request request;
private final ActionListener<Response> listener;
private final ClusterState clusterState;
private final DiscoveryNodes nodes;
private final GroupShardsIterator shardsIts;
private final int expectedOps;
private final AtomicInteger counterOps = new AtomicInteger();
private final AtomicReferenceArray shardsResponses;
AsyncBroadcastAction(Request request, ActionListener<Response> listener) {
this.request = request;
this.listener = listener;
clusterState = clusterService.state();
ClusterBlockException blockException = checkGlobalBlock(clusterState, request);
if (blockException != null) {
throw blockException;
}
// update to concrete indices
String[] concreteIndices = clusterState.metaData().concreteIndices(request.indices(), request.indicesOptions());
blockException = checkRequestBlock(clusterState, request, concreteIndices);
if (blockException != null) {
throw blockException;
}
nodes = clusterState.nodes();
shardsIts = shards(clusterState, request, concreteIndices);
expectedOps = shardsIts.size();
shardsResponses = new AtomicReferenceArray<Object>(expectedOps);
}
public void start() {
if (shardsIts.size() == 0) {
// no shards
try {
listener.onResponse(newResponse(request, new AtomicReferenceArray(0), clusterState));
} catch (Throwable e) {
listener.onFailure(e);
}
return;
}
request.beforeStart();
// count the local operations, and perform the non local ones
int localOperations = 0;
int shardIndex = -1;
for (final ShardIterator shardIt : shardsIts) {
shardIndex++;
final ShardRouting shard = shardIt.firstOrNull();
if (shard != null) {
if (shard.currentNodeId().equals(nodes.localNodeId())) {
localOperations++;
} else {
// do the remote operation here, the localAsync flag is not relevant
performOperation(shardIt, shardIndex, true);
}
} else {
// really, no shards active in this group
onOperation(null, shardIt, shardIndex, new NoShardAvailableActionException(shardIt.shardId()));
}
}
// we have local operations, perform them now
if (localOperations > 0) {
if (request.operationThreading() == BroadcastOperationThreading.SINGLE_THREAD) {
request.beforeLocalFork();
threadPool.executor(executor).execute(new Runnable() {
@Override
public void run() {
int shardIndex = -1;
for (final ShardIterator shardIt : shardsIts) {
shardIndex++;
final ShardRouting shard = shardIt.firstOrNull();
if (shard != null) {
if (shard.currentNodeId().equals(nodes.localNodeId())) {
performOperation(shardIt, shardIndex, false);
}
}
}
}
});
} else {
boolean localAsync = request.operationThreading() == BroadcastOperationThreading.THREAD_PER_SHARD;
if (localAsync) {
request.beforeLocalFork();
}
shardIndex = -1;
for (final ShardIterator shardIt : shardsIts) {
shardIndex++;
final ShardRouting shard = shardIt.firstOrNull();
if (shard != null) {
if (shard.currentNodeId().equals(nodes.localNodeId())) {
performOperation(shardIt, shardIndex, localAsync);
}
}
}
}
}
}
void performOperation(final ShardIterator shardIt, int shardIndex, boolean localAsync) {
performOperation(shardIt, shardIt.nextOrNull(), shardIndex, localAsync);
}
void performOperation(final ShardIterator shardIt, final ShardRouting shard, final int shardIndex, boolean localAsync) {
if (shard == null) {
// no more active shards... (we should not really get here, just safety)
onOperation(null, shardIt, shardIndex, new NoShardAvailableActionException(shardIt.shardId()));
} else {
try {
final ShardRequest shardRequest = newShardRequest(shard, request);
if (shard.currentNodeId().equals(nodes.localNodeId())) {
if (localAsync) {
threadPool.executor(executor).execute(new Runnable() {
@Override
public void run() {
try {
onOperation(shard, shardIndex, shardOperation(shardRequest));
} catch (Throwable e) {
onOperation(shard, shardIt, shardIndex, e);
}
}
});
} else {
onOperation(shard, shardIndex, shardOperation(shardRequest));
}
} else {
DiscoveryNode node = nodes.get(shard.currentNodeId());
if (node == null) {
// no node connected, act as failure
onOperation(shard, shardIt, shardIndex, new NoShardAvailableActionException(shardIt.shardId()));
} else {
transportService.sendRequest(node, transportShardAction, shardRequest, new BaseTransportResponseHandler<ShardResponse>() {
@Override
public ShardResponse newInstance() {
return newShardResponse();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void handleResponse(ShardResponse response) {
onOperation(shard, shardIndex, response);
}
@Override
public void handleException(TransportException e) {
onOperation(shard, shardIt, shardIndex, e);
}
});
}
}
} catch (Throwable e) {
onOperation(shard, shardIt, shardIndex, e);
}
}
}
@SuppressWarnings({"unchecked"})
void onOperation(ShardRouting shard, int shardIndex, ShardResponse response) {
shardsResponses.set(shardIndex, response);
if (expectedOps == counterOps.incrementAndGet()) {
finishHim();
}
}
@SuppressWarnings({"unchecked"})
void onOperation(@Nullable ShardRouting shard, final ShardIterator shardIt, int shardIndex, Throwable t) {
// we set the shard failure always, even if its the first in the replication group, and the next one
// will work (it will just override it...)
setFailure(shardIt, shardIndex, t);
ShardRouting nextShard = shardIt.nextOrNull();
if (nextShard != null) {
if (t != null) {
if (logger.isTraceEnabled()) {
if (!TransportActions.isShardNotAvailableException(t)) {
if (shard != null) {
logger.trace(shard.shortSummary() + ": Failed to execute [" + request + "]", t);
} else {
logger.trace(shardIt.shardId() + ": Failed to execute [" + request + "]", t);
}
}
}
}
// we are not threaded here if we got here from the transport
// or we possibly threaded if we got from a local threaded one,
// in which case, the next shard in the partition will not be local one
// so there is no meaning to this flag
performOperation(shardIt, nextShard, shardIndex, true);
} else {
if (logger.isDebugEnabled()) {
if (t != null) {
if (!TransportActions.isShardNotAvailableException(t)) {
if (shard != null) {
logger.debug(shard.shortSummary() + ": Failed to execute [" + request + "]", t);
} else {
logger.debug(shardIt.shardId() + ": Failed to execute [" + request + "]", t);
}
}
}
}
if (expectedOps == counterOps.incrementAndGet()) {
finishHim();
}
}
}
void finishHim() {
try {
listener.onResponse(newResponse(request, shardsResponses, clusterState));
} catch (Throwable e) {
listener.onFailure(e);
}
}
void setFailure(ShardIterator shardIt, int shardIndex, Throwable t) {
// we don't aggregate shard failures on non active shards (but do keep the header counts right)
if (TransportActions.isShardNotAvailableException(t)) {
return;
}
if (!(t instanceof BroadcastShardOperationFailedException)) {
t = new BroadcastShardOperationFailedException(shardIt.shardId(), t);
}
Object response = shardsResponses.get(shardIndex);
if (response == null) {
// just override it and return
shardsResponses.set(shardIndex, t);
}
if (!(response instanceof Throwable)) {
// we should never really get here...
return;
}
// the failure is already present, try and not override it with an exception that is less meaningless
// for example, getting illegal shard state
if (TransportActions.isReadOverrideException(t)) {
shardsResponses.set(shardIndex, t);
}
}
}
class TransportHandler extends BaseTransportRequestHandler<Request> {
@Override
public Request newInstance() {
return newRequest();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void messageReceived(Request request, final TransportChannel channel) throws Exception {
// we just send back a response, no need to fork a listener
request.listenerThreaded(false);
// we don't spawn, so if we get a request with no threading, change it to single threaded
if (request.operationThreading() == BroadcastOperationThreading.NO_THREADS) {
request.operationThreading(BroadcastOperationThreading.SINGLE_THREAD);
}
execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response response) {
try {
channel.sendResponse(response);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send response", e1);
}
}
});
}
}
class ShardTransportHandler extends BaseTransportRequestHandler<ShardRequest> {
@Override
public ShardRequest newInstance() {
return newShardRequest();
}
@Override
public String executor() {
return executor;
}
@Override
public void messageReceived(final ShardRequest request, final TransportChannel channel) throws Exception {
channel.sendResponse(shardOperation(request));
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_support_broadcast_TransportBroadcastOperationAction.java
|
1,476 |
public class RoutingNodes implements Iterable<RoutingNode> {
private final MetaData metaData;
private final ClusterBlocks blocks;
private final RoutingTable routingTable;
private final Map<String, RoutingNode> nodesToShards = newHashMap();
private final UnassignedShards unassignedShards = new UnassignedShards();
private final List<MutableShardRouting> ignoredUnassignedShards = newArrayList();
private final Map<ShardId, List<MutableShardRouting>> assignedShards = newHashMap();
private int inactivePrimaryCount = 0;
private int inactiveShardCount = 0;
private int relocatingShards = 0;
private Set<ShardId> clearPostAllocationFlag;
private final Map<String, ObjectIntOpenHashMap<String>> nodesPerAttributeNames = new HashMap<String, ObjectIntOpenHashMap<String>>();
public RoutingNodes(ClusterState clusterState) {
this.metaData = clusterState.metaData();
this.blocks = clusterState.blocks();
this.routingTable = clusterState.routingTable();
Map<String, List<MutableShardRouting>> nodesToShards = newHashMap();
// fill in the nodeToShards with the "live" nodes
for (ObjectCursor<DiscoveryNode> cursor : clusterState.nodes().dataNodes().values()) {
nodesToShards.put(cursor.value.id(), new ArrayList<MutableShardRouting>());
}
// fill in the inverse of node -> shards allocated
// also fill replicaSet information
for (IndexRoutingTable indexRoutingTable : routingTable.indicesRouting().values()) {
for (IndexShardRoutingTable indexShard : indexRoutingTable) {
for (ShardRouting shard : indexShard) {
// to get all the shards belonging to an index, including the replicas,
// we define a replica set and keep track of it. A replica set is identified
// by the ShardId, as this is common for primary and replicas.
// A replica Set might have one (and not more) replicas with the state of RELOCATING.
if (shard.assignedToNode()) {
List<MutableShardRouting> entries = nodesToShards.get(shard.currentNodeId());
if (entries == null) {
entries = newArrayList();
nodesToShards.put(shard.currentNodeId(), entries);
}
MutableShardRouting sr = new MutableShardRouting(shard);
entries.add(sr);
assignedShardsAdd(sr);
if (shard.relocating()) {
entries = nodesToShards.get(shard.relocatingNodeId());
relocatingShards++;
if (entries == null) {
entries = newArrayList();
nodesToShards.put(shard.relocatingNodeId(), entries);
}
// add the counterpart shard with relocatingNodeId reflecting the source from which
// it's relocating from.
sr = new MutableShardRouting(shard.index(), shard.id(), shard.relocatingNodeId(),
shard.currentNodeId(), shard.primary(), ShardRoutingState.INITIALIZING, shard.version());
entries.add(sr);
assignedShardsAdd(sr);
} else if (!shard.active()) { // shards that are initializing without being relocated
if (shard.primary()) {
inactivePrimaryCount++;
}
inactiveShardCount++;
}
} else {
MutableShardRouting sr = new MutableShardRouting(shard);
assignedShardsAdd(sr);
unassignedShards.add(sr);
}
}
}
}
for (Map.Entry<String, List<MutableShardRouting>> entry : nodesToShards.entrySet()) {
String nodeId = entry.getKey();
this.nodesToShards.put(nodeId, new RoutingNode(nodeId, clusterState.nodes().get(nodeId), entry.getValue()));
}
}
@Override
public Iterator<RoutingNode> iterator() {
return Iterators.unmodifiableIterator(nodesToShards.values().iterator());
}
public RoutingTable routingTable() {
return routingTable;
}
public RoutingTable getRoutingTable() {
return routingTable();
}
public MetaData metaData() {
return this.metaData;
}
public MetaData getMetaData() {
return metaData();
}
public ClusterBlocks blocks() {
return this.blocks;
}
public ClusterBlocks getBlocks() {
return this.blocks;
}
public int requiredAverageNumberOfShardsPerNode() {
int totalNumberOfShards = 0;
// we need to recompute to take closed shards into account
for (ObjectCursor<IndexMetaData> cursor : metaData.indices().values()) {
IndexMetaData indexMetaData = cursor.value;
if (indexMetaData.state() == IndexMetaData.State.OPEN) {
totalNumberOfShards += indexMetaData.totalNumberOfShards();
}
}
return totalNumberOfShards / nodesToShards.size();
}
public boolean hasUnassigned() {
return !unassignedShards.isEmpty();
}
public List<MutableShardRouting> ignoredUnassigned() {
return this.ignoredUnassignedShards;
}
public UnassignedShards unassigned() {
return this.unassignedShards;
}
public RoutingNodesIterator nodes() {
return new RoutingNodesIterator(nodesToShards.values().iterator());
}
/**
* Clears the post allocation flag for the provided shard id. NOTE: this should be used cautiously
* since it will lead to data loss of the primary shard is not allocated, as it will allocate
* the primary shard on a node and *not* expect it to have an existing valid index there.
*/
public void addClearPostAllocationFlag(ShardId shardId) {
if (clearPostAllocationFlag == null) {
clearPostAllocationFlag = Sets.newHashSet();
}
clearPostAllocationFlag.add(shardId);
}
public Iterable<ShardId> getShardsToClearPostAllocationFlag() {
if (clearPostAllocationFlag == null) {
return ImmutableSet.of();
}
return clearPostAllocationFlag;
}
public RoutingNode node(String nodeId) {
return nodesToShards.get(nodeId);
}
public ObjectIntOpenHashMap<String> nodesPerAttributesCounts(String attributeName) {
ObjectIntOpenHashMap<String> nodesPerAttributesCounts = nodesPerAttributeNames.get(attributeName);
if (nodesPerAttributesCounts != null) {
return nodesPerAttributesCounts;
}
nodesPerAttributesCounts = new ObjectIntOpenHashMap<String>();
for (RoutingNode routingNode : this) {
String attrValue = routingNode.node().attributes().get(attributeName);
nodesPerAttributesCounts.addTo(attrValue, 1);
}
nodesPerAttributeNames.put(attributeName, nodesPerAttributesCounts);
return nodesPerAttributesCounts;
}
public boolean hasUnassignedPrimaries() {
return unassignedShards.numPrimaries() > 0;
}
public boolean hasUnassignedShards() {
return !unassignedShards.isEmpty();
}
public boolean hasInactivePrimaries() {
return inactivePrimaryCount > 0;
}
public boolean hasInactiveShards() {
return inactiveShardCount > 0;
}
public int getRelocatingShardCount() {
return relocatingShards;
}
/**
* Returns the active primary shard for the given ShardRouting or <code>null</code> if
* no primary is found or the primary is not active.
*/
public MutableShardRouting activePrimary(ShardRouting shard) {
assert !shard.primary();
for (MutableShardRouting shardRouting : assignedShards(shard.shardId())) {
if (shardRouting.primary() && shardRouting.active()) {
return shardRouting;
}
}
return null;
}
/**
* Returns one active replica shard for the given ShardRouting shard ID or <code>null</code> if
* no active replica is found.
*/
public MutableShardRouting activeReplica(ShardRouting shard) {
for (MutableShardRouting shardRouting : assignedShards(shard.shardId())) {
if (!shardRouting.primary() && shardRouting.active()) {
return shardRouting;
}
}
return null;
}
/**
* Returns all shards that are not in the state UNASSIGNED with the same shard
* ID as the given shard.
*/
public Iterable<MutableShardRouting> assignedShards(ShardRouting shard) {
return assignedShards(shard.shardId());
}
/**
* Returns <code>true</code> iff all replicas are active for the given shard routing. Otherwise <code>false</code>
*/
public boolean allReplicasActive(ShardRouting shardRouting) {
final List<MutableShardRouting> shards = assignedShards(shardRouting.shardId());
if (shards.isEmpty() || shards.size() < this.routingTable.index(shardRouting.index()).shard(shardRouting.id()).size()) {
return false; // if we are empty nothing is active if we have less than total at least one is unassigned
}
for (MutableShardRouting shard : shards) {
if (!shard.active()) {
return false;
}
}
return true;
}
public List<MutableShardRouting> shards(Predicate<MutableShardRouting> predicate) {
List<MutableShardRouting> shards = newArrayList();
for (RoutingNode routingNode : this) {
for (MutableShardRouting shardRouting : routingNode) {
if (predicate.apply(shardRouting)) {
shards.add(shardRouting);
}
}
}
return shards;
}
public List<MutableShardRouting> shardsWithState(ShardRoutingState... state) {
// TODO these are used on tests only - move into utils class
List<MutableShardRouting> shards = newArrayList();
for (RoutingNode routingNode : this) {
shards.addAll(routingNode.shardsWithState(state));
}
return shards;
}
public List<MutableShardRouting> shardsWithState(String index, ShardRoutingState... state) {
// TODO these are used on tests only - move into utils class
List<MutableShardRouting> shards = newArrayList();
for (RoutingNode routingNode : this) {
shards.addAll(routingNode.shardsWithState(index, state));
}
return shards;
}
public String prettyPrint() {
StringBuilder sb = new StringBuilder("routing_nodes:\n");
for (RoutingNode routingNode : this) {
sb.append(routingNode.prettyPrint());
}
sb.append("---- unassigned\n");
for (MutableShardRouting shardEntry : unassignedShards) {
sb.append("--------").append(shardEntry.shortSummary()).append('\n');
}
return sb.toString();
}
/**
* Assign a shard to a node. This will increment the inactiveShardCount counter
* and the inactivePrimaryCount counter if the shard is the primary.
* In case the shard is already assigned and started, it will be marked as
* relocating, which is accounted for, too, so the number of concurrent relocations
* can be retrieved easily.
* This method can be called several times for the same shard, only the first time
* will change the state.
*
* INITIALIZING => INITIALIZING
* UNASSIGNED => INITIALIZING
* STARTED => RELOCATING
* RELOCATING => RELOCATING
*
* @param shard the shard to be assigned
* @param nodeId the nodeId this shard should initialize on or relocate from
*/
public void assign(MutableShardRouting shard, String nodeId) {
// state will not change if the shard is already initializing.
ShardRoutingState oldState = shard.state();
shard.assignToNode(nodeId);
node(nodeId).add(shard);
if (oldState == ShardRoutingState.UNASSIGNED) {
inactiveShardCount++;
if (shard.primary()) {
inactivePrimaryCount++;
}
}
if (shard.state() == ShardRoutingState.RELOCATING) {
relocatingShards++;
}
assignedShardsAdd(shard);
}
/**
* Relocate a shard to another node.
*/
public void relocate(MutableShardRouting shard, String nodeId) {
relocatingShards++;
shard.relocate(nodeId);
}
/**
* Mark a shard as started and adjusts internal statistics.
*/
public void started(MutableShardRouting shard) {
if (!shard.active() && shard.relocatingNodeId() == null) {
inactiveShardCount--;
if (shard.primary()) {
inactivePrimaryCount--;
}
} else if (shard.relocating()) {
relocatingShards--;
}
assert !shard.started();
shard.moveToStarted();
}
/**
* Cancels a relocation of a shard that shard must relocating.
*/
public void cancelRelocation(MutableShardRouting shard) {
relocatingShards--;
shard.cancelRelocation();
}
/**
* swaps the status of a shard, making replicas primary and vice versa.
*
* @param shards the shard to have its primary status swapped.
*/
public void swapPrimaryFlag(MutableShardRouting... shards) {
for (MutableShardRouting shard : shards) {
if (shard.primary()) {
shard.moveFromPrimary();
if (shard.unassigned()) {
unassignedShards.primaries--;
}
} else {
shard.moveToPrimary();
if (shard.unassigned()) {
unassignedShards.primaries++;
}
}
}
}
private static final List<MutableShardRouting> EMPTY = Collections.emptyList();
private List<MutableShardRouting> assignedShards(ShardId shardId) {
final List<MutableShardRouting> replicaSet = assignedShards.get(shardId);
return replicaSet == null ? EMPTY : Collections.unmodifiableList(replicaSet);
}
/**
* Cancels the give shard from the Routing nodes internal statistics and cancels
* the relocation if the shard is relocating.
* @param shard
*/
private void remove(MutableShardRouting shard) {
if (!shard.active() && shard.relocatingNodeId() == null) {
inactiveShardCount--;
assert inactiveShardCount >= 0;
if (shard.primary()) {
inactivePrimaryCount--;
}
} else if (shard.relocating()) {
cancelRelocation(shard);
}
assignedShardsRemove(shard);
}
private void assignedShardsAdd(MutableShardRouting shard) {
if (shard.unassigned()) {
// no unassigned
return;
}
List<MutableShardRouting> shards = assignedShards.get(shard.shardId());
if (shards == null) {
shards = Lists.newArrayList();
assignedShards.put(shard.shardId(), shards);
}
assert assertInstanceNotInList(shard, shards);
shards.add(shard);
}
private boolean assertInstanceNotInList(MutableShardRouting shard, List<MutableShardRouting> shards) {
for (MutableShardRouting s : shards) {
assert s != shard;
}
return true;
}
private void assignedShardsRemove(MutableShardRouting shard) {
final List<MutableShardRouting> replicaSet = assignedShards.get(shard.shardId());
if (replicaSet != null) {
final Iterator<MutableShardRouting> iterator = replicaSet.iterator();
while(iterator.hasNext()) {
// yes we check identity here
if (shard == iterator.next()) {
iterator.remove();
return;
}
}
assert false : "Illegal state";
}
}
public boolean isKnown(DiscoveryNode node) {
return nodesToShards.containsKey(node.getId());
}
public void addNode(DiscoveryNode node) {
RoutingNode routingNode = new RoutingNode(node.id(), node);
nodesToShards.put(routingNode.nodeId(), routingNode);
}
public RoutingNodeIterator routingNodeIter(String nodeId) {
final RoutingNode routingNode = nodesToShards.get(nodeId);
if (routingNode == null) {
return null;
}
assert assertShardStats(this);
return new RoutingNodeIterator(routingNode);
}
public RoutingNode[] toArray() {
return nodesToShards.values().toArray(new RoutingNode[nodesToShards.size()]);
}
public final static class UnassignedShards implements Iterable<MutableShardRouting> {
private final List<MutableShardRouting> unassigned;
private int primaries = 0;
private long transactionId = 0;
private final UnassignedShards source;
private final long sourceTransactionId;
public UnassignedShards(UnassignedShards other) {
source = other;
sourceTransactionId = other.transactionId;
unassigned = new ArrayList<MutableShardRouting>(other.unassigned);
primaries = other.primaries;
}
public UnassignedShards() {
unassigned = new ArrayList<MutableShardRouting>();
source = null;
sourceTransactionId = -1;
}
public void add(MutableShardRouting mutableShardRouting) {
if(mutableShardRouting.primary()) {
primaries++;
}
unassigned.add(mutableShardRouting);
transactionId++;
}
public void addAll(Collection<MutableShardRouting> mutableShardRoutings) {
for (MutableShardRouting r : mutableShardRoutings) {
add(r);
}
}
public int size() {
return unassigned.size();
}
public int numPrimaries() {
return primaries;
}
@Override
public Iterator<MutableShardRouting> iterator() {
final Iterator<MutableShardRouting> iterator = unassigned.iterator();
return new Iterator<MutableShardRouting>() {
private MutableShardRouting current;
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public MutableShardRouting next() {
return current = iterator.next();
}
@Override
public void remove() {
iterator.remove();
if (current.primary()) {
primaries--;
}
transactionId++;
}
};
}
public boolean isEmpty() {
return unassigned.isEmpty();
}
public void shuffle() {
Collections.shuffle(unassigned);
}
public void clear() {
transactionId++;
unassigned.clear();
primaries = 0;
}
public void transactionEnd(UnassignedShards shards) {
assert shards.source == this && shards.sourceTransactionId == transactionId :
"Expected ID: " + shards.sourceTransactionId + " actual: " + transactionId + " Expected Source: " + shards.source + " actual: " + this;
transactionId++;
this.unassigned.clear();
this.unassigned.addAll(shards.unassigned);
this.primaries = shards.primaries;
}
public UnassignedShards transactionBegin() {
return new UnassignedShards(this);
}
public MutableShardRouting[] drain() {
MutableShardRouting[] mutableShardRoutings = unassigned.toArray(new MutableShardRouting[unassigned.size()]);
unassigned.clear();
primaries = 0;
transactionId++;
return mutableShardRoutings;
}
}
/**
* Calculates RoutingNodes statistics by iterating over all {@link MutableShardRouting}s
* in the cluster to ensure the book-keeping is correct.
* For performance reasons, this should only be called from asserts
*
* @return this method always returns <code>true</code> or throws an assertion error. If assertion are not enabled
* this method does nothing.
*/
public static boolean assertShardStats(RoutingNodes routingNodes) {
boolean run = false;
assert (run = true); // only run if assertions are enabled!
if (!run) {
return true;
}
int unassignedPrimaryCount = 0;
int inactivePrimaryCount = 0;
int inactiveShardCount = 0;
int relocating = 0;
final Set<ShardId> seenShards = newHashSet();
Map<String, Integer> indicesAndShards = new HashMap<String, Integer>();
for (RoutingNode node : routingNodes) {
for (MutableShardRouting shard : node) {
if (!shard.active() && shard.relocatingNodeId() == null) {
if (!shard.relocating()) {
inactiveShardCount++;
if (shard.primary()) {
inactivePrimaryCount++;
}
}
}
if (shard.relocating()) {
relocating++;
}
seenShards.add(shard.shardId());
Integer i = indicesAndShards.get(shard.index());
if (i == null) {
i = shard.id();
}
indicesAndShards.put(shard.index(), Math.max(i, shard.id()));
}
}
// Assert that the active shard routing are identical.
Set<Map.Entry<String, Integer>> entries = indicesAndShards.entrySet();
final List<MutableShardRouting> shards = newArrayList();
for (Map.Entry<String, Integer> e : entries) {
String index = e.getKey();
for (int i = 0; i < e.getValue(); i++) {
for (RoutingNode routingNode : routingNodes) {
for (MutableShardRouting shardRouting : routingNode) {
if (shardRouting.index().equals(index) && shardRouting.id() == i) {
shards.add(shardRouting);
}
}
}
List<MutableShardRouting> mutableShardRoutings = routingNodes.assignedShards(new ShardId(index, i));
assert mutableShardRoutings.size() == shards.size();
for (MutableShardRouting r : mutableShardRoutings) {
assert shards.contains(r);
shards.remove(r);
}
assert shards.isEmpty();
}
}
for (MutableShardRouting shard : routingNodes.unassigned()) {
if (shard.primary()) {
unassignedPrimaryCount++;
}
seenShards.add(shard.shardId());
}
assert unassignedPrimaryCount == routingNodes.unassignedShards.numPrimaries() :
"Unassigned primaries is [" + unassignedPrimaryCount + "] but RoutingNodes returned unassigned primaries [" + routingNodes.unassigned().numPrimaries() + "]";
assert inactivePrimaryCount == routingNodes.inactivePrimaryCount :
"Inactive Primary count [" + inactivePrimaryCount + "] but RoutingNodes returned inactive primaries [" + routingNodes.inactivePrimaryCount + "]";
assert inactiveShardCount == routingNodes.inactiveShardCount :
"Inactive Shard count [" + inactiveShardCount + "] but RoutingNodes returned inactive shards [" + routingNodes.inactiveShardCount + "]";
assert routingNodes.getRelocatingShardCount() == relocating : "Relocating shards mismatch [" + routingNodes.getRelocatingShardCount() + "] but expected [" + relocating + "]";
return true;
}
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();
}
}
public final class RoutingNodeIterator implements Iterator<MutableShardRouting>, Iterable<MutableShardRouting> {
private final RoutingNode iterable;
private MutableShardRouting shard;
private final Iterator<MutableShardRouting> delegate;
public RoutingNodeIterator(RoutingNode iterable) {
this.delegate = iterable.mutableIterator();
this.iterable = iterable;
}
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public MutableShardRouting next() {
return shard = delegate.next();
}
public void remove() {
delegate.remove();
RoutingNodes.this.remove(shard);
}
@Override
public Iterator<MutableShardRouting> iterator() {
return iterable.iterator();
}
public void moveToUnassigned() {
iterator().remove();
unassigned().add(new MutableShardRouting(shard.index(), shard.id(),
null, shard.primary(), ShardRoutingState.UNASSIGNED, shard.version() + 1));
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_cluster_routing_RoutingNodes.java
|
856 |
public class SetRequest extends ModifyRequest {
public SetRequest() {
}
public SetRequest(String name, Data update) {
super(name, update);
}
@Override
protected Operation prepareOperation() {
return new SetOperation(name, update);
}
@Override
public int getClassId() {
return AtomicReferencePortableHook.SET;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_concurrent_atomicreference_client_SetRequest.java
|
46 |
public class TouchCommandProcessor extends MemcacheCommandProcessor<TouchCommand> {
private final ILogger logger;
public TouchCommandProcessor(TextCommandServiceImpl textCommandService) {
super(textCommandService);
logger = textCommandService.getNode().getLogger(this.getClass().getName());
}
public void handle(TouchCommand touchCommand) {
String key = null;
try {
key = URLDecoder.decode(touchCommand.getKey(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new HazelcastException(e);
}
String mapName = DEFAULT_MAP_NAME;
int index = key.indexOf(':');
if (index != -1) {
mapName = MAP_NAME_PRECEDER + key.substring(0, index);
key = key.substring(index + 1);
}
int ttl = textCommandService.getAdjustedTTLSeconds(touchCommand.getExpiration());
try {
textCommandService.lock(mapName, key);
} catch (Exception e) {
touchCommand.setResponse(NOT_STORED);
if (touchCommand.shouldReply()) {
textCommandService.sendResponse(touchCommand);
}
return;
}
final Object value = textCommandService.get(mapName, key);
textCommandService.incrementTouchCount();
if (value != null) {
textCommandService.put(mapName, key, value, ttl);
touchCommand.setResponse(TOUCHED);
} else {
touchCommand.setResponse(NOT_STORED);
}
textCommandService.unlock(mapName, key);
if (touchCommand.shouldReply()) {
textCommandService.sendResponse(touchCommand);
}
}
public void handleRejection(TouchCommand request) {
request.setResponse(NOT_STORED);
if (request.shouldReply()) {
textCommandService.sendResponse(request);
}
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_ascii_memcache_TouchCommandProcessor.java
|
3,307 |
public abstract class DoubleArrayAtomicFieldData extends AbstractAtomicNumericFieldData {
public static DoubleArrayAtomicFieldData empty(int numDocs) {
return new Empty(numDocs);
}
private final int numDocs;
protected long size = -1;
public DoubleArrayAtomicFieldData(int numDocs) {
super(true);
this.numDocs = numDocs;
}
@Override
public void close() {
}
@Override
public int getNumDocs() {
return numDocs;
}
static class Empty extends DoubleArrayAtomicFieldData {
Empty(int numDocs) {
super(numDocs);
}
@Override
public LongValues getLongValues() {
return LongValues.EMPTY;
}
@Override
public DoubleValues getDoubleValues() {
return DoubleValues.EMPTY;
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public boolean isValuesOrdered() {
return false;
}
@Override
public long getNumberUniqueValues() {
return 0;
}
@Override
public long getMemorySizeInBytes() {
return 0;
}
@Override
public BytesValues getBytesValues(boolean needsHashes) {
return BytesValues.EMPTY;
}
@Override
public ScriptDocValues getScriptValues() {
return ScriptDocValues.EMPTY;
}
}
public static class WithOrdinals extends DoubleArrayAtomicFieldData {
private final BigDoubleArrayList values;
private final Ordinals ordinals;
public WithOrdinals(BigDoubleArrayList values, int numDocs, Ordinals ordinals) {
super(numDocs);
this.values = values;
this.ordinals = ordinals;
}
@Override
public boolean isMultiValued() {
return ordinals.isMultiValued();
}
@Override
public boolean isValuesOrdered() {
return true;
}
@Override
public long getNumberUniqueValues() {
return ordinals.getNumOrds();
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = RamUsageEstimator.NUM_BYTES_INT/*size*/ + RamUsageEstimator.NUM_BYTES_INT/*numDocs*/ + values.sizeInBytes() + ordinals.getMemorySizeInBytes();
}
return size;
}
@Override
public LongValues getLongValues() {
return new LongValues(values, ordinals.ordinals());
}
@Override
public DoubleValues getDoubleValues() {
return new DoubleValues(values, ordinals.ordinals());
}
static class LongValues extends org.elasticsearch.index.fielddata.LongValues.WithOrdinals {
private final BigDoubleArrayList values;
LongValues(BigDoubleArrayList values, Ordinals.Docs ordinals) {
super(ordinals);
this.values = values;
}
@Override
public final long getValueByOrd(long ord) {
assert ord != Ordinals.MISSING_ORDINAL;
return (long) values.get(ord);
}
}
static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues.WithOrdinals {
private final BigDoubleArrayList values;
DoubleValues(BigDoubleArrayList values, Ordinals.Docs ordinals) {
super(ordinals);
this.values = values;
}
@Override
public double getValueByOrd(long ord) {
assert ord != Ordinals.MISSING_ORDINAL;
return values.get(ord);
}
}
}
/**
* A single valued case, where not all values are "set", so we have a FixedBitSet that
* indicates which values have an actual value.
*/
public static class SingleFixedSet extends DoubleArrayAtomicFieldData {
private final BigDoubleArrayList values;
private final FixedBitSet set;
private final long numOrds;
public SingleFixedSet(BigDoubleArrayList values, int numDocs, FixedBitSet set, long numOrds) {
super(numDocs);
this.values = values;
this.set = set;
this.numOrds = numOrds;
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public boolean isValuesOrdered() {
return false;
}
@Override
public long getNumberUniqueValues() {
return numOrds;
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.sizeInBytes() + RamUsageEstimator.sizeOf(set.getBits());
}
return size;
}
@Override
public LongValues getLongValues() {
return new LongValues(values, set);
}
@Override
public DoubleValues getDoubleValues() {
return new DoubleValues(values, set);
}
static class LongValues extends org.elasticsearch.index.fielddata.LongValues {
private final BigDoubleArrayList values;
private final FixedBitSet set;
LongValues(BigDoubleArrayList values, FixedBitSet set) {
super(false);
this.values = values;
this.set = set;
}
@Override
public int setDocument(int docId) {
this.docId = docId;
return set.get(docId) ? 1 : 0;
}
@Override
public long nextValue() {
return (long) values.get(docId);
}
}
static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues {
private final BigDoubleArrayList values;
private final FixedBitSet set;
DoubleValues(BigDoubleArrayList values, FixedBitSet set) {
super(false);
this.values = values;
this.set = set;
}
@Override
public int setDocument(int docId) {
this.docId = docId;
return set.get(docId) ? 1 : 0;
}
@Override
public double nextValue() {
return values.get(docId);
}
}
}
/**
* Assumes all the values are "set", and docId is used as the index to the value array.
*/
public static class Single extends DoubleArrayAtomicFieldData {
private final BigDoubleArrayList values;
private final long numOrds;
/**
* Note, here, we assume that there is no offset by 1 from docId, so position 0
* is the value for docId 0.
*/
public Single(BigDoubleArrayList values, int numDocs, long numOrds) {
super(numDocs);
this.values = values;
this.numOrds = numOrds;
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public boolean isValuesOrdered() {
return false;
}
@Override
public long getNumberUniqueValues() {
return numOrds;
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.sizeInBytes();
}
return size;
}
@Override
public LongValues getLongValues() {
return new LongValues(values);
}
@Override
public DoubleValues getDoubleValues() {
return new DoubleValues(values);
}
static final class LongValues extends DenseLongValues {
private final BigDoubleArrayList values;
LongValues(BigDoubleArrayList values) {
super(false);
this.values = values;
}
@Override
public long nextValue() {
return (long) values.get(docId);
}
}
static final class DoubleValues extends DenseDoubleValues {
private final BigDoubleArrayList values;
DoubleValues(BigDoubleArrayList values) {
super(false);
this.values = values;
}
@Override
public double nextValue() {
return values.get(docId);
}
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_fielddata_plain_DoubleArrayAtomicFieldData.java
|
21 |
@SuppressWarnings("rawtypes")
static final class KeySet<E> extends AbstractSet<E> implements ONavigableSet<E> {
private final ONavigableMap<E, Object> m;
KeySet(ONavigableMap<E, Object> map) {
m = map;
}
@Override
public OLazyIterator<E> iterator() {
if (m instanceof OMVRBTree)
return ((OMVRBTree<E, Object>) m).keyIterator();
else
return (((OMVRBTree.NavigableSubMap) m).keyIterator());
}
public OLazyIterator<E> descendingIterator() {
if (m instanceof OMVRBTree)
return ((OMVRBTree<E, Object>) m).descendingKeyIterator();
else
return (((OMVRBTree.NavigableSubMap) m).descendingKeyIterator());
}
@Override
public int size() {
return m.size();
}
@Override
public boolean isEmpty() {
return m.isEmpty();
}
@Override
public boolean contains(final Object o) {
return m.containsKey(o);
}
@Override
public void clear() {
m.clear();
}
public E lower(final E e) {
return m.lowerKey(e);
}
public E floor(final E e) {
return m.floorKey(e);
}
public E ceiling(final E e) {
return m.ceilingKey(e);
}
public E higher(final E e) {
return m.higherKey(e);
}
public E first() {
return m.firstKey();
}
public E last() {
return m.lastKey();
}
public Comparator<? super E> comparator() {
return m.comparator();
}
public E pollFirst() {
final Map.Entry<E, Object> e = m.pollFirstEntry();
return e == null ? null : e.getKey();
}
public E pollLast() {
final Map.Entry<E, Object> e = m.pollLastEntry();
return e == null ? null : e.getKey();
}
@Override
public boolean remove(final Object o) {
final int oldSize = size();
m.remove(o);
return size() != oldSize;
}
public ONavigableSet<E> subSet(final E fromElement, final boolean fromInclusive, final E toElement, final boolean toInclusive) {
return new OMVRBTreeSet<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive));
}
public ONavigableSet<E> headSet(final E toElement, final boolean inclusive) {
return new OMVRBTreeSet<E>(m.headMap(toElement, inclusive));
}
public ONavigableSet<E> tailSet(final E fromElement, final boolean inclusive) {
return new OMVRBTreeSet<E>(m.tailMap(fromElement, inclusive));
}
public SortedSet<E> subSet(final E fromElement, final E toElement) {
return subSet(fromElement, true, toElement, false);
}
public SortedSet<E> headSet(final E toElement) {
return headSet(toElement, false);
}
public SortedSet<E> tailSet(final E fromElement) {
return tailSet(fromElement, true);
}
public ONavigableSet<E> descendingSet() {
return new OMVRBTreeSet<E>(m.descendingMap());
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
|
2,601 |
private class SymmetricCipherPacketWriter implements PacketWriter {
final Cipher cipher;
ByteBuffer packetBuffer = ByteBuffer.allocate(ioService.getSocketSendBufferSize() * IOService.KILO_BYTE);
boolean packetWritten;
SymmetricCipherPacketWriter() {
cipher = init();
}
private Cipher init() {
Cipher c;
try {
c = CipherHelper.createSymmetricWriterCipher(ioService.getSymmetricEncryptionConfig());
} catch (Exception e) {
logger.severe("Symmetric Cipher for WriteHandler cannot be initialized.", e);
CipherHelper.handleCipherException(e, connection);
throw ExceptionUtil.rethrow(e);
}
return c;
}
public boolean writePacket(Packet packet, ByteBuffer socketBuffer) throws Exception {
if (!packetWritten) {
if (socketBuffer.remaining() < CONST_BUFFER_NO) {
return false;
}
int size = cipher.getOutputSize(packet.size());
socketBuffer.putInt(size);
if (packetBuffer.capacity() < packet.size()) {
packetBuffer = ByteBuffer.allocate(packet.size());
}
if (!packet.writeTo(packetBuffer)) {
throw new HazelcastException("Packet didn't fit into the buffer!");
}
packetBuffer.flip();
packetWritten = true;
}
if (socketBuffer.hasRemaining()) {
int outputSize = cipher.getOutputSize(packetBuffer.remaining());
if (outputSize <= socketBuffer.remaining()) {
cipher.update(packetBuffer, socketBuffer);
} else {
int min = Math.min(packetBuffer.remaining(), socketBuffer.remaining());
int len = min / 2;
if (len > 0) {
int limitOld = packetBuffer.limit();
packetBuffer.limit(packetBuffer.position() + len);
cipher.update(packetBuffer, socketBuffer);
packetBuffer.limit(limitOld);
}
}
if (!packetBuffer.hasRemaining()) {
if (socketBuffer.remaining() >= cipher.getOutputSize(0)) {
socketBuffer.put(cipher.doFinal());
packetWritten = false;
packetBuffer.clear();
return true;
}
}
}
return false;
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_nio_SocketPacketWriter.java
|
4,802 |
public class RestClusterStateAction extends BaseRestHandler {
private final SettingsFilter settingsFilter;
@Inject
public RestClusterStateAction(Settings settings, Client client, RestController controller,
SettingsFilter settingsFilter) {
super(settings, client);
controller.registerHandler(RestRequest.Method.GET, "/_cluster/state", this);
controller.registerHandler(RestRequest.Method.GET, "/_cluster/state/{metric}", this);
controller.registerHandler(RestRequest.Method.GET, "/_cluster/state/{metric}/{indices}", this);
this.settingsFilter = settingsFilter;
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel) {
final ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest();
clusterStateRequest.listenerThreaded(false);
clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));
final String[] indices = Strings.splitStringByCommaToArray(request.param("indices", "_all"));
boolean isAllIndicesOnly = indices.length == 1 && "_all".equals(indices[0]);
if (!isAllIndicesOnly) {
clusterStateRequest.indices(indices);
}
Set<String> metrics = Strings.splitStringByCommaToSet(request.param("metric", "_all"));
boolean isAllMetricsOnly = metrics.size() == 1 && metrics.contains("_all");
if (!isAllMetricsOnly) {
clusterStateRequest.nodes(metrics.contains("nodes"));
clusterStateRequest.routingTable(metrics.contains("routing_table"));
clusterStateRequest.metaData(metrics.contains("metadata"));
clusterStateRequest.blocks(metrics.contains("blocks"));
clusterStateRequest.indexTemplates(request.paramAsStringArray("index_templates", Strings.EMPTY_ARRAY));
}
client.admin().cluster().state(clusterStateRequest, new ActionListener<ClusterStateResponse>() {
@Override
public void onResponse(ClusterStateResponse response) {
try {
XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
builder.startObject();
builder.field(Fields.CLUSTER_NAME, response.getClusterName().value());
response.getState().settingsFilter(settingsFilter).toXContent(builder, request);
builder.endObject();
channel.sendResponse(new XContentRestResponse(request, RestStatus.OK, builder));
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
if (logger.isDebugEnabled()) {
logger.debug("failed to handle cluster state", e);
}
try {
channel.sendResponse(new XContentThrowableRestResponse(request, e));
} catch (IOException e1) {
logger.error("Failed to send failure response", e1);
}
}
});
}
static final class Fields {
static final XContentBuilderString CLUSTER_NAME = new XContentBuilderString("cluster_name");
}
}
| 1no label
|
src_main_java_org_elasticsearch_rest_action_admin_cluster_state_RestClusterStateAction.java
|
58 |
@SuppressWarnings("serial")
static final class ForEachTransformedMappingTask<K,V,U>
extends BulkTask<K,V,Void> {
final BiFun<? super K, ? super V, ? extends U> transformer;
final Action<? super U> action;
ForEachTransformedMappingTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
BiFun<? super K, ? super V, ? extends U> transformer,
Action<? super U> action) {
super(p, b, i, f, t);
this.transformer = transformer; this.action = action;
}
public final void compute() {
final BiFun<? super K, ? super V, ? extends U> transformer;
final Action<? super U> action;
if ((transformer = this.transformer) != null &&
(action = this.action) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
new ForEachTransformedMappingTask<K,V,U>
(this, batch >>>= 1, baseLimit = h, f, tab,
transformer, action).fork();
}
for (Node<K,V> p; (p = advance()) != null; ) {
U u;
if ((u = transformer.apply(p.key, p.val)) != null)
action.apply(u);
}
propagateCompletion();
}
}
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
527 |
public class FlushResponse extends BroadcastOperationResponse {
FlushResponse() {
}
FlushResponse(int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
super(totalShards, successfulShards, failedShards, shardFailures);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_flush_FlushResponse.java
|
441 |
public static class JvmStats implements Streamable, ToXContent {
ObjectIntOpenHashMap<JvmVersion> versions;
long threads;
long maxUptime;
long heapUsed;
long heapMax;
JvmStats() {
versions = new ObjectIntOpenHashMap<JvmVersion>();
threads = 0;
maxUptime = 0;
heapMax = 0;
heapUsed = 0;
}
public ObjectIntOpenHashMap<JvmVersion> getVersions() {
return versions;
}
/**
* The total number of threads in the cluster
*/
public long getThreads() {
return threads;
}
/**
* The maximum uptime of a node in the cluster
*/
public TimeValue getMaxUpTime() {
return new TimeValue(maxUptime);
}
/**
* Total heap used in the cluster
*/
public ByteSizeValue getHeapUsed() {
return new ByteSizeValue(heapUsed);
}
/**
* Maximum total heap available to the cluster
*/
public ByteSizeValue getHeapMax() {
return new ByteSizeValue(heapMax);
}
public void addNodeInfoStats(NodeInfo nodeInfo, NodeStats nodeStats) {
versions.addTo(new JvmVersion(nodeInfo.getJvm()), 1);
org.elasticsearch.monitor.jvm.JvmStats js = nodeStats.getJvm();
if (js == null) {
return;
}
if (js.threads() != null) {
threads += js.threads().count();
}
maxUptime = Math.max(maxUptime, js.uptime().millis());
if (js.mem() != null) {
heapUsed += js.mem().getHeapUsed().bytes();
heapMax += js.mem().getHeapMax().bytes();
}
}
@Override
public void readFrom(StreamInput in) throws IOException {
int size = in.readVInt();
versions = new ObjectIntOpenHashMap<JvmVersion>(size);
for (; size > 0; size--) {
versions.addTo(JvmVersion.readJvmVersion(in), in.readVInt());
}
threads = in.readVLong();
maxUptime = in.readVLong();
heapUsed = in.readVLong();
heapMax = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVInt(versions.size());
for (ObjectIntCursor<JvmVersion> v : versions) {
v.key.writeTo(out);
out.writeVInt(v.value);
}
out.writeVLong(threads);
out.writeVLong(maxUptime);
out.writeVLong(heapUsed);
out.writeVLong(heapMax);
}
public static JvmStats readJvmStats(StreamInput in) throws IOException {
JvmStats jvmStats = new JvmStats();
jvmStats.readFrom(in);
return jvmStats;
}
static final class Fields {
static final XContentBuilderString VERSIONS = new XContentBuilderString("versions");
static final XContentBuilderString VERSION = new XContentBuilderString("version");
static final XContentBuilderString VM_NAME = new XContentBuilderString("vm_name");
static final XContentBuilderString VM_VERSION = new XContentBuilderString("vm_version");
static final XContentBuilderString VM_VENDOR = new XContentBuilderString("vm_vendor");
static final XContentBuilderString COUNT = new XContentBuilderString("count");
static final XContentBuilderString THREADS = new XContentBuilderString("threads");
static final XContentBuilderString MAX_UPTIME = new XContentBuilderString("max_uptime");
static final XContentBuilderString MAX_UPTIME_IN_MILLIS = new XContentBuilderString("max_uptime_in_millis");
static final XContentBuilderString MEM = new XContentBuilderString("mem");
static final XContentBuilderString HEAP_USED = new XContentBuilderString("heap_used");
static final XContentBuilderString HEAP_USED_IN_BYTES = new XContentBuilderString("heap_used_in_bytes");
static final XContentBuilderString HEAP_MAX = new XContentBuilderString("heap_max");
static final XContentBuilderString HEAP_MAX_IN_BYTES = new XContentBuilderString("heap_max_in_bytes");
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.timeValueField(Fields.MAX_UPTIME_IN_MILLIS, Fields.MAX_UPTIME, maxUptime);
builder.startArray(Fields.VERSIONS);
for (ObjectIntCursor<JvmVersion> v : versions) {
builder.startObject();
builder.field(Fields.VERSION, v.key.version);
builder.field(Fields.VM_NAME, v.key.vmName);
builder.field(Fields.VM_VERSION, v.key.vmVersion);
builder.field(Fields.VM_VENDOR, v.key.vmVendor);
builder.field(Fields.COUNT, v.value);
builder.endObject();
}
builder.endArray();
builder.startObject(Fields.MEM);
builder.byteSizeField(Fields.HEAP_USED_IN_BYTES, Fields.HEAP_USED, heapUsed);
builder.byteSizeField(Fields.HEAP_MAX_IN_BYTES, Fields.HEAP_MAX, heapMax);
builder.endObject();
builder.field(Fields.THREADS, threads);
return builder;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsNodes.java
|
958 |
public abstract class ClusterInfoRequestBuilder<Request extends ClusterInfoRequest<Request>, Response extends ActionResponse, Builder extends ClusterInfoRequestBuilder<Request, Response, Builder>> extends MasterNodeReadOperationRequestBuilder<Request, Response, Builder> {
protected ClusterInfoRequestBuilder(InternalGenericClient client, Request request) {
super(client, request);
}
@SuppressWarnings("unchecked")
public Builder setIndices(String... indices) {
request.indices(indices);
return (Builder) this;
}
@SuppressWarnings("unchecked")
public Builder addIndices(String... indices) {
request.indices(ObjectArrays.concat(request.indices(), indices, String.class));
return (Builder) this;
}
@SuppressWarnings("unchecked")
public Builder setTypes(String... types) {
request.types(types);
return (Builder) this;
}
@SuppressWarnings("unchecked")
public Builder addTypes(String... types) {
request.types(ObjectArrays.concat(request.types(), types, String.class));
return (Builder) this;
}
@SuppressWarnings("unchecked")
public Builder setIndicesOptions(IndicesOptions indicesOptions) {
request.indicesOptions(indicesOptions);
return (Builder) this;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_master_info_ClusterInfoRequestBuilder.java
|
16 |
public static interface AsynchronousCompletionTask {
}
| 0true
|
src_main_java_jsr166e_CompletableFuture.java
|
178 |
public static class Map extends EnumMap<EntryMetaData,Object> {
public Map() {
super(EntryMetaData.class);
}
@Override
public Object put(EntryMetaData key, Object value) {
Preconditions.checkArgument(key.isValidData(value),"Invalid meta data [%s] for [%s]",value,key);
return super.put(key,value);
}
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_EntryMetaData.java
|
586 |
public interface FulfillmentPriceExceptionResponse extends Serializable {
public boolean isErrorDetected();
public void setErrorDetected(boolean isErrorDetected);
public String getErrorCode();
public void setErrorCode(String errorCode);
public String getErrorText();
public void setErrorText(String errorText);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_vendor_service_message_FulfillmentPriceExceptionResponse.java
|
599 |
public abstract class BLCAbstractHandlerMapping extends AbstractHandlerMapping {
protected String controllerName;
@Override
/**
* This handler mapping does not provide a default handler. This method
* has been coded to always return null.
*/
public Object getDefaultHandler() {
return null;
}
/**
* Returns the controllerName if set or "blPageController" by default.
* @return
*/
public String getControllerName() {
return controllerName;
}
/**
* Sets the name of the bean to use as the Handler. Typically the name of
* a controller bean.
*
* @param controllerName
*/
public void setControllerName(String controllerName) {
this.controllerName = controllerName;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_web_BLCAbstractHandlerMapping.java
|
645 |
public class DeleteIndexTemplateRequestBuilder extends MasterNodeOperationRequestBuilder<DeleteIndexTemplateRequest, DeleteIndexTemplateResponse, DeleteIndexTemplateRequestBuilder> {
public DeleteIndexTemplateRequestBuilder(IndicesAdminClient indicesClient) {
super((InternalIndicesAdminClient) indicesClient, new DeleteIndexTemplateRequest());
}
public DeleteIndexTemplateRequestBuilder(IndicesAdminClient indicesClient, String name) {
super((InternalIndicesAdminClient) indicesClient, new DeleteIndexTemplateRequest(name));
}
@Override
protected void doExecute(ActionListener<DeleteIndexTemplateResponse> listener) {
((IndicesAdminClient) client).deleteTemplate(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_template_delete_DeleteIndexTemplateRequestBuilder.java
|
567 |
metaDataMappingService.putMapping(updateRequest, new ClusterStateUpdateListener() {
@Override
public void onResponse(ClusterStateUpdateResponse response) {
listener.onResponse(new PutMappingResponse(response.isAcknowledged()));
}
@Override
public void onFailure(Throwable t) {
logger.debug("failed to put mappings on indices [{}], type [{}]", t, request.indices(), request.type());
listener.onFailure(t);
}
});
| 1no label
|
src_main_java_org_elasticsearch_action_admin_indices_mapping_put_TransportPutMappingAction.java
|
444 |
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class ClientQueueTest {
final static int maxSizeForQueue = 8;
final static String queueWithMaxSize = "queueWithMaxSize*";
static HazelcastInstance client;
static HazelcastInstance server;
@BeforeClass
public static void init(){
Config config = new Config();
QueueConfig queueConfig = config.getQueueConfig(queueWithMaxSize);
queueConfig.setMaxSize(maxSizeForQueue);
server = Hazelcast.newHazelcastInstance(config);
client = HazelcastClient.newHazelcastClient();
}
@AfterClass
public static void destroy() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testOffer() {
final IQueue q = client.getQueue(randomString());
assertTrue(q.offer(1));
assertEquals(1, q.size());
}
@Test
public void testadd() {
final IQueue q = client.getQueue(randomString());
assertTrue(q.add(1));
assertEquals(1, q.size());
}
@Test
public void testAdd_whenReachingMaximumCapacity() {
final IQueue q = client.getQueue(queueWithMaxSize+randomString());
for(int i=0; i<maxSizeForQueue; i++){
q.add(1);
}
assertEquals(maxSizeForQueue, q.size());
}
@Test(expected = IllegalStateException.class)
public void testAdd_whenExceedingMaximumCapacity() {
final IQueue q = client.getQueue(queueWithMaxSize+randomString());
for(int i=0; i<maxSizeForQueue; i++){
q.add(1);
}
q.add(1);
}
@Test
public void testPut() throws InterruptedException {
final IQueue q = client.getQueue(randomString());
q.put(1);
assertEquals(1, q.size());
}
@Test
public void testTake() throws InterruptedException {
final IQueue q = client.getQueue(randomString());
q.put(1);
assertEquals(1, q.take());
}
@Test(expected = InterruptedException.class)
public void testTake_whenInterruptedWhileBlocking() throws InterruptedException {
IQueue queue = client.getQueue(randomString());
interruptCurrentThread(2000);
queue.take();
}
@Test
public void testEmptyPeak() throws InterruptedException {
final IQueue q = client.getQueue(randomString());
assertNull(q.peek());
}
@Test
public void testPeak() throws InterruptedException {
final IQueue q = client.getQueue(randomString());
q.offer(1);
assertEquals(1, q.peek());
assertEquals(1, q.peek());
assertEquals(1, q.size());
}
@Test(expected = NoSuchElementException.class)
public void testEmptyElement() throws InterruptedException {
final IQueue q = client.getQueue(randomString());
q.element();
}
@Test
public void testElement() throws InterruptedException {
final IQueue q = client.getQueue(randomString());
q.offer(1);
assertEquals(1, q.element());
}
@Test
public void testPoll() throws InterruptedException {
final IQueue q = client.getQueue(randomString());
q.offer(1);
assertEquals(1, q.poll());
}
@Test(expected = InterruptedException.class)
public void testPoll_whenInterruptedWhileBlocking() throws InterruptedException {
IQueue queue = client.getQueue(randomString());
interruptCurrentThread(2000);
queue.poll(1, TimeUnit.MINUTES);
}
@Test
public void testOfferWithTimeOut() throws IOException, InterruptedException {
final IQueue q = client.getQueue(randomString());
boolean result = q.offer(1, 50, TimeUnit.MILLISECONDS);
assertTrue(result);
}
@Test
public void testRemainingCapacity() throws IOException {
final IQueue q = client.getQueue(randomString());
assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
q.offer("one");
assertEquals(Integer.MAX_VALUE-1, q.remainingCapacity());
}
@Test(expected = NoSuchElementException.class)
public void testEmptyRemove() throws IOException {
final IQueue q = client.getQueue(randomString());
q.remove();
}
@Test
public void testRemoveTop() throws IOException, InterruptedException {
final IQueue q = client.getQueue(randomString());
q.offer(1);
assertEquals(1, q.remove());
}
@Test
public void testRemove() throws IOException {
final IQueue q = client.getQueue(randomString());
q.offer(1);
assertTrue(q.remove(1));
assertFalse(q.remove(2));
}
@Test
public void testContains() {
final IQueue q = client.getQueue(randomString());
q.offer(1);
assertTrue(q.contains(1));
assertFalse(q.contains(2));
}
@Test
public void testContainsAll() {
final int maxItems = 11;
final IQueue q = client.getQueue(randomString());
List trueList = new ArrayList();
List falseList = new ArrayList();
for(int i=0; i<maxItems; i++){
q.offer(i);
trueList.add(i);
falseList.add(i+1);
}
assertTrue(q.containsAll(trueList));
assertFalse(q.containsAll(falseList));
}
@Test
public void testDrain() {
final int maxItems = 12;
final IQueue q = client.getQueue(randomString());
List offeredList = new LinkedList();
for(int i=0; i<maxItems; i++){
q.offer(i);
offeredList.add(i);
}
List drainedList = new LinkedList();
int totalDrained = q.drainTo(drainedList);
assertEquals(maxItems, totalDrained);
assertEquals(offeredList, drainedList);
}
@Test
public void testPartialDrain() {
final int maxItems = 15;
final int itemsToDrain = maxItems/2;
final IQueue q = client.getQueue(randomString());
List expectedList = new LinkedList();
for(int i=0; i<maxItems; i++){
q.offer(i);
if(i < itemsToDrain){
expectedList.add(i);
}
}
List drainedList = new LinkedList();
int totalDrained = q.drainTo(drainedList, itemsToDrain);
assertEquals(itemsToDrain, totalDrained);
assertEquals(expectedList, drainedList);
}
@Test
public void testIterator(){
final int maxItems = 18;
final IQueue q = client.getQueue(randomString());
for(int i=0; i<maxItems; i++){
q.offer(i);
}
int i=0;
for (Object o : q) {
assertEquals(i++, o);
}
}
@Test
public void testToArray(){
final int maxItems = 19;
final IQueue q = client.getQueue(randomString());
Object[] offered = new Object[maxItems];
for(int i=0; i<maxItems; i++){
q.offer(i);
offered[i]=i;
}
Object[] result = q.toArray();
assertEquals(offered, result);
}
@Test
public void testToPartialArray(){
final int maxItems = 74;
final int arraySZ = maxItems / 2 ;
final IQueue q = client.getQueue(randomString());
Object[] offered = new Object[maxItems];
for(int i=0; i<maxItems; i++){
q.offer(i);
offered[i]=i;
}
Object[] result = q.toArray(new Object[arraySZ]);
assertEquals(offered, result);
}
@Test
public void testAddAll() throws IOException {
final int maxItems = 13;
final IQueue q = client.getQueue(randomString());
Collection coll = new ArrayList(maxItems);
for(int i=0; i<maxItems; i++){
coll.add(i);
}
assertTrue(q.addAll(coll));
assertEquals(coll.size(), q.size());
}
@Test
public void testRemoveList() throws IOException {
final int maxItems = 131;
final IQueue q = client.getQueue(randomString());
List removeList = new LinkedList();
for(int i=0; i<maxItems; i++){
q.add(i);
removeList.add(i);
}
assertTrue(q.removeAll(removeList));
assertEquals(0, q.size());
}
@Test
public void testRemoveList_whereNotFound() throws IOException {
final int maxItems = 131;
final IQueue q = client.getQueue(randomString());
List removeList = new LinkedList();
for(int i=0; i<maxItems; i++){
q.add(i);
}
removeList.add(maxItems+1);
removeList.add(maxItems+2);
assertFalse(q.removeAll(removeList));
assertEquals(maxItems, q.size());
}
@Test
public void testRetainEmptyList() throws IOException {
final int maxItems = 131;
final IQueue q = client.getQueue(randomString());
for(int i=0; i<maxItems; i++){
q.add(i);
}
List retain = new LinkedList();
assertTrue(q.retainAll(retain));
assertEquals(0, q.size());
}
@Test
public void testRetainAllList() throws IOException {
final int maxItems = 181;
final IQueue q = client.getQueue(randomString());
List retain = new LinkedList();
for(int i=0; i<maxItems; i++){
q.add(i);
retain.add(i);
}
assertFalse(q.retainAll(retain));
assertEquals(maxItems, q.size());
}
@Test
public void testRetainAll_ListNotFound() throws IOException {
final int maxItems = 181;
final IQueue q = client.getQueue(randomString());
List retain = new LinkedList();
for(int i=0; i<maxItems; i++){
q.add(i);
}
retain.add(maxItems+1);
retain.add(maxItems+2);
assertTrue(q.retainAll(retain));
assertEquals(0, q.size());
}
@Test
public void testRetainAll_mixedList() throws IOException {
final int maxItems = 181;
final IQueue q = client.getQueue(randomString());
List retain = new LinkedList();
for(int i=0; i<maxItems; i++){
q.add(i);
}
retain.add(maxItems-1);
retain.add(maxItems+1);
assertTrue(q.retainAll(retain));
assertEquals(1, q.size());
}
@Test
public void testSize(){
final int maxItems = 143;
final IQueue q = client.getQueue(randomString());
for(int i=0; i<maxItems; i++){
q.add(i);
}
assertEquals(maxItems, q.size());
}
@Test
public void testIsEmpty(){
final IQueue q = client.getQueue(randomString());
assertTrue(q.isEmpty());
}
@Test
public void testNotIsEmpty(){
final IQueue q = client.getQueue(randomString());
q.offer(1);
assertFalse(q.isEmpty());
}
@Test
public void testClear(){
final int maxItems = 123;
final IQueue q = client.getQueue(randomString());
for(int i=0; i<maxItems; i++){
q.add(i);
}
assertEquals(maxItems, q.size());
q.clear();
assertEquals(0, q.size());
}
@Test
public void testListener() throws Exception {
final int maxItems = 10;
final CountDownLatch itemAddedLatch = new CountDownLatch(maxItems);
final CountDownLatch itemRemovedLatch = new CountDownLatch(maxItems);
final IQueue queue = client.getQueue(randomString());
String id = queue.addItemListener(new ItemListener() {
public void itemAdded(ItemEvent itemEvent) {
itemAddedLatch.countDown();
}
public void itemRemoved(ItemEvent item) {
itemRemovedLatch.countDown();
}
}, true);
new Thread(){
public void run() {
for (int i=0; i<maxItems; i++){
queue.offer(i);
queue.remove(i);
}
}
}.start();
assertTrue(itemAddedLatch.await(5, TimeUnit.SECONDS));
assertTrue(itemRemovedLatch.await(5, TimeUnit.SECONDS));
queue.removeItemListener(id);
}
@Test(expected = UnsupportedOperationException.class)
public void testGetLocalQueueStats() {
final IQueue q = client.getQueue(randomString());
q.getLocalQueueStats();
}
@Test
public void testOffer_whenExceedingMaxCapacity(){
final IQueue q = client.getQueue(queueWithMaxSize+randomString());
for(int i=0; i< maxSizeForQueue; i++){
q.offer(i);
}
assertFalse(q.offer(maxSizeForQueue));
}
@Test
public void testOfferPoll() throws IOException, InterruptedException {
final IQueue q = client.getQueue(queueWithMaxSize+randomString());
for (int i=0; i<10; i++){
boolean result = q.offer("item");
if (i<maxSizeForQueue){
assertTrue(result);
}
else {
assertFalse(result);
}
}
assertEquals(maxSizeForQueue, q.size());
final Thread t1 = new Thread() {
public void run() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
q.poll();
}
};
t1.start();
boolean result = q.offer("item",5, TimeUnit.SECONDS);
assertTrue(result);
for (int i=0; i<10; i++){
Object o = q.poll();
if (i<maxSizeForQueue){
assertNotNull(o);
}
else {
assertNull(o);
}
}
assertEquals(0, q.size());
final Thread t2 = new Thread() {
public void run() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
q.offer("item1");
}
};
t2.start();
Object o = q.poll(5, TimeUnit.SECONDS);
assertEquals("item1", o);
t1.join(10000);
t2.join(10000);
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_queue_ClientQueueTest.java
|
148 |
final class JavaClientExceptionConverter implements ClientExceptionConverter {
@Override
public Object convert(Throwable t) {
return t;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_client_JavaClientExceptionConverter.java
|
199 |
public static class Name {
public static final String Audit = "Auditable_Tab";
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_audit_Auditable.java
|
2,682 |
class FieldDefinitionImpl implements DataSerializable, FieldDefinition {
int index;
String fieldName;
FieldType type;
int classId;
int factoryId;
FieldDefinitionImpl() {
}
FieldDefinitionImpl(int index, String fieldName, FieldType type) {
this(index, fieldName, type, 0, Data.NO_CLASS_ID);
}
FieldDefinitionImpl(int index, String fieldName, FieldType type, int factoryId, int classId) {
this.classId = classId;
this.type = type;
this.fieldName = fieldName;
this.index = index;
this.factoryId = factoryId;
}
public FieldType getType() {
return type;
}
public String getName() {
return fieldName;
}
public int getIndex() {
return index;
}
public int getFactoryId() {
return factoryId;
}
public int getClassId() {
return classId;
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(index);
out.writeUTF(fieldName);
out.writeByte(type.getId());
out.writeInt(factoryId);
out.writeInt(classId);
}
public void readData(ObjectDataInput in) throws IOException {
index = in.readInt();
fieldName = in.readUTF();
type = FieldType.get(in.readByte());
factoryId = in.readInt();
classId = in.readInt();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FieldDefinitionImpl that = (FieldDefinitionImpl) o;
if (classId != that.classId) {
return false;
}
if (factoryId != that.factoryId) {
return false;
}
if (fieldName != null ? !fieldName.equals(that.fieldName) : that.fieldName != null) {
return false;
}
if (type != that.type) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = fieldName != null ? fieldName.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + classId;
result = 31 * result + factoryId;
return result;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("FieldDefinitionImpl{");
sb.append("index=").append(index);
sb.append(", fieldName='").append(fieldName).append('\'');
sb.append(", type=").append(type);
sb.append(", classId=").append(classId);
sb.append(", factoryId=").append(factoryId);
sb.append('}');
return sb.toString();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_nio_serialization_FieldDefinitionImpl.java
|
637 |
public class MemberAttributeChange implements DataSerializable {
private String uuid;
private MemberAttributeOperationType operationType;
private String key;
private Object value;
public MemberAttributeChange() {
}
public MemberAttributeChange(String uuid, MemberAttributeOperationType operationType, String key, Object value) {
this.uuid = uuid;
this.operationType = operationType;
this.key = key;
this.value = value;
}
public String getUuid() {
return uuid;
}
public MemberAttributeOperationType getOperationType() {
return operationType;
}
public String getKey() {
return key;
}
public Object getValue() {
return value;
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(uuid);
out.writeUTF(key);
out.writeByte(operationType.getId());
if (operationType == PUT) {
IOUtil.writeAttributeValue(value, out);
}
}
@Override
public void readData(ObjectDataInput in) throws IOException {
uuid = in.readUTF();
key = in.readUTF();
operationType = MemberAttributeOperationType.getValue(in.readByte());
if (operationType == PUT) {
value = IOUtil.readAttributeValue(in);
}
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_cluster_client_MemberAttributeChange.java
|
3 |
ceylonOutputFolder.accept(new IResourceVisitor() {
@Override
public boolean visit(IResource resource) throws CoreException {
if (resource instanceof IFile) {
filesToAddInArchive.add((IFile)resource);
}
return true;
}
});
| 0true
|
plugins_com.redhat.ceylon.eclipse.android.plugin_src_com_redhat_ceylon_eclipse_android_plugin_AndroidBuildHookProvider.java
|
122 |
class FindArgumentsVisitor extends Visitor
implements NaturalVisitor {
Tree.MemberOrTypeExpression smte;
Tree.NamedArgumentList namedArgs;
Tree.PositionalArgumentList positionalArgs;
ProducedType currentType;
ProducedType expectedType;
boolean found = false;
boolean inEnumeration = false;
FindArgumentsVisitor(Tree.MemberOrTypeExpression smte) {
this.smte = smte;
}
@Override
public void visit(Tree.MemberOrTypeExpression that) {
super.visit(that);
if (that==smte) {
expectedType = currentType;
found = true;
}
}
@Override
public void visit(Tree.InvocationExpression that) {
super.visit(that);
if (that.getPrimary()==smte) {
namedArgs = that.getNamedArgumentList();
positionalArgs = that.getPositionalArgumentList();
}
}
@Override
public void visit(Tree.NamedArgument that) {
ProducedType ct = currentType;
currentType = that.getParameter()==null ?
null : that.getParameter().getType();
super.visit(that);
currentType = ct;
}
@Override
public void visit(Tree.PositionalArgument that) {
if (inEnumeration) {
inEnumeration = false;
super.visit(that);
inEnumeration = true;
}
else {
ProducedType ct = currentType;
currentType = that.getParameter()==null ?
null : that.getParameter().getType();
super.visit(that);
currentType = ct;
}
}
@Override
public void visit(Tree.AttributeDeclaration that) {
currentType = that.getType().getTypeModel();
super.visit(that);
currentType = null;
}
/*@Override
public void visit(Tree.Variable that) {
currentType = that.getType().getTypeModel();
super.visit(that);
currentType = null;
}*/
@Override
public void visit(Tree.Resource that) {
Unit unit = that.getUnit();
currentType = unionType(unit.getDestroyableDeclaration().getType(),
unit.getObtainableDeclaration().getType(), unit);
super.visit(that);
currentType = null;
}
@Override
public void visit(Tree.BooleanCondition that) {
currentType = that.getUnit().getBooleanDeclaration().getType();
super.visit(that);
currentType = null;
}
@Override
public void visit(Tree.ExistsCondition that) {
ProducedType varType = that.getVariable().getType().getTypeModel();
currentType = that.getUnit().getOptionalType(varType);
super.visit(that);
currentType = null;
}
@Override
public void visit(Tree.NonemptyCondition that) {
ProducedType varType = that.getVariable().getType().getTypeModel();
currentType = that.getUnit().getEmptyType(varType);
super.visit(that);
currentType = null;
}
@Override
public void visit(Tree.Exists that) {
ProducedType oit = currentType;
currentType = that.getUnit().getAnythingDeclaration().getType();
super.visit(that);
currentType = oit;
}
@Override
public void visit(Tree.Nonempty that) {
Unit unit = that.getUnit();
ProducedType oit = currentType;
currentType = unit.getSequentialType(unit.getAnythingDeclaration().getType());
super.visit(that);
currentType = oit;
}
@Override
public void visit(Tree.SatisfiesCondition that) {
ProducedType objectType = that.getUnit().getObjectDeclaration().getType();
currentType = objectType;
super.visit(that);
currentType = null;
}
@Override
public void visit(Tree.ValueIterator that) {
ProducedType varType = that.getVariable().getType().getTypeModel();
currentType = that.getUnit().getIterableType(varType);
super.visit(that);
currentType = null;
}
@Override
public void visit(Tree.KeyValueIterator that) {
ProducedType keyType = that.getKeyVariable().getType().getTypeModel();
ProducedType valueType = that.getValueVariable().getType().getTypeModel();
currentType = that.getUnit().getIterableType(that.getUnit()
.getEntryType(keyType, valueType));
super.visit(that);
currentType = null;
}
@Override
public void visit(Tree.BinaryOperatorExpression that) {
if (currentType==null) {
//fallback strategy for binary operators
//TODO: not quite appropriate for a
// couple of them!
Tree.Term rightTerm = that.getRightTerm();
Tree.Term leftTerm = that.getLeftTerm();
if (rightTerm!=null &&
!isTypeUnknown(rightTerm.getTypeModel())) {
currentType = rightTerm.getTypeModel();
}
if (leftTerm!=null) leftTerm.visit(this);
if (leftTerm!=null &&
!isTypeUnknown(leftTerm.getTypeModel())) {
currentType = leftTerm.getTypeModel();
}
if (rightTerm!=null) rightTerm.visit(this);
currentType = null;
}
else {
super.visit(that);
}
}
@Override public void visit(Tree.EntryOp that) {
Unit unit = that.getUnit();
if (currentType!=null &&
currentType.getDeclaration().equals(unit.getEntryDeclaration())) {
ProducedType oit = currentType;
currentType = unit.getKeyType(oit);
if (that.getLeftTerm()!=null) {
that.getLeftTerm().visit(this);
}
currentType = unit.getValueType(oit);
if (that.getRightTerm()!=null) {
that.getRightTerm().visit(this);
}
currentType = oit;
}
else {
ProducedType oit = currentType;
currentType = that.getUnit().getObjectDeclaration().getType();
super.visit(that);
currentType = oit;
}
}
@Override public void visit(Tree.RangeOp that) {
Unit unit = that.getUnit();
if (currentType!=null &&
unit.isIterableType(currentType)) {
ProducedType oit = currentType;
currentType = unit.getIteratedType(oit);
super.visit(that);
currentType = oit;
}
else {
ProducedType oit = currentType;
currentType = that.getUnit().getObjectDeclaration().getType();
super.visit(that);
currentType = oit;
}
}
@Override public void visit(Tree.SegmentOp that) {
Unit unit = that.getUnit();
if (currentType!=null &&
unit.isIterableType(currentType)) {
ProducedType oit = currentType;
currentType = unit.getIteratedType(oit);
super.visit(that);
currentType = oit;
}
else {
ProducedType oit = currentType;
currentType = that.getUnit().getObjectDeclaration().getType();
super.visit(that);
currentType = oit;
}
}
@Override public void visit(Tree.IndexExpression that) {
Unit unit = that.getUnit();
Tree.ElementOrRange eor = that.getElementOrRange();
Tree.Primary primary = that.getPrimary();
ProducedType oit = currentType;
ProducedType indexType = unit.getObjectDeclaration().getType();
if (eor instanceof Tree.Element) {
Tree.Expression e = ((Tree.Element) eor).getExpression();
if (e!=null && !isTypeUnknown(e.getTypeModel())) {
indexType = e.getTypeModel();
}
}
if (eor instanceof Tree.ElementRange) {
Tree.Expression l = ((Tree.ElementRange) eor).getLowerBound();
Tree.Expression u = ((Tree.ElementRange) eor).getUpperBound();
if (l!=null && !isTypeUnknown(l.getTypeModel())) {
indexType = l.getTypeModel();
}
else if (u!=null && !isTypeUnknown(u.getTypeModel())) {
indexType = u.getTypeModel();
}
}
currentType = producedType(unit.getCorrespondenceDeclaration(),
indexType, unit.getDefiniteType(currentType));
if (primary!=null) {
primary.visit(this);
}
currentType = unit.getObjectDeclaration().getType();
if (primary!=null && !isTypeUnknown(primary.getTypeModel())) {
//TODO: move this to Unit!
ProducedType supertype = primary.getTypeModel()
.getSupertype(unit.getCorrespondenceDeclaration());
if (supertype!=null && !supertype.getTypeArgumentList().isEmpty()) {
currentType = supertype.getTypeArgumentList().get(0);
}
}
if (eor!=null) {
eor.visit(this);
}
currentType = oit;
}
@Override public void visit(Tree.LogicalOp that) {
Unit unit = that.getUnit();
ProducedType oit = currentType;
currentType = unit.getBooleanDeclaration().getType();
super.visit(that);
currentType = oit;
}
@Override public void visit(Tree.BitwiseOp that) {
Unit unit = that.getUnit();
ProducedType oit = currentType;
currentType = unit.getSetType(unit.getObjectDeclaration().getType()).getType();
super.visit(that);
currentType = oit;
}
@Override public void visit(Tree.NotOp that) {
Unit unit = that.getUnit();
ProducedType oit = currentType;
currentType = unit.getBooleanDeclaration().getType();
super.visit(that);
currentType = oit;
}
@Override public void visit(Tree.InOp that) {
Unit unit = that.getUnit();
ProducedType oit = currentType;
currentType = unit.getObjectDeclaration().getType();
if (that.getLeftTerm()!=null) {
that.getLeftTerm().visit(this);
}
currentType = unit.getCategoryDeclaration().getType();
if (that.getRightTerm()!=null) {
that.getRightTerm().visit(this);
}
currentType = oit;
}
@Override public void visit(Tree.SequenceEnumeration that) {
Unit unit = that.getUnit();
if (currentType!=null &&
unit.isIterableType(currentType)) {
ProducedType oit = currentType;
boolean oie = inEnumeration;
inEnumeration = true;
currentType = unit.getIteratedType(oit);
super.visit(that);
currentType = oit;
inEnumeration = oie;
}
else {
ProducedType oit = currentType;
currentType = that.getUnit().getAnythingDeclaration().getType();
super.visit(that);
currentType = oit;
}
}
@Override public void visit(Tree.Tuple that) {
Unit unit = that.getUnit();
if (currentType!=null &&
unit.isIterableType(currentType)) {
ProducedType oit = currentType;
boolean oie = inEnumeration;
inEnumeration = true;
currentType = unit.getIteratedType(oit);
super.visit(that);
currentType = oit;
inEnumeration = oie;
}
else {
ProducedType oit = currentType;
currentType = that.getUnit().getAnythingDeclaration().getType();
super.visit(that);
currentType = oit;
}
}
@Override
public void visit(Tree.SpecifierStatement that) {
currentType = that.getBaseMemberExpression().getTypeModel();
Tree.SpecifierExpression se = that.getSpecifierExpression();
if (se!=null) {
if (isTypeUnknown(currentType) &&
se.getExpression()!=null) {
currentType = se.getExpression().getTypeModel();
}
}
else {
currentType = null;
}
super.visit(that);
currentType = null;
}
@Override
public void visit(Tree.AssignmentOp that) {
ProducedType ct = currentType;
Tree.Term leftTerm = that.getLeftTerm();
Tree.Term rightTerm = that.getRightTerm();
if (leftTerm!=null && rightTerm!=null) {
currentType = leftTerm.getTypeModel();
if (isTypeUnknown(currentType) ) {
currentType = rightTerm.getTypeModel();
}
}
else {
currentType = null;
}
super.visit(that);
currentType = ct;
}
@Override
public void visit(Tree.Return that) {
if (that.getDeclaration() instanceof TypedDeclaration) {
currentType = ((TypedDeclaration) that.getDeclaration()).getType();
}
super.visit(that);
currentType = null;
}
@Override
public void visit(Tree.Throw that) {
super.visit(that);
//set expected type to Exception
}
@Override
public void visitAny(Node that) {
if (!found) super.visitAny(that);
}
@Override
public void visit(Tree.FunctionArgument that) {
ProducedType ct = currentType;
currentType = null;
super.visit(that);
currentType = ct;
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_FindArgumentsVisitor.java
|
130 |
public enum SchemaAction {
/**
* Registers the index with all instances in the graph cluster. After an index is installed, it must be registered
* with all graph instances.
*/
REGISTER_INDEX,
/**
* Re-builds the index from the graph
*/
REINDEX,
/**
* Enables the index so that it can be used by the query processing engine. An index must be registered before it
* can be enabled.
*/
ENABLE_INDEX,
/**
* Disables the index in the graph so that it is no longer used.
*/
DISABLE_INDEX,
/**
* Removes the index from the graph (optional operation)
*/
REMOVE_INDEX;
public Set<SchemaStatus> getApplicableStatus() {
switch(this) {
case REGISTER_INDEX: return ImmutableSet.of(SchemaStatus.INSTALLED);
case REINDEX: return ImmutableSet.of(SchemaStatus.REGISTERED,SchemaStatus.ENABLED);
case ENABLE_INDEX: return ImmutableSet.of(SchemaStatus.REGISTERED);
case DISABLE_INDEX: return ImmutableSet.of(SchemaStatus.REGISTERED,SchemaStatus.INSTALLED,SchemaStatus.ENABLED);
case REMOVE_INDEX: return ImmutableSet.of(SchemaStatus.DISABLED);
default: throw new IllegalArgumentException("Action is invalid: " + this);
}
}
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_schema_SchemaAction.java
|
258 |
public class ODefaultCollateFactory implements OCollateFactory {
private static final Map<String, OCollate> COLLATES = new HashMap<String, OCollate>(2);
static {
register(new ODefaultCollate());
register(new OCaseInsensitiveCollate());
}
/**
* @return Set of supported collate names of this factory
*/
@Override
public Set<String> getNames() {
return COLLATES.keySet();
}
/**
* Returns the requested collate
*
* @param name
*/
@Override
public OCollate getCollate(final String name) {
return COLLATES.get(name);
}
private static void register(final OCollate iCollate) {
COLLATES.put(iCollate.getName(), iCollate);
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_collate_ODefaultCollateFactory.java
|
3,208 |
constructors[VECTOR] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new VectorClock();
}
};
| 1no label
|
hazelcast_src_main_java_com_hazelcast_replicatedmap_operation_ReplicatedMapDataSerializerHook.java
|
333 |
static class NodeInfoRequest extends NodeOperationRequest {
NodesInfoRequest request;
NodeInfoRequest() {
}
NodeInfoRequest(String nodeId, NodesInfoRequest request) {
super(request, nodeId);
this.request = request;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
request = new NodesInfoRequest();
request.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
request.writeTo(out);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_node_info_TransportNodesInfoAction.java
|
668 |
public class DeleteWarmerAction extends IndicesAction<DeleteWarmerRequest, DeleteWarmerResponse, DeleteWarmerRequestBuilder> {
public static final DeleteWarmerAction INSTANCE = new DeleteWarmerAction();
public static final String NAME = "indices/warmer/delete";
private DeleteWarmerAction() {
super(NAME);
}
@Override
public DeleteWarmerResponse newResponse() {
return new DeleteWarmerResponse();
}
@Override
public DeleteWarmerRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new DeleteWarmerRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_warmer_delete_DeleteWarmerAction.java
|
92 |
public class StaticAssetStorageServiceImplTest extends TestCase {
/**
* * For example, if the URL is /product/myproductimage.jpg, then the MD5 would be
* 35ec52a8dbd8cf3e2c650495001fe55f resulting in the following file on the filesystem
* {assetFileSystemPath}/64/a7/myproductimage.jpg.
*
* If there is a "siteId" in the BroadleafRequestContext then the site is also distributed
* using a similar algorithm but the system attempts to keep images for sites in their own
* directory resulting in an extra two folders required to reach any given product. So, for
* site with id 125, the system will MD5 "site125" in order to build the URL string. "site125" has an md5
* string of "7d905e85b8cb72a0477632be2c342bd6".
*
* So, in this case with the above product URL in site125, the full URL on the filesystem
* will be:
*
* {assetFileSystemPath}/7d/site125/64/a7/myproductimage.jpg.
* @throws Exception
*/
public void testGenerateStorageFileName() throws Exception {
StaticAssetStorageServiceImpl staticAssetStorageService = new StaticAssetStorageServiceImpl();
staticAssetStorageService.assetFileSystemPath = "/test";
staticAssetStorageService.assetServerMaxGeneratedDirectories = 2;
String fileName = staticAssetStorageService.generateStorageFileName("/product/myproductimage.jpg", false);
assertTrue(fileName.equals("/test/35/ec/myproductimage.jpg"));
BroadleafRequestContext brc = new BroadleafRequestContext();
BroadleafRequestContext.setBroadleafRequestContext(brc);
Site site = new SiteImpl();
site.setId(125L);
brc.setSite(site);
// try with site specific directory
fileName = staticAssetStorageService.generateStorageFileName("/product/myproductimage.jpg", false);
assertTrue(fileName.equals("/test/7f/site-125/35/ec/myproductimage.jpg"));
// try with 3 max generated directories
staticAssetStorageService.assetServerMaxGeneratedDirectories = 3;
fileName = staticAssetStorageService.generateStorageFileName("/product/myproductimage.jpg", false);
assertTrue(fileName.equals("/test/7f/site-125/35/ec/52/myproductimage.jpg"));
staticAssetStorageService.assetServerMaxGeneratedDirectories = 2;
fileName = staticAssetStorageService.generateStorageFileName("testwithoutslash", false);
assertTrue(fileName.equals("/test/7f/site-125/e9/90/testwithoutslash"));
}
/**
* Will throw an exception because the string being uploaded is too long.
* @throws Exception
*/
public void testUploadFileThatIsTooLarge() throws Exception {
StaticAssetStorageServiceImpl staticAssetStorageService = new StaticAssetStorageServiceImpl();
staticAssetStorageService.assetFileSystemPath = System.getProperty("java.io.tmpdir");
staticAssetStorageService.assetServerMaxGeneratedDirectories = 2;
String str = "This string is too long";
staticAssetStorageService.maxUploadableFileSize = str.length() - 1;
// convert String into InputStream
InputStream is = new ByteArrayInputStream(str.getBytes());
MockMultipartFile mpf = new MockMultipartFile("Test File", is);
StaticAsset staticAsset = new StaticAssetImpl();
staticAsset.setFileExtension(".jpg");
staticAsset.setFullUrl("/product/myproduct.jpg");
staticAsset.setStorageType(StorageType.FILESYSTEM);
// Remember this, we may need to delete this file.
String fileName = staticAssetStorageService.generateStorageFileName(staticAsset, false);
boolean exceptionThrown = false;
try {
staticAssetStorageService.createStaticAssetStorageFromFile(mpf, staticAsset);
} catch (Exception e) {
exceptionThrown = true;
}
assertTrue("Service call threw an exception", exceptionThrown);
File f = new File(staticAssetStorageService.assetFileSystemPath + fileName);
if (f.exists()) {
f.delete();
}
}
/**
* Tests uploading a file that is an allowed size.
* @throws Exception
*/
public void testUploadFileThatIsAllowedSize() throws Exception {
StaticAssetStorageServiceImpl staticAssetStorageService = new StaticAssetStorageServiceImpl();
staticAssetStorageService.assetFileSystemPath = System.getProperty("java.io.tmpdir");
staticAssetStorageService.assetServerMaxGeneratedDirectories = 2;
String str = "This string is not too long.";
staticAssetStorageService.maxUploadableFileSize = str.length();
// convert String into InputStream
InputStream is = new ByteArrayInputStream(str.getBytes());
MockMultipartFile mpf = new MockMultipartFile("Test File", is);
StaticAsset staticAsset = new StaticAssetImpl();
staticAsset.setFileExtension(".jpg");
staticAsset.setFullUrl("/product/myproduct.jpg");
staticAsset.setStorageType(StorageType.FILESYSTEM);
// Remember this, we may need to delete this file.
String fileName = staticAssetStorageService.generateStorageFileName(staticAsset, false);
boolean exceptionThrown = false;
try {
staticAssetStorageService.createStaticAssetStorageFromFile(mpf, staticAsset);
} catch (Exception e) {
exceptionThrown = true;
}
assertFalse("Service call threw an exception", exceptionThrown);
File f = new File(fileName);
if (f.exists()) {
f.delete();
}
}
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_test_java_org_broadleafcommerce_cms_file_service_StaticAssetStorageServiceImplTest.java
|
3,743 |
final class HazelcastInstanceLoader {
public static final String INSTANCE_NAME = "instance-name";
public static final String CONFIG_LOCATION = "config-location";
public static final String USE_CLIENT = "use-client";
public static final String CLIENT_CONFIG_LOCATION = "client-config-location";
private static final ILogger LOGGER = Logger.getLogger(HazelcastInstanceLoader.class);
private static final int DEFAULT_CONNECTION_ATTEMPT_LIMIT = 3;
private HazelcastInstanceLoader() {
}
public static HazelcastInstance createInstance(final FilterConfig filterConfig, final Properties properties)
throws ServletException {
final String instanceName = properties.getProperty(INSTANCE_NAME);
final String configLocation = properties.getProperty(CONFIG_LOCATION);
final String useClientProp = properties.getProperty(USE_CLIENT);
final String clientConfigLocation = properties.getProperty(CLIENT_CONFIG_LOCATION);
final boolean useClient = !isEmpty(useClientProp) && Boolean.parseBoolean(useClientProp);
URL configUrl = null;
if (useClient && !isEmpty(clientConfigLocation)) {
configUrl = getConfigURL(filterConfig, clientConfigLocation);
} else if (!isEmpty(configLocation)) {
configUrl = getConfigURL(filterConfig, configLocation);
}
if (useClient) {
return createClientInstance(configUrl);
}
Config config;
if (configUrl == null) {
config = new XmlConfigBuilder().build();
} else {
try {
config = new UrlXmlConfig(configUrl);
} catch (IOException e) {
throw new ServletException(e);
}
}
return createHazelcastInstance(instanceName, config);
}
private static HazelcastInstance createHazelcastInstance(String instanceName, Config config) {
if (!isEmpty(instanceName)) {
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info(format("getOrCreateHazelcastInstance for session replication, using name '%s'", instanceName));
}
config.setInstanceName(instanceName);
return Hazelcast.getOrCreateHazelcastInstance(config);
} else {
LOGGER.info("Creating a new HazelcastInstance for session replication");
return Hazelcast.newHazelcastInstance(config);
}
}
private static HazelcastInstance createClientInstance(URL configUrl) throws ServletException {
LOGGER.warning("Creating HazelcastClient for session replication...");
LOGGER.warning("make sure this client has access to an already running cluster...");
ClientConfig clientConfig;
if (configUrl == null) {
clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().setConnectionAttemptLimit(DEFAULT_CONNECTION_ATTEMPT_LIMIT);
} else {
try {
clientConfig = new XmlClientConfigBuilder(configUrl).build();
} catch (IOException e) {
throw new ServletException(e);
}
}
return HazelcastClient.newHazelcastClient(clientConfig);
}
private static URL getConfigURL(final FilterConfig filterConfig, final String configLocation) throws ServletException {
URL configUrl = null;
try {
configUrl = filterConfig.getServletContext().getResource(configLocation);
} catch (MalformedURLException ignore) {
LOGGER.info("ignored MalformedURLException");
}
if (configUrl == null) {
configUrl = ConfigLoader.locateConfig(configLocation);
}
if (configUrl == null) {
throw new ServletException("Could not load configuration '" + configLocation + "'");
}
return configUrl;
}
private static boolean isEmpty(String s) {
return s == null || s.trim().length() == 0;
}
}
| 1no label
|
hazelcast-wm_src_main_java_com_hazelcast_web_HazelcastInstanceLoader.java
|
245 |
assertTrueEventually(new AssertTask() {
public void run() throws Exception {
assertTrue(map.containsKey(member.getUuid()));
}
});
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceSubmitTest.java
|
2,349 |
public class StartProcessingJobOperation<K>
extends AbstractOperation
implements IdentifiedDataSerializable {
private String name;
private Collection<K> keys;
private String jobId;
private KeyPredicate<K> predicate;
public StartProcessingJobOperation() {
}
public StartProcessingJobOperation(String name, String jobId, Collection<K> keys, KeyPredicate<K> predicate) {
this.name = name;
this.keys = keys;
this.jobId = jobId;
this.predicate = predicate;
}
@Override
public boolean returnsResponse() {
return false;
}
@Override
public String getServiceName() {
return MapReduceService.SERVICE_NAME;
}
@Override
public void run()
throws Exception {
MapReduceService mapReduceService = getService();
JobSupervisor supervisor = mapReduceService.getJobSupervisor(name, jobId);
if (supervisor == null) {
if (mapReduceService.unregisterJobSupervisorCancellation(name, jobId)) {
// Supervisor was cancelled prior to creation
AbstractJobTracker jobTracker = (AbstractJobTracker) mapReduceService.getJobTracker(name);
TrackableJobFuture future = jobTracker.unregisterTrackableJob(jobId);
if (future != null) {
Exception exception = new CancellationException("Operation was cancelled by the user");
future.setResult(exception);
}
}
return;
}
MappingPhase mappingPhase = new KeyValueSourceMappingPhase(keys, predicate);
supervisor.startTasks(mappingPhase);
}
@Override
public void writeInternal(ObjectDataOutput out)
throws IOException {
out.writeUTF(name);
out.writeUTF(jobId);
out.writeInt(keys == null ? 0 : keys.size());
if (keys != null) {
for (Object key : keys) {
out.writeObject(key);
}
}
out.writeObject(predicate);
}
@Override
public void readInternal(ObjectDataInput in)
throws IOException {
name = in.readUTF();
jobId = in.readUTF();
int size = in.readInt();
keys = new ArrayList<K>();
for (int i = 0; i < size; i++) {
keys.add((K) in.readObject());
}
predicate = in.readObject();
}
@Override
public int getFactoryId() {
return MapReduceDataSerializerHook.F_ID;
}
@Override
public int getId() {
return MapReduceDataSerializerHook.START_PROCESSING_OPERATION;
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_mapreduce_impl_operation_StartProcessingJobOperation.java
|
284 |
public class VelocityMessageCreator extends MessageCreator {
private VelocityEngine velocityEngine;
private Map<String, Object> additionalConfigItems;
public VelocityMessageCreator(VelocityEngine velocityEngine, JavaMailSender mailSender, HashMap<String, Object> additionalConfigItems) {
super(mailSender);
this.additionalConfigItems = additionalConfigItems;
this.velocityEngine = velocityEngine;
}
@Override
public String buildMessageBody(EmailInfo info, HashMap<String,Object> props) {
@SuppressWarnings("unchecked")
HashMap<String,Object> propsCopy = (HashMap<String, Object>) props.clone();
if (additionalConfigItems != null) {
propsCopy.putAll(additionalConfigItems);
}
return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, info.getEmailTemplate(), propsCopy);
}
public VelocityEngine getVelocityEngine() {
return velocityEngine;
}
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
public Map<String, Object> getAdditionalConfigItems() {
return additionalConfigItems;
}
public void setAdditionalConfigItems(
Map<String, Object> additionalConfigItems) {
this.additionalConfigItems = additionalConfigItems;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_email_service_message_VelocityMessageCreator.java
|
5,101 |
class SearchFreeContextTransportHandler extends BaseTransportRequestHandler<SearchFreeContextRequest> {
static final String ACTION = "search/freeContext";
@Override
public SearchFreeContextRequest newInstance() {
return new SearchFreeContextRequest();
}
@Override
public void messageReceived(SearchFreeContextRequest request, TransportChannel channel) throws Exception {
searchService.freeContext(request.id());
channel.sendResponse(TransportResponse.Empty.INSTANCE);
}
@Override
public String executor() {
// freeing the context is cheap,
// no need for fork it to another thread
return ThreadPool.Names.SAME;
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_action_SearchServiceTransportAction.java
|
20 |
public class DeleteCommand extends AbstractTextCommand {
ByteBuffer response;
private final String key;
private final int expiration;
private final boolean noreply;
public DeleteCommand(String key, int expiration, boolean noreply) {
super(TextCommandType.DELETE);
this.key = key;
this.expiration = expiration;
this.noreply = noreply;
}
public boolean readFrom(ByteBuffer cb) {
return true;
}
public void setResponse(byte[] value) {
this.response = ByteBuffer.wrap(value);
}
public boolean writeTo(ByteBuffer bb) {
if (response == null) {
response = ByteBuffer.wrap(STORED);
}
while (bb.hasRemaining() && response.hasRemaining()) {
bb.put(response.get());
}
return !response.hasRemaining();
}
public boolean shouldReply() {
return !noreply;
}
public int getExpiration() {
return expiration;
}
public String getKey() {
return key;
}
@Override
public String toString() {
return "DeleteCommand [" + type + "]{"
+ "key='" + key + '\''
+ ", expiration=" + expiration
+ ", noreply=" + noreply + '}'
+ super.toString();
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_ascii_memcache_DeleteCommand.java
|
621 |
public class NullBroadleafTemplateResolver implements ITemplateResolver {
@Override
public String getName() {
return "NullBroadleafTemplateResolver";
}
@Override
public Integer getOrder() {
return 9999;
}
@Override
public TemplateResolution resolveTemplate(TemplateProcessingParameters templateProcessingParameters) {
return null;
}
@Override
public void initialize() {
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_web_NullBroadleafTemplateResolver.java
|
614 |
indexEngine.getValuesMinor(iRangeTo, isInclusive, MultiValuesTransformer.INSTANCE, new OIndexEngine.ValuesResultListener() {
@Override
public boolean addResult(OIdentifiable identifiable) {
return resultListener.addResult(identifiable);
}
});
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_index_OIndexMultiValues.java
|
345 |
public class ElasticSearchConstants {
public static final String ES_PROPERTIES_FILE = "titan-es.properties";
public static final Version ES_VERSION_EXPECTED;
private static final Logger log = LoggerFactory.getLogger(ElasticSearchConstants.class);
static {
Properties props;
try {
props = new Properties();
props.load(TitanFactory.class.getClassLoader().getResourceAsStream(ES_PROPERTIES_FILE));
} catch (IOException e) {
throw new AssertionError(e);
}
String vs = props.getProperty("es.version");
// The string formatting here assumes that there's no Beta or RC
// suffix.
String versionConstantName = String.format("V_%s_%s_%s", (Object[])vs.split("\\."));
ES_VERSION_EXPECTED = getExpectedVersionReflectively(versionConstantName);
}
private static Version getExpectedVersionReflectively(String fieldName) {
final String msg = "Failed to load expected ES version";
try {
return (Version)Version.class.getField(fieldName).get(null);
} catch (NoSuchFieldException e) {
log.error(msg, e);
throw new RuntimeException(e);
} catch (SecurityException e) {
log.error(msg, e);
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
log.error(msg, e);
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
log.error(msg, e);
throw new RuntimeException(e);
}
}
}
| 1no label
|
titan-es_src_main_java_com_thinkaurelius_titan_diskstorage_es_ElasticSearchConstants.java
|
331 |
public interface ODatabase extends OBackupable, Closeable {
public static enum OPTIONS {
SECURITY
}
public static enum STATUS {
OPEN, CLOSED, IMPORTING
}
public static enum ATTRIBUTES {
TYPE, STATUS, DEFAULTCLUSTERID, DATEFORMAT, DATETIMEFORMAT, TIMEZONE, LOCALECOUNTRY, LOCALELANGUAGE, CHARSET, CUSTOM
}
/**
* Opens a database using the user and password received as arguments.
*
* @param iUserName
* Username to login
* @param iUserPassword
* Password associated to the user
* @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <DB extends ODatabase> DB open(final String iUserName, final String iUserPassword);
/**
* Creates a new database.
*
* @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <DB extends ODatabase> DB create();
/**
* Reloads the database information like the cluster list.
*/
public void reload();
/**
* Drops a database.
*
*/
public void drop();
/**
* Declares an intent to the database. Intents aim to optimize common use cases.
*
* @param iIntent
* The intent
*/
public boolean declareIntent(final OIntent iIntent);
/**
* Checks if the database exists.
*
* @return True if already exists, otherwise false.
*/
public boolean exists();
/**
* Closes an opened database.
*/
public void close();
/**
* Returns the current status of database.
*/
public STATUS getStatus();
/**
* Returns the total size of database as the real used space.
*/
public long getSize();
/**
* Returns the current status of database.
*/
public <DB extends ODatabase> DB setStatus(STATUS iStatus);
/**
* Returns the database name.
*
* @return Name of the database
*/
public String getName();
/**
* Returns the database URL.
*
* @return URL of the database
*/
public String getURL();
/**
* Returns the underlying storage implementation.
*
* @return The underlying storage implementation
* @see OStorage
*/
public OStorage getStorage();
/**
* Internal only: replace the storage with a new one.
*
* @param iNewStorage
* The new storage to use. Usually it's a wrapped instance of the current cluster.
*/
public void replaceStorage(OStorage iNewStorage);
/**
* Returns the level1 cache. Cannot be null.
*
* @return Current cache.
*/
public OLevel1RecordCache getLevel1Cache();
/**
* Returns the level1 cache. Cannot be null.
*
* @return Current cache.
*/
public OLevel2RecordCache getLevel2Cache();
/**
* Returns the data segment id by name.
*
* @param iDataSegmentName
* Data segment name
* @return The id of searched data segment.
*/
public int getDataSegmentIdByName(String iDataSegmentName);
public String getDataSegmentNameById(int dataSegmentId);
/**
* Returns the default cluster id. If not specified all the new entities will be stored in the default cluster.
*
* @return The default cluster id
*/
public int getDefaultClusterId();
/**
* Returns the number of clusters.
*
* @return Number of the clusters
*/
public int getClusters();
/**
* Returns true if the cluster exists, otherwise false.
*
* @param iClusterName
* Cluster name
* @return true if the cluster exists, otherwise false
*/
public boolean existsCluster(String iClusterName);
/**
* Returns all the names of the clusters.
*
* @return Collection of cluster names.
*/
public Collection<String> getClusterNames();
/**
* Returns the cluster id by name.
*
* @param iClusterName
* Cluster name
* @return The id of searched cluster.
*/
public int getClusterIdByName(String iClusterName);
/**
* Returns the cluster type.
*
* @param iClusterName
* Cluster name
* @return The cluster type as string
*/
public String getClusterType(String iClusterName);
/**
* Returns the cluster name by id.
*
* @param iClusterId
* Cluster id
* @return The name of searched cluster.
*/
public String getClusterNameById(int iClusterId);
/**
* Returns the total size of records contained in the cluster defined by its name.
*
* @param iClusterName
* Cluster name
* @return Total size of records contained.
*/
public long getClusterRecordSizeByName(String iClusterName);
/**
* Returns the total size of records contained in the cluster defined by its id.
*
* @param iClusterId
* Cluster id
* @return The name of searched cluster.
*/
public long getClusterRecordSizeById(int iClusterId);
/**
* Checks if the database is closed.
*
* @return true if is closed, otherwise false.
*/
public boolean isClosed();
/**
* Counts all the entities in the specified cluster id.
*
* @param iCurrentClusterId
* Cluster id
* @return Total number of entities contained in the specified cluster
*/
public long countClusterElements(int iCurrentClusterId);
public long countClusterElements(int iCurrentClusterId, boolean countTombstones);
/**
* Counts all the entities in the specified cluster ids.
*
* @param iClusterIds
* Array of cluster ids Cluster id
* @return Total number of entities contained in the specified clusters
*/
public long countClusterElements(int[] iClusterIds);
public long countClusterElements(int[] iClusterIds, boolean countTombstones);
/**
* Counts all the entities in the specified cluster name.
*
* @param iClusterName
* Cluster name
* @return Total number of entities contained in the specified cluster
*/
public long countClusterElements(String iClusterName);
/**
* Adds a new cluster.
*
* @param iClusterName
* Cluster name
* @param iType
* Cluster type between the defined ones
* @param iParameters
* Additional parameters to pass to the factories
* @return Cluster id
*/
public int addCluster(String iClusterName, CLUSTER_TYPE iType, Object... iParameters);
/**
* Adds a new cluster.
*
* @param iType
* Cluster type between the defined ones
* @param iClusterName
* Cluster name
* @param iDataSegmentName
* Data segment where to store record of this cluster. null means 'default'
* @param iParameters
* Additional parameters to pass to the factories
*
* @return Cluster id
*/
public int addCluster(String iType, String iClusterName, String iLocation, final String iDataSegmentName, Object... iParameters);
/**
* Adds a new cluster.
*
* @param iType
* Cluster type between the defined ones
* @param iClusterName
* Cluster name
* @param iRequestedId
* requested id of the cluster
* @param iDataSegmentName
* Data segment where to store record of this cluster. null means 'default'
* @param iParameters
* Additional parameters to pass to the factories
*
* @return Cluster id
*/
public int addCluster(String iType, String iClusterName, int iRequestedId, String iLocation, final String iDataSegmentName,
Object... iParameters);
/**
*
* Drops a cluster by its name. Physical clusters will be completely deleted
*
* @param iClusterName
* @return
*/
public boolean dropCluster(String iClusterName, final boolean iTruncate);
/**
* Drops a cluster by its id. Physical clusters will be completely deleted.
*
* @param iClusterId
* @return true if has been removed, otherwise false
*/
public boolean dropCluster(int iClusterId, final boolean iTruncate);
/**
* Adds a data segment where to store record content. Data segments contain the content of records. Cluster segments contain the
* pointer to them.
*/
public int addDataSegment(String iSegmentName, String iLocation);
/**
* Drop a data segment and all the contained data.
*
* @param name
* segment name
* @return true if the segment has been removed, otherwise false
*/
public boolean dropDataSegment(String name);
/**
* Sets a property value
*
* @param iName
* Property name
* @param iValue
* new value to set
* @return The previous value if any, otherwise null
*/
public Object setProperty(String iName, Object iValue);
/**
* Gets the property value.
*
* @param iName
* Property name
* @return The previous value if any, otherwise null
*/
public Object getProperty(String iName);
/**
* Returns an iterator of the property entries
*/
public Iterator<Map.Entry<String, Object>> getProperties();
/**
* Returns a database attribute value
*
* @param iAttribute
* Attributes between #ATTRIBUTES enum
* @return The attribute value
*/
public Object get(ATTRIBUTES iAttribute);
/**
* Sets a database attribute value
*
* @param iAttribute
* Attributes between #ATTRIBUTES enum
* @param iValue
* Value to set
* @return
*/
public <DB extends ODatabase> DB set(ATTRIBUTES iAttribute, Object iValue);
/**
* Registers a listener to the database events.
*
* @param iListener
*/
public void registerListener(ODatabaseListener iListener);
/**
* Unregisters a listener to the database events.
*
* @param iListener
*/
public void unregisterListener(ODatabaseListener iListener);
public <V> V callInLock(Callable<V> iCallable, boolean iExclusiveLock);
public <V> V callInRecordLock(Callable<V> iCallable, ORID rid, boolean iExclusiveLock);
public ORecordMetadata getRecordMetadata(final ORID rid);
/**
* Flush cached storage content to the disk.
*
* After this call users can perform only select queries. All write-related commands will queued till {@link #release()} command
* will be called.
*
* Given command waits till all on going modifications in indexes or DB will be finished.
*
* IMPORTANT: This command is not reentrant.
*/
public void freeze();
/**
* Allows to execute write-related commands on DB. Called after {@link #freeze()} command.
*/
public void release();
/**
* Flush cached storage content to the disk.
*
* After this call users can perform only select queries. All write-related commands will queued till {@link #release()} command
* will be called or exception will be thrown on attempt to modify DB data. Concrete behaviour depends on
* <code>throwException</code> parameter.
*
* IMPORTANT: This command is not reentrant.
*
* @param throwException
* If <code>true</code> {@link com.orientechnologies.common.concur.lock.OModificationOperationProhibitedException}
* exception will be thrown in case of write command will be performed.
*/
public void freeze(boolean throwException);
/**
* Flush cached cluster content to the disk.
*
* After this call users can perform only select queries. All write-related commands will queued till {@link #releaseCluster(int)}
* command will be called.
*
* Given command waits till all on going modifications in indexes or DB will be finished.
*
* IMPORTANT: This command is not reentrant.
*
* @param iClusterId
* that must be released
*/
public void freezeCluster(int iClusterId);
/**
* Allows to execute write-related commands on the cluster
*
* @param iClusterId
* that must be released
*/
public void releaseCluster(int iClusterId);
/**
* Flush cached cluster content to the disk.
*
* After this call users can perform only select queries. All write-related commands will queued till {@link #releaseCluster(int)}
* command will be called.
*
* Given command waits till all on going modifications in indexes or DB will be finished.
*
* IMPORTANT: This command is not reentrant.
*
* @param iClusterId
* that must be released
* @param throwException
* If <code>true</code> {@link com.orientechnologies.common.concur.lock.OModificationOperationProhibitedException}
* exception will be thrown in case of write command will be performed.
*/
public void freezeCluster(int iClusterId, boolean throwException);
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_ODatabase.java
|
135 |
public interface StructuredContentFieldTemplate extends Serializable {
/**
* Gets the primary key.
*
* @return the primary key
*/
@Nullable
public Long getId();
/**
* Sets the primary key.
*
* @param id the new primary key
*/
public void setId(@Nullable Long id);
/**
* Gets the name.
*
* @return the name
*/
@Nonnull
String getName();
/**
* Sets the name.
*/
void setName(@Nonnull String name);
/**
* Returns the list of the field groups for this template.
* @return a list of FieldGroups associated with this template
*/
@Nullable
List<FieldGroup> getFieldGroups();
/**
* Sets the list of field groups for this template.
* @param fieldGroups
*/
void setFieldGroups(@Nullable List<FieldGroup> fieldGroups);
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContentFieldTemplate.java
|
416 |
static final class Fields {
static final XContentBuilderString SNAPSHOTS = new XContentBuilderString("snapshots");
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_get_GetSnapshotsResponse.java
|
666 |
constructors[COLLECTION_RESERVE_ADD] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new CollectionReserveAddOperation();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
|
214 |
Comparator <Snippet> comparator = new Comparator<Snippet>() {
@Override
public int compare(Snippet o1, Snippet o2) {
return (int)Math.signum(o1.getScore() - o2.getScore());
}
};
| 0true
|
src_test_java_org_apache_lucene_search_postingshighlight_CustomPostingsHighlighterTests.java
|
2,585 |
public class SocketAcceptor implements Runnable {
private final ServerSocketChannel serverSocketChannel;
private final TcpIpConnectionManager connectionManager;
private final ILogger logger;
public SocketAcceptor(ServerSocketChannel serverSocketChannel, TcpIpConnectionManager connectionManager) {
this.serverSocketChannel = serverSocketChannel;
this.connectionManager = connectionManager;
this.logger = connectionManager.ioService.getLogger(this.getClass().getName());
}
public void run() {
Selector selector = null;
try {
if (logger.isFinestEnabled()) {
log(Level.FINEST, "Starting SocketAcceptor on " + serverSocketChannel);
}
selector = Selector.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (connectionManager.isLive()) {
// block until new connection or interruption.
final int keyCount = selector.select();
if (Thread.currentThread().isInterrupted()) {
break;
}
if (keyCount == 0) {
continue;
}
final Set<SelectionKey> setSelectedKeys = selector.selectedKeys();
final Iterator<SelectionKey> it = setSelectedKeys.iterator();
while (it.hasNext()) {
final SelectionKey sk = it.next();
it.remove();
// of course it is acceptable!
if (sk.isValid() && sk.isAcceptable()) {
acceptSocket();
}
}
}
} catch (OutOfMemoryError e) {
OutOfMemoryErrorDispatcher.onOutOfMemory(e);
} catch (IOException e) {
log(Level.SEVERE, e.getClass().getName() + ": " + e.getMessage(), e);
} finally {
closeSelector(selector);
}
}
private void closeSelector(Selector selector) {
if (selector != null) {
try {
if (logger.isFinestEnabled()) {
logger.finest("Closing selector " + Thread.currentThread().getName());
}
selector.close();
} catch (final Exception ignored) {
}
}
}
private void acceptSocket() {
if (!connectionManager.isLive()) {
return;
}
SocketChannelWrapper socketChannelWrapper = null;
try {
final SocketChannel socketChannel = serverSocketChannel.accept();
if (socketChannel != null) {
socketChannelWrapper = connectionManager.wrapSocketChannel(socketChannel, false);
}
} catch (Exception e) {
if (e instanceof ClosedChannelException && !connectionManager.isLive()) {
// ClosedChannelException
// or AsynchronousCloseException
// or ClosedByInterruptException
logger.finest("Terminating socket acceptor thread...", e);
} else {
String error = "Unexpected error while accepting connection! "
+ e.getClass().getName() + ": " + e.getMessage();
log(Level.WARNING, error);
try {
serverSocketChannel.close();
} catch (Exception ignore) {
}
connectionManager.ioService.onFatalError(e);
}
}
if (socketChannelWrapper != null) {
final SocketChannelWrapper socketChannel = socketChannelWrapper;
log(Level.INFO, "Accepting socket connection from " + socketChannel.socket().getRemoteSocketAddress());
final MemberSocketInterceptor memberSocketInterceptor = connectionManager.getMemberSocketInterceptor();
if (memberSocketInterceptor == null) {
configureAndAssignSocket(socketChannel, null);
} else {
connectionManager.ioService.executeAsync(new Runnable() {
public void run() {
configureAndAssignSocket(socketChannel, memberSocketInterceptor);
}
});
}
}
}
private void configureAndAssignSocket(SocketChannelWrapper socketChannel, MemberSocketInterceptor memberSocketInterceptor) {
try {
connectionManager.initSocket(socketChannel.socket());
if (memberSocketInterceptor != null) {
log(Level.FINEST, "Calling member socket interceptor: " + memberSocketInterceptor + " for " + socketChannel);
memberSocketInterceptor.onAccept(socketChannel.socket());
}
socketChannel.configureBlocking(false);
connectionManager.assignSocketChannel(socketChannel);
} catch (Exception e) {
log(Level.WARNING, e.getClass().getName() + ": " + e.getMessage(), e);
IOUtil.closeResource(socketChannel);
}
}
private void log(Level level, String message) {
log(level, message, null);
}
private void log(Level level, String message, Exception e) {
logger.log(level, message, e);
connectionManager.ioService.getSystemLogService().logConnection(message);
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_nio_SocketAcceptor.java
|
6 |
Collections.sort(abbreviationsForPhrase, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
| 0true
|
tableViews_src_main_java_gov_nasa_arc_mct_abbreviation_impl_AbbreviationsManager.java
|
300 |
public class SiteNotFoundException extends RuntimeException {
public SiteNotFoundException() {
//do nothing
}
public SiteNotFoundException(Throwable cause) {
super(cause);
}
public SiteNotFoundException(String message) {
super(message);
}
public SiteNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_exception_SiteNotFoundException.java
|
1,013 |
execute(request, new ActionListener<Response>() {
@Override
public void onResponse(Response result) {
try {
channel.sendResponse(result);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send response for get", e1);
}
}
});
| 0true
|
src_main_java_org_elasticsearch_action_support_single_custom_TransportSingleCustomOperationAction.java
|
428 |
public class ClusterStateRequestBuilder extends MasterNodeReadOperationRequestBuilder<ClusterStateRequest, ClusterStateResponse, ClusterStateRequestBuilder> {
public ClusterStateRequestBuilder(ClusterAdminClient clusterClient) {
super((InternalClusterAdminClient) clusterClient, new ClusterStateRequest());
}
/**
* Include all data
*/
public ClusterStateRequestBuilder all() {
request.all();
return this;
}
/**
* Do not include any data
*/
public ClusterStateRequestBuilder clear() {
request.clear();
return this;
}
public ClusterStateRequestBuilder setBlocks(boolean filter) {
request.blocks(filter);
return this;
}
/**
* Should the cluster state result include the {@link org.elasticsearch.cluster.metadata.MetaData}. Defaults
* to <tt>true</tt>.
*/
public ClusterStateRequestBuilder setMetaData(boolean filter) {
request.metaData(filter);
return this;
}
/**
* Should the cluster state result include the {@link org.elasticsearch.cluster.node.DiscoveryNodes}. Defaults
* to <tt>true</tt>.
*/
public ClusterStateRequestBuilder setNodes(boolean filter) {
request.nodes(filter);
return this;
}
/**
* Should the cluster state result include teh {@link org.elasticsearch.cluster.routing.RoutingTable}. Defaults
* to <tt>true</tt>.
*/
public ClusterStateRequestBuilder setRoutingTable(boolean filter) {
request.routingTable(filter);
return this;
}
/**
* When {@link #setMetaData(boolean)} is set, which indices to return the {@link org.elasticsearch.cluster.metadata.IndexMetaData}
* for. Defaults to all indices.
*/
public ClusterStateRequestBuilder setIndices(String... indices) {
request.indices(indices);
return this;
}
public ClusterStateRequestBuilder setIndexTemplates(String... templates) {
request.indexTemplates(templates);
return this;
}
@Override
protected void doExecute(ActionListener<ClusterStateResponse> listener) {
((ClusterAdminClient) client).state(request, listener);
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_admin_cluster_state_ClusterStateRequestBuilder.java
|
139 |
public class DistributedObjectListenerRequest extends CallableClientRequest implements RetryableRequest {
public DistributedObjectListenerRequest() {
}
@Override
public Object call() throws Exception {
ProxyService proxyService = clientEngine.getProxyService();
String registrationId = proxyService.addProxyListener(new MyDistributedObjectListener());
endpoint.setDistributedObjectListener(registrationId);
return registrationId;
}
@Override
public String getServiceName() {
return null;
}
@Override
public int getFactoryId() {
return ClientPortableHook.ID;
}
@Override
public int getClassId() {
return ClientPortableHook.LISTENER;
}
private class MyDistributedObjectListener implements DistributedObjectListener {
@Override
public void distributedObjectCreated(DistributedObjectEvent event) {
send(event);
}
@Override
public void distributedObjectDestroyed(DistributedObjectEvent event) {
}
private void send(DistributedObjectEvent event) {
if (endpoint.live()) {
PortableDistributedObjectEvent portableEvent = new PortableDistributedObjectEvent(
event.getEventType(), event.getDistributedObject().getName(), event.getServiceName());
endpoint.sendEvent(portableEvent, getCallId());
}
}
}
@Override
public Permission getRequiredPermission() {
return null;
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_client_DistributedObjectListenerRequest.java
|
413 |
public class GetSnapshotsRequest extends MasterNodeOperationRequest<GetSnapshotsRequest> {
private String repository;
private String[] snapshots = Strings.EMPTY_ARRAY;
GetSnapshotsRequest() {
}
/**
* Constructs a new get snapshots request with given repository name and list of snapshots
*
* @param repository repository name
* @param snapshots list of snapshots
*/
public GetSnapshotsRequest(String repository, String[] snapshots) {
this.repository = repository;
this.snapshots = snapshots;
}
/**
* Constructs a new get snapshots request with given repository name
*
* @param repository repository name
*/
public GetSnapshotsRequest(String repository) {
this.repository = repository;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (repository == null) {
validationException = addValidationError("repository is missing", validationException);
}
return validationException;
}
/**
* Sets repository name
*
* @param repository repository name
* @return this request
*/
public GetSnapshotsRequest repository(String repository) {
this.repository = repository;
return this;
}
/**
* Returns repository name
*
* @return repository name
*/
public String repository() {
return this.repository;
}
/**
* Returns the names of the snapshots.
*
* @return the names of snapshots
*/
public String[] snapshots() {
return this.snapshots;
}
/**
* Sets the list of snapshots to be returned
*
* @param snapshots
* @return this request
*/
public GetSnapshotsRequest snapshots(String[] snapshots) {
this.snapshots = snapshots;
return this;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
repository = in.readString();
snapshots = in.readStringArray();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(repository);
out.writeStringArray(snapshots);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_get_GetSnapshotsRequest.java
|
1,126 |
public class OSQLFunctionSysdate extends OSQLFunctionAbstract {
public static final String NAME = "sysdate";
private final Date now;
private SimpleDateFormat format;
/**
* Get the date at construction to have the same date for all the iteration.
*/
public OSQLFunctionSysdate() {
super(NAME, 0, 2);
now = new Date();
}
public Object execute(final OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParameters,
OCommandContext iContext) {
if (iParameters.length == 0)
return now;
if (format == null) {
format = new SimpleDateFormat((String) iParameters[0]);
if (iParameters.length == 2)
format.setTimeZone(TimeZone.getTimeZone(iParameters[1].toString()));
else
format.setTimeZone(ODateHelper.getDatabaseTimeZone());
}
return format.format(now);
}
public boolean aggregateResults(final Object[] configuredParameters) {
return false;
}
public String getSyntax() {
return "Syntax error: sysdate([<format>] [,<timezone>])";
}
@Override
public Object getResult() {
return null;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_functions_misc_OSQLFunctionSysdate.java
|
1,038 |
public class GetTermVectorCheckDocFreqTests extends ElasticsearchIntegrationTest {
@Test
public void testSimpleTermVectors() throws ElasticsearchException, IOException {
XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type1")
.startObject("properties")
.startObject("field")
.field("type", "string")
.field("term_vector", "with_positions_offsets_payloads")
.field("analyzer", "tv_test")
.endObject()
.endObject()
.endObject().endObject();
ElasticsearchAssertions.assertAcked(prepareCreate("test").addMapping("type1", mapping).setSettings(
ImmutableSettings.settingsBuilder()
.put("index.number_of_shards", 1)
.put("index.analysis.analyzer.tv_test.tokenizer", "whitespace")
.put("index.number_of_replicas", 0)
.putArray("index.analysis.analyzer.tv_test.filter", "type_as_payload", "lowercase")));
ensureGreen();
int numDocs = 15;
for (int i = 0; i < numDocs; i++) {
client().prepareIndex("test", "type1", Integer.toString(i))
.setSource(XContentFactory.jsonBuilder().startObject().field("field", "the quick brown fox jumps over the lazy dog")
// 0the3 4quick9 10brown15 16fox19 20jumps25 26over30
// 31the34 35lazy39 40dog43
.endObject()).execute().actionGet();
refresh();
}
String[] values = { "brown", "dog", "fox", "jumps", "lazy", "over", "quick", "the" };
int[] freq = { 1, 1, 1, 1, 1, 1, 1, 2 };
int[][] pos = { { 2 }, { 8 }, { 3 }, { 4 }, { 7 }, { 5 }, { 1 }, { 0, 6 } };
int[][] startOffset = { { 10 }, { 40 }, { 16 }, { 20 }, { 35 }, { 26 }, { 4 }, { 0, 31 } };
int[][] endOffset = { { 15 }, { 43 }, { 19 }, { 25 }, { 39 }, { 30 }, { 9 }, { 3, 34 } };
for (int i = 0; i < numDocs; i++) {
checkAllInfo(numDocs, values, freq, pos, startOffset, endOffset, i);
checkWithoutTermStatistics(numDocs, values, freq, pos, startOffset, endOffset, i);
checkWithoutFieldStatistics(numDocs, values, freq, pos, startOffset, endOffset, i);
}
}
private void checkWithoutFieldStatistics(int numDocs, String[] values, int[] freq, int[][] pos, int[][] startOffset, int[][] endOffset,
int i) throws IOException {
TermVectorRequestBuilder resp = client().prepareTermVector("test", "type1", Integer.toString(i)).setPayloads(true).setOffsets(true)
.setPositions(true).setTermStatistics(true).setFieldStatistics(false).setSelectedFields();
TermVectorResponse response = resp.execute().actionGet();
assertThat("doc id: " + i + " doesn't exists but should", response.isExists(), equalTo(true));
Fields fields = response.getFields();
assertThat(fields.size(), equalTo(1));
Terms terms = fields.terms("field");
assertThat(terms.size(), equalTo(8l));
assertThat(terms.getSumTotalTermFreq(), Matchers.equalTo((long) -1));
assertThat(terms.getDocCount(), Matchers.equalTo(-1));
assertThat(terms.getSumDocFreq(), equalTo((long) -1));
TermsEnum iterator = terms.iterator(null);
for (int j = 0; j < values.length; j++) {
String string = values[j];
BytesRef next = iterator.next();
assertThat(next, Matchers.notNullValue());
assertThat("expected " + string, string, equalTo(next.utf8ToString()));
assertThat(next, Matchers.notNullValue());
if (string.equals("the")) {
assertThat("expected ttf of " + string, numDocs * 2, equalTo((int) iterator.totalTermFreq()));
} else {
assertThat("expected ttf of " + string, numDocs, equalTo((int) iterator.totalTermFreq()));
}
DocsAndPositionsEnum docsAndPositions = iterator.docsAndPositions(null, null);
assertThat(docsAndPositions.nextDoc(), equalTo(0));
assertThat(freq[j], equalTo(docsAndPositions.freq()));
assertThat(iterator.docFreq(), equalTo(numDocs));
int[] termPos = pos[j];
int[] termStartOffset = startOffset[j];
int[] termEndOffset = endOffset[j];
assertThat(termPos.length, equalTo(freq[j]));
assertThat(termStartOffset.length, equalTo(freq[j]));
assertThat(termEndOffset.length, equalTo(freq[j]));
for (int k = 0; k < freq[j]; k++) {
int nextPosition = docsAndPositions.nextPosition();
assertThat("term: " + string, nextPosition, equalTo(termPos[k]));
assertThat("term: " + string, docsAndPositions.startOffset(), equalTo(termStartOffset[k]));
assertThat("term: " + string, docsAndPositions.endOffset(), equalTo(termEndOffset[k]));
assertThat("term: " + string, docsAndPositions.getPayload(), equalTo(new BytesRef("word")));
}
}
assertThat(iterator.next(), Matchers.nullValue());
XContentBuilder xBuilder = new XContentFactory().jsonBuilder();
response.toXContent(xBuilder, null);
BytesStream bytesStream = xBuilder.bytesStream();
String utf8 = bytesStream.bytes().toUtf8();
String expectedString = "{\"_index\":\"test\",\"_type\":\"type1\",\"_id\":\""
+ i
+ "\",\"_version\":1,\"found\":true,\"term_vectors\":{\"field\":{\"terms\":{\"brown\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":2,\"start_offset\":10,\"end_offset\":15,\"payload\":\"d29yZA==\"}]},\"dog\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":8,\"start_offset\":40,\"end_offset\":43,\"payload\":\"d29yZA==\"}]},\"fox\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":3,\"start_offset\":16,\"end_offset\":19,\"payload\":\"d29yZA==\"}]},\"jumps\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":4,\"start_offset\":20,\"end_offset\":25,\"payload\":\"d29yZA==\"}]},\"lazy\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":7,\"start_offset\":35,\"end_offset\":39,\"payload\":\"d29yZA==\"}]},\"over\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":5,\"start_offset\":26,\"end_offset\":30,\"payload\":\"d29yZA==\"}]},\"quick\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":1,\"start_offset\":4,\"end_offset\":9,\"payload\":\"d29yZA==\"}]},\"the\":{\"doc_freq\":15,\"ttf\":30,\"term_freq\":2,\"tokens\":[{\"position\":0,\"start_offset\":0,\"end_offset\":3,\"payload\":\"d29yZA==\"},{\"position\":6,\"start_offset\":31,\"end_offset\":34,\"payload\":\"d29yZA==\"}]}}}}}";
assertThat(utf8, equalTo(expectedString));
}
private void checkWithoutTermStatistics(int numDocs, String[] values, int[] freq, int[][] pos, int[][] startOffset, int[][] endOffset,
int i) throws IOException {
TermVectorRequestBuilder resp = client().prepareTermVector("test", "type1", Integer.toString(i)).setPayloads(true).setOffsets(true)
.setPositions(true).setTermStatistics(false).setFieldStatistics(true).setSelectedFields();
assertThat(resp.request().termStatistics(), equalTo(false));
TermVectorResponse response = resp.execute().actionGet();
assertThat("doc id: " + i + " doesn't exists but should", response.isExists(), equalTo(true));
Fields fields = response.getFields();
assertThat(fields.size(), equalTo(1));
Terms terms = fields.terms("field");
assertThat(terms.size(), equalTo(8l));
assertThat(terms.getSumTotalTermFreq(), Matchers.equalTo((long) (9 * numDocs)));
assertThat(terms.getDocCount(), Matchers.equalTo(numDocs));
assertThat(terms.getSumDocFreq(), equalTo((long) numDocs * values.length));
TermsEnum iterator = terms.iterator(null);
for (int j = 0; j < values.length; j++) {
String string = values[j];
BytesRef next = iterator.next();
assertThat(next, Matchers.notNullValue());
assertThat("expected " + string, string, equalTo(next.utf8ToString()));
assertThat(next, Matchers.notNullValue());
assertThat("expected ttf of " + string, -1, equalTo((int) iterator.totalTermFreq()));
DocsAndPositionsEnum docsAndPositions = iterator.docsAndPositions(null, null);
assertThat(docsAndPositions.nextDoc(), equalTo(0));
assertThat(freq[j], equalTo(docsAndPositions.freq()));
assertThat(iterator.docFreq(), equalTo(-1));
int[] termPos = pos[j];
int[] termStartOffset = startOffset[j];
int[] termEndOffset = endOffset[j];
assertThat(termPos.length, equalTo(freq[j]));
assertThat(termStartOffset.length, equalTo(freq[j]));
assertThat(termEndOffset.length, equalTo(freq[j]));
for (int k = 0; k < freq[j]; k++) {
int nextPosition = docsAndPositions.nextPosition();
assertThat("term: " + string, nextPosition, equalTo(termPos[k]));
assertThat("term: " + string, docsAndPositions.startOffset(), equalTo(termStartOffset[k]));
assertThat("term: " + string, docsAndPositions.endOffset(), equalTo(termEndOffset[k]));
assertThat("term: " + string, docsAndPositions.getPayload(), equalTo(new BytesRef("word")));
}
}
assertThat(iterator.next(), Matchers.nullValue());
XContentBuilder xBuilder = new XContentFactory().jsonBuilder();
response.toXContent(xBuilder, null);
BytesStream bytesStream = xBuilder.bytesStream();
String utf8 = bytesStream.bytes().toUtf8();
String expectedString = "{\"_index\":\"test\",\"_type\":\"type1\",\"_id\":\""
+ i
+ "\",\"_version\":1,\"found\":true,\"term_vectors\":{\"field\":{\"field_statistics\":{\"sum_doc_freq\":120,\"doc_count\":15,\"sum_ttf\":135},\"terms\":{\"brown\":{\"term_freq\":1,\"tokens\":[{\"position\":2,\"start_offset\":10,\"end_offset\":15,\"payload\":\"d29yZA==\"}]},\"dog\":{\"term_freq\":1,\"tokens\":[{\"position\":8,\"start_offset\":40,\"end_offset\":43,\"payload\":\"d29yZA==\"}]},\"fox\":{\"term_freq\":1,\"tokens\":[{\"position\":3,\"start_offset\":16,\"end_offset\":19,\"payload\":\"d29yZA==\"}]},\"jumps\":{\"term_freq\":1,\"tokens\":[{\"position\":4,\"start_offset\":20,\"end_offset\":25,\"payload\":\"d29yZA==\"}]},\"lazy\":{\"term_freq\":1,\"tokens\":[{\"position\":7,\"start_offset\":35,\"end_offset\":39,\"payload\":\"d29yZA==\"}]},\"over\":{\"term_freq\":1,\"tokens\":[{\"position\":5,\"start_offset\":26,\"end_offset\":30,\"payload\":\"d29yZA==\"}]},\"quick\":{\"term_freq\":1,\"tokens\":[{\"position\":1,\"start_offset\":4,\"end_offset\":9,\"payload\":\"d29yZA==\"}]},\"the\":{\"term_freq\":2,\"tokens\":[{\"position\":0,\"start_offset\":0,\"end_offset\":3,\"payload\":\"d29yZA==\"},{\"position\":6,\"start_offset\":31,\"end_offset\":34,\"payload\":\"d29yZA==\"}]}}}}}";
assertThat(utf8, equalTo(expectedString));
}
private void checkAllInfo(int numDocs, String[] values, int[] freq, int[][] pos, int[][] startOffset, int[][] endOffset, int i)
throws IOException {
TermVectorRequestBuilder resp = client().prepareTermVector("test", "type1", Integer.toString(i)).setPayloads(true).setOffsets(true)
.setPositions(true).setFieldStatistics(true).setTermStatistics(true).setSelectedFields();
assertThat(resp.request().fieldStatistics(), equalTo(true));
TermVectorResponse response = resp.execute().actionGet();
assertThat("doc id: " + i + " doesn't exists but should", response.isExists(), equalTo(true));
Fields fields = response.getFields();
assertThat(fields.size(), equalTo(1));
Terms terms = fields.terms("field");
assertThat(terms.size(), equalTo(8l));
assertThat(terms.getSumTotalTermFreq(), Matchers.equalTo((long) (9 * numDocs)));
assertThat(terms.getDocCount(), Matchers.equalTo(numDocs));
assertThat(terms.getSumDocFreq(), equalTo((long) numDocs * values.length));
TermsEnum iterator = terms.iterator(null);
for (int j = 0; j < values.length; j++) {
String string = values[j];
BytesRef next = iterator.next();
assertThat(next, Matchers.notNullValue());
assertThat("expected " + string, string, equalTo(next.utf8ToString()));
assertThat(next, Matchers.notNullValue());
if (string.equals("the")) {
assertThat("expected ttf of " + string, numDocs * 2, equalTo((int) iterator.totalTermFreq()));
} else {
assertThat("expected ttf of " + string, numDocs, equalTo((int) iterator.totalTermFreq()));
}
DocsAndPositionsEnum docsAndPositions = iterator.docsAndPositions(null, null);
assertThat(docsAndPositions.nextDoc(), equalTo(0));
assertThat(freq[j], equalTo(docsAndPositions.freq()));
assertThat(iterator.docFreq(), equalTo(numDocs));
int[] termPos = pos[j];
int[] termStartOffset = startOffset[j];
int[] termEndOffset = endOffset[j];
assertThat(termPos.length, equalTo(freq[j]));
assertThat(termStartOffset.length, equalTo(freq[j]));
assertThat(termEndOffset.length, equalTo(freq[j]));
for (int k = 0; k < freq[j]; k++) {
int nextPosition = docsAndPositions.nextPosition();
assertThat("term: " + string, nextPosition, equalTo(termPos[k]));
assertThat("term: " + string, docsAndPositions.startOffset(), equalTo(termStartOffset[k]));
assertThat("term: " + string, docsAndPositions.endOffset(), equalTo(termEndOffset[k]));
assertThat("term: " + string, docsAndPositions.getPayload(), equalTo(new BytesRef("word")));
}
}
assertThat(iterator.next(), Matchers.nullValue());
XContentBuilder xBuilder = new XContentFactory().jsonBuilder();
response.toXContent(xBuilder, null);
BytesStream bytesStream = xBuilder.bytesStream();
String utf8 = bytesStream.bytes().toUtf8();
String expectedString = "{\"_index\":\"test\",\"_type\":\"type1\",\"_id\":\""
+ i
+ "\",\"_version\":1,\"found\":true,\"term_vectors\":{\"field\":{\"field_statistics\":{\"sum_doc_freq\":120,\"doc_count\":15,\"sum_ttf\":135},\"terms\":{\"brown\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":2,\"start_offset\":10,\"end_offset\":15,\"payload\":\"d29yZA==\"}]},\"dog\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":8,\"start_offset\":40,\"end_offset\":43,\"payload\":\"d29yZA==\"}]},\"fox\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":3,\"start_offset\":16,\"end_offset\":19,\"payload\":\"d29yZA==\"}]},\"jumps\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":4,\"start_offset\":20,\"end_offset\":25,\"payload\":\"d29yZA==\"}]},\"lazy\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":7,\"start_offset\":35,\"end_offset\":39,\"payload\":\"d29yZA==\"}]},\"over\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":5,\"start_offset\":26,\"end_offset\":30,\"payload\":\"d29yZA==\"}]},\"quick\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":1,\"start_offset\":4,\"end_offset\":9,\"payload\":\"d29yZA==\"}]},\"the\":{\"doc_freq\":15,\"ttf\":30,\"term_freq\":2,\"tokens\":[{\"position\":0,\"start_offset\":0,\"end_offset\":3,\"payload\":\"d29yZA==\"},{\"position\":6,\"start_offset\":31,\"end_offset\":34,\"payload\":\"d29yZA==\"}]}}}}}";
assertThat(utf8, equalTo(expectedString));
}
}
| 0true
|
src_test_java_org_elasticsearch_action_termvector_GetTermVectorCheckDocFreqTests.java
|
195 |
public static class Group {
public static class Name {
public static final String Audit = "Auditable_Audit";
}
public static class Order {
public static final int Audit = 1000;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_audit_Auditable.java
|
22 |
public class LogPruneStrategies
{
public static final LogPruneStrategy NO_PRUNING = new LogPruneStrategy()
{
@Override
public void prune( LogLoader source )
{ // Don't prune logs at all.
}
@Override
public String toString()
{
return "NO_PRUNING";
}
};
private interface Threshold
{
boolean reached( File file, long version, LogLoader source );
}
private abstract static class AbstractPruneStrategy implements LogPruneStrategy
{
protected final FileSystemAbstraction fileSystem;
AbstractPruneStrategy( FileSystemAbstraction fileSystem )
{
this.fileSystem = fileSystem;
}
@Override
public void prune( LogLoader source )
{
if ( source.getHighestLogVersion() == 0 )
return;
long upper = source.getHighestLogVersion()-1;
Threshold threshold = newThreshold();
boolean exceeded = false;
while ( upper >= 0 )
{
File file = source.getFileName( upper );
if ( !fileSystem.fileExists( file ) )
// There aren't logs to prune anything. Just return
return;
if ( fileSystem.getFileSize( file ) > LogIoUtils.LOG_HEADER_SIZE &&
threshold.reached( file, upper, source ) )
{
exceeded = true;
break;
}
upper--;
}
if ( !exceeded )
return;
// Find out which log is the earliest existing (lower bound to prune)
long lower = upper;
while ( fileSystem.fileExists( source.getFileName( lower-1 ) ) )
lower--;
// The reason we delete from lower to upper is that if it crashes in the middle
// we can be sure that no holes are created
for ( long version = lower; version < upper; version++ )
fileSystem.deleteFile( source.getFileName( version ) );
}
/**
* @return a {@link Threshold} which if returning {@code false} states that the log file
* is within the threshold and doesn't need to be pruned. The first time it returns
* {@code true} it says that the threshold has been reached and the log file it just
* returned {@code true} for should be kept, but all previous logs should be pruned.
*/
protected abstract Threshold newThreshold();
}
public static LogPruneStrategy nonEmptyFileCount( FileSystemAbstraction fileSystem, int maxLogCountToKeep )
{
return new FileCountPruneStrategy( fileSystem, maxLogCountToKeep );
}
private static class FileCountPruneStrategy extends AbstractPruneStrategy
{
private final int maxNonEmptyLogCount;
public FileCountPruneStrategy( FileSystemAbstraction fileSystem, int maxNonEmptyLogCount )
{
super( fileSystem );
this.maxNonEmptyLogCount = maxNonEmptyLogCount;
}
@Override
protected Threshold newThreshold()
{
return new Threshold()
{
int nonEmptyLogCount = 0;
@Override
public boolean reached( File file, long version, LogLoader source )
{
return ++nonEmptyLogCount >= maxNonEmptyLogCount;
}
};
}
@Override
public String toString()
{
return getClass().getSimpleName() + "[max:" + maxNonEmptyLogCount + "]";
}
}
public static LogPruneStrategy totalFileSize( FileSystemAbstraction fileSystem, int numberOfBytes )
{
return new FileSizePruneStrategy( fileSystem, numberOfBytes );
}
public static class FileSizePruneStrategy extends AbstractPruneStrategy
{
private final int maxSize;
public FileSizePruneStrategy( FileSystemAbstraction fileystem, int maxSizeBytes )
{
super( fileystem );
this.maxSize = maxSizeBytes;
}
@Override
protected Threshold newThreshold()
{
return new Threshold()
{
private int size;
@Override
public boolean reached( File file, long version, LogLoader source )
{
size += fileSystem.getFileSize( file );
return size >= maxSize;
}
};
}
}
public static LogPruneStrategy transactionCount( FileSystemAbstraction fileSystem, int maxCount )
{
return new TransactionCountPruneStrategy( fileSystem, maxCount );
}
public static class TransactionCountPruneStrategy extends AbstractPruneStrategy
{
private final int maxTransactionCount;
public TransactionCountPruneStrategy( FileSystemAbstraction fileSystem, int maxTransactionCount )
{
super( fileSystem );
this.maxTransactionCount = maxTransactionCount;
}
@Override
protected Threshold newThreshold()
{
return new Threshold()
{
private Long highest;
@Override
public boolean reached( File file, long version, LogLoader source )
{
// Here we know that the log version exists (checked in AbstractPruneStrategy#prune)
long tx = source.getFirstCommittedTxId( version );
if ( highest == null )
{
highest = source.getLastCommittedTxId();
return false;
}
return highest-tx >= maxTransactionCount;
}
};
}
}
public static LogPruneStrategy transactionTimeSpan( FileSystemAbstraction fileSystem, int timeToKeep, TimeUnit timeUnit )
{
return new TransactionTimeSpanPruneStrategy( fileSystem, timeToKeep, timeUnit );
}
public static class TransactionTimeSpanPruneStrategy extends AbstractPruneStrategy
{
private final int timeToKeep;
private final TimeUnit unit;
public TransactionTimeSpanPruneStrategy( FileSystemAbstraction fileSystem, int timeToKeep, TimeUnit unit )
{
super( fileSystem );
this.timeToKeep = timeToKeep;
this.unit = unit;
}
@Override
protected Threshold newThreshold()
{
return new Threshold()
{
private long lowerLimit = System.currentTimeMillis() - unit.toMillis( timeToKeep );
@Override
public boolean reached( File file, long version, LogLoader source )
{
try
{
return source.getFirstStartRecordTimestamp( version ) < lowerLimit;
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
};
}
}
/**
* Parses a configuration value for log specifying log pruning. It has one of these forms:
* <ul>
* <li>all</li>
* <li>[number][unit] [type]</li>
* </ul>
* For example:
* <ul>
* <li>100M size - For keeping last 100 megabytes of log data</li>
* <li>20 pcs - For keeping last 20 non-empty log files</li>
* <li>7 days - For keeping last 7 days worth of log data</li>
* <li>1k hours - For keeping last 1000 hours worth of log data</li>
* </ul>
*/
public static LogPruneStrategy fromConfigValue( FileSystemAbstraction fileSystem, String configValue )
{
String[] tokens = configValue.split( " " );
if ( tokens.length == 0 )
throw new IllegalArgumentException( "Invalid log pruning configuration value '" + configValue + "'" );
String numberWithUnit = tokens[0];
if ( tokens.length == 1 )
{
if ( numberWithUnit.equals( "true" ) )
return NO_PRUNING;
else if ( numberWithUnit.equals( "false" ) )
return transactionCount( fileSystem, 1 );
else
throw new IllegalArgumentException( "Invalid log pruning configuration value '" + configValue +
"'. The form is 'all' or '<number><unit> <type>' for example '100k txs' " +
"for the latest 100 000 transactions" );
}
String[] types = new String[] { "files", "size", "txs", "hours", "days" };
String type = tokens[1];
int number = (int) parseLongWithUnit( numberWithUnit );
int typeIndex = 0;
if ( type.equals( types[typeIndex++] ) )
return nonEmptyFileCount( fileSystem, number );
else if ( type.equals( types[typeIndex++] ) )
return totalFileSize( fileSystem, number );
else if ( type.equals( types[typeIndex++] ) )
return transactionCount( fileSystem, number );
else if ( type.equals( types[typeIndex++] ) )
return transactionTimeSpan( fileSystem, number, TimeUnit.HOURS );
else if ( type.equals( types[typeIndex++] ) )
return transactionTimeSpan( fileSystem, number, TimeUnit.DAYS );
else
throw new IllegalArgumentException( "Invalid log pruning configuration value '" + configValue +
"'. Invalid type '" + type + "', valid are " + Arrays.asList( types ) );
}
}
| 1no label
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogPruneStrategies.java
|
2,315 |
public class MapReduceService
implements ManagedService, RemoteService {
/**
* The service name to retrieve an instance of the MapReduceService
*/
public static final String SERVICE_NAME = "hz:impl:mapReduceService";
private static final ILogger LOGGER = Logger.getLogger(MapReduceService.class);
private static final int DEFAULT_RETRY_SLEEP_MILLIS = 100;
private final ConstructorFunction<String, NodeJobTracker> constructor = new ConstructorFunction<String, NodeJobTracker>() {
@Override
public NodeJobTracker createNew(String arg) {
JobTrackerConfig jobTrackerConfig = config.findJobTrackerConfig(arg);
return new NodeJobTracker(arg, jobTrackerConfig.getAsReadOnly(), nodeEngine, MapReduceService.this);
}
};
private final ConcurrentMap<String, NodeJobTracker> jobTrackers;
private final ConcurrentMap<JobSupervisorKey, JobSupervisor> jobSupervisors;
private final InternalPartitionService partitionService;
private final ClusterService clusterService;
private final NodeEngineImpl nodeEngine;
private final Config config;
public MapReduceService(NodeEngine nodeEngine) {
this.config = nodeEngine.getConfig();
this.nodeEngine = (NodeEngineImpl) nodeEngine;
this.clusterService = nodeEngine.getClusterService();
this.partitionService = nodeEngine.getPartitionService();
this.jobTrackers = new ConcurrentHashMap<String, NodeJobTracker>();
this.jobSupervisors = new ConcurrentHashMap<JobSupervisorKey, JobSupervisor>();
}
public JobTracker getJobTracker(String name) {
return (JobTracker) createDistributedObject(name);
}
public JobSupervisor getJobSupervisor(String name, String jobId) {
JobSupervisorKey key = new JobSupervisorKey(name, jobId);
return jobSupervisors.get(key);
}
public boolean registerJobSupervisorCancellation(String name, String jobId, Address jobOwner) {
NodeJobTracker jobTracker = (NodeJobTracker) createDistributedObject(name);
if (jobTracker.registerJobSupervisorCancellation(jobId) && getLocalAddress().equals(jobOwner)) {
for (MemberImpl member : clusterService.getMemberList()) {
if (!member.getAddress().equals(jobOwner)) {
try {
ProcessingOperation operation = new CancelJobSupervisorOperation(name, jobId);
processRequest(member.getAddress(), operation, name);
} catch (Exception ignore) {
LOGGER.finest("Member might be already unavailable", ignore);
}
}
}
return true;
}
return false;
}
public boolean unregisterJobSupervisorCancellation(String name, String jobId) {
NodeJobTracker jobTracker = (NodeJobTracker) createDistributedObject(name);
return jobTracker.unregisterJobSupervisorCancellation(jobId);
}
public JobSupervisor createJobSupervisor(JobTaskConfiguration configuration) {
// Job might already be cancelled (due to async processing)
NodeJobTracker jobTracker = (NodeJobTracker) createDistributedObject(configuration.getName());
if (jobTracker.unregisterJobSupervisorCancellation(configuration.getJobId())) {
return null;
}
JobSupervisorKey key = new JobSupervisorKey(configuration.getName(), configuration.getJobId());
boolean ownerNode = nodeEngine.getThisAddress().equals(configuration.getJobOwner());
JobSupervisor jobSupervisor = new JobSupervisor(configuration, jobTracker, ownerNode, this);
JobSupervisor oldSupervisor = jobSupervisors.putIfAbsent(key, jobSupervisor);
return oldSupervisor != null ? oldSupervisor : jobSupervisor;
}
public boolean destroyJobSupervisor(JobSupervisor supervisor) {
String name = supervisor.getConfiguration().getName();
String jobId = supervisor.getConfiguration().getJobId();
NodeJobTracker jobTracker = (NodeJobTracker) createDistributedObject(name);
if (jobTracker != null) {
jobTracker.unregisterJobSupervisorCancellation(jobId);
}
JobSupervisorKey key = new JobSupervisorKey(supervisor);
return jobSupervisors.remove(key) == supervisor;
}
public ExecutorService getExecutorService(String name) {
return nodeEngine.getExecutionService().getExecutor(MapReduceUtil.buildExecutorName(name));
}
@Override
public void init(NodeEngine nodeEngine, Properties properties) {
}
@Override
public void reset() {
}
@Override
public void shutdown(boolean terminate) {
for (JobTracker jobTracker : jobTrackers.values()) {
jobTracker.destroy();
}
jobTrackers.clear();
}
@Override
public DistributedObject createDistributedObject(String objectName) {
return ConcurrencyUtil.getOrPutSynchronized(jobTrackers, objectName, jobTrackers, constructor);
}
@Override
public void destroyDistributedObject(String objectName) {
JobTracker jobTracker = jobTrackers.remove(objectName);
if (jobTracker != null) {
jobTracker.destroy();
}
}
public Address getKeyMember(Object key) {
int partitionId = partitionService.getPartitionId(key);
Address owner;
while ((owner = partitionService.getPartitionOwner(partitionId)) == null) {
try {
Thread.sleep(DEFAULT_RETRY_SLEEP_MILLIS);
} catch (Exception ignore) {
// Partitions might not assigned yet so we need to retry
LOGGER.finest("Partitions not yet assigned, retry", ignore);
}
}
return owner;
}
public boolean checkAssignedMembersAvailable(Collection<Address> assignedMembers) {
Collection<MemberImpl> members = clusterService.getMemberList();
List<Address> addresses = new ArrayList<Address>(members.size());
for (MemberImpl member : members) {
addresses.add(member.getAddress());
}
for (Address address : assignedMembers) {
if (!addresses.contains(address)) {
return false;
}
}
return true;
}
public <R> R processRequest(Address address, ProcessingOperation processingOperation, String name)
throws ExecutionException, InterruptedException {
String executorName = MapReduceUtil.buildExecutorName(name);
InvocationBuilder invocation = nodeEngine.getOperationService()
.createInvocationBuilder(SERVICE_NAME, processingOperation, address);
Future<R> future = invocation.setExecutorName(executorName).invoke();
return future.get();
}
public void sendNotification(Address address, MapReduceNotification notification) {
try {
String name = MapReduceUtil.buildExecutorName(notification.getName());
ProcessingOperation operation = new FireNotificationOperation(notification);
processRequest(address, operation, name);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public final Address getLocalAddress() {
return nodeEngine.getThisAddress();
}
public NodeEngine getNodeEngine() {
return nodeEngine;
}
public void dispatchEvent(MapReduceNotification notification) {
String name = notification.getName();
String jobId = notification.getJobId();
JobSupervisor supervisor = getJobSupervisor(name, jobId);
if (supervisor == null) {
throw new NullPointerException("JobSupervisor name=" + name + ", jobId=" + jobId + " not found");
}
supervisor.onNotification(notification);
}
/**
* This key type is used for assigning {@link com.hazelcast.mapreduce.impl.task.JobSupervisor}s to their
* corresponding job trackers by JobTracker name and the unique jobId.
*/
private static final class JobSupervisorKey {
private final String name;
private final String jobId;
private JobSupervisorKey(String name, String jobId) {
this.name = name;
this.jobId = jobId;
}
private JobSupervisorKey(JobSupervisor supervisor) {
this.name = supervisor.getConfiguration().getName();
this.jobId = supervisor.getConfiguration().getJobId();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
JobSupervisorKey that = (JobSupervisorKey) o;
if (!jobId.equals(that.jobId)) {
return false;
}
return name.equals(that.name);
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (jobId != null ? jobId.hashCode() : 0);
return result;
}
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_mapreduce_impl_MapReduceService.java
|
1,332 |
@ClusterScope(scope=Scope.TEST, numNodes=0)
public class UpdateSettingsValidationTests extends ElasticsearchIntegrationTest {
@Test
public void testUpdateSettingsValidation() throws Exception {
String master = cluster().startNode(settingsBuilder().put("node.data", false).build());
String node_1 = cluster().startNode(settingsBuilder().put("node.master", false).build());
String node_2 = cluster().startNode(settingsBuilder().put("node.master", false).build());
client().admin().indices().prepareCreate("test")
.setSettings(settingsBuilder().put("index.number_of_shards", 5).put("index.number_of_replicas", 1)).execute().actionGet();
ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth("test").setWaitForEvents(Priority.LANGUID).setWaitForNodes("3").setWaitForGreenStatus().execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
assertThat(healthResponse.getIndices().get("test").getActiveShards(), equalTo(10));
client().admin().indices().prepareUpdateSettings("test").setSettings(settingsBuilder().put("index.number_of_replicas", 0)).execute().actionGet();
healthResponse = client().admin().cluster().prepareHealth("test").setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet();
assertThat(healthResponse.isTimedOut(), equalTo(false));
assertThat(healthResponse.getIndices().get("test").getActiveShards(), equalTo(5));
try {
client().admin().indices().prepareUpdateSettings("test").setSettings(settingsBuilder().put("index.refresh_interval", "")).execute().actionGet();
fail();
} catch (ElasticsearchIllegalArgumentException ex) {
logger.info("Error message: [{}]", ex.getMessage());
}
}
}
| 0true
|
src_test_java_org_elasticsearch_cluster_UpdateSettingsValidationTests.java
|
750 |
public class GetResponse extends ActionResponse implements Iterable<GetField>, ToXContent {
private GetResult getResult;
GetResponse() {
}
GetResponse(GetResult getResult) {
this.getResult = getResult;
}
/**
* Does the document exists.
*/
public boolean isExists() {
return getResult.isExists();
}
/**
* The index the document was fetched from.
*/
public String getIndex() {
return getResult.getIndex();
}
/**
* The type of the document.
*/
public String getType() {
return getResult.getType();
}
/**
* The id of the document.
*/
public String getId() {
return getResult.getId();
}
/**
* The version of the doc.
*/
public long getVersion() {
return getResult.getVersion();
}
/**
* The source of the document if exists.
*/
public byte[] getSourceAsBytes() {
return getResult.source();
}
/**
* Returns the internal source bytes, as they are returned without munging (for example,
* might still be compressed).
*/
public BytesReference getSourceInternal() {
return getResult.internalSourceRef();
}
/**
* Returns bytes reference, also un compress the source if needed.
*/
public BytesReference getSourceAsBytesRef() {
return getResult.sourceRef();
}
/**
* Is the source empty (not available) or not.
*/
public boolean isSourceEmpty() {
return getResult.isSourceEmpty();
}
/**
* The source of the document (as a string).
*/
public String getSourceAsString() {
return getResult.sourceAsString();
}
/**
* The source of the document (As a map).
*/
@SuppressWarnings({"unchecked"})
public Map<String, Object> getSourceAsMap() throws ElasticsearchParseException {
return getResult.sourceAsMap();
}
public Map<String, Object> getSource() {
return getResult.getSource();
}
public Map<String, GetField> getFields() {
return getResult.getFields();
}
public GetField getField(String name) {
return getResult.field(name);
}
@Override
public Iterator<GetField> iterator() {
return getResult.iterator();
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return getResult.toXContent(builder, params);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
getResult = GetResult.readGetResult(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
getResult.writeTo(out);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_get_GetResponse.java
|
199 |
public class TrackingConcurrentMergeScheduler extends ConcurrentMergeScheduler {
protected final ESLogger logger;
private final MeanMetric totalMerges = new MeanMetric();
private final CounterMetric totalMergesNumDocs = new CounterMetric();
private final CounterMetric totalMergesSizeInBytes = new CounterMetric();
private final CounterMetric currentMerges = new CounterMetric();
private final CounterMetric currentMergesNumDocs = new CounterMetric();
private final CounterMetric currentMergesSizeInBytes = new CounterMetric();
private final Set<OnGoingMerge> onGoingMerges = ConcurrentCollections.newConcurrentSet();
private final Set<OnGoingMerge> readOnlyOnGoingMerges = Collections.unmodifiableSet(onGoingMerges);
public TrackingConcurrentMergeScheduler(ESLogger logger) {
super();
this.logger = logger;
}
public long totalMerges() {
return totalMerges.count();
}
public long totalMergeTime() {
return totalMerges.sum();
}
public long totalMergeNumDocs() {
return totalMergesNumDocs.count();
}
public long totalMergeSizeInBytes() {
return totalMergesSizeInBytes.count();
}
public long currentMerges() {
return currentMerges.count();
}
public long currentMergesNumDocs() {
return currentMergesNumDocs.count();
}
public long currentMergesSizeInBytes() {
return currentMergesSizeInBytes.count();
}
public Set<OnGoingMerge> onGoingMerges() {
return readOnlyOnGoingMerges;
}
@Override
protected void doMerge(MergePolicy.OneMerge merge) throws IOException {
int totalNumDocs = merge.totalNumDocs();
// don't used #totalBytesSize() since need to be executed under IW lock, might be fixed in future Lucene version
long totalSizeInBytes = merge.estimatedMergeBytes;
long time = System.currentTimeMillis();
currentMerges.inc();
currentMergesNumDocs.inc(totalNumDocs);
currentMergesSizeInBytes.inc(totalSizeInBytes);
OnGoingMerge onGoingMerge = new OnGoingMerge(merge);
onGoingMerges.add(onGoingMerge);
if (logger.isTraceEnabled()) {
logger.trace("merge [{}] starting..., merging [{}] segments, [{}] docs, [{}] size, into [{}] estimated_size", merge.info == null ? "_na_" : merge.info.info.name, merge.segments.size(), totalNumDocs, new ByteSizeValue(totalSizeInBytes), new ByteSizeValue(merge.estimatedMergeBytes));
}
try {
beforeMerge(onGoingMerge);
super.doMerge(merge);
} finally {
long took = System.currentTimeMillis() - time;
onGoingMerges.remove(onGoingMerge);
afterMerge(onGoingMerge);
currentMerges.dec();
currentMergesNumDocs.dec(totalNumDocs);
currentMergesSizeInBytes.dec(totalSizeInBytes);
totalMergesNumDocs.inc(totalNumDocs);
totalMergesSizeInBytes.inc(totalSizeInBytes);
totalMerges.inc(took);
if (took > 20000) { // if more than 20 seconds, DEBUG log it
logger.debug("merge [{}] done, took [{}]", merge.info == null ? "_na_" : merge.info.info.name, TimeValue.timeValueMillis(took));
} else if (logger.isTraceEnabled()) {
logger.trace("merge [{}] done, took [{}]", merge.info == null ? "_na_" : merge.info.info.name, TimeValue.timeValueMillis(took));
}
}
}
/**
* A callback allowing for custom logic before an actual merge starts.
*/
protected void beforeMerge(OnGoingMerge merge) {
}
/**
* A callback allowing for custom logic before an actual merge starts.
*/
protected void afterMerge(OnGoingMerge merge) {
}
@Override
public MergeScheduler clone() {
// Lucene IW makes a clone internally but since we hold on to this instance
// the clone will just be the identity.
return this;
}
}
| 0true
|
src_main_java_org_apache_lucene_index_TrackingConcurrentMergeScheduler.java
|
56 |
public class AddAnnotionProposal extends CorrectionProposal {
private static final List<String> ANNOTATIONS_ORDER =
asList("doc", "throws", "see", "tagged", "shared", "abstract",
"actual", "formal", "default", "variable");
private static final List<String> ANNOTATIONS_ON_SEPARATE_LINE =
asList("doc", "throws", "see", "tagged");
private final Declaration dec;
private final String annotation;
AddAnnotionProposal(Declaration dec, String annotation,
String desc, int offset, TextFileChange change,
Region selection) {
super(desc, change, selection);
this.dec = dec;
this.annotation = annotation;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AddAnnotionProposal) {
AddAnnotionProposal that = (AddAnnotionProposal) obj;
return that.dec.equals(dec) &&
that.annotation.equals(annotation);
}
else {
return super.equals(obj);
}
}
@Override
public int hashCode() {
return dec.hashCode();
}
private static void addAddAnnotationProposal(Node node, String annotation,
String desc, Declaration dec, Collection<ICompletionProposal> proposals,
IProject project) {
if (dec!=null && dec.getName()!=null &&
!(node instanceof Tree.MissingDeclaration)) {
for (PhasedUnit unit: getUnits(project)) {
if (dec.getUnit().equals(unit.getUnit())) {
FindDeclarationNodeVisitor fdv =
new FindDeclarationNodeVisitor(dec);
getRootNode(unit).visit(fdv);
Tree.Declaration decNode =
(Tree.Declaration) fdv.getDeclarationNode();
if (decNode!=null) {
addAddAnnotationProposal(annotation, desc, dec,
proposals, unit, node, decNode);
}
break;
}
}
}
}
private static void addAddAnnotationProposal(String annotation, String desc,
Declaration dec, Collection<ICompletionProposal> proposals,
PhasedUnit unit, Node node, Tree.Declaration decNode) {
IFile file = getFile(unit);
TextFileChange change = new TextFileChange(desc, file);
change.setEdit(new MultiTextEdit());
TextEdit edit = createReplaceAnnotationEdit(annotation, node, change);
if (edit==null) {
edit = createInsertAnnotationEdit(annotation, decNode,
EditorUtil.getDocument(change));
}
change.addEdit(edit);
if (decNode instanceof Tree.TypedDeclaration &&
!(decNode instanceof Tree.ObjectDefinition)) {
Tree.Type type = ((Tree.TypedDeclaration) decNode).getType();
if (type.getToken()!=null &&
(type instanceof Tree.FunctionModifier ||
type instanceof Tree.ValueModifier)) {
ProducedType it = type.getTypeModel();
if (it!=null && !(it.getDeclaration() instanceof UnknownType)) {
String explicitType = it.getProducedTypeName();
change.addEdit(new ReplaceEdit(type.getStartIndex(),
type.getText().length(), explicitType));
}
}
}
Region selection;
if (node!=null && node.getUnit().equals(decNode.getUnit())) {
selection = new Region(edit.getOffset(), annotation.length());
}
else {
selection = null;
}
Scope container = dec.getContainer();
String containerDesc = container instanceof TypeDeclaration ?
" in '" + ((TypeDeclaration) container).getName() + "'" : "";
String description =
"Make '" + dec.getName() + "' " + annotation + containerDesc;
AddAnnotionProposal p = new AddAnnotionProposal(dec, annotation,
description, edit.getOffset(), change, selection);
if (!proposals.contains(p)) {
proposals.add(p);
}
}
private static ReplaceEdit createReplaceAnnotationEdit(String annotation,
Node node, TextFileChange change) {
String toRemove;
if ("formal".equals(annotation)) {
toRemove = "default";
}
else if ("abstract".equals(annotation)) {
toRemove = "final";
}
else {
return null;
}
Tree.AnnotationList annotationList = getAnnotationList(node);
if (annotationList != null) {
for (Tree.Annotation ann:
annotationList.getAnnotations()) {
if (toRemove.equals(getAnnotationIdentifier(ann))) {
return new ReplaceEdit(ann.getStartIndex(),
ann.getStopIndex()+1-ann.getStartIndex(),
annotation);
}
}
}
return null;
}
public static InsertEdit createInsertAnnotationEdit(String newAnnotation,
Node node, IDocument doc) {
String newAnnotationName = getAnnotationWithoutParam(newAnnotation);
Tree.Annotation prevAnnotation = null;
Tree.Annotation nextAnnotation = null;
Tree.AnnotationList annotationList = getAnnotationList(node);
if (annotationList != null) {
for (Tree.Annotation annotation:
annotationList.getAnnotations()) {
if (isAnnotationAfter(newAnnotationName,
getAnnotationIdentifier(annotation))) {
prevAnnotation = annotation;
} else if (nextAnnotation == null) {
nextAnnotation = annotation;
break;
}
}
}
int nextNodeStartIndex;
if (nextAnnotation != null) {
nextNodeStartIndex = nextAnnotation.getStartIndex();
}
else {
if (node instanceof Tree.AnyAttribute ||
node instanceof Tree.AnyMethod ) {
nextNodeStartIndex =
((Tree.TypedDeclaration) node).getType().getStartIndex();
}
else if (node instanceof Tree.ObjectDefinition ) {
nextNodeStartIndex =
((CommonToken) node.getMainToken()).getStartIndex();
}
else if (node instanceof Tree.ClassOrInterface) {
nextNodeStartIndex =
((CommonToken) node.getMainToken()).getStartIndex();
}
else {
nextNodeStartIndex = node.getStartIndex();
}
}
int newAnnotationOffset;
StringBuilder newAnnotationText = new StringBuilder();
if (isAnnotationOnSeparateLine(newAnnotationName) &&
!(node instanceof Tree.Parameter)) {
if (prevAnnotation != null &&
isAnnotationOnSeparateLine(getAnnotationIdentifier(prevAnnotation))) {
newAnnotationOffset = prevAnnotation.getStopIndex() + 1;
newAnnotationText.append(System.lineSeparator());
newAnnotationText.append(getIndent(node, doc));
newAnnotationText.append(newAnnotation);
} else {
newAnnotationOffset = nextNodeStartIndex;
newAnnotationText.append(newAnnotation);
newAnnotationText.append(System.lineSeparator());
newAnnotationText.append(getIndent(node, doc));
}
} else {
newAnnotationOffset = nextNodeStartIndex;
newAnnotationText.append(newAnnotation);
newAnnotationText.append(" ");
}
return new InsertEdit(newAnnotationOffset,
newAnnotationText.toString());
}
public static Tree.AnnotationList getAnnotationList(Node node) {
Tree.AnnotationList annotationList = null;
if (node instanceof Tree.Declaration) {
annotationList =
((Tree.Declaration) node).getAnnotationList();
}
else if (node instanceof Tree.ModuleDescriptor) {
annotationList =
((Tree.ModuleDescriptor) node).getAnnotationList();
}
else if (node instanceof Tree.PackageDescriptor) {
annotationList =
((Tree.PackageDescriptor) node).getAnnotationList();
}
else if (node instanceof Tree.Assertion) {
annotationList =
((Tree.Assertion) node).getAnnotationList();
}
return annotationList;
}
public static String getAnnotationIdentifier(Tree.Annotation annotation) {
String annotationName = null;
if (annotation != null) {
if (annotation.getPrimary() instanceof Tree.BaseMemberExpression) {
Tree.BaseMemberExpression bme =
(Tree.BaseMemberExpression) annotation.getPrimary();
annotationName = bme.getIdentifier().getText();
}
}
return annotationName;
}
private static String getAnnotationWithoutParam(String annotation) {
int index = annotation.indexOf("(");
if (index != -1) {
return annotation.substring(0, index).trim();
}
index = annotation.indexOf("\"");
if (index != -1) {
return annotation.substring(0, index).trim();
}
index = annotation.indexOf(" ");
if (index != -1) {
return annotation.substring(0, index).trim();
}
return annotation.trim();
}
private static boolean isAnnotationAfter(String annotation1, String annotation2) {
int index1 = ANNOTATIONS_ORDER.indexOf(annotation1);
int index2 = ANNOTATIONS_ORDER.indexOf(annotation2);
return index1 >= index2;
}
private static boolean isAnnotationOnSeparateLine(String annotation) {
return ANNOTATIONS_ON_SEPARATE_LINE.contains(annotation);
}
static void addMakeActualDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec;
if (node instanceof Tree.Declaration) {
dec = ((Tree.Declaration) node).getDeclarationModel();
}
else {
dec = (Declaration) node.getScope();
}
boolean shared = dec.isShared();
addAddAnnotationProposal(node,
shared ? "actual" : "shared actual",
shared ? "Make Actual" : "Make Shared Actual",
dec, proposals, project);
}
static void addMakeDefaultProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration d;
if (node instanceof Tree.Declaration) {
Tree.Declaration decNode = (Tree.Declaration) node;
d = decNode.getDeclarationModel();
}
else if (node instanceof Tree.BaseMemberExpression) {
d = ((Tree.BaseMemberExpression) node).getDeclaration();
}
else {
return;
}
if (d.isClassOrInterfaceMember()) {
List<Declaration> rds =
((ClassOrInterface) d.getContainer())
.getInheritedMembers(d.getName());
Declaration rd=null;
if (rds.isEmpty()) {
rd=d; //TODO: is this really correct? What case does it handle?
}
else {
for (Declaration r: rds) {
if (!r.isDefault()) {
//just take the first one :-/
//TODO: this is very wrong! Instead, make them all default!
rd = r;
break;
}
}
}
if (rd!=null) {
addAddAnnotationProposal(node,
"default", "Make Default",
rd, proposals, project);
}
}
}
static void addMakeDefaultDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec;
if (node instanceof Tree.Declaration) {
dec = ((Tree.Declaration) node).getDeclarationModel();
}
else {
dec = (Declaration) node.getScope();
}
addAddAnnotationProposal(node,
dec.isShared() ? "default" : "shared default",
dec.isShared() ? "Make Default" : "Make Shared Default",
dec, proposals, project);
}
static void addMakeFormalDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec;
if (node instanceof Tree.Declaration) {
dec = ((Tree.Declaration) node).getDeclarationModel();
}
else {
dec = (Declaration) node.getScope();
}
addAddAnnotationProposal(node,
dec.isShared() ? "formal" : "shared formal",
dec.isShared() ? "Make Formal" : "Make Shared Formal",
dec, proposals, project);
}
static void addMakeAbstractDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec;
if (node instanceof Tree.Declaration) {
dec = ((Tree.Declaration) node).getDeclarationModel();
}
else {
dec = (Declaration) node.getScope();
}
if (dec instanceof Class) {
addAddAnnotationProposal(node,
"abstract", "Make Abstract",
dec, proposals, project);
}
}
static void addMakeContainerAbstractProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec;
if (node instanceof Tree.Declaration) {
Scope container =
((Tree.Declaration) node).getDeclarationModel().getContainer();
if (container instanceof Declaration) {
dec = (Declaration) container;
}
else {
return;
}
}
else {
dec = (Declaration) node.getScope();
}
addAddAnnotationProposal(node,
"abstract", "Make Abstract",
dec, proposals, project);
}
static void addMakeVariableProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Tree.Term term;
if (node instanceof Tree.AssignmentOp) {
term = ((Tree.AssignOp) node).getLeftTerm();
}
else if (node instanceof Tree.UnaryOperatorExpression) {
term = ((Tree.PrefixOperatorExpression) node).getTerm();
}
else if (node instanceof Tree.MemberOrTypeExpression) {
term = (Tree.MemberOrTypeExpression) node;
}
else if (node instanceof Tree.SpecifierStatement) {
term = ((Tree.SpecifierStatement) node).getBaseMemberExpression();
}
else {
return;
}
if (term instanceof Tree.MemberOrTypeExpression) {
Declaration dec =
((Tree.MemberOrTypeExpression) term).getDeclaration();
if (dec instanceof Value) {
if (((Value) dec).getOriginalDeclaration()==null) {
addAddAnnotationProposal(node,
"variable", "Make Variable",
dec, proposals, project);
}
}
}
}
static void addMakeVariableDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Tree.Declaration node) {
final Declaration dec = node.getDeclarationModel();
if (dec instanceof Value && node instanceof Tree.AttributeDeclaration) {
final Value v = (Value) dec;
if (!v.isVariable() && !v.isTransient()) {
addAddAnnotationProposal(node,
"variable", "Make Variable",
dec, proposals, project);
}
}
}
static void addMakeVariableDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Tree.CompilationUnit cu, Node node) {
final Tree.SpecifierOrInitializerExpression sie =
(Tree.SpecifierOrInitializerExpression) node;
class GetInitializedVisitor extends Visitor {
Value dec;
@Override
public void visit(Tree.AttributeDeclaration that) {
super.visit(that);
if (that.getSpecifierOrInitializerExpression()==sie) {
dec = that.getDeclarationModel();
}
}
}
GetInitializedVisitor v = new GetInitializedVisitor();
v.visit(cu);
addAddAnnotationProposal(node,
"variable", "Make Variable",
v.dec, proposals, project);
}
static void addMakeSharedProposalForSupertypes(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
if (node instanceof Tree.ClassOrInterface) {
Tree.ClassOrInterface c = (Tree.ClassOrInterface) node;
ProducedType extendedType =
c.getDeclarationModel().getExtendedType();
if (extendedType!=null) {
addMakeSharedProposal(proposals, project,
extendedType.getDeclaration());
for (ProducedType typeArgument:
extendedType.getTypeArgumentList()) {
addMakeSharedProposal(proposals, project,
typeArgument.getDeclaration());
}
}
List<ProducedType> satisfiedTypes =
c.getDeclarationModel().getSatisfiedTypes();
if (satisfiedTypes!=null) {
for (ProducedType satisfiedType: satisfiedTypes) {
addMakeSharedProposal(proposals, project,
satisfiedType.getDeclaration());
for (ProducedType typeArgument:
satisfiedType.getTypeArgumentList()) {
addMakeSharedProposal(proposals, project,
typeArgument.getDeclaration());
}
}
}
}
}
static void addMakeRefinedSharedProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
if (node instanceof Tree.Declaration) {
Declaration refined = ((Tree.Declaration) node).getDeclarationModel()
.getRefinedDeclaration();
if (refined.isDefault() || refined.isFormal()) {
addMakeSharedProposal(proposals, project, refined);
}
else {
addAddAnnotationProposal(node,
"shared default", "Make Shared Default",
refined, proposals, project);
}
}
}
static void addMakeSharedProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
Declaration dec = null;
List<ProducedType> typeArgumentList = null;
if (node instanceof Tree.StaticMemberOrTypeExpression) {
Tree.StaticMemberOrTypeExpression qmte =
(Tree.StaticMemberOrTypeExpression) node;
dec = qmte.getDeclaration();
}
//TODO: handle much more kinds of types!
else if (node instanceof Tree.SimpleType) {
Tree.SimpleType st = (Tree.SimpleType) node;
dec = st.getDeclarationModel();
}
else if (node instanceof Tree.OptionalType) {
Tree.OptionalType ot = (Tree.OptionalType) node;
if (ot.getDefiniteType() instanceof Tree.SimpleType) {
Tree.SimpleType st = (Tree.SimpleType) ot.getDefiniteType();
dec = st.getDeclarationModel();
}
}
else if (node instanceof Tree.IterableType) {
Tree.IterableType it = (Tree.IterableType) node;
if (it.getElementType() instanceof Tree.SimpleType) {
Tree.SimpleType st = (Tree.SimpleType) it.getElementType();
dec = st.getDeclarationModel();
}
}
else if (node instanceof Tree.SequenceType) {
Tree.SequenceType qt = (Tree.SequenceType) node;
if (qt.getElementType() instanceof Tree.SimpleType) {
Tree.SimpleType st = (Tree.SimpleType) qt.getElementType();
dec = st.getDeclarationModel();
}
}
else if (node instanceof Tree.ImportMemberOrType) {
Tree.ImportMemberOrType imt = (Tree.ImportMemberOrType) node;
dec = imt.getDeclarationModel();
}
else if (node instanceof Tree.TypedDeclaration) {
Tree.TypedDeclaration td = ((Tree.TypedDeclaration) node);
if (td.getDeclarationModel() != null) {
ProducedType pt = td.getDeclarationModel().getType();
dec = pt.getDeclaration();
typeArgumentList = pt.getTypeArgumentList();
}
}
else if (node instanceof Tree.Parameter) {
Tree.Parameter parameter = ((Tree.Parameter) node);
if (parameter.getParameterModel()!=null &&
parameter.getParameterModel().getType()!=null) {
ProducedType pt = parameter.getParameterModel().getType();
dec = pt.getDeclaration();
typeArgumentList = pt.getTypeArgumentList();
}
}
addMakeSharedProposal(proposals, project, dec);
if (typeArgumentList != null) {
for (ProducedType typeArgument : typeArgumentList) {
addMakeSharedProposal(proposals, project,
typeArgument.getDeclaration());
}
}
}
static void addMakeSharedProposal(Collection<ICompletionProposal> proposals,
IProject project, Declaration dec) {
if (dec!=null) {
if (dec instanceof UnionType) {
List<ProducedType> caseTypes =
((UnionType) dec).getCaseTypes();
for (ProducedType caseType: caseTypes) {
addMakeSharedProposal(proposals, project,
caseType.getDeclaration());
for (ProducedType typeArgument:
caseType.getTypeArgumentList()) {
addMakeSharedProposal(proposals, project,
typeArgument.getDeclaration());
}
}
}
else if (dec instanceof IntersectionType) {
List<ProducedType> satisfiedTypes =
((IntersectionType) dec).getSatisfiedTypes();
for (ProducedType satisfiedType: satisfiedTypes) {
addMakeSharedProposal(proposals, project,
satisfiedType.getDeclaration());
for (ProducedType typeArgument:
satisfiedType.getTypeArgumentList()) {
addMakeSharedProposal(proposals, project,
typeArgument.getDeclaration());
}
}
}
else if (dec instanceof TypedDeclaration ||
dec instanceof ClassOrInterface ||
dec instanceof TypeAlias) {
if (!dec.isShared()) {
addAddAnnotationProposal(null,
"shared", "Make Shared",
dec, proposals, project);
}
}
}
}
static void addMakeSharedDecProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
if (node instanceof Tree.Declaration) {
Declaration d = ((Tree.Declaration) node).getDeclarationModel();
addAddAnnotationProposal(node,
"shared", "Make Shared",
d, proposals, project);
}
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AddAnnotionProposal.java
|
395 |
public class ClusterSearchShardsRequestBuilder extends MasterNodeReadOperationRequestBuilder<ClusterSearchShardsRequest, ClusterSearchShardsResponse, ClusterSearchShardsRequestBuilder> {
public ClusterSearchShardsRequestBuilder(ClusterAdminClient clusterClient) {
super((InternalClusterAdminClient) clusterClient, new ClusterSearchShardsRequest());
}
/**
* Sets the indices the search will be executed on.
*/
public ClusterSearchShardsRequestBuilder setIndices(String... indices) {
request.indices(indices);
return this;
}
/**
* The document types to execute the search against. Defaults to be executed against
* all types.
*/
public ClusterSearchShardsRequestBuilder setTypes(String... types) {
request.types(types);
return this;
}
/**
* A comma separated list of routing values to control the shards the search will be executed on.
*/
public ClusterSearchShardsRequestBuilder setRouting(String routing) {
request.routing(routing);
return this;
}
/**
* The routing values to control the shards that the search will be executed on.
*/
public ClusterSearchShardsRequestBuilder setRouting(String... routing) {
request.routing(routing);
return this;
}
/**
* Sets the preference to execute the search. Defaults to randomize across shards. Can be set to
* <tt>_local</tt> to prefer local shards, <tt>_primary</tt> to execute only on primary shards, or
* a custom value, which guarantees that the same order will be used across different requests.
*/
public ClusterSearchShardsRequestBuilder setPreference(String preference) {
request.preference(preference);
return this;
}
/**
* Specifies what type of requested indices to ignore and how to deal indices wildcard expressions.
* For example indices that don't exist.
*/
public ClusterSearchShardsRequestBuilder setIndicesOptions(IndicesOptions indicesOptions) {
request().indicesOptions(indicesOptions);
return this;
}
@Override
protected void doExecute(ActionListener<ClusterSearchShardsResponse> listener) {
((ClusterAdminClient) client).searchShards(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_shards_ClusterSearchShardsRequestBuilder.java
|
1,484 |
public class Hibernate4CacheEntrySerializerHook
implements SerializerHook {
private static final String SKIP_INIT_MSG = "Hibernate4 not available, skipping serializer initialization";
private final Class<?> cacheEntryClass;
public Hibernate4CacheEntrySerializerHook() {
Class<?> cacheEntryClass = null;
if (UnsafeHelper.UNSAFE_AVAILABLE) {
try {
cacheEntryClass = Class.forName("org.hibernate.cache.spi.entry.CacheEntry");
} catch (Exception e) {
Logger.getLogger(Hibernate4CacheEntrySerializerHook.class).finest(SKIP_INIT_MSG);
}
}
this.cacheEntryClass = cacheEntryClass;
}
@Override
public Class getSerializationType() {
return cacheEntryClass;
}
@Override
public Serializer createSerializer() {
if (cacheEntryClass != null) {
return new Hibernate4CacheEntrySerializer();
}
return null;
}
@Override
public boolean isOverwritable() {
return true;
}
}
| 1no label
|
hazelcast-hibernate_hazelcast-hibernate4_src_main_java_com_hazelcast_hibernate_serialization_Hibernate4CacheEntrySerializerHook.java
|
434 |
public class ClientSetProxy<E> extends AbstractClientCollectionProxy<E> implements ISet<E> {
public ClientSetProxy(String instanceName, String serviceName, String name) {
super(instanceName, serviceName, name);
}
@Override
public String toString() {
return "ISet{" + "name='" + getName() + '\'' + '}';
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientSetProxy.java
|
344 |
public class ODatabasePoolEntry {
public String url;
public String userName;
public String userPassword;
public ODatabasePoolEntry(String url, String userName, String userPassword) {
super();
this.url = url;
this.userName = userName;
this.userPassword = userPassword;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((url == null) ? 0 : url.hashCode());
result = prime * result + ((userName == null) ? 0 : userName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ODatabasePoolEntry other = (ODatabasePoolEntry) obj;
if (url == null) {
if (other.url != null)
return false;
} else if (!url.equals(other.url))
return false;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
return true;
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_ODatabasePoolEntry.java
|
1,251 |
public class ClientTransportModule extends AbstractModule {
@Override
protected void configure() {
bind(InternalTransportClient.class).asEagerSingleton();
bind(InternalTransportAdminClient.class).asEagerSingleton();
bind(InternalTransportIndicesAdminClient.class).asEagerSingleton();
bind(InternalTransportClusterAdminClient.class).asEagerSingleton();
bind(TransportClientNodesService.class).asEagerSingleton();
}
}
| 0true
|
src_main_java_org_elasticsearch_client_transport_ClientTransportModule.java
|
2 |
Files.walkFileTree(java.nio.file.FileSystems.getDefault().getPath(libsDirectory.getAbsolutePath()), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException
{
if (areModulesChanged || isFullBuild ?
path.getFileName().toString().startsWith(CEYLON_GENERATED_ARCHIVES_PREFIX) :
path.getFileName().toString().equals(CEYLON_GENERATED_CLASSES_ARCHIVE)) {
try {
Files.delete(path);
} catch(IOException ioe) {
CeylonAndroidPlugin.logError("Could not delete a ceylon jar from the android libs directory", ioe);
}
}
return FileVisitResult.CONTINUE;
}
});
| 0true
|
plugins_com.redhat.ceylon.eclipse.android.plugin_src_com_redhat_ceylon_eclipse_android_plugin_AndroidBuildHookProvider.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
|
458 |
public class OSBTreeRIDSet implements Set<OIdentifiable>, OStringBuilderSerializable, ORecordLazyMultiValue {
private final long fileId;
private final OBonsaiBucketPointer rootPointer;
private ORecordInternal<?> owner;
private boolean autoConvertToRecord = true;
private final OSBTreeCollectionManager collectionManager;
protected static final OProfilerMBean PROFILER = Orient.instance().getProfiler();
private OSBTreeRIDSet(ODatabaseRecord database) {
collectionManager = database.getSbTreeCollectionManager();
OSBTreeBonsai<OIdentifiable, Boolean> tree = collectionManager.createSBTree();
fileId = tree.getFileId();
rootPointer = tree.getRootBucketPointer();
}
public OSBTreeRIDSet() {
this(ODatabaseRecordThreadLocal.INSTANCE.get());
this.owner = null;
}
public OSBTreeRIDSet(ORecordInternal<?> owner) {
this(owner.getDatabase());
this.owner = owner;
}
public OSBTreeRIDSet(ORecordInternal<?> owner, long fileId, OBonsaiBucketPointer rootPointer) {
this.owner = owner;
this.fileId = fileId;
this.rootPointer = rootPointer;
if (owner != null)
collectionManager = owner.getDatabase().getSbTreeCollectionManager();
else
collectionManager = ODatabaseRecordThreadLocal.INSTANCE.get().getSbTreeCollectionManager();
}
public OSBTreeRIDSet(ODocument owner, Collection<OIdentifiable> iValue) {
this(owner);
addAll(iValue);
}
private OSBTreeBonsai<OIdentifiable, Boolean> getTree() {
return collectionManager.loadSBTree(fileId, rootPointer);
}
protected long getFileId() {
return fileId;
}
protected OBonsaiBucketPointer getRootPointer() {
return rootPointer;
}
@Override
public int size() {
return (int) getTree().size();
}
@Override
public boolean isEmpty() {
return getTree().size() == 0L;
}
@Override
public boolean contains(Object o) {
return o instanceof OIdentifiable && contains((OIdentifiable) o);
}
public boolean contains(OIdentifiable o) {
return getTree().get(o) != null;
}
@Override
public Iterator<OIdentifiable> iterator() {
return new TreeKeyIterator(getTree(), autoConvertToRecord);
}
@Override
public Object[] toArray() {
// TODO replace with more efficient implementation
final ArrayList<OIdentifiable> list = new ArrayList<OIdentifiable>(size());
for (OIdentifiable identifiable : this) {
if (autoConvertToRecord)
identifiable = identifiable.getRecord();
list.add(identifiable);
}
return list.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
// TODO replace with more efficient implementation.
final ArrayList<OIdentifiable> list = new ArrayList<OIdentifiable>(size());
for (OIdentifiable identifiable : this) {
if (autoConvertToRecord)
identifiable = identifiable.getRecord();
list.add(identifiable);
}
return list.toArray(a);
}
@Override
public boolean add(OIdentifiable oIdentifiable) {
return add(getTree(), oIdentifiable);
}
private boolean add(OSBTreeBonsai<OIdentifiable, Boolean> tree, OIdentifiable oIdentifiable) {
return tree.put(oIdentifiable, Boolean.TRUE);
}
@Override
public boolean remove(Object o) {
return o instanceof OIdentifiable && remove((OIdentifiable) o);
}
public boolean remove(OIdentifiable o) {
return getTree().remove(o) != null;
}
@Override
public boolean containsAll(Collection<?> c) {
for (Object e : c)
if (!contains(e))
return false;
return true;
}
@Override
public boolean addAll(Collection<? extends OIdentifiable> c) {
final OSBTreeBonsai<OIdentifiable, Boolean> tree = getTree();
boolean modified = false;
for (OIdentifiable e : c)
if (add(tree, e))
modified = true;
return modified;
}
@Override
public boolean retainAll(Collection<?> c) {
boolean modified = false;
Iterator<OIdentifiable> it = iterator();
while (it.hasNext()) {
if (!c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
@Override
public boolean removeAll(Collection<?> c) {
boolean modified = false;
for (Object o : c) {
modified |= remove(o);
}
return modified;
}
@Override
public void clear() {
getTree().clear();
}
@Override
public OSBTreeRIDSet toStream(StringBuilder iOutput) throws OSerializationException {
final long timer = PROFILER.startChrono();
try {
iOutput.append(OStringSerializerHelper.LINKSET_PREFIX);
final ODocument document = new ODocument();
document.field("rootIndex", getRootPointer().getPageIndex());
document.field("rootOffset", getRootPointer().getPageOffset());
document.field("fileId", getFileId());
iOutput.append(new String(document.toStream()));
iOutput.append(OStringSerializerHelper.SET_END);
} finally {
PROFILER.stopChrono(PROFILER.getProcessMetric("mvrbtree.toStream"), "Serialize a MVRBTreeRID", timer);
}
return this;
}
public byte[] toStream() {
final StringBuilder iOutput = new StringBuilder();
toStream(iOutput);
return iOutput.toString().getBytes();
}
@Override
public OStringBuilderSerializable fromStream(StringBuilder iInput) throws OSerializationException {
throw new UnsupportedOperationException("unimplemented yet");
}
public static OSBTreeRIDSet fromStream(String stream, ORecordInternal<?> owner) {
stream = stream.substring(OStringSerializerHelper.LINKSET_PREFIX.length(), stream.length() - 1);
final ODocument doc = new ODocument();
doc.fromString(stream);
final OBonsaiBucketPointer rootIndex = new OBonsaiBucketPointer((Long) doc.field("rootIndex"),
(Integer) doc.field("rootOffset"));
final long fileId = doc.field("fileId");
return new OSBTreeRIDSet(owner, fileId, rootIndex);
}
@Override
public Iterator<OIdentifiable> rawIterator() {
return new TreeKeyIterator(getTree(), false);
}
@Override
public void convertLinks2Records() {
throw new UnsupportedOperationException();
}
@Override
public boolean convertRecords2Links() {
throw new UnsupportedOperationException();
}
@Override
public boolean isAutoConvertToRecord() {
return autoConvertToRecord;
}
@Override
public void setAutoConvertToRecord(boolean convertToRecord) {
autoConvertToRecord = convertToRecord;
}
@Override
public boolean detach() {
throw new UnsupportedOperationException();
}
private static class TreeKeyIterator implements Iterator<OIdentifiable> {
private final boolean autoConvertToRecord;
private OSBTreeMapEntryIterator<OIdentifiable, Boolean> entryIterator;
public TreeKeyIterator(OTreeInternal<OIdentifiable, Boolean> tree, boolean autoConvertToRecord) {
entryIterator = new OSBTreeMapEntryIterator<OIdentifiable, Boolean>(tree);
this.autoConvertToRecord = autoConvertToRecord;
}
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public OIdentifiable next() {
final OIdentifiable identifiable = entryIterator.next().getKey();
if (autoConvertToRecord)
return identifiable.getRecord();
else
return identifiable;
}
@Override
public void remove() {
entryIterator.remove();
}
}
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_record_ridset_sbtree_OSBTreeRIDSet.java
|
936 |
threadPool.executor(executor).execute(new Runnable() {
@Override
public void run() {
try {
onOperation(shard, shardIndex, shardOperation(shardRequest));
} catch (Throwable e) {
onOperation(shard, shardIt, shardIndex, e);
}
}
});
| 0true
|
src_main_java_org_elasticsearch_action_support_broadcast_TransportBroadcastOperationAction.java
|
2,061 |
@Component("blCustomerStateRequestProcessor")
public class CustomerStateRequestProcessor extends AbstractBroadleafWebRequestProcessor implements ApplicationEventPublisherAware {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
public static final String BLC_RULE_MAP_PARAM = "blRuleMap";
@Resource(name="blCustomerService")
protected CustomerService customerService;
protected ApplicationEventPublisher eventPublisher;
protected static String customerRequestAttributeName = "customer";
public static final String ANONYMOUS_CUSTOMER_SESSION_ATTRIBUTE_NAME = "_blc_anonymousCustomer";
public static final String ANONYMOUS_CUSTOMER_ID_SESSION_ATTRIBUTE_NAME = "_blc_anonymousCustomerId";
private static final String LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME = "_blc_lastPublishedEvent";
@Override
public void process(WebRequest request) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Customer customer = null;
if ((authentication != null) && !(authentication instanceof AnonymousAuthenticationToken)) {
String userName = authentication.getName();
customer = (Customer) request.getAttribute(customerRequestAttributeName, WebRequest.SCOPE_REQUEST);
if (userName != null && (customer == null || !userName.equals(customer.getUsername()))) {
// can only get here if the authenticated user does not match the user in session
customer = customerService.readCustomerByUsername(userName);
if (logger.isDebugEnabled() && customer != null) {
logger.debug("Customer found by username " + userName);
}
}
if (customer != null) {
ApplicationEvent lastPublishedEvent = (ApplicationEvent) request.getAttribute(LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME, WebRequest.SCOPE_REQUEST);
if (authentication instanceof RememberMeAuthenticationToken) {
// set transient property of customer
customer.setCookied(true);
boolean publishRememberMeEvent = true;
if (lastPublishedEvent != null && lastPublishedEvent instanceof CustomerAuthenticatedFromCookieEvent) {
CustomerAuthenticatedFromCookieEvent cookieEvent = (CustomerAuthenticatedFromCookieEvent) lastPublishedEvent;
if (userName.equals(cookieEvent.getCustomer().getUsername())) {
publishRememberMeEvent = false;
}
}
if (publishRememberMeEvent) {
CustomerAuthenticatedFromCookieEvent cookieEvent = new CustomerAuthenticatedFromCookieEvent(customer, this.getClass().getName());
eventPublisher.publishEvent(cookieEvent);
request.setAttribute(LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME, cookieEvent, WebRequest.SCOPE_REQUEST);
}
} else if (authentication instanceof UsernamePasswordAuthenticationToken) {
customer.setLoggedIn(true);
boolean publishLoggedInEvent = true;
if (lastPublishedEvent != null && lastPublishedEvent instanceof CustomerLoggedInEvent) {
CustomerLoggedInEvent loggedInEvent = (CustomerLoggedInEvent) lastPublishedEvent;
if (userName.equals(loggedInEvent.getCustomer().getUsername())) {
publishLoggedInEvent= false;
}
}
if (publishLoggedInEvent) {
CustomerLoggedInEvent loggedInEvent = new CustomerLoggedInEvent(customer, this.getClass().getName());
eventPublisher.publishEvent(loggedInEvent);
request.setAttribute(LAST_PUBLISHED_EVENT_SESSION_ATTRIBUTED_NAME, loggedInEvent, WebRequest.SCOPE_REQUEST);
}
} else {
customer = resolveAuthenticatedCustomer(authentication);
}
}
}
if (customer == null) {
// This is an anonymous customer.
// TODO: Handle a custom cookie (different than remember me) that is just for anonymous users.
// This can be used to remember their cart from a previous visit.
// Cookie logic probably needs to be configurable - with TCS as the exception.
customer = resolveAnonymousCustomer(request);
}
CustomerState.setCustomer(customer);
// Setup customer for content rule processing
Map<String,Object> ruleMap = (Map<String, Object>) request.getAttribute(BLC_RULE_MAP_PARAM, WebRequest.SCOPE_REQUEST);
if (ruleMap == null) {
ruleMap = new HashMap<String,Object>();
}
ruleMap.put("customer", customer);
request.setAttribute(BLC_RULE_MAP_PARAM, ruleMap, WebRequest.SCOPE_REQUEST);
}
/**
* Subclasses can extend to resolve other types of Authentication tokens
* @param authentication
* @return
*/
public Customer resolveAuthenticatedCustomer(Authentication authentication) {
return null;
}
/**
* <p>Implementors can subclass to change how anonymous customers are created. Note that this method is intended to actually create the anonymous
* customer if one does not exist. If you are looking to just get the current anonymous customer (if it exists) then instead use the
* {@link #getAnonymousCustomer(WebRequest)} method.<p>
*
* <p>The intended behavior of this method is as follows:</p>
*
* <ul>
* <li>Look for a {@link Customer} on the session</li>
* <ul>
* <li>If a customer is found in session, keep using the session-based customer</li>
* <li>If a customer is not found in session</li>
* <ul>
* <li>Look for a customer ID in session</li>
* <li>If a customer ID is found in session:</li>
* <ul><li>Look up the customer in the database</ul></li>
* </ul>
* <li>If no there is no customer ID in session (and thus no {@link Customer})</li>
* <ol>
* <li>Create a new customer</li>
* <li>Put the newly-created {@link Customer} in session</li>
* </ol>
* </ul>
* </ul>
*
* @param request
* @return
* @see {@link #getAnonymousCustomer(WebRequest)}
* @see {@link #getAnonymousCustomerAttributeName()}
* @see {@link #getAnonymousCustomerIdAttributeName()}
*/
public Customer resolveAnonymousCustomer(WebRequest request) {
Customer customer;
customer = getAnonymousCustomer(request);
//If there is no Customer object in session, AND no customer id in session, create a new customer
//and store the entire customer in session (don't persist to DB just yet)
if (customer == null) {
customer = customerService.createNewCustomer();
request.setAttribute(getAnonymousCustomerSessionAttributeName(), customer, WebRequest.SCOPE_GLOBAL_SESSION);
}
customer.setAnonymous(true);
return customer;
}
/**
* Returns the anonymous customer that was saved in session. This first checks for a full customer in session (meaning
* that the customer has not already been persisted) and returns that. If there is no full customer in session (and
* there is instead just an anonymous customer ID) then this will look up the customer from the database using that and
* return it.
*
* @param request the current request
* @return the anonymous customer in session or null if there is no anonymous customer represented in session
* @see {@link #getAnonymousCustomerSessionAttributeName()}
* @see {@link #getAnonymousCustomerIdSessionAttributeName()}
*/
public Customer getAnonymousCustomer(WebRequest request) {
Customer anonymousCustomer = (Customer) request.getAttribute(getAnonymousCustomerSessionAttributeName(),
WebRequest.SCOPE_GLOBAL_SESSION);
if (anonymousCustomer == null) {
//Customer is not in session, see if we have just a customer ID in session (the anonymous customer might have
//already been persisted)
Long customerId = (Long) request.getAttribute(getAnonymousCustomerIdSessionAttributeName(), WebRequest.SCOPE_GLOBAL_SESSION);
if (customerId != null) {
//we have a customer ID in session, look up the customer from the database to ensure we have an up-to-date
//customer to store in CustomerState
anonymousCustomer = customerService.readCustomerById(customerId);
}
}
return anonymousCustomer;
}
/**
* Returns the session attribute to store the anonymous customer.
* Some implementations may wish to have a different anonymous customer instance (and as a result a different cart).
*
* The entire Customer should be stored in session ONLY if that Customer has not already been persisted to the database.
* Once it has been persisted (like once the user has added something to the cart) then {@link #getAnonymousCustomerIdAttributeName()}
* should be used instead.
*
* @return the session attribute for an anonymous {@link Customer} that has not been persisted to the database yet
*/
public static String getAnonymousCustomerSessionAttributeName() {
return ANONYMOUS_CUSTOMER_SESSION_ATTRIBUTE_NAME;
}
/**
* <p>Returns the session attribute to store the anonymous customer ID. This session attribute should be used to track
* anonymous customers that have not registered but have state in the database. When users first visit the Broadleaf
* site, a new {@link Customer} is instantiated but is <b>only saved in session</b> and not persisted to the database. However,
* once that user adds something to the cart, that {@link Customer} is now saved in the database and it no longer makes
* sense to pull back a full {@link Customer} object from session, as any session-based {@link Customer} will be out of
* date in regards to Hibernate (specifically with lists).</p>
*
* <p>So, once Broadleaf detects that the session-based {@link Customer} has been persisted, it should remove the session-based
* {@link Customer} and then utilize just the customer ID from session.</p>
*
* @see {@link CustomerStateRefresher}
*/
public static String getAnonymousCustomerIdSessionAttributeName() {
return ANONYMOUS_CUSTOMER_ID_SESSION_ATTRIBUTE_NAME;
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
/**
* The request-scoped attribute that should store the {@link Customer}.
*
* <pre>
* Customer customer = (Customer) request.getAttribute(CustomerStateRequestProcessor.getCustomerRequestAttributeName());
* //this is equivalent to the above invocation
* Customer customer = CustomerState.getCustomer();
* </pre>
* @return
* @see {@link CustomerState}
*/
public static String getCustomerRequestAttributeName() {
return customerRequestAttributeName;
}
public static void setCustomerRequestAttributeName(String customerRequestAttributeName) {
CustomerStateRequestProcessor.customerRequestAttributeName = customerRequestAttributeName;
}
}
| 1no label
|
core_broadleaf-profile-web_src_main_java_org_broadleafcommerce_profile_web_core_security_CustomerStateRequestProcessor.java
|
3,257 |
public class ListPermission extends InstancePermission {
private static final int ADD = 0x4;
private static final int READ = 0x8;
private static final int REMOVE = 0x16;
private static final int LISTEN = 0x32;
private static final int ALL = ADD | REMOVE | READ | CREATE | DESTROY | LISTEN;
public ListPermission(String name, String... actions) {
super(name, actions);
}
@Override
protected int initMask(String[] actions) {
int mask = NONE;
for (String action : actions) {
if (ActionConstants.ACTION_ALL.equals(action)) {
return ALL;
}
if (ActionConstants.ACTION_CREATE.equals(action)) {
mask |= CREATE;
} else if (ActionConstants.ACTION_ADD.equals(action)) {
mask |= ADD;
} else if (ActionConstants.ACTION_REMOVE.equals(action)) {
mask |= REMOVE;
} else if (ActionConstants.ACTION_READ.equals(action)) {
mask |= READ;
} else if (ActionConstants.ACTION_DESTROY.equals(action)) {
mask |= DESTROY;
} else if (ActionConstants.ACTION_LISTEN.equals(action)) {
mask |= LISTEN;
}
}
return mask;
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_security_permission_ListPermission.java
|
5,090 |
transportService.sendRequest(node, SearchQueryByIdTransportHandler.ACTION, request, new BaseTransportResponseHandler<QuerySearchResult>() {
@Override
public QuerySearchResult newInstance() {
return new QuerySearchResult();
}
@Override
public void handleResponse(QuerySearchResult response) {
listener.onResult(response);
}
@Override
public void handleException(TransportException exp) {
listener.onFailure(exp);
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
});
| 1no label
|
src_main_java_org_elasticsearch_search_action_SearchServiceTransportAction.java
|
92 |
public class ReadOnlyTxManager extends AbstractTransactionManager
implements Lifecycle
{
private ThreadLocalWithSize<ReadOnlyTransactionImpl> txThreadMap;
private int eventIdentifierCounter = 0;
private XaDataSourceManager xaDsManager = null;
private final StringLogger logger;
private final Factory<byte[]> xidGlobalIdFactory;
public ReadOnlyTxManager( XaDataSourceManager xaDsManagerToUse, Factory<byte[]> xidGlobalIdFactory,
StringLogger logger )
{
xaDsManager = xaDsManagerToUse;
this.xidGlobalIdFactory = xidGlobalIdFactory;
this.logger = logger;
}
synchronized int getNextEventIdentifier()
{
return eventIdentifierCounter++;
}
@Override
public void init()
{
}
@Override
public void start()
{
txThreadMap = new ThreadLocalWithSize<>();
}
@Override
public void stop()
{
}
@Override
public void shutdown()
{
}
@Override
public void begin() throws NotSupportedException
{
if ( txThreadMap.get() != null )
{
throw new NotSupportedException(
"Nested transactions not supported" );
}
txThreadMap.set( new ReadOnlyTransactionImpl( xidGlobalIdFactory.newInstance(), this, logger ) );
}
@Override
public void commit() throws RollbackException, HeuristicMixedException,
IllegalStateException
{
ReadOnlyTransactionImpl tx = txThreadMap.get();
if ( tx == null )
{
throw new IllegalStateException( "Not in transaction" );
}
if ( tx.getStatus() != Status.STATUS_ACTIVE
&& tx.getStatus() != Status.STATUS_MARKED_ROLLBACK )
{
throw new IllegalStateException( "Tx status is: "
+ getTxStatusAsString( tx.getStatus() ) );
}
tx.doBeforeCompletion();
if ( tx.getStatus() == Status.STATUS_ACTIVE )
{
commit( tx );
}
else if ( tx.getStatus() == Status.STATUS_MARKED_ROLLBACK )
{
rollbackCommit( tx );
}
else
{
throw new IllegalStateException( "Tx status is: "
+ getTxStatusAsString( tx.getStatus() ) );
}
}
private void commit( ReadOnlyTransactionImpl tx )
{
if ( tx.getResourceCount() == 0 )
{
tx.setStatus( Status.STATUS_COMMITTED );
}
tx.doAfterCompletion();
txThreadMap.remove();
tx.setStatus( Status.STATUS_NO_TRANSACTION );
}
private void rollbackCommit( ReadOnlyTransactionImpl tx )
throws HeuristicMixedException, RollbackException
{
try
{
tx.doRollback();
}
catch ( XAException e )
{
logger.error( "Unable to rollback marked transaction. "
+ "Some resources may be commited others not. "
+ "Neo4j kernel should be SHUTDOWN for "
+ "resource maintance and transaction recovery ---->", e );
throw Exceptions.withCause(
new HeuristicMixedException( "Unable to rollback " + " ---> error code for rollback: "
+ e.errorCode ), e );
}
tx.doAfterCompletion();
txThreadMap.remove();
tx.setStatus( Status.STATUS_NO_TRANSACTION );
throw new RollbackException(
"Failed to commit, transaction rolled back" );
}
@Override
public void rollback() throws IllegalStateException, SystemException
{
ReadOnlyTransactionImpl tx = txThreadMap.get();
if ( tx == null )
{
throw new IllegalStateException( "Not in transaction" );
}
if ( tx.getStatus() == Status.STATUS_ACTIVE ||
tx.getStatus() == Status.STATUS_MARKED_ROLLBACK ||
tx.getStatus() == Status.STATUS_PREPARING )
{
tx.doBeforeCompletion();
try
{
tx.doRollback();
}
catch ( XAException e )
{
logger.error("Unable to rollback marked or active transaction. "
+ "Some resources may be commited others not. "
+ "Neo4j kernel should be SHUTDOWN for "
+ "resource maintance and transaction recovery ---->", e );
throw Exceptions.withCause( new SystemException( "Unable to rollback "
+ " ---> error code for rollback: " + e.errorCode ), e );
}
tx.doAfterCompletion();
txThreadMap.remove();
tx.setStatus( Status.STATUS_NO_TRANSACTION );
}
else
{
throw new IllegalStateException( "Tx status is: "
+ getTxStatusAsString( tx.getStatus() ) );
}
}
@Override
public int getStatus()
{
ReadOnlyTransactionImpl tx = txThreadMap.get();
if ( tx != null )
{
return tx.getStatus();
}
return Status.STATUS_NO_TRANSACTION;
}
@Override
public Transaction getTransaction()
{
return txThreadMap.get();
}
@Override
public void resume( Transaction tx ) throws IllegalStateException
{
if ( txThreadMap.get() != null )
{
throw new IllegalStateException( "Transaction already associated" );
}
if ( tx != null )
{
ReadOnlyTransactionImpl txImpl = (ReadOnlyTransactionImpl) tx;
if ( txImpl.getStatus() != Status.STATUS_NO_TRANSACTION )
{
txImpl.markAsActive();
txThreadMap.set( txImpl );
}
}
}
@Override
public Transaction suspend()
{
ReadOnlyTransactionImpl tx = txThreadMap.get();
txThreadMap.remove();
if ( tx != null )
{
tx.markAsSuspended();
}
return tx;
}
@Override
public void setRollbackOnly() throws IllegalStateException
{
ReadOnlyTransactionImpl tx = txThreadMap.get();
if ( tx == null )
{
throw new IllegalStateException( "Not in transaction" );
}
tx.setRollbackOnly();
}
@Override
public void setTransactionTimeout( int seconds )
{
}
byte[] getBranchId( XAResource xaRes )
{
if ( xaRes instanceof XaResource )
{
byte branchId[] = ((XaResource) xaRes).getBranchId();
if ( branchId != null )
{
return branchId;
}
}
return xaDsManager.getBranchId( xaRes );
}
String getTxStatusAsString( int status )
{
switch ( status )
{
case Status.STATUS_ACTIVE:
return "STATUS_ACTIVE";
case Status.STATUS_NO_TRANSACTION:
return "STATUS_NO_TRANSACTION";
case Status.STATUS_PREPARING:
return "STATUS_PREPARING";
case Status.STATUS_PREPARED:
return "STATUS_PREPARED";
case Status.STATUS_COMMITTING:
return "STATUS_COMMITING";
case Status.STATUS_COMMITTED:
return "STATUS_COMMITED";
case Status.STATUS_ROLLING_BACK:
return "STATUS_ROLLING_BACK";
case Status.STATUS_ROLLEDBACK:
return "STATUS_ROLLEDBACK";
case Status.STATUS_UNKNOWN:
return "STATUS_UNKNOWN";
case Status.STATUS_MARKED_ROLLBACK:
return "STATUS_MARKED_ROLLBACK";
default:
return "STATUS_UNKNOWN(" + status + ")";
}
}
@Override
public int getEventIdentifier()
{
TransactionImpl tx = (TransactionImpl) getTransaction();
if ( tx != null )
{
return tx.getEventIdentifier();
}
return -1;
}
@Override
public void doRecovery() throws Throwable
{
}
@Override
public TransactionState getTransactionState()
{
return TransactionState.NO_STATE;
}
}
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_ReadOnlyTxManager.java
|
69 |
public interface TitanRelation extends TitanElement {
/**
* Establishes a unidirectional edge between this relation and the given vertex for the specified label.
* The label must be defined {@link EdgeLabel#isUnidirected()}.
*
* @param label
* @param vertex
*/
public void setProperty(EdgeLabel label, TitanVertex vertex);
/**
* Returns the vertex associated to this relation by a unidirected edge of the given label or NULL if such does not exist.
*
* @param label
* @return
*/
public TitanVertex getProperty(EdgeLabel label);
/**
* Returns the type of this relation.
* <p/>
* The type is either a label ({@link EdgeLabel} if this relation is an edge or a key ({@link PropertyKey}) if this
* relation is a property.
*
* @return Type of this relation
*/
public RelationType getType();
/**
* Returns the direction of this relation from the perspective of the specified vertex.
*
* @param vertex vertex on which the relation is incident
* @return The direction of this relation from the perspective of the specified vertex.
* @throws InvalidElementException if this relation is not incident on the vertex
*/
public Direction getDirection(TitanVertex vertex);
/**
* Checks whether this relation is incident on the specified vertex.
*
* @param vertex vertex to check incidence for
* @return true, if this relation is incident on the vertex, else false
*/
public boolean isIncidentOn(TitanVertex vertex);
/**
* Checks whether this relation is a loop.
* An relation is a loop if it connects a vertex with itself.
*
* @return true, if this relation is a loop, else false.
*/
boolean isLoop();
/**
* Checks whether this relation is a property.
*
* @return true, if this relation is a property, else false.
* @see TitanProperty
*/
boolean isProperty();
/**
* Checks whether this relation is an edge.
*
* @return true, if this relation is an edge, else false.
* @see TitanEdge
*/
boolean isEdge();
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_TitanRelation.java
|
963 |
public abstract class NodesOperationRequestBuilder<Request extends NodesOperationRequest<Request>, Response extends NodesOperationResponse, RequestBuilder extends NodesOperationRequestBuilder<Request, Response, RequestBuilder>>
extends ActionRequestBuilder<Request, Response, RequestBuilder> {
protected NodesOperationRequestBuilder(InternalGenericClient client, Request request) {
super(client, request);
}
@SuppressWarnings("unchecked")
public final RequestBuilder setNodesIds(String... nodesIds) {
request.nodesIds(nodesIds);
return (RequestBuilder) this;
}
@SuppressWarnings("unchecked")
public final RequestBuilder setTimeout(TimeValue timeout) {
request.timeout(timeout);
return (RequestBuilder) this;
}
@SuppressWarnings("unchecked")
public final RequestBuilder setTimeout(String timeout) {
request.timeout(timeout);
return (RequestBuilder) this;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_nodes_NodesOperationRequestBuilder.java
|
569 |
return new DataSerializableFactory() {
@Override
public IdentifiedDataSerializable create(int typeId) {
switch (typeId) {
case DATA:
return new Data();
case ADDRESS:
return new Address();
case MEMBER:
return new MemberImpl();
case HEARTBEAT:
return new HeartbeatOperation();
case CONFIG_CHECK:
return new ConfigCheck();
case MEMBERSHIP_EVENT:
return new ClientMembershipEvent();
default:
return null;
}
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_cluster_ClusterDataSerializerHook.java
|
1,448 |
public abstract class TitanInputFormat extends InputFormat<NullWritable, FaunusVertex> implements Configurable {
private static final String SETUP_PACKAGE_PREFIX = "com.thinkaurelius.titan.hadoop.formats.util.input.";
private static final String SETUP_CLASS_NAME = ".TitanHadoopSetupImpl";
protected FaunusVertexQueryFilter vertexQuery;
protected boolean trackPaths;
protected TitanHadoopSetup titanSetup;
protected ModifiableHadoopConfiguration faunusConf;
protected ModifiableConfiguration inputConf;
// TODO why does this class even implement setConf? It doesn't save any overhead. Might as well make all the state final, delete setConf, and construct instances instead
@Override
public void setConf(final Configuration config) {
this.faunusConf = ModifiableHadoopConfiguration.of(config);
this.vertexQuery = FaunusVertexQueryFilter.create(faunusConf);
this.inputConf = faunusConf.getInputConf();
final String titanVersion = faunusConf.get(TITAN_INPUT_VERSION);
this.trackPaths = faunusConf.get(PIPELINE_TRACK_PATHS);
final String className = SETUP_PACKAGE_PREFIX + titanVersion + SETUP_CLASS_NAME;
this.titanSetup = ConfigurationUtil.instantiate(className, new Object[]{config}, new Class[]{Configuration.class});
}
}
| 1no label
|
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_formats_util_TitanInputFormat.java
|
1,356 |
public class JDTAnnotation implements AnnotationMirror {
private Map<String, Object> values;
public JDTAnnotation(AnnotationBinding annotation) {
values = new HashMap<String, Object>();
ElementValuePair[] annotationVaues = annotation.getElementValuePairs();
for (ElementValuePair annotationValue : annotationVaues) {
String name = new String(annotationValue.getName());
MethodBinding elementMethod = annotationValue.getMethodBinding();
Object value = null;
if (elementMethod != null) {
value = convertValue(annotationValue.getMethodBinding().returnType, annotationValue.getValue());
} else {
value = JDTType.UNKNOWN_TYPE;
}
values.put(name, value);
}
}
@Override
public Object getValue(String fieldName) {
return values.get(fieldName);
}
private Object convertValue(TypeBinding returnType, Object value) {
if(value.getClass().isArray()){
Object[] array = (Object[])value;
List<Object> values = new ArrayList<Object>(array.length);
TypeBinding elementType = ((ArrayBinding)returnType).elementsType();
for(Object val : array)
values.add(convertValue(elementType, val));
return values;
}
if(returnType.isArrayType()){
// got a single value but expecting array
List<Object> values = new ArrayList<Object>(1);
TypeBinding elementType = ((ArrayBinding)returnType).elementsType();
values.add(convertValue(elementType, value));
return values;
}
if(value instanceof AnnotationBinding){
return new JDTAnnotation((AnnotationBinding) value);
}
if(value instanceof TypeBinding){
return new JDTType((TypeBinding) value);
}
if(value instanceof FieldBinding){
return new String(((FieldBinding) value).name);
}
if(value instanceof Constant){
Constant constant = (Constant) value;
return JDTUtils.fromConstant(constant);
}
return value;
}
@Override
public Object getValue() {
return getValue("value");
}
}
| 1no label
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_model_mirror_JDTAnnotation.java
|
830 |
public class SearchRequest extends ActionRequest<SearchRequest> {
private static final XContentType contentType = Requests.CONTENT_TYPE;
private SearchType searchType = SearchType.DEFAULT;
private String[] indices;
@Nullable
private String routing;
@Nullable
private String preference;
private BytesReference source;
private boolean sourceUnsafe;
private BytesReference extraSource;
private boolean extraSourceUnsafe;
private Scroll scroll;
private String[] types = Strings.EMPTY_ARRAY;
private SearchOperationThreading operationThreading = SearchOperationThreading.THREAD_PER_SHARD;
private IndicesOptions indicesOptions = IndicesOptions.strict();
public SearchRequest() {
}
/**
* Constructs a new search request against the indices. No indices provided here means that search
* will run against all indices.
*/
public SearchRequest(String... indices) {
indices(indices);
}
/**
* Constructs a new search request against the provided indices with the given search source.
*/
public SearchRequest(String[] indices, byte[] source) {
indices(indices);
this.source = new BytesArray(source);
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
// no need to check, we resolve to match all query
// if (source == null && extraSource == null) {
// validationException = addValidationError("search source is missing", validationException);
// }
return validationException;
}
public void beforeStart() {
// we always copy over if needed, the reason is that a request might fail while being search remotely
// and then we need to keep the buffer around
if (source != null && sourceUnsafe) {
source = source.copyBytesArray();
sourceUnsafe = false;
}
if (extraSource != null && extraSourceUnsafe) {
extraSource = extraSource.copyBytesArray();
extraSourceUnsafe = false;
}
}
/**
* Internal.
*/
public void beforeLocalFork() {
}
/**
* Sets the indices the search will be executed on.
*/
public SearchRequest indices(String... indices) {
if (indices == null) {
throw new ElasticsearchIllegalArgumentException("indices must not be null");
} else {
for (int i = 0; i < indices.length; i++) {
if (indices[i] == null) {
throw new ElasticsearchIllegalArgumentException("indices[" + i +"] must not be null");
}
}
}
this.indices = indices;
return this;
}
/**
* Controls the the search operation threading model.
*/
public SearchOperationThreading operationThreading() {
return this.operationThreading;
}
/**
* Controls the the search operation threading model.
*/
public SearchRequest operationThreading(SearchOperationThreading operationThreading) {
this.operationThreading = operationThreading;
return this;
}
/**
* Sets the string representation of the operation threading model. Can be one of
* "no_threads", "single_thread" and "thread_per_shard".
*/
public SearchRequest operationThreading(String operationThreading) {
return operationThreading(SearchOperationThreading.fromString(operationThreading, this.operationThreading));
}
public IndicesOptions indicesOptions() {
return indicesOptions;
}
public SearchRequest indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = indicesOptions;
return this;
}
/**
* The document types to execute the search against. Defaults to be executed against
* all types.
*/
public String[] types() {
return types;
}
/**
* The document types to execute the search against. Defaults to be executed against
* all types.
*/
public SearchRequest types(String... types) {
this.types = types;
return this;
}
/**
* A comma separated list of routing values to control the shards the search will be executed on.
*/
public String routing() {
return this.routing;
}
/**
* A comma separated list of routing values to control the shards the search will be executed on.
*/
public SearchRequest routing(String routing) {
this.routing = routing;
return this;
}
/**
* The routing values to control the shards that the search will be executed on.
*/
public SearchRequest routing(String... routings) {
this.routing = Strings.arrayToCommaDelimitedString(routings);
return this;
}
/**
* Sets the preference to execute the search. Defaults to randomize across shards. Can be set to
* <tt>_local</tt> to prefer local shards, <tt>_primary</tt> to execute only on primary shards, or
* a custom value, which guarantees that the same order will be used across different requests.
*/
public SearchRequest preference(String preference) {
this.preference = preference;
return this;
}
public String preference() {
return this.preference;
}
/**
* The search type to execute, defaults to {@link SearchType#DEFAULT}.
*/
public SearchRequest searchType(SearchType searchType) {
this.searchType = searchType;
return this;
}
/**
* The a string representation search type to execute, defaults to {@link SearchType#DEFAULT}. Can be
* one of "dfs_query_then_fetch"/"dfsQueryThenFetch", "dfs_query_and_fetch"/"dfsQueryAndFetch",
* "query_then_fetch"/"queryThenFetch", and "query_and_fetch"/"queryAndFetch".
*/
public SearchRequest searchType(String searchType) throws ElasticsearchIllegalArgumentException {
return searchType(SearchType.fromString(searchType));
}
/**
* The source of the search request.
*/
public SearchRequest source(SearchSourceBuilder sourceBuilder) {
this.source = sourceBuilder.buildAsBytes(contentType);
this.sourceUnsafe = false;
return this;
}
/**
* The source of the search request. Consider using either {@link #source(byte[])} or
* {@link #source(org.elasticsearch.search.builder.SearchSourceBuilder)}.
*/
public SearchRequest source(String source) {
this.source = new BytesArray(source);
this.sourceUnsafe = false;
return this;
}
/**
* The source of the search request in the form of a map.
*/
public SearchRequest source(Map source) {
try {
XContentBuilder builder = XContentFactory.contentBuilder(contentType);
builder.map(source);
return source(builder);
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
}
}
public SearchRequest source(XContentBuilder builder) {
this.source = builder.bytes();
this.sourceUnsafe = false;
return this;
}
/**
* The search source to execute.
*/
public SearchRequest source(byte[] source) {
return source(source, 0, source.length, false);
}
/**
* The search source to execute.
*/
public SearchRequest source(byte[] source, int offset, int length) {
return source(source, offset, length, false);
}
/**
* The search source to execute.
*/
public SearchRequest source(byte[] source, int offset, int length, boolean unsafe) {
return source(new BytesArray(source, offset, length), unsafe);
}
/**
* The search source to execute.
*/
public SearchRequest source(BytesReference source, boolean unsafe) {
this.source = source;
this.sourceUnsafe = unsafe;
return this;
}
/**
* The search source to execute.
*/
public BytesReference source() {
return source;
}
/**
* Allows to provide additional source that will be used as well.
*/
public SearchRequest extraSource(SearchSourceBuilder sourceBuilder) {
if (sourceBuilder == null) {
extraSource = null;
return this;
}
this.extraSource = sourceBuilder.buildAsBytes(contentType);
this.extraSourceUnsafe = false;
return this;
}
public SearchRequest extraSource(Map extraSource) {
try {
XContentBuilder builder = XContentFactory.contentBuilder(contentType);
builder.map(extraSource);
return extraSource(builder);
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
}
}
public SearchRequest extraSource(XContentBuilder builder) {
this.extraSource = builder.bytes();
this.extraSourceUnsafe = false;
return this;
}
/**
* Allows to provide additional source that will use used as well.
*/
public SearchRequest extraSource(String source) {
this.extraSource = new BytesArray(source);
this.extraSourceUnsafe = false;
return this;
}
/**
* Allows to provide additional source that will be used as well.
*/
public SearchRequest extraSource(byte[] source) {
return extraSource(source, 0, source.length, false);
}
/**
* Allows to provide additional source that will be used as well.
*/
public SearchRequest extraSource(byte[] source, int offset, int length) {
return extraSource(source, offset, length, false);
}
/**
* Allows to provide additional source that will be used as well.
*/
public SearchRequest extraSource(byte[] source, int offset, int length, boolean unsafe) {
return extraSource(new BytesArray(source, offset, length), unsafe);
}
/**
* Allows to provide additional source that will be used as well.
*/
public SearchRequest extraSource(BytesReference source, boolean unsafe) {
this.extraSource = source;
this.extraSourceUnsafe = unsafe;
return this;
}
/**
* Additional search source to execute.
*/
public BytesReference extraSource() {
return this.extraSource;
}
/**
* The tye of search to execute.
*/
public SearchType searchType() {
return searchType;
}
/**
* The indices
*/
public String[] indices() {
return indices;
}
/**
* If set, will enable scrolling of the search request.
*/
public Scroll scroll() {
return scroll;
}
/**
* If set, will enable scrolling of the search request.
*/
public SearchRequest scroll(Scroll scroll) {
this.scroll = scroll;
return this;
}
/**
* If set, will enable scrolling of the search request for the specified timeout.
*/
public SearchRequest scroll(TimeValue keepAlive) {
return scroll(new Scroll(keepAlive));
}
/**
* If set, will enable scrolling of the search request for the specified timeout.
*/
public SearchRequest scroll(String keepAlive) {
return scroll(new Scroll(TimeValue.parseTimeValue(keepAlive, null)));
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
operationThreading = SearchOperationThreading.fromId(in.readByte());
searchType = SearchType.fromId(in.readByte());
indices = new String[in.readVInt()];
for (int i = 0; i < indices.length; i++) {
indices[i] = in.readString();
}
routing = in.readOptionalString();
preference = in.readOptionalString();
if (in.readBoolean()) {
scroll = readScroll(in);
}
sourceUnsafe = false;
source = in.readBytesReference();
extraSourceUnsafe = false;
extraSource = in.readBytesReference();
types = in.readStringArray();
indicesOptions = IndicesOptions.readIndicesOptions(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeByte(operationThreading.id());
out.writeByte(searchType.id());
out.writeVInt(indices.length);
for (String index : indices) {
out.writeString(index);
}
out.writeOptionalString(routing);
out.writeOptionalString(preference);
if (scroll == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
scroll.writeTo(out);
}
out.writeBytesReference(source);
out.writeBytesReference(extraSource);
out.writeStringArray(types);
indicesOptions.writeIndicesOptions(out);
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_search_SearchRequest.java
|
405 |
public interface OTrackedMultiValue<K, V> {
/**
* Add change listener.
*
* @param changeListener
* Change listener instance.
*/
public void addChangeListener(OMultiValueChangeListener<K, V> changeListener);
/**
* Remove change listener.
*
* @param changeListener
* Change listener instance.
*/
public void removeRecordChangeListener(OMultiValueChangeListener<K, V> changeListener);
/**
*
* Reverts all operations that were performed on collection and return original collection state.
*
* @param changeEvents
* List of operations that were performed on collection.
*
* @return Original collection state.
*/
public Object returnOriginalState(List<OMultiValueChangeEvent<K, V>> changeEvents);
public Class<?> getGenericClass();
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_record_OTrackedMultiValue.java
|
70 |
public interface TitanTransaction extends TitanGraphTransaction {
/* ---------------------------------------------------------------
* Modifications
* ---------------------------------------------------------------
*/
/**
* Creates a new vertex in the graph with the given vertex id and the given vertex label.
* Note, that an exception is thrown if the vertex id is not a valid Titan vertex id or if a vertex with the given
* id already exists.
* <p/>
* Custom id setting must be enabled via the configuration option {@link com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration#ALLOW_SETTING_VERTEX_ID}.
* <p/>
* Use {@link com.thinkaurelius.titan.core.util.TitanId#toVertexId(long)} to construct a valid Titan vertex id from a user id.
*
* @param id vertex id of the vertex to be created
* @param vertexLabel vertex label for this vertex - can be null if no vertex label should be set.
* @return New vertex
*/
public TitanVertex addVertex(Long id, VertexLabel vertexLabel);
/**
* Creates a new edge connecting the specified vertices.
* <p/>
* Creates and returns a new {@link TitanEdge} with given label connecting the vertices in the order
* specified.
*
* @param label label of the edge to be created
* @param outVertex outgoing vertex of the edge
* @param inVertex incoming vertex of the edge
* @return new edge
*/
public TitanEdge addEdge(TitanVertex outVertex, TitanVertex inVertex, EdgeLabel label);
/**
* Creates a new edge connecting the specified vertices.
* <p/>
* Creates and returns a new {@link TitanEdge} with given label connecting the vertices in the order
* specified.
* <br />
* Automatically creates the edge label if it does not exist and automatic creation of types is enabled. Otherwise,
* this method with throw an {@link IllegalArgumentException}.
*
* @param label label of the edge to be created
* @param outVertex outgoing vertex of the edge
* @param inVertex incoming vertex of the edge
* @return new edge
*/
public TitanEdge addEdge(TitanVertex outVertex, TitanVertex inVertex, String label);
/**
* Creates a new property for the given vertex and key with the specified value.
* <p/>
* Creates and returns a new {@link TitanProperty} with specified property key and the given object being the value.
*
* @param key key of the property to be created
* @param vertex vertex for which to create the property
* @param value value of the property to be created
* @return new property
* @throws IllegalArgumentException if the value does not match the data type of the given property key.
*/
public TitanProperty addProperty(TitanVertex vertex, PropertyKey key, Object value);
/**
* Creates a new property for the given vertex and key with the specified value.
* <p/>
* Creates and returns a new {@link TitanProperty} with specified property key and the given object being the value.
* <br />
* Automatically creates the property key if it does not exist and automatic creation of types is enabled. Otherwise,
* this method with throw an {@link IllegalArgumentException}.
*
* @param key key of the property to be created
* @param vertex vertex for which to create the property
* @param value value of the property to be created
* @return new property
* @throws IllegalArgumentException if the value does not match the data type of the given property key.
*/
public TitanProperty addProperty(TitanVertex vertex, String key, Object value);
/**
* Retrieves all vertices which have a property of the given key with the specified value.
* <p/>
* For this operation to be efficient, please ensure that the given property key is indexed.
* Some storage backends may not support this method without a pre-configured index.
*
* @param key key
* @param value value value
* @return All vertices which have a property of the given key with the specified value.
* @see com.thinkaurelius.titan.core.schema.TitanManagement#buildIndex(String, Class)
*/
public Iterable<TitanVertex> getVertices(PropertyKey key, Object value);
/**
* Retrieves all vertices which have a property of the given key with the specified value.
* <p/>
* For this operation to be efficient, please ensure that the given property key is indexed.
* Some storage backends may not support this method without a pre-configured index.
*
* @param key key
* @param value value value
* @return All edges which have a property of the given key with the specified value.
* @see com.thinkaurelius.titan.core.schema.TitanManagement#buildIndex(String, Class)
*/
public Iterable<TitanEdge> getEdges(PropertyKey key, Object value);
/* ---------------------------------------------------------------
* Closing and admin
* ---------------------------------------------------------------
*/
/**
* Commits and closes the transaction.
* <p/>
* Will attempt to persist all modifications which may result in exceptions in case of persistence failures or
* lock contention.
* <br />
* The call releases data structures if possible. All element references (e.g. vertex objects) retrieved
* through this transaction are stale after the transaction closes and should no longer be used.
*
* @throws com.thinkaurelius.titan.diskstorage.BackendException
* if an error arises during persistence
*/
public void commit();
/**
* Aborts and closes the transaction. Will discard all modifications.
* <p/>
* The call releases data structures if possible. All element references (e.g. vertex objects) retrieved
* through this transaction are stale after the transaction closes and should no longer be used.
*
* @throws com.thinkaurelius.titan.diskstorage.BackendException
* if an error arises when releasing the transaction handle
*/
public void rollback();
/**
* Checks whether the transaction is still open.
*
* @return true, when the transaction is open, else false
*/
public boolean isOpen();
/**
* Checks whether the transaction has been closed.
*
* @return true, if the transaction has been closed, else false
*/
public boolean isClosed();
/**
* Checks whether any changes to the graph database have been made in this transaction.
* <p/>
* A modification may be an edge or vertex update, addition, or deletion.
*
* @return true, if the transaction contains updates, else false.
*/
public boolean hasModifications();
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_TitanTransaction.java
|
185 |
public class UrlRewriteTag extends TagSupport {
private static final long serialVersionUID = 1L;
// The following attribute is set in BroadleafProcessURLFilter
public static final String REQUEST_DTO = "blRequestDTO";
private String value;
private String var;
private static StaticAssetService staticAssetService;
protected void initServices() {
if (staticAssetService == null) {
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());
staticAssetService = (StaticAssetService) applicationContext.getBean("blStaticAssetService");
}
}
/**
* Returns true if the current request.scheme = HTTPS or if the request.isSecure value is true.
* @return
*/
protected boolean isRequestSecure() {
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
return ("HTTPS".equalsIgnoreCase(request.getScheme()) || request.isSecure());
}
public int doStartTag() throws JspException {
initServices();
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
String returnValue = staticAssetService.convertAssetPath(value, request.getContextPath(), isRequestSecure());
if (var != null) {
pageContext.setAttribute(var, returnValue);
} else {
try {
pageContext.getOut().print(returnValue);
} catch (IOException ioe) {
throw new JspTagException(ioe.toString(), ioe);
}
}
return EVAL_PAGE;
}
@Override
public int doEndTag() throws JspException {
var=null;
return super.doEndTag();
}
@Override
public void release() {
var = null;
super.release();
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getVar() {
return var;
}
public void setVar(String var) {
this.var = var;
}
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_web_file_UrlRewriteTag.java
|
212 |
public interface HydratedCacheManager {
public Object getHydratedCacheElementItem(String cacheRegion, String cacheName, Serializable elementKey, String elementItemName);
public void addHydratedCacheElementItem(String cacheRegion, String cacheName, Serializable elementKey, String elementItemName, Object elementValue);
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_cache_engine_HydratedCacheManager.java
|
716 |
public class CollectionRemoveBackupOperation extends CollectionOperation implements BackupOperation {
private long itemId;
public CollectionRemoveBackupOperation() {
}
public CollectionRemoveBackupOperation(String name, long itemId) {
super(name);
this.itemId = itemId;
}
@Override
public void beforeRun() throws Exception {
}
@Override
public void run() throws Exception {
getOrCreateContainer().removeBackup(itemId);
}
@Override
public void afterRun() throws Exception {
}
@Override
public int getId() {
return CollectionDataSerializerHook.COLLECTION_REMOVE_BACKUP;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeLong(itemId);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
itemId = in.readLong();
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionRemoveBackupOperation.java
|
731 |
return new Map.Entry<K, V>() {
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
throw new UnsupportedOperationException("setValue");
}
};
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_index_sbtree_local_OSBTree.java
|
448 |
final Thread t2 = new Thread() {
public void run() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
q.offer("item1");
}
};
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_queue_ClientQueueTest.java
|
453 |
executor.execute(new Runnable() {
@Override
public void run() {
int half = testValues.length / 2;
for (int i = 0; i < testValues.length; i++) {
final ReplicatedMap map = i < half ? map1 : map2;
final AbstractMap.SimpleEntry<Integer, Integer> entry = testValues[i];
map.put(entry.getKey(), entry.getValue());
}
}
}, 2, EntryEventType.ADDED, 100, 0.75, map1, map2);
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_replicatedmap_ClientReplicatedMapTest.java
|
1,350 |
private class NodeIndexStoreDeletedTransportHandler extends BaseTransportRequestHandler<NodeIndexStoreDeletedMessage> {
static final String ACTION = "cluster/nodeIndexStoreDeleted";
@Override
public NodeIndexStoreDeletedMessage newInstance() {
return new NodeIndexStoreDeletedMessage();
}
@Override
public void messageReceived(NodeIndexStoreDeletedMessage message, TransportChannel channel) throws Exception {
innerNodeIndexStoreDeleted(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
|
1,027 |
threadPool.executor(executor).execute(new Runnable() {
@Override
public void run() {
try {
Response response = shardOperation(request, shardRouting.id());
listener.onResponse(response);
} catch (Throwable e) {
onFailure(shardRouting, e);
}
}
});
| 0true
|
src_main_java_org_elasticsearch_action_support_single_shard_TransportShardSingleOperationAction.java
|
431 |
public class ClusterStatsAction extends ClusterAction<ClusterStatsRequest, ClusterStatsResponse, ClusterStatsRequestBuilder> {
public static final ClusterStatsAction INSTANCE = new ClusterStatsAction();
public static final String NAME = "cluster/stats";
private ClusterStatsAction() {
super(NAME);
}
@Override
public ClusterStatsResponse newResponse() {
return new ClusterStatsResponse();
}
@Override
public ClusterStatsRequestBuilder newRequestBuilder(ClusterAdminClient client) {
return new ClusterStatsRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsAction.java
|
135 |
class InvertIfElseProposal extends CorrectionProposal {
InvertIfElseProposal(int offset, TextChange change) {
super("Invert if-else", change, new Region(offset, 0));
}
static void addReverseIfElseProposal(IDocument doc,
Collection<ICompletionProposal> proposals, IFile file,
final Statement statement, Tree.CompilationUnit cu) {
try {
Tree.IfStatement ifStmt;
if (statement instanceof Tree.IfStatement) {
ifStmt = (IfStatement) statement;
}
else {
class FindIf extends Visitor {
Tree.IfStatement result;
@Override
public void visit(Tree.IfStatement that) {
super.visit(that);
if (that.getIfClause()!=null &&
that.getIfClause().getBlock()
.getStatements().contains(statement)) {
result = that;
}
if (that.getElseClause()!=null &&
that.getElseClause().getBlock()
.getStatements().contains(statement)) {
result = that;
}
}
}
FindIf fi = new FindIf();
fi.visit(cu);
if (fi.result==null) {
return;
}
else {
ifStmt = fi.result;
}
}
if (ifStmt.getElseClause() == null) {
return;
}
IfClause ifClause = ifStmt.getIfClause();
Block ifBlock = ifClause.getBlock();
Block elseBlock = ifStmt.getElseClause().getBlock();
List<Condition> conditions = ifClause.getConditionList()
.getConditions();
if (conditions.size()!=1) {
return;
}
Condition ifCondition = conditions.get(0);
String test = null;
String term = getTerm(doc, ifCondition);
if (term.equals("(true)")) {
test = "false";
} else if (term.equals("(false)")) {
test = "true";
} else if (ifCondition instanceof BooleanCondition) {
BooleanCondition boolCond = (BooleanCondition) ifCondition;
Term bt = boolCond.getExpression().getTerm();
if (bt instanceof NotOp) {
test = removeEnclosingParenthesis(getTerm(doc, ((NotOp) bt).getTerm()));
} else if (bt instanceof EqualityOp) {
test = getInvertedEqualityTest(doc, (EqualityOp)bt);
} else if (bt instanceof ComparisonOp) {
test = getInvertedComparisonTest(doc, (ComparisonOp)bt);
} else if (! (bt instanceof Tree.OperatorExpression) || bt instanceof Tree.UnaryOperatorExpression) {
term = removeEnclosingParenthesis(term);
}
} else {
term = removeEnclosingParenthesis(term);
}
if (test == null) {
test = "!" + term;
}
String baseIndent = getIndent(ifStmt, doc);
String indent = getDefaultIndent();
String delim = getDefaultLineDelimiter(doc);
String elseStr = getTerm(doc, elseBlock);
elseStr = addEnclosingBraces(elseStr, baseIndent,
indent, delim);
test = removeEnclosingParenthesis(test);
StringBuilder replace = new StringBuilder();
replace.append("if (").append(test).append(") ")
.append(elseStr);
if (isElseOnOwnLine(doc, ifBlock, elseBlock)) {
replace.append(delim)
.append(baseIndent);
} else {
replace.append(" ");
}
replace.append("else ")
.append(getTerm(doc, ifBlock));
TextChange change = new TextFileChange("Invert if-else", file);
change.setEdit(new ReplaceEdit(ifStmt.getStartIndex(),
ifStmt.getStopIndex() - ifStmt.getStartIndex() + 1, replace.toString()));
proposals.add(new InvertIfElseProposal(ifStmt.getStartIndex(), change));
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getInvertedEqualityTest(IDocument doc, EqualityOp eqyalityOp)
throws BadLocationException {
String op;
if (eqyalityOp instanceof EqualOp) {
op = " != ";
} else {
op = " == ";
}
return getTerm(doc, eqyalityOp.getLeftTerm()) + op + getTerm(doc, eqyalityOp.getRightTerm());
}
private static String getInvertedComparisonTest(IDocument doc, ComparisonOp compOp)
throws BadLocationException {
String op;
if (compOp instanceof LargerOp) {
op = " <= ";
} else if (compOp instanceof LargeAsOp) {
op = " < ";
} else if (compOp instanceof SmallerOp) {
op = " >= ";
} else if (compOp instanceof SmallAsOp) {
op = " > ";
} else {
throw new RuntimeException("Unknown Comarision op " + compOp);
}
return getTerm(doc, compOp.getLeftTerm()) + op + getTerm(doc, compOp.getRightTerm());
}
private static boolean isElseOnOwnLine(IDocument doc, Block ifBlock,
Block elseBlock) throws BadLocationException {
return doc.getLineOfOffset(ifBlock.getStopIndex()) != doc.getLineOfOffset(elseBlock.getStartIndex());
}
private static String addEnclosingBraces(String s, String baseIndent,
String indent, String delim) {
if (s.charAt(0) != '{') {
return "{" + delim + baseIndent +
indent + indent(s, indent, delim) +
delim + baseIndent + "}";
}
return s;
}
private static String indent(String s, String indentation,
String delim) {
return s.replaceAll(delim+"(\\s*)", delim+"$1" + indentation);
}
private static String removeEnclosingParenthesis(String s) {
if (s.charAt(0) == '(') {
int endIndex = 0;
int startIndex = 0;
//Make sure we are not in this case ((a) == (b))
while ((endIndex = s.indexOf(')', endIndex + 1)) > 0) {
if (endIndex == s.length() -1 ) {
return s.substring(1, s.length() - 1);
}
if ((startIndex = s.indexOf('(', startIndex + 1)) > endIndex) {
return s;
}
}
}
return s;
}
private static String getTerm(IDocument doc, Node node) throws BadLocationException {
return doc.get(node.getStartIndex(), node.getStopIndex() - node.getStartIndex() + 1);
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_InvertIfElseProposal.java
|
1,288 |
public class ReviewStatusType {
private static final long serialVersionUID = 1L;
private static final Map<String, ReviewStatusType> TYPES = new HashMap<String, ReviewStatusType>();
public static final ReviewStatusType PENDING = new ReviewStatusType("PENDING");
public static final ReviewStatusType APPROVED = new ReviewStatusType("APPROVED");
public static final ReviewStatusType REJECTED = new ReviewStatusType("REJECTED");
public static ReviewStatusType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
public ReviewStatusType() {
}
public ReviewStatusType(final String type) {
setType(type);
}
public String getType() {
return type;
}
private void setType(String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ReviewStatusType other = (ReviewStatusType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_rating_service_type_ReviewStatusType.java
|
301 |
public enum WriteConsistencyLevel {
DEFAULT((byte) 0),
ONE((byte) 1),
QUORUM((byte) 2),
ALL((byte) 3);
private final byte id;
WriteConsistencyLevel(byte id) {
this.id = id;
}
public byte id() {
return id;
}
public static WriteConsistencyLevel fromId(byte value) {
if (value == 0) {
return DEFAULT;
} else if (value == 1) {
return ONE;
} else if (value == 2) {
return QUORUM;
} else if (value == 3) {
return ALL;
}
throw new ElasticsearchIllegalArgumentException("No write consistency match [" + value + "]");
}
public static WriteConsistencyLevel fromString(String value) {
if (value.equals("default")) {
return DEFAULT;
} else if (value.equals("one")) {
return ONE;
} else if (value.equals("quorum")) {
return QUORUM;
} else if (value.equals("all")) {
return ALL;
}
throw new ElasticsearchIllegalArgumentException("No write consistency match [" + value + "]");
}
}
| 0true
|
src_main_java_org_elasticsearch_action_WriteConsistencyLevel.java
|
594 |
public class LogStatusHandler implements StatusHandler {
private static final Log LOG = LogFactory.getLog(LogStatusHandler.class);
public void handleStatus(String serviceName, ServiceStatusType status) {
if (status.equals(ServiceStatusType.DOWN)) {
LOG.error(serviceName + " is reporting a status of DOWN");
} else if (status.equals(ServiceStatusType.PAUSED)) {
LOG.warn(serviceName + " is reporting a status of PAUSED");
} else {
LOG.info(serviceName + " is reporting a status of UP");
}
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_vendor_service_monitor_handler_LogStatusHandler.java
|
2,920 |
public class PreBuiltAnalyzerProviderFactory implements AnalyzerProviderFactory {
private final PreBuiltAnalyzerProvider analyzerProvider;
public PreBuiltAnalyzerProviderFactory(String name, AnalyzerScope scope, Analyzer analyzer) {
analyzerProvider = new PreBuiltAnalyzerProvider(name, scope, analyzer);
}
@Override
public AnalyzerProvider create(String name, Settings settings) {
Version indexVersion = settings.getAsVersion(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT);
if (!Version.CURRENT.equals(indexVersion)) {
Analyzer analyzer = PreBuiltAnalyzers.valueOf(name.toUpperCase(Locale.ROOT)).getAnalyzer(indexVersion);
return new PreBuiltAnalyzerProvider(name, AnalyzerScope.INDICES, analyzer);
}
return analyzerProvider;
}
public Analyzer analyzer() {
return analyzerProvider.get();
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_analysis_PreBuiltAnalyzerProviderFactory.java
|
480 |
final OIndexManager indexManagerTwo = makeDbCall(databaseDocumentTxTwo, new ODbRelatedCall<OIndexManager>() {
public OIndexManager call() {
return databaseDocumentTxTwo.getMetadata().getIndexManager();
}
});
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java
|
486 |
public class TransportAnalyzeAction extends TransportSingleCustomOperationAction<AnalyzeRequest, AnalyzeResponse> {
private final IndicesService indicesService;
private final IndicesAnalysisService indicesAnalysisService;
@Inject
public TransportAnalyzeAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService,
IndicesService indicesService, IndicesAnalysisService indicesAnalysisService) {
super(settings, threadPool, clusterService, transportService);
this.indicesService = indicesService;
this.indicesAnalysisService = indicesAnalysisService;
}
@Override
protected String executor() {
return ThreadPool.Names.INDEX;
}
@Override
protected AnalyzeRequest newRequest() {
return new AnalyzeRequest();
}
@Override
protected AnalyzeResponse newResponse() {
return new AnalyzeResponse();
}
@Override
protected String transportAction() {
return AnalyzeAction.NAME;
}
@Override
protected ClusterBlockException checkGlobalBlock(ClusterState state, AnalyzeRequest request) {
return state.blocks().globalBlockedException(ClusterBlockLevel.READ);
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, AnalyzeRequest request) {
if (request.index() != null) {
request.index(state.metaData().concreteIndex(request.index()));
return state.blocks().indexBlockedException(ClusterBlockLevel.READ, request.index());
}
return null;
}
@Override
protected ShardsIterator shards(ClusterState state, AnalyzeRequest request) {
if (request.index() == null) {
// just execute locally....
return null;
}
return state.routingTable().index(request.index()).randomAllActiveShardsIt();
}
@Override
protected AnalyzeResponse shardOperation(AnalyzeRequest request, int shardId) throws ElasticsearchException {
IndexService indexService = null;
if (request.index() != null) {
indexService = indicesService.indexServiceSafe(request.index());
}
Analyzer analyzer = null;
boolean closeAnalyzer = false;
String field = null;
if (request.field() != null) {
if (indexService == null) {
throw new ElasticsearchIllegalArgumentException("No index provided, and trying to analyzer based on a specific field which requires the index parameter");
}
FieldMapper<?> fieldMapper = indexService.mapperService().smartNameFieldMapper(request.field());
if (fieldMapper != null) {
if (fieldMapper.isNumeric()) {
throw new ElasticsearchIllegalArgumentException("Can't process field [" + request.field() + "], Analysis requests are not supported on numeric fields");
}
analyzer = fieldMapper.indexAnalyzer();
field = fieldMapper.names().indexName();
}
}
if (field == null) {
if (indexService != null) {
field = indexService.queryParserService().defaultField();
} else {
field = AllFieldMapper.NAME;
}
}
if (analyzer == null && request.analyzer() != null) {
if (indexService == null) {
analyzer = indicesAnalysisService.analyzer(request.analyzer());
} else {
analyzer = indexService.analysisService().analyzer(request.analyzer());
}
if (analyzer == null) {
throw new ElasticsearchIllegalArgumentException("failed to find analyzer [" + request.analyzer() + "]");
}
} else if (request.tokenizer() != null) {
TokenizerFactory tokenizerFactory;
if (indexService == null) {
TokenizerFactoryFactory tokenizerFactoryFactory = indicesAnalysisService.tokenizerFactoryFactory(request.tokenizer());
if (tokenizerFactoryFactory == null) {
throw new ElasticsearchIllegalArgumentException("failed to find global tokenizer under [" + request.tokenizer() + "]");
}
tokenizerFactory = tokenizerFactoryFactory.create(request.tokenizer(), ImmutableSettings.Builder.EMPTY_SETTINGS);
} else {
tokenizerFactory = indexService.analysisService().tokenizer(request.tokenizer());
if (tokenizerFactory == null) {
throw new ElasticsearchIllegalArgumentException("failed to find tokenizer under [" + request.tokenizer() + "]");
}
}
TokenFilterFactory[] tokenFilterFactories = new TokenFilterFactory[0];
if (request.tokenFilters() != null && request.tokenFilters().length > 0) {
tokenFilterFactories = new TokenFilterFactory[request.tokenFilters().length];
for (int i = 0; i < request.tokenFilters().length; i++) {
String tokenFilterName = request.tokenFilters()[i];
if (indexService == null) {
TokenFilterFactoryFactory tokenFilterFactoryFactory = indicesAnalysisService.tokenFilterFactoryFactory(tokenFilterName);
if (tokenFilterFactoryFactory == null) {
throw new ElasticsearchIllegalArgumentException("failed to find global token filter under [" + request.tokenizer() + "]");
}
tokenFilterFactories[i] = tokenFilterFactoryFactory.create(tokenFilterName, ImmutableSettings.Builder.EMPTY_SETTINGS);
} else {
tokenFilterFactories[i] = indexService.analysisService().tokenFilter(tokenFilterName);
if (tokenFilterFactories[i] == null) {
throw new ElasticsearchIllegalArgumentException("failed to find token filter under [" + request.tokenizer() + "]");
}
}
if (tokenFilterFactories[i] == null) {
throw new ElasticsearchIllegalArgumentException("failed to find token filter under [" + request.tokenizer() + "]");
}
}
}
analyzer = new CustomAnalyzer(tokenizerFactory, new CharFilterFactory[0], tokenFilterFactories);
closeAnalyzer = true;
} else if (analyzer == null) {
if (indexService == null) {
analyzer = Lucene.STANDARD_ANALYZER;
} else {
analyzer = indexService.analysisService().defaultIndexAnalyzer();
}
}
if (analyzer == null) {
throw new ElasticsearchIllegalArgumentException("failed to find analyzer");
}
List<AnalyzeResponse.AnalyzeToken> tokens = Lists.newArrayList();
TokenStream stream = null;
try {
stream = analyzer.tokenStream(field, request.text());
stream.reset();
CharTermAttribute term = stream.addAttribute(CharTermAttribute.class);
PositionIncrementAttribute posIncr = stream.addAttribute(PositionIncrementAttribute.class);
OffsetAttribute offset = stream.addAttribute(OffsetAttribute.class);
TypeAttribute type = stream.addAttribute(TypeAttribute.class);
int position = 0;
while (stream.incrementToken()) {
int increment = posIncr.getPositionIncrement();
if (increment > 0) {
position = position + increment;
}
tokens.add(new AnalyzeResponse.AnalyzeToken(term.toString(), position, offset.startOffset(), offset.endOffset(), type.type()));
}
stream.end();
} catch (IOException e) {
throw new ElasticsearchException("failed to analyze", e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// ignore
}
}
if (closeAnalyzer) {
analyzer.close();
}
}
return new AnalyzeResponse(tokens);
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_admin_indices_analyze_TransportAnalyzeAction.java
|
877 |
kryos = new ThreadLocal<Kryo>() {
public Kryo initialValue() {
Kryo k = new Kryo();
k.setRegistrationRequired(registerRequired);
k.register(Class.class,new DefaultSerializers.ClassSerializer());
for (int i=0;i<defaultRegistrations.size();i++) {
Class clazz = defaultRegistrations.get(i);
k.register(clazz, KRYO_ID_OFFSET + i);
}
return k;
}
};
| 1no label
|
titan-core_src_main_java_com_thinkaurelius_titan_graphdb_database_serialize_kryo_KryoSerializer.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.