Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
325 | new Thread() {
public void run() {
map.forceUnlock("key1");
latch.countDown();
}
}.start(); | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java |
1,335 | public interface SolrIndexService {
/**
* Rebuilds the current index.
*
* @throws IOException
* @throws ServiceException
*/
public void rebuildIndex() throws ServiceException, IOException;
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_service_solr_SolrIndexService.java |
4,487 | RecoveryResponse recoveryResponse = transportService.submitRequest(request.sourceNode(), RecoverySource.Actions.START_RECOVERY, request, new FutureTransportResponseHandler<RecoveryResponse>() {
@Override
public RecoveryResponse newInstance() {
return new RecoveryResponse();
}
}).txGet(); | 1no label
| src_main_java_org_elasticsearch_indices_recovery_RecoveryTarget.java |
2,626 | abstract class BinaryClassDefinition implements ClassDefinition {
protected int factoryId;
protected int classId;
protected int version = -1;
private transient byte[] binary;
public BinaryClassDefinition() {
}
public final int getFactoryId() {
return factoryId;
}
public final int getClassId() {
return classId;
}
public final int getVersion() {
return version;
}
public final byte[] getBinary() {
return binary;
}
final void setBinary(byte[] binary) {
this.binary = binary;
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_nio_serialization_BinaryClassDefinition.java |
103 | CONTAINS_PREFIX {
@Override
public boolean evaluate(Object value, Object condition) {
this.preevaluate(value,condition);
if (value == null) return false;
return evaluateRaw(value.toString(),(String)condition);
}
@Override
public boolean evaluateRaw(String value, String prefix) {
for (String token : tokenize(value.toLowerCase())) {
if (PREFIX.evaluateRaw(token,prefix.toLowerCase())) return true;
}
return false;
}
@Override
public boolean isValidCondition(Object condition) {
return condition != null && condition instanceof String;
}
}, | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Text.java |
222 | private static class LimitedStoredFieldVisitor extends StoredFieldVisitor {
private final String fields[];
private final char valueSeparators[];
private final int maxLength;
private final StringBuilder builders[];
private int currentField = -1;
public LimitedStoredFieldVisitor(String fields[], char valueSeparators[], int maxLength) {
assert fields.length == valueSeparators.length;
this.fields = fields;
this.valueSeparators = valueSeparators;
this.maxLength = maxLength;
builders = new StringBuilder[fields.length];
for (int i = 0; i < builders.length; i++) {
builders[i] = new StringBuilder();
}
}
@Override
public void stringField(FieldInfo fieldInfo, String value) throws IOException {
assert currentField >= 0;
StringBuilder builder = builders[currentField];
if (builder.length() > 0 && builder.length() < maxLength) {
builder.append(valueSeparators[currentField]);
}
if (builder.length() + value.length() > maxLength) {
builder.append(value, 0, maxLength - builder.length());
} else {
builder.append(value);
}
}
@Override
public Status needsField(FieldInfo fieldInfo) throws IOException {
currentField = Arrays.binarySearch(fields, fieldInfo.name);
if (currentField < 0) {
return Status.NO;
} else if (builders[currentField].length() > maxLength) {
return fields.length == 1 ? Status.STOP : Status.NO;
}
return Status.YES;
}
String getValue(int i) {
return builders[i].toString();
}
void reset() {
currentField = -1;
for (int i = 0; i < fields.length; i++) {
builders[i].setLength(0);
}
}
} | 0true
| src_main_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighter.java |
37 | public class CompletionException extends RuntimeException {
private static final long serialVersionUID = 7830266012832686185L;
/**
* Constructs a {@code CompletionException} with no detail message.
* The cause is not initialized, and may subsequently be
* initialized by a call to {@link #initCause(Throwable) initCause}.
*/
protected CompletionException() { }
/**
* Constructs a {@code CompletionException} with the specified detail
* message. The cause is not initialized, and may subsequently be
* initialized by a call to {@link #initCause(Throwable) initCause}.
*
* @param message the detail message
*/
protected CompletionException(String message) {
super(message);
}
/**
* Constructs a {@code CompletionException} with the specified detail
* message and cause.
*
* @param message the detail message
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method)
*/
public CompletionException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a {@code CompletionException} with the specified cause.
* The detail message is set to {@code (cause == null ? null :
* cause.toString())} (which typically contains the class and
* detail message of {@code cause}).
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method)
*/
public CompletionException(Throwable cause) {
super(cause);
}
} | 0true
| src_main_java_jsr166e_CompletionException.java |
2,524 | static final MapFactory SIMPLE_MAP_FACTORY = new MapFactory() {
@Override
public Map<String, Object> newMap() {
return new HashMap<String, Object>();
}
}; | 0true
| src_main_java_org_elasticsearch_common_xcontent_support_AbstractXContentParser.java |
1,935 | public abstract class BindingImpl<T> implements Binding<T> {
private final Injector injector;
private final Key<T> key;
private final Object source;
private final Scoping scoping;
private final InternalFactory<? extends T> internalFactory;
public BindingImpl(Injector injector, Key<T> key, Object source,
InternalFactory<? extends T> internalFactory, Scoping scoping) {
this.injector = injector;
this.key = key;
this.source = source;
this.internalFactory = internalFactory;
this.scoping = scoping;
}
protected BindingImpl(Object source, Key<T> key, Scoping scoping) {
this.internalFactory = null;
this.injector = null;
this.source = source;
this.key = key;
this.scoping = scoping;
}
public Key<T> getKey() {
return key;
}
public Object getSource() {
return source;
}
private volatile Provider<T> provider;
public Provider<T> getProvider() {
if (provider == null) {
if (injector == null) {
throw new UnsupportedOperationException("getProvider() not supported for module bindings");
}
provider = injector.getProvider(key);
}
return provider;
}
public InternalFactory<? extends T> getInternalFactory() {
return internalFactory;
}
public Scoping getScoping() {
return scoping;
}
/**
* Is this a constant binding? This returns true for constant bindings as
* well as toInstance() bindings.
*/
public boolean isConstant() {
return this instanceof InstanceBinding;
}
public <V> V acceptVisitor(ElementVisitor<V> visitor) {
return visitor.visit(this);
}
public <V> V acceptScopingVisitor(BindingScopingVisitor<V> visitor) {
return scoping.acceptVisitor(visitor);
}
protected BindingImpl<T> withScoping(Scoping scoping) {
throw new AssertionError();
}
protected BindingImpl<T> withKey(Key<T> key) {
throw new AssertionError();
}
@Override
public String toString() {
return new ToStringBuilder(Binding.class)
.add("key", key)
.add("scope", scoping)
.add("source", source)
.toString();
}
public Injector getInjector() {
return injector;
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_internal_BindingImpl.java |
246 | public class NullBroadleafCurrency implements BroadleafCurrency {
private static final long serialVersionUID = 7926395625817119455L;
@Override
public String getCurrencyCode() {
return null;
}
@Override
public void setCurrencyCode(String code) {
// Do nothing
}
@Override
public String getFriendlyName() {
return null;
}
@Override
public void setFriendlyName(String friendlyName) {
// Do nothing
}
@Override
public boolean getDefaultFlag() {
return false;
}
@Override
public void setDefaultFlag(boolean defaultFlag) {
// Do nothing
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_currency_domain_NullBroadleafCurrency.java |
802 | public class TransportMultiPercolateAction extends TransportAction<MultiPercolateRequest, MultiPercolateResponse> {
private final ClusterService clusterService;
private final PercolatorService percolatorService;
private final TransportMultiGetAction multiGetAction;
private final TransportShardMultiPercolateAction shardMultiPercolateAction;
@Inject
public TransportMultiPercolateAction(Settings settings, ThreadPool threadPool, TransportShardMultiPercolateAction shardMultiPercolateAction,
ClusterService clusterService, TransportService transportService, PercolatorService percolatorService,
TransportMultiGetAction multiGetAction) {
super(settings, threadPool);
this.shardMultiPercolateAction = shardMultiPercolateAction;
this.clusterService = clusterService;
this.percolatorService = percolatorService;
this.multiGetAction = multiGetAction;
transportService.registerHandler(MultiPercolateAction.NAME, new TransportHandler());
}
@Override
protected void doExecute(final MultiPercolateRequest request, final ActionListener<MultiPercolateResponse> listener) {
final ClusterState clusterState = clusterService.state();
clusterState.blocks().globalBlockedRaiseException(ClusterBlockLevel.READ);
final List<Object> percolateRequests = new ArrayList<Object>(request.requests().size());
// Can have a mixture of percolate requests. (normal percolate requests & percolate existing doc),
// so we need to keep track for what percolate request we had a get request
final IntArrayList getRequestSlots = new IntArrayList();
List<GetRequest> existingDocsRequests = new ArrayList<GetRequest>();
for (int slot = 0; slot < request.requests().size(); slot++) {
PercolateRequest percolateRequest = request.requests().get(slot);
percolateRequest.startTime = System.currentTimeMillis();
percolateRequests.add(percolateRequest);
if (percolateRequest.getRequest() != null) {
existingDocsRequests.add(percolateRequest.getRequest());
getRequestSlots.add(slot);
}
}
if (!existingDocsRequests.isEmpty()) {
final MultiGetRequest multiGetRequest = new MultiGetRequest();
for (GetRequest getRequest : existingDocsRequests) {
multiGetRequest.add(
new MultiGetRequest.Item(getRequest.index(), getRequest.type(), getRequest.id())
.routing(getRequest.routing())
);
}
multiGetAction.execute(multiGetRequest, new ActionListener<MultiGetResponse>() {
@Override
public void onResponse(MultiGetResponse multiGetItemResponses) {
for (int i = 0; i < multiGetItemResponses.getResponses().length; i++) {
MultiGetItemResponse itemResponse = multiGetItemResponses.getResponses()[i];
int slot = getRequestSlots.get(i);
if (!itemResponse.isFailed()) {
GetResponse getResponse = itemResponse.getResponse();
if (getResponse.isExists()) {
PercolateRequest originalRequest = (PercolateRequest) percolateRequests.get(slot);
percolateRequests.set(slot, new PercolateRequest(originalRequest, getResponse.getSourceAsBytesRef()));
} else {
logger.trace("mpercolate existing doc, item[{}] doesn't exist", slot);
percolateRequests.set(slot, new DocumentMissingException(null, getResponse.getType(), getResponse.getId()));
}
} else {
logger.trace("mpercolate existing doc, item[{}] failure {}", slot, itemResponse.getFailure());
percolateRequests.set(slot, itemResponse.getFailure());
}
}
new ASyncAction(percolateRequests, listener, clusterState).run();
}
@Override
public void onFailure(Throwable e) {
listener.onFailure(e);
}
});
} else {
new ASyncAction(percolateRequests, listener, clusterState).run();
}
}
private class ASyncAction {
final ActionListener<MultiPercolateResponse> finalListener;
final Map<ShardId, TransportShardMultiPercolateAction.Request> requestsByShard;
final List<Object> percolateRequests;
final Map<ShardId, IntArrayList> shardToSlots;
final AtomicInteger expectedOperations;
final AtomicArray<Object> reducedResponses;
final AtomicReferenceArray<AtomicInteger> expectedOperationsPerItem;
final AtomicReferenceArray<AtomicReferenceArray> responsesByItemAndShard;
ASyncAction(List<Object> percolateRequests, ActionListener<MultiPercolateResponse> finalListener, ClusterState clusterState) {
this.finalListener = finalListener;
this.percolateRequests = percolateRequests;
responsesByItemAndShard = new AtomicReferenceArray<AtomicReferenceArray>(percolateRequests.size());
expectedOperationsPerItem = new AtomicReferenceArray<AtomicInteger>(percolateRequests.size());
reducedResponses = new AtomicArray<Object>(percolateRequests.size());
// Resolving concrete indices and routing and grouping the requests by shard
requestsByShard = new HashMap<ShardId, TransportShardMultiPercolateAction.Request>();
// Keep track what slots belong to what shard, in case a request to a shard fails on all copies
shardToSlots = new HashMap<ShardId, IntArrayList>();
int expectedResults = 0;
for (int slot = 0; slot < percolateRequests.size(); slot++) {
Object element = percolateRequests.get(slot);
assert element != null;
if (element instanceof PercolateRequest) {
PercolateRequest percolateRequest = (PercolateRequest) element;
String[] concreteIndices;
try {
concreteIndices = clusterState.metaData().concreteIndices(percolateRequest.indices(), percolateRequest.indicesOptions());
} catch (IndexMissingException e) {
reducedResponses.set(slot, e);
responsesByItemAndShard.set(slot, new AtomicReferenceArray(0));
expectedOperationsPerItem.set(slot, new AtomicInteger(0));
continue;
}
Map<String, Set<String>> routing = clusterState.metaData().resolveSearchRouting(percolateRequest.routing(), percolateRequest.indices());
// TODO: I only need shardIds, ShardIterator(ShardRouting) is only needed in TransportShardMultiPercolateAction
GroupShardsIterator shards = clusterService.operationRouting().searchShards(
clusterState, percolateRequest.indices(), concreteIndices, routing, percolateRequest.preference()
);
if (shards.size() == 0) {
reducedResponses.set(slot, new UnavailableShardsException(null, "No shards available"));
responsesByItemAndShard.set(slot, new AtomicReferenceArray(0));
expectedOperationsPerItem.set(slot, new AtomicInteger(0));
continue;
}
responsesByItemAndShard.set(slot, new AtomicReferenceArray(shards.size()));
expectedOperationsPerItem.set(slot, new AtomicInteger(shards.size()));
for (ShardIterator shard : shards) {
ShardId shardId = shard.shardId();
TransportShardMultiPercolateAction.Request requests = requestsByShard.get(shardId);
if (requests == null) {
requestsByShard.put(shardId, requests = new TransportShardMultiPercolateAction.Request(shard.shardId().getIndex(), shardId.id(), percolateRequest.preference()));
}
logger.trace("Adding shard[{}] percolate request for item[{}]", shardId, slot);
requests.add(new TransportShardMultiPercolateAction.Request.Item(slot, new PercolateShardRequest(shardId, percolateRequest)));
IntArrayList items = shardToSlots.get(shardId);
if (items == null) {
shardToSlots.put(shardId, items = new IntArrayList());
}
items.add(slot);
}
expectedResults++;
} else if (element instanceof Throwable || element instanceof MultiGetResponse.Failure) {
logger.trace("item[{}] won't be executed, reason: {}", slot, element);
reducedResponses.set(slot, element);
responsesByItemAndShard.set(slot, new AtomicReferenceArray(0));
expectedOperationsPerItem.set(slot, new AtomicInteger(0));
}
}
expectedOperations = new AtomicInteger(expectedResults);
}
void run() {
if (expectedOperations.get() == 0) {
finish();
return;
}
logger.trace("mpercolate executing for shards {}", requestsByShard.keySet());
for (Map.Entry<ShardId, TransportShardMultiPercolateAction.Request> entry : requestsByShard.entrySet()) {
final ShardId shardId = entry.getKey();
TransportShardMultiPercolateAction.Request shardRequest = entry.getValue();
shardMultiPercolateAction.execute(shardRequest, new ActionListener<TransportShardMultiPercolateAction.Response>() {
@Override
public void onResponse(TransportShardMultiPercolateAction.Response response) {
onShardResponse(shardId, response);
}
@Override
public void onFailure(Throwable e) {
onShardFailure(shardId, e);
}
});
}
}
@SuppressWarnings("unchecked")
void onShardResponse(ShardId shardId, TransportShardMultiPercolateAction.Response response) {
logger.debug("{} Percolate shard response", shardId);
try {
for (TransportShardMultiPercolateAction.Response.Item item : response.items()) {
AtomicReferenceArray shardResults = responsesByItemAndShard.get(item.slot());
if (shardResults == null) {
assert false : "shardResults can't be null";
continue;
}
if (item.failed()) {
shardResults.set(shardId.id(), new BroadcastShardOperationFailedException(shardId, item.error().string()));
} else {
shardResults.set(shardId.id(), item.response());
}
assert expectedOperationsPerItem.get(item.slot()).get() >= 1 : "slot[" + item.slot() + "] can't be lower than one";
if (expectedOperationsPerItem.get(item.slot()).decrementAndGet() == 0) {
// Failure won't bubble up, since we fail the whole request now via the catch clause below,
// so expectedOperationsPerItem will not be decremented twice.
reduce(item.slot());
}
}
} catch (Throwable e) {
logger.error("{} Percolate original reduce error", e, shardId);
finalListener.onFailure(e);
}
}
@SuppressWarnings("unchecked")
void onShardFailure(ShardId shardId, Throwable e) {
logger.debug("{} Shard multi percolate failure", e, shardId);
try {
IntArrayList slots = shardToSlots.get(shardId);
for (int i = 0; i < slots.size(); i++) {
int slot = slots.get(i);
AtomicReferenceArray shardResults = responsesByItemAndShard.get(slot);
if (shardResults == null) {
continue;
}
shardResults.set(shardId.id(), new BroadcastShardOperationFailedException(shardId, e));
assert expectedOperationsPerItem.get(slot).get() >= 1 : "slot[" + slot + "] can't be lower than one. Caused by: " + e.getMessage();
if (expectedOperationsPerItem.get(slot).decrementAndGet() == 0) {
reduce(slot);
}
}
} catch (Throwable t) {
logger.error("{} Percolate original reduce error, original error {}", t, shardId, e);
finalListener.onFailure(t);
}
}
void reduce(int slot) {
AtomicReferenceArray shardResponses = responsesByItemAndShard.get(slot);
PercolateResponse reducedResponse = TransportPercolateAction.reduce((PercolateRequest) percolateRequests.get(slot), shardResponses, percolatorService);
reducedResponses.set(slot, reducedResponse);
assert expectedOperations.get() >= 1 : "slot[" + slot + "] expected options should be >= 1 but is " + expectedOperations.get();
if (expectedOperations.decrementAndGet() == 0) {
finish();
}
}
void finish() {
MultiPercolateResponse.Item[] finalResponse = new MultiPercolateResponse.Item[reducedResponses.length()];
for (int slot = 0; slot < reducedResponses.length(); slot++) {
Object element = reducedResponses.get(slot);
assert element != null : "Element[" + slot + "] shouldn't be null";
if (element instanceof PercolateResponse) {
finalResponse[slot] = new MultiPercolateResponse.Item((PercolateResponse) element);
} else if (element instanceof Throwable) {
finalResponse[slot] = new MultiPercolateResponse.Item(ExceptionsHelper.detailedMessage((Throwable) element));
} else if (element instanceof MultiGetResponse.Failure) {
finalResponse[slot] = new MultiPercolateResponse.Item(((MultiGetResponse.Failure)element).getMessage());
}
}
finalListener.onResponse(new MultiPercolateResponse(finalResponse));
}
}
class TransportHandler extends BaseTransportRequestHandler<MultiPercolateRequest> {
@Override
public MultiPercolateRequest newInstance() {
return new MultiPercolateRequest();
}
@Override
public void messageReceived(final MultiPercolateRequest request, final TransportChannel channel) throws Exception {
// no need to use threaded listener, since we just send a response
request.listenerThreaded(false);
execute(request, new ActionListener<MultiPercolateResponse>() {
@Override
public void onResponse(MultiPercolateResponse response) {
try {
channel.sendResponse(response);
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(e);
} catch (Exception e1) {
logger.warn("Failed to send error response for action [mpercolate] and request [" + request + "]", e1);
}
}
});
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}
} | 0true
| src_main_java_org_elasticsearch_action_percolate_TransportMultiPercolateAction.java |
200 | private static class KnownTxIdCollector implements LogEntryCollector
{
private final Map<Integer,List<LogEntry>> transactions = new HashMap<Integer,List<LogEntry>>();
private final long startTxId;
private int identifier;
private final Map<Long, List<LogEntry>> futureQueue = new HashMap<Long, List<LogEntry>>();
private long nextExpectedTxId;
private LogEntry.Start lastStartEntry;
KnownTxIdCollector( long startTxId )
{
this.startTxId = startTxId;
this.nextExpectedTxId = startTxId;
}
@Override
public int getIdentifier()
{
return identifier;
}
@Override
public boolean hasInFutureQueue()
{
return futureQueue.containsKey( nextExpectedTxId );
}
@Override
public LogEntry.Start getLastStartEntry()
{
return lastStartEntry;
}
@Override
public LogEntry collect( LogEntry entry, LogBuffer target ) throws IOException
{
if ( futureQueue.containsKey( nextExpectedTxId ) )
{
long txId = nextExpectedTxId++;
List<LogEntry> list = futureQueue.remove( txId );
lastStartEntry = (LogEntry.Start)list.get( 0 );
writeToBuffer( list, target );
return commitEntryOf( txId, list );
}
if ( entry instanceof LogEntry.Start )
{
List<LogEntry> list = new LinkedList<LogEntry>();
list.add( entry );
transactions.put( entry.getIdentifier(), list );
}
else if ( entry instanceof LogEntry.Commit )
{
long commitTxId = ((LogEntry.Commit) entry).getTxId();
if ( commitTxId < startTxId ) return null;
identifier = entry.getIdentifier();
List<LogEntry> entries = transactions.get( identifier );
if ( entries == null ) return null;
entries.add( entry );
if ( nextExpectedTxId != startTxId && commitTxId < nextExpectedTxId )
{ // Have returned some previous tx
// If we encounter an already extracted tx in the middle of the stream
// then just ignore it. This can happen when we do log rotation,
// where records are copied over from the active log to the new.
return null;
}
if ( commitTxId != nextExpectedTxId )
{ // There seems to be a hole in the tx stream, or out-of-ordering
futureQueue.put( commitTxId, entries );
return null;
}
writeToBuffer( entries, target );
nextExpectedTxId = commitTxId+1;
lastStartEntry = (LogEntry.Start)entries.get( 0 );
return entry;
}
else if ( entry instanceof LogEntry.Command || entry instanceof LogEntry.Prepare )
{
List<LogEntry> list = transactions.get( entry.getIdentifier() );
// Since we can start reading at any position in the log it might be the case
// that we come across a record which corresponding start record resides
// before the position we started reading from. If that should be the case
// then skip it since it isn't an important record for us here.
if ( list != null )
{
list.add( entry );
}
}
else if ( entry instanceof LogEntry.Done )
{
transactions.remove( entry.getIdentifier() );
}
else
{
throw new RuntimeException( "Unknown entry: " + entry );
}
return null;
}
private LogEntry commitEntryOf( long txId, List<LogEntry> list ) throws IOException
{
for ( LogEntry entry : list )
{
if ( entry instanceof LogEntry.Commit ) return entry;
}
throw new NoSuchTransactionException( txId, "No commit entry in " + list );
}
private void writeToBuffer( List<LogEntry> entries, LogBuffer target ) throws IOException
{
if ( target != null )
{
for ( LogEntry entry : entries )
{
LogIoUtils.writeLogEntry( entry, target );
}
}
}
} | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogExtractor.java |
219 | PriorityQueue<Passage> passageQueue = new PriorityQueue<Passage>(n, new Comparator<Passage>() {
@Override
public int compare(Passage left, Passage right) {
if (left.score < right.score) {
return -1;
} else if (left.score > right.score) {
return 1;
} else {
return left.startOffset - right.startOffset;
}
}
}); | 0true
| src_main_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighter.java |
1,401 | public interface OMVRBTreeProvider<K, V> {
public void setKeySize(int keySize);
public int getKeySize();
public int getSize();
public int getDefaultPageSize();
public ORID getRoot();
public boolean setRoot(ORID iRid);
public boolean setSize(int iSize);
/** Give a chance to update config parameters (defaultSizePage, ...) */
public boolean updateConfig();
public boolean isDirty();
public boolean setDirty();
public OMVRBTreeEntryDataProvider<K, V> createEntry();
public OMVRBTreeEntryDataProvider<K, V> getEntry(ORID iRid);
public void load();
public void save();
public void delete();
public int getClusterId();
public String getClusterName();
public OMVRBTreeProvider<K, V> copy();
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_type_tree_provider_OMVRBTreeProvider.java |
807 | public interface OfferAudit extends Serializable {
/**
* System generated unique id for this audit record.
* @return
*/
public Long getId();
/**
* Sets the id.
* @param id
*/
public void setId(Long id);
/**
* The associated offer id.
* @return
*/
public Long getOfferId();
/**
* Sets the associated offer id.
* @param offerId
*/
public void setOfferId(Long offerId);
/**
* <p>The offer code that was used to retrieve the offer. This will be null if the offer was automatically applied
* and not obtained by an {@link OfferCode}.</p>
*
* <p>For any 3.0 version starting with 3.0.6-GA and above, this has the potential to throw an {@link UnsupportedOperationException}.
* This column did not exist until 3.0.6-GA. Rather than prevent a drop-in release of 3.0.6-GA, by making this database
* modification, {@link OfferAuditWeaveImpl} should instead be weaved into this class to obtain the column definition
* along with correct implementation of this method.</p>
* @see {@link OfferAuditWeaveImpl}
*/
public Long getOfferCodeId() throws UnsupportedOperationException;
/**
* <p>Sets the offer code that was used to retrieve the offer. This should be null if the offer was automatically applied
* and not obtained by an {@link OfferCode}.</p>
*
* <p>For any 3.0 version starting with 3.0.6-GA and above, this has the potential to throw an {@link UnsupportedOperationException}.
* This column did not exist until 3.0.6-GA. Rather than prevent a drop-in release of 3.0.6-GA, by making this database
* modification, {@link OfferAuditWeaveImpl} should instead be weaved into this class to obtain the column definition
* along with correct implementation of this method.</p>
* @see {@link OfferAuditWeaveImpl}
*/
public void setOfferCodeId(Long offerCodeId) throws UnsupportedOperationException;
/**
* The associated order id.
* @return
*/
public Long getOrderId();
/**
* Sets the associated order id.
* @param orderId
*/
public void setOrderId(Long orderId);
/**
* The id of the associated customer.
* @return
*/
public Long getCustomerId();
/**
* Sets the customer id.
* @param customerId
*/
public void setCustomerId(Long customerId);
/**
* The date the offer was applied to the order.
* @return
*/
public Date getRedeemedDate();
/**
* Sets the offer redeemed date.
* @param redeemedDate
*/
public void setRedeemedDate(Date redeemedDate);
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_OfferAudit.java |
1,846 | T t = callInContext(new ContextualCallable<T>() {
public T call(InternalContext context) throws ErrorsException {
context.setDependency(dependency);
try {
return factory.get(errors, context, dependency);
} finally {
context.setDependency(null);
}
}
}); | 0true
| src_main_java_org_elasticsearch_common_inject_InjectorImpl.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,496 | enum NumberType {
INT, LONG, FLOAT, DOUBLE
} | 0true
| src_main_java_org_elasticsearch_common_xcontent_XContentParser.java |
1,578 | public abstract class AbstractLogger implements ILogger {
@Override
public void finest(String message) {
log(Level.FINEST, message);
}
@Override
public void finest(String message, Throwable thrown) {
log(Level.FINEST, message, thrown);
}
@Override
public void finest(Throwable thrown) {
log(Level.FINEST, thrown.getMessage(), thrown);
}
@Override
public boolean isFinestEnabled() {
return isLoggable(Level.FINEST);
}
@Override
public void info(String message) {
log(Level.INFO, message);
}
@Override
public void severe(String message) {
log(Level.SEVERE, message);
}
@Override
public void severe(Throwable thrown) {
log(Level.SEVERE, thrown.getMessage(), thrown);
}
@Override
public void severe(String message, Throwable thrown) {
log(Level.SEVERE, message, thrown);
}
@Override
public void warning(String message) {
log(Level.WARNING, message);
}
@Override
public void warning(Throwable thrown) {
log(Level.WARNING, thrown.getMessage(), thrown);
}
@Override
public void warning(String message, Throwable thrown) {
log(Level.WARNING, message, thrown);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_logging_AbstractLogger.java |
554 | public class OImmutableRecordId extends ORecordId {
private static final long serialVersionUID = 1L;
public OImmutableRecordId(final int iClusterId, final OClusterPosition iClusterPosition) {
super(iClusterId, iClusterPosition);
}
public OImmutableRecordId(final ORecordId iRID) {
super(iRID);
}
@Override
public void copyFrom(final ORID iSource) {
throw new UnsupportedOperationException("copyFrom");
}
@Override
public ORecordId fromStream(byte[] iBuffer) {
throw new UnsupportedOperationException("fromStream");
}
@Override
public ORecordId fromStream(OMemoryStream iStream) {
throw new UnsupportedOperationException("fromStream");
}
@Override
public ORecordId fromStream(InputStream iStream) throws IOException {
throw new UnsupportedOperationException("fromStream");
}
@Override
public void fromString(String iRecordId) {
throw new UnsupportedOperationException("fromString");
}
@Override
public void reset() {
throw new UnsupportedOperationException("reset");
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_id_OImmutableRecordId.java |
373 | public class AspectUtil {
public static Object exposeRootBean(Object managedBean) {
try {
if (AopUtils.isAopProxy(managedBean) && managedBean instanceof Advised) {
Advised advised = (Advised) managedBean;
managedBean = advised.getTargetSource().getTarget();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return managedBean;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_jmx_AspectUtil.java |
1,237 | public interface IndicesAdminClient {
<Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> ActionFuture<Response> execute(final IndicesAction<Request, Response, RequestBuilder> action, final Request request);
<Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void execute(final IndicesAction<Request, Response, RequestBuilder> action, final Request request, ActionListener<Response> listener);
<Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> RequestBuilder prepareExecute(final IndicesAction<Request, Response, RequestBuilder> action);
/**
* Indices Exists.
*
* @param request The indices exists request
* @return The result future
* @see Requests#indicesExistsRequest(String...)
*/
ActionFuture<IndicesExistsResponse> exists(IndicesExistsRequest request);
/**
* The status of one or more indices.
*
* @param request The indices status request
* @param listener A listener to be notified with a result
* @see Requests#indicesExistsRequest(String...)
*/
void exists(IndicesExistsRequest request, ActionListener<IndicesExistsResponse> listener);
/**
* Indices exists.
*/
IndicesExistsRequestBuilder prepareExists(String... indices);
/**
* Types Exists.
*
* @param request The types exists request
* @return The result future
*/
ActionFuture<TypesExistsResponse> typesExists(TypesExistsRequest request);
/**
* Types exists
*
* @param request The types exists
* @param listener A listener to be notified with a result
*/
void typesExists(TypesExistsRequest request, ActionListener<TypesExistsResponse> listener);
/**
* Indices exists.
*/
TypesExistsRequestBuilder prepareTypesExists(String... index);
/**
* Indices stats.
*/
ActionFuture<IndicesStatsResponse> stats(IndicesStatsRequest request);
/**
* Indices stats.
*/
void stats(IndicesStatsRequest request, ActionListener<IndicesStatsResponse> listener);
/**
* Indices stats.
*/
IndicesStatsRequestBuilder prepareStats(String... indices);
/**
* The status of one or more indices.
*
* @param request The indices status request
* @return The result future
* @see Requests#indicesStatusRequest(String...)
*/
ActionFuture<IndicesStatusResponse> status(IndicesStatusRequest request);
/**
* The status of one or more indices.
*
* @param request The indices status request
* @param listener A listener to be notified with a result
* @see Requests#indicesStatusRequest(String...)
*/
void status(IndicesStatusRequest request, ActionListener<IndicesStatusResponse> listener);
/**
* The status of one or more indices.
*/
IndicesStatusRequestBuilder prepareStatus(String... indices);
/**
* The segments of one or more indices.
*
* @param request The indices segments request
* @return The result future
* @see Requests#indicesSegmentsRequest(String...)
*/
ActionFuture<IndicesSegmentResponse> segments(IndicesSegmentsRequest request);
/**
* The segments of one or more indices.
*
* @param request The indices segments request
* @param listener A listener to be notified with a result
* @see Requests#indicesSegmentsRequest(String...)
*/
void segments(IndicesSegmentsRequest request, ActionListener<IndicesSegmentResponse> listener);
/**
* The segments of one or more indices.
*/
IndicesSegmentsRequestBuilder prepareSegments(String... indices);
/**
* Creates an index using an explicit request allowing to specify the settings of the index.
*
* @param request The create index request
* @return The result future
* @see org.elasticsearch.client.Requests#createIndexRequest(String)
*/
ActionFuture<CreateIndexResponse> create(CreateIndexRequest request);
/**
* Creates an index using an explicit request allowing to specify the settings of the index.
*
* @param request The create index request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#createIndexRequest(String)
*/
void create(CreateIndexRequest request, ActionListener<CreateIndexResponse> listener);
/**
* Creates an index using an explicit request allowing to specify the settings of the index.
*
* @param index The index name to create
*/
CreateIndexRequestBuilder prepareCreate(String index);
/**
* Deletes an index based on the index name.
*
* @param request The delete index request
* @return The result future
* @see org.elasticsearch.client.Requests#deleteIndexRequest(String)
*/
ActionFuture<DeleteIndexResponse> delete(DeleteIndexRequest request);
/**
* Deletes an index based on the index name.
*
* @param request The delete index request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#deleteIndexRequest(String)
*/
void delete(DeleteIndexRequest request, ActionListener<DeleteIndexResponse> listener);
/**
* Deletes an index based on the index name.
*
* @param indices The indices to delete. Empty array to delete all indices.
*/
DeleteIndexRequestBuilder prepareDelete(String... indices);
/**
* Closes an index based on the index name.
*
* @param request The close index request
* @return The result future
* @see org.elasticsearch.client.Requests#closeIndexRequest(String)
*/
ActionFuture<CloseIndexResponse> close(CloseIndexRequest request);
/**
* Closes an index based on the index name.
*
* @param request The close index request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#closeIndexRequest(String)
*/
void close(CloseIndexRequest request, ActionListener<CloseIndexResponse> listener);
/**
* Closes one or more indices based on their index name.
*
* @param indices The name of the indices to close
*/
CloseIndexRequestBuilder prepareClose(String... indices);
/**
* Open an index based on the index name.
*
* @param request The close index request
* @return The result future
* @see org.elasticsearch.client.Requests#openIndexRequest(String)
*/
ActionFuture<OpenIndexResponse> open(OpenIndexRequest request);
/**
* Open an index based on the index name.
*
* @param request The close index request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#openIndexRequest(String)
*/
void open(OpenIndexRequest request, ActionListener<OpenIndexResponse> listener);
/**
* Opens one or more indices based on their index name.
*
* @param indices The name of the indices to close
*/
OpenIndexRequestBuilder prepareOpen(String... indices);
/**
* Explicitly refresh one or more indices (making the content indexed since the last refresh searchable).
*
* @param request The refresh request
* @return The result future
* @see org.elasticsearch.client.Requests#refreshRequest(String...)
*/
ActionFuture<RefreshResponse> refresh(RefreshRequest request);
/**
* Explicitly refresh one or more indices (making the content indexed since the last refresh searchable).
*
* @param request The refresh request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#refreshRequest(String...)
*/
void refresh(RefreshRequest request, ActionListener<RefreshResponse> listener);
/**
* Explicitly refresh one or more indices (making the content indexed since the last refresh searchable).
*/
RefreshRequestBuilder prepareRefresh(String... indices);
/**
* Explicitly flush one or more indices (releasing memory from the node).
*
* @param request The flush request
* @return A result future
* @see org.elasticsearch.client.Requests#flushRequest(String...)
*/
ActionFuture<FlushResponse> flush(FlushRequest request);
/**
* Explicitly flush one or more indices (releasing memory from the node).
*
* @param request The flush request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#flushRequest(String...)
*/
void flush(FlushRequest request, ActionListener<FlushResponse> listener);
/**
* Explicitly flush one or more indices (releasing memory from the node).
*/
FlushRequestBuilder prepareFlush(String... indices);
/**
* Explicitly optimize one or more indices into a the number of segments.
*
* @param request The optimize request
* @return A result future
* @see org.elasticsearch.client.Requests#optimizeRequest(String...)
*/
ActionFuture<OptimizeResponse> optimize(OptimizeRequest request);
/**
* Explicitly optimize one or more indices into a the number of segments.
*
* @param request The optimize request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#optimizeRequest(String...)
*/
void optimize(OptimizeRequest request, ActionListener<OptimizeResponse> listener);
/**
* Explicitly optimize one or more indices into a the number of segments.
*/
OptimizeRequestBuilder prepareOptimize(String... indices);
/**
* Get the complete mappings of one or more types
*/
void getMappings(GetMappingsRequest request, ActionListener<GetMappingsResponse> listener);
/**
* Get the complete mappings of one or more types
*/
ActionFuture<GetMappingsResponse> getMappings(GetMappingsRequest request);
/**
* Get the complete mappings of one or more types
*/
GetMappingsRequestBuilder prepareGetMappings(String... indices);
/**
* Get the mappings of specific fields
*/
void getFieldMappings(GetFieldMappingsRequest request, ActionListener<GetFieldMappingsResponse> listener);
/**
* Get the mappings of specific fields
*/
GetFieldMappingsRequestBuilder prepareGetFieldMappings(String... indices);
/**
* Get the mappings of specific fields
*/
ActionFuture<GetFieldMappingsResponse> getFieldMappings(GetFieldMappingsRequest request);
/**
* Add mapping definition for a type into one or more indices.
*
* @param request The create mapping request
* @return A result future
* @see org.elasticsearch.client.Requests#putMappingRequest(String...)
*/
ActionFuture<PutMappingResponse> putMapping(PutMappingRequest request);
/**
* Add mapping definition for a type into one or more indices.
*
* @param request The create mapping request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#putMappingRequest(String...)
*/
void putMapping(PutMappingRequest request, ActionListener<PutMappingResponse> listener);
/**
* Add mapping definition for a type into one or more indices.
*/
PutMappingRequestBuilder preparePutMapping(String... indices);
/**
* Deletes mapping (and all its data) from one or more indices.
*
* @param request The delete mapping request
* @return A result future
* @see org.elasticsearch.client.Requests#deleteMappingRequest(String...)
*/
ActionFuture<DeleteMappingResponse> deleteMapping(DeleteMappingRequest request);
/**
* Deletes mapping definition for a type into one or more indices.
*
* @param request The delete mapping request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#deleteMappingRequest(String...)
*/
void deleteMapping(DeleteMappingRequest request, ActionListener<DeleteMappingResponse> listener);
/**
* Deletes mapping definition for a type into one or more indices.
*/
DeleteMappingRequestBuilder prepareDeleteMapping(String... indices);
/**
* Explicitly perform gateway snapshot for one or more indices.
*
* @param request The gateway snapshot request
* @return The result future
* @see org.elasticsearch.client.Requests#gatewaySnapshotRequest(String...)
* @deprecated Use snapshot/restore API instead
*/
@Deprecated
ActionFuture<GatewaySnapshotResponse> gatewaySnapshot(GatewaySnapshotRequest request);
/**
* Explicitly perform gateway snapshot for one or more indices.
*
* @param request The gateway snapshot request
* @param listener A listener to be notified with a result
* @see org.elasticsearch.client.Requests#gatewaySnapshotRequest(String...)
* @deprecated Use snapshot/restore API instead
*/
@Deprecated
void gatewaySnapshot(GatewaySnapshotRequest request, ActionListener<GatewaySnapshotResponse> listener);
/**
* Explicitly perform gateway snapshot for one or more indices.
*
* @deprecated Use snapshot/restore API instead
*/
@Deprecated
GatewaySnapshotRequestBuilder prepareGatewaySnapshot(String... indices);
/**
* Allows to add/remove aliases from indices.
*
* @param request The index aliases request
* @return The result future
* @see Requests#indexAliasesRequest()
*/
ActionFuture<IndicesAliasesResponse> aliases(IndicesAliasesRequest request);
/**
* Allows to add/remove aliases from indices.
*
* @param request The index aliases request
* @param listener A listener to be notified with a result
* @see Requests#indexAliasesRequest()
*/
void aliases(IndicesAliasesRequest request, ActionListener<IndicesAliasesResponse> listener);
/**
* Allows to add/remove aliases from indices.
*/
IndicesAliasesRequestBuilder prepareAliases();
/**
* Get specific index aliases that exists in particular indices and / or by name.
*
* @param request The result future
*/
ActionFuture<GetAliasesResponse> getAliases(GetAliasesRequest request);
/**
* Get specific index aliases that exists in particular indices and / or by name.
*
* @param request The index aliases request
* @param listener A listener to be notified with a result
*/
void getAliases(GetAliasesRequest request, ActionListener<GetAliasesResponse> listener);
/**
* Get specific index aliases that exists in particular indices and / or by name.
*/
GetAliasesRequestBuilder prepareGetAliases(String... aliases);
/**
* Allows to check to existence of aliases from indices.
*/
AliasesExistRequestBuilder prepareAliasesExist(String... aliases);
/**
* Check to existence of index aliases.
*
* @param request The result future
*/
ActionFuture<AliasesExistResponse> aliasesExist(GetAliasesRequest request);
/**
* Check the existence of specified index aliases.
*
* @param request The index aliases request
* @param listener A listener to be notified with a result
*/
void aliasesExist(GetAliasesRequest request, ActionListener<AliasesExistResponse> listener);
/**
* Clear indices cache.
*
* @param request The clear indices cache request
* @return The result future
* @see Requests#clearIndicesCacheRequest(String...)
*/
ActionFuture<ClearIndicesCacheResponse> clearCache(ClearIndicesCacheRequest request);
/**
* Clear indices cache.
*
* @param request The clear indices cache request
* @param listener A listener to be notified with a result
* @see Requests#clearIndicesCacheRequest(String...)
*/
void clearCache(ClearIndicesCacheRequest request, ActionListener<ClearIndicesCacheResponse> listener);
/**
* Clear indices cache.
*/
ClearIndicesCacheRequestBuilder prepareClearCache(String... indices);
/**
* Updates settings of one or more indices.
*
* @param request the update settings request
* @return The result future
*/
ActionFuture<UpdateSettingsResponse> updateSettings(UpdateSettingsRequest request);
/**
* Updates settings of one or more indices.
*
* @param request the update settings request
* @param listener A listener to be notified with the response
*/
void updateSettings(UpdateSettingsRequest request, ActionListener<UpdateSettingsResponse> listener);
/**
* Update indices settings.
*/
UpdateSettingsRequestBuilder prepareUpdateSettings(String... indices);
/**
* Analyze text under the provided index.
*/
ActionFuture<AnalyzeResponse> analyze(AnalyzeRequest request);
/**
* Analyze text under the provided index.
*/
void analyze(AnalyzeRequest request, ActionListener<AnalyzeResponse> listener);
/**
* Analyze text under the provided index.
*
* @param index The index name
* @param text The text to analyze
*/
AnalyzeRequestBuilder prepareAnalyze(@Nullable String index, String text);
/**
* Analyze text.
*
* @param text The text to analyze
*/
AnalyzeRequestBuilder prepareAnalyze(String text);
/**
* Puts an index template.
*/
ActionFuture<PutIndexTemplateResponse> putTemplate(PutIndexTemplateRequest request);
/**
* Puts an index template.
*/
void putTemplate(PutIndexTemplateRequest request, ActionListener<PutIndexTemplateResponse> listener);
/**
* Puts an index template.
*
* @param name The name of the template.
*/
PutIndexTemplateRequestBuilder preparePutTemplate(String name);
/**
* Deletes index template.
*/
ActionFuture<DeleteIndexTemplateResponse> deleteTemplate(DeleteIndexTemplateRequest request);
/**
* Deletes an index template.
*/
void deleteTemplate(DeleteIndexTemplateRequest request, ActionListener<DeleteIndexTemplateResponse> listener);
/**
* Deletes an index template.
*
* @param name The name of the template.
*/
DeleteIndexTemplateRequestBuilder prepareDeleteTemplate(String name);
/**
* Gets index template.
*/
ActionFuture<GetIndexTemplatesResponse> getTemplates(GetIndexTemplatesRequest request);
/**
* Gets an index template.
*/
void getTemplates(GetIndexTemplatesRequest request, ActionListener<GetIndexTemplatesResponse> listener);
/**
* Gets an index template (optional).
*/
GetIndexTemplatesRequestBuilder prepareGetTemplates(String... name);
/**
* Validate a query for correctness.
*
* @param request The count request
* @return The result future
* @see Requests#countRequest(String...)
*/
ActionFuture<ValidateQueryResponse> validateQuery(ValidateQueryRequest request);
/**
* Validate a query for correctness.
*
* @param request The count request
* @param listener A listener to be notified of the result
* @see Requests#countRequest(String...)
*/
void validateQuery(ValidateQueryRequest request, ActionListener<ValidateQueryResponse> listener);
/**
* Validate a query for correctness.
*/
ValidateQueryRequestBuilder prepareValidateQuery(String... indices);
/**
* Puts an index search warmer to be applies when applicable.
*/
ActionFuture<PutWarmerResponse> putWarmer(PutWarmerRequest request);
/**
* Puts an index search warmer to be applies when applicable.
*/
void putWarmer(PutWarmerRequest request, ActionListener<PutWarmerResponse> listener);
/**
* Puts an index search warmer to be applies when applicable.
*/
PutWarmerRequestBuilder preparePutWarmer(String name);
/**
* Deletes an index warmer.
*/
ActionFuture<DeleteWarmerResponse> deleteWarmer(DeleteWarmerRequest request);
/**
* Deletes an index warmer.
*/
void deleteWarmer(DeleteWarmerRequest request, ActionListener<DeleteWarmerResponse> listener);
/**
* Deletes an index warmer.
*/
DeleteWarmerRequestBuilder prepareDeleteWarmer();
void getWarmers(GetWarmersRequest request, ActionListener<GetWarmersResponse> listener);
ActionFuture<GetWarmersResponse> getWarmers(GetWarmersRequest request);
GetWarmersRequestBuilder prepareGetWarmers(String... indices);
void getSettings(GetSettingsRequest request, ActionListener<GetSettingsResponse> listener);
ActionFuture<GetSettingsResponse> getSettings(GetSettingsRequest request);
GetSettingsRequestBuilder prepareGetSettings(String... indices);
} | 0true
| src_main_java_org_elasticsearch_client_IndicesAdminClient.java |
203 | public class XSimpleQueryParser extends QueryBuilder {
static {
assert Version.LUCENE_46.onOrAfter(Lucene.VERSION) : "Lucene 4.7 adds SimpleQueryParser, remove me!";
}
/** Map of fields to query against with their weights */
protected final Map<String,Float> weights;
/** flags to the parser (to turn features on/off) */
protected final int flags;
/** Enables {@code AND} operator (+) */
public static final int AND_OPERATOR = 1<<0;
/** Enables {@code NOT} operator (-) */
public static final int NOT_OPERATOR = 1<<1;
/** Enables {@code OR} operator (|) */
public static final int OR_OPERATOR = 1<<2;
/** Enables {@code PREFIX} operator (*) */
public static final int PREFIX_OPERATOR = 1<<3;
/** Enables {@code PHRASE} operator (") */
public static final int PHRASE_OPERATOR = 1<<4;
/** Enables {@code PRECEDENCE} operators: {@code (} and {@code )} */
public static final int PRECEDENCE_OPERATORS = 1<<5;
/** Enables {@code ESCAPE} operator (\) */
public static final int ESCAPE_OPERATOR = 1<<6;
/** Enables {@code WHITESPACE} operators: ' ' '\n' '\r' '\t' */
public static final int WHITESPACE_OPERATOR = 1<<7;
private BooleanClause.Occur defaultOperator = BooleanClause.Occur.SHOULD;
/** Creates a new parser searching over a single field. */
public XSimpleQueryParser(Analyzer analyzer, String field) {
this(analyzer, Collections.singletonMap(field, 1.0F));
}
/** Creates a new parser searching over multiple fields with different weights. */
public XSimpleQueryParser(Analyzer analyzer, Map<String, Float> weights) {
this(analyzer, weights, -1);
}
/** Creates a new parser with custom flags used to enable/disable certain features. */
public XSimpleQueryParser(Analyzer analyzer, Map<String, Float> weights, int flags) {
super(analyzer);
this.weights = weights;
this.flags = flags;
}
/** Parses the query text and returns parsed query (or null if empty) */
public Query parse(String queryText) {
char data[] = queryText.toCharArray();
char buffer[] = new char[data.length];
State state = new State(data, buffer, 0, data.length);
parseSubQuery(state);
return state.top;
}
private void parseSubQuery(State state) {
while (state.index < state.length) {
if (state.data[state.index] == '(' && (flags & PRECEDENCE_OPERATORS) != 0) {
// the beginning of a subquery has been found
consumeSubQuery(state);
} else if (state.data[state.index] == ')' && (flags & PRECEDENCE_OPERATORS) != 0) {
// this is an extraneous character so it is ignored
++state.index;
} else if (state.data[state.index] == '"' && (flags & PHRASE_OPERATOR) != 0) {
// the beginning of a phrase has been found
consumePhrase(state);
} else if (state.data[state.index] == '+' && (flags & AND_OPERATOR) != 0) {
// an and operation has been explicitly set
// if an operation has already been set this one is ignored
// if a term (or phrase or subquery) has not been found yet the
// operation is also ignored since there is no previous
// term (or phrase or subquery) to and with
if (state.currentOperation == null && state.top != null) {
state.currentOperation = BooleanClause.Occur.MUST;
}
++state.index;
} else if (state.data[state.index] == '|' && (flags & OR_OPERATOR) != 0) {
// an or operation has been explicitly set
// if an operation has already been set this one is ignored
// if a term (or phrase or subquery) has not been found yet the
// operation is also ignored since there is no previous
// term (or phrase or subquery) to or with
if (state.currentOperation == null && state.top != null) {
state.currentOperation = BooleanClause.Occur.SHOULD;
}
++state.index;
} else if (state.data[state.index] == '-' && (flags & NOT_OPERATOR) != 0) {
// a not operator has been found, so increase the not count
// two not operators in a row negate each other
++state.not;
++state.index;
// continue so the not operator is not reset
// before the next character is determined
continue;
} else if ((state.data[state.index] == ' '
|| state.data[state.index] == '\t'
|| state.data[state.index] == '\n'
|| state.data[state.index] == '\r') && (flags & WHITESPACE_OPERATOR) != 0) {
// ignore any whitespace found as it may have already been
// used a delimiter across a term (or phrase or subquery)
// or is simply extraneous
++state.index;
} else {
// the beginning of a token has been found
consumeToken(state);
}
// reset the not operator as even whitespace is not allowed when
// specifying the not operation for a term (or phrase or subquery)
state.not = 0;
}
}
private void consumeSubQuery(State state) {
assert (flags & PRECEDENCE_OPERATORS) != 0;
int start = ++state.index;
int precedence = 1;
boolean escaped = false;
while (state.index < state.length) {
if (!escaped) {
if (state.data[state.index] == '\\' && (flags & ESCAPE_OPERATOR) != 0) {
// an escape character has been found so
// whatever character is next will become
// part of the subquery unless the escape
// character is the last one in the data
escaped = true;
++state.index;
continue;
} else if (state.data[state.index] == '(') {
// increase the precedence as there is a
// subquery in the current subquery
++precedence;
} else if (state.data[state.index] == ')') {
--precedence;
if (precedence == 0) {
// this should be the end of the subquery
// all characters found will used for
// creating the subquery
break;
}
}
}
escaped = false;
++state.index;
}
if (state.index == state.length) {
// a closing parenthesis was never found so the opening
// parenthesis is considered extraneous and will be ignored
state.index = start;
} else if (state.index == start) {
// a closing parenthesis was found immediately after the opening
// parenthesis so the current operation is reset since it would
// have been applied to this subquery
state.currentOperation = null;
++state.index;
} else {
// a complete subquery has been found and is recursively parsed by
// starting over with a new state object
State subState = new State(state.data, state.buffer, start, state.index);
parseSubQuery(subState);
buildQueryTree(state, subState.top);
++state.index;
}
}
private void consumePhrase(State state) {
assert (flags & PHRASE_OPERATOR) != 0;
int start = ++state.index;
int copied = 0;
boolean escaped = false;
while (state.index < state.length) {
if (!escaped) {
if (state.data[state.index] == '\\' && (flags & ESCAPE_OPERATOR) != 0) {
// an escape character has been found so
// whatever character is next will become
// part of the phrase unless the escape
// character is the last one in the data
escaped = true;
++state.index;
continue;
} else if (state.data[state.index] == '"') {
// this should be the end of the phrase
// all characters found will used for
// creating the phrase query
break;
}
}
escaped = false;
state.buffer[copied++] = state.data[state.index++];
}
if (state.index == state.length) {
// a closing double quote was never found so the opening
// double quote is considered extraneous and will be ignored
state.index = start;
} else if (state.index == start) {
// a closing double quote was found immediately after the opening
// double quote so the current operation is reset since it would
// have been applied to this phrase
state.currentOperation = null;
++state.index;
} else {
// a complete phrase has been found and is parsed through
// through the analyzer from the given field
String phrase = new String(state.buffer, 0, copied);
Query branch = newPhraseQuery(phrase);
buildQueryTree(state, branch);
++state.index;
}
}
private void consumeToken(State state) {
int copied = 0;
boolean escaped = false;
boolean prefix = false;
while (state.index < state.length) {
if (!escaped) {
if (state.data[state.index] == '\\' && (flags & ESCAPE_OPERATOR) != 0) {
// an escape character has been found so
// whatever character is next will become
// part of the term unless the escape
// character is the last one in the data
escaped = true;
prefix = false;
++state.index;
continue;
} else if ((state.data[state.index] == '"' && (flags & PHRASE_OPERATOR) != 0)
|| (state.data[state.index] == '|' && (flags & OR_OPERATOR) != 0)
|| (state.data[state.index] == '+' && (flags & AND_OPERATOR) != 0)
|| (state.data[state.index] == '(' && (flags & PRECEDENCE_OPERATORS) != 0)
|| (state.data[state.index] == ')' && (flags & PRECEDENCE_OPERATORS) != 0)
|| ((state.data[state.index] == ' '
|| state.data[state.index] == '\t'
|| state.data[state.index] == '\n'
|| state.data[state.index] == '\r') && (flags & WHITESPACE_OPERATOR) != 0)) {
// this should be the end of the term
// all characters found will used for
// creating the term query
break;
}
// wildcard tracks whether or not the last character
// was a '*' operator that hasn't been escaped
// there must be at least one valid character before
// searching for a prefixed set of terms
prefix = copied > 0 && state.data[state.index] == '*' && (flags & PREFIX_OPERATOR) != 0;
}
escaped = false;
state.buffer[copied++] = state.data[state.index++];
}
if (copied > 0) {
final Query branch;
if (prefix) {
// if a term is found with a closing '*' it is considered to be a prefix query
// and will have prefix added as an option
String token = new String(state.buffer, 0, copied - 1);
branch = newPrefixQuery(token);
} else {
// a standard term has been found so it will be run through
// the entire analysis chain from the specified schema field
String token = new String(state.buffer, 0, copied);
branch = newDefaultQuery(token);
}
buildQueryTree(state, branch);
}
}
// buildQueryTree should be called after a term, phrase, or subquery
// is consumed to be added to our existing query tree
// this method will only add to the existing tree if the branch contained in state is not null
private void buildQueryTree(State state, Query branch) {
if (branch != null) {
// modify our branch to a BooleanQuery wrapper for not
// this is necessary any time a term, phrase, or subquery is negated
if (state.not % 2 == 1) {
BooleanQuery nq = new BooleanQuery();
nq.add(branch, BooleanClause.Occur.MUST_NOT);
nq.add(new MatchAllDocsQuery(), BooleanClause.Occur.SHOULD);
branch = nq;
}
// first term (or phrase or subquery) found and will begin our query tree
if (state.top == null) {
state.top = branch;
} else {
// more than one term (or phrase or subquery) found
// set currentOperation to the default if no other operation is explicitly set
if (state.currentOperation == null) {
state.currentOperation = defaultOperator;
}
// operational change requiring a new parent node
// this occurs if the previous operation is not the same as current operation
// because the previous operation must be evaluated separately to preserve
// the proper precedence and the current operation will take over as the top of the tree
if (state.previousOperation != state.currentOperation) {
BooleanQuery bq = new BooleanQuery();
bq.add(state.top, state.currentOperation);
state.top = bq;
}
// reset all of the state for reuse
((BooleanQuery)state.top).add(branch, state.currentOperation);
state.previousOperation = state.currentOperation;
}
// reset the current operation as it was intended to be applied to
// the incoming term (or phrase or subquery) even if branch was null
// due to other possible errors
state.currentOperation = null;
}
}
/**
* Factory method to generate a standard query (no phrase or prefix operators).
*/
protected Query newDefaultQuery(String text) {
BooleanQuery bq = new BooleanQuery(true);
for (Map.Entry<String,Float> entry : weights.entrySet()) {
Query q = createBooleanQuery(entry.getKey(), text, defaultOperator);
if (q != null) {
q.setBoost(entry.getValue());
bq.add(q, BooleanClause.Occur.SHOULD);
}
}
return simplify(bq);
}
/**
* Factory method to generate a phrase query.
*/
protected Query newPhraseQuery(String text) {
BooleanQuery bq = new BooleanQuery(true);
for (Map.Entry<String,Float> entry : weights.entrySet()) {
Query q = createPhraseQuery(entry.getKey(), text);
if (q != null) {
q.setBoost(entry.getValue());
bq.add(q, BooleanClause.Occur.SHOULD);
}
}
return simplify(bq);
}
/**
* Factory method to generate a prefix query.
*/
protected Query newPrefixQuery(String text) {
BooleanQuery bq = new BooleanQuery(true);
for (Map.Entry<String,Float> entry : weights.entrySet()) {
PrefixQuery prefix = new PrefixQuery(new Term(entry.getKey(), text));
prefix.setBoost(entry.getValue());
bq.add(prefix, BooleanClause.Occur.SHOULD);
}
return simplify(bq);
}
/**
* Helper to simplify boolean queries with 0 or 1 clause
*/
protected Query simplify(BooleanQuery bq) {
if (bq.clauses().isEmpty()) {
return null;
} else if (bq.clauses().size() == 1) {
return bq.clauses().get(0).getQuery();
} else {
return bq;
}
}
/**
* Returns the implicit operator setting, which will be
* either {@code SHOULD} or {@code MUST}.
*/
public BooleanClause.Occur getDefaultOperator() {
return defaultOperator;
}
/**
* Sets the implicit operator setting, which must be
* either {@code SHOULD} or {@code MUST}.
*/
public void setDefaultOperator(BooleanClause.Occur operator) {
if (operator != BooleanClause.Occur.SHOULD && operator != BooleanClause.Occur.MUST) {
throw new IllegalArgumentException("invalid operator: only SHOULD or MUST are allowed");
}
this.defaultOperator = operator;
}
static class State {
final char[] data; // the characters in the query string
final char[] buffer; // a temporary buffer used to reduce necessary allocations
int index;
int length;
BooleanClause.Occur currentOperation;
BooleanClause.Occur previousOperation;
int not;
Query top;
State(char[] data, char[] buffer, int index, int length) {
this.data = data;
this.buffer = buffer;
this.index = index;
this.length = length;
}
}
} | 0true
| src_main_java_org_apache_lucene_queryparser_XSimpleQueryParser.java |
1,276 | public interface RatingDetail {
public Long getId();
public void setId(Long id);
public Double getRating();
public void setRating(Double newRating);
public Customer getCustomer();
public void setCustomer(Customer customer);
public Date getRatingSubmittedDate();
public void setRatingSubmittedDate(Date ratingSubmittedDate);
public RatingSummary getRatingSummary();
public void setRatingSummary(RatingSummary ratingSummary);
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_rating_domain_RatingDetail.java |
2,422 | public class SlicedDoubleListTests extends ElasticsearchTestCase {
@Test
public void testCapacity() {
SlicedDoubleList list = new SlicedDoubleList(5);
assertThat(list.length, equalTo(5));
assertThat(list.offset, equalTo(0));
assertThat(list.values.length, equalTo(5));
assertThat(list.size(), equalTo(5));
list = new SlicedDoubleList(new double[10], 5, 5);
assertThat(list.length, equalTo(5));
assertThat(list.offset, equalTo(5));
assertThat(list.size(), equalTo(5));
assertThat(list.values.length, equalTo(10));
}
@Test
public void testGrow() {
SlicedDoubleList list = new SlicedDoubleList(5);
list.length = 1000;
for (int i = 0; i < list.length; i++) {
list.grow(i+1);
list.values[i] = ((double)i);
}
int expected = 0;
for (Double d : list) {
assertThat((double)expected++, equalTo(d));
}
for (int i = 0; i < list.length; i++) {
assertThat((double)i, equalTo(list.get(i)));
}
int count = 0;
for (int i = list.offset; i < list.offset+list.length; i++) {
assertThat((double)count++, equalTo(list.values[i]));
}
}
@Test
public void testIndexOf() {
SlicedDoubleList list = new SlicedDoubleList(5);
list.length = 1000;
for (int i = 0; i < list.length; i++) {
list.grow(i+1);
list.values[i] = ((double)i%100);
}
assertThat(999, equalTo(list.lastIndexOf(99.0d)));
assertThat(99, equalTo(list.indexOf(99.0d)));
assertThat(-1, equalTo(list.lastIndexOf(100.0d)));
assertThat(-1, equalTo(list.indexOf(100.0d)));
}
public void testIsEmpty() {
SlicedDoubleList list = new SlicedDoubleList(5);
assertThat(false, equalTo(list.isEmpty()));
list.length = 0;
assertThat(true, equalTo(list.isEmpty()));
}
@Test
public void testSet() {
SlicedDoubleList list = new SlicedDoubleList(5);
try {
list.set(0, (double)4);
fail();
} catch (UnsupportedOperationException ex) {
}
try {
list.add((double)4);
fail();
} catch (UnsupportedOperationException ex) {
}
}
@Test
public void testToString() {
SlicedDoubleList list = new SlicedDoubleList(5);
assertThat("[0.0, 0.0, 0.0, 0.0, 0.0]", equalTo(list.toString()));
for (int i = 0; i < list.length; i++) {
list.grow(i+1);
list.values[i] = ((double)i);
}
assertThat("[0.0, 1.0, 2.0, 3.0, 4.0]", equalTo(list.toString()));
}
} | 0true
| src_test_java_org_elasticsearch_common_util_SlicedDoubleListTests.java |
2,340 | static class Helper {
public static Map<String, String> loadNestedFromMap(@Nullable Map map) {
Map<String, String> settings = newHashMap();
if (map == null) {
return settings;
}
StringBuilder sb = new StringBuilder();
List<String> path = newArrayList();
serializeMap(settings, sb, path, map);
return settings;
}
private static void serializeMap(Map<String, String> settings, StringBuilder sb, List<String> path, Map<Object, Object> map) {
for (Map.Entry<Object, Object> entry : map.entrySet()) {
if (entry.getValue() instanceof Map) {
path.add((String) entry.getKey());
serializeMap(settings, sb, path, (Map<Object, Object>) entry.getValue());
path.remove(path.size() - 1);
} else if (entry.getValue() instanceof List) {
path.add((String) entry.getKey());
serializeList(settings, sb, path, (List) entry.getValue());
path.remove(path.size() - 1);
} else {
serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue());
}
}
}
private static void serializeList(Map<String, String> settings, StringBuilder sb, List<String> path, List list) {
int counter = 0;
for (Object listEle : list) {
if (listEle instanceof Map) {
path.add(Integer.toString(counter));
serializeMap(settings, sb, path, (Map<Object, Object>) listEle);
path.remove(path.size() - 1);
} else if (listEle instanceof List) {
path.add(Integer.toString(counter));
serializeList(settings, sb, path, (List) listEle);
path.remove(path.size() - 1);
} else {
serializeValue(settings, sb, path, Integer.toString(counter), listEle);
}
counter++;
}
}
private static void serializeValue(Map<String, String> settings, StringBuilder sb, List<String> path, String name, Object value) {
if (value == null) {
return;
}
sb.setLength(0);
for (String pathEle : path) {
sb.append(pathEle).append('.');
}
sb.append(name);
settings.put(sb.toString(), value.toString());
}
} | 0true
| src_main_java_org_elasticsearch_common_settings_loader_SettingsLoader.java |
206 | viewer.getTextWidget().addCaretListener(new CaretListener() {
@Override
public void caretMoved(CaretEvent event) {
Object adapter = getAdapter(IVerticalRulerInfo.class);
if (adapter instanceof CompositeRuler) {
// redraw initializer annotations according to cursor position
((CompositeRuler) adapter).update();
}
}
}); | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonEditor.java |
341 | class Evictor extends TimerTask {
private HashMap<String, Map<DB, Long>> evictionMap = new HashMap<String, Map<DB, Long>>();
private long minIdleTime;
public Evictor(long minIdleTime) {
this.minIdleTime = minIdleTime;
}
/**
* Run pool maintenance. Evict objects qualifying for eviction
*/
@Override
public void run() {
OLogManager.instance().debug(this, "Running Connection Pool Evictor Service...");
lock();
try {
for (Entry<String, Map<DB, Long>> pool : this.evictionMap.entrySet()) {
Map<DB, Long> poolDbs = pool.getValue();
Iterator<Entry<DB, Long>> iterator = poolDbs.entrySet().iterator();
while (iterator.hasNext()) {
Entry<DB, Long> db = iterator.next();
if (System.currentTimeMillis() - db.getValue() >= this.minIdleTime) {
OResourcePool<String, DB> oResourcePool = pools.get(pool.getKey());
if (oResourcePool != null) {
OLogManager.instance().debug(this, "Closing idle pooled database '%s'...", db.getKey().getName());
((ODatabasePooled) db.getKey()).forceClose();
oResourcePool.remove(db.getKey());
iterator.remove();
}
}
}
}
} finally {
unlock();
}
}
public void updateIdleTime(final String poolName, final DB iDatabase) {
Map<DB, Long> pool = this.evictionMap.get(poolName);
if (pool == null) {
pool = new HashMap<DB, Long>();
this.evictionMap.put(poolName, pool);
}
pool.put(iDatabase, System.currentTimeMillis());
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_ODatabasePoolAbstract.java |
715 | class ShardCountRequest extends BroadcastShardOperationRequest {
private float minScore;
private BytesReference querySource;
private String[] types = Strings.EMPTY_ARRAY;
private long nowInMillis;
@Nullable
private String[] filteringAliases;
ShardCountRequest() {
}
public ShardCountRequest(String index, int shardId, @Nullable String[] filteringAliases, CountRequest request) {
super(index, shardId, request);
this.minScore = request.minScore();
this.querySource = request.source();
this.types = request.types();
this.filteringAliases = filteringAliases;
this.nowInMillis = request.nowInMillis;
}
public float minScore() {
return minScore;
}
public BytesReference querySource() {
return querySource;
}
public String[] types() {
return this.types;
}
public String[] filteringAliases() {
return filteringAliases;
}
public long nowInMillis() {
return this.nowInMillis;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
minScore = in.readFloat();
querySource = in.readBytesReference();
int typesSize = in.readVInt();
if (typesSize > 0) {
types = new String[typesSize];
for (int i = 0; i < typesSize; i++) {
types[i] = in.readString();
}
}
int aliasesSize = in.readVInt();
if (aliasesSize > 0) {
filteringAliases = new String[aliasesSize];
for (int i = 0; i < aliasesSize; i++) {
filteringAliases[i] = in.readString();
}
}
nowInMillis = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeFloat(minScore);
out.writeBytesReference(querySource);
out.writeVInt(types.length);
for (String type : types) {
out.writeString(type);
}
if (filteringAliases != null) {
out.writeVInt(filteringAliases.length);
for (String alias : filteringAliases) {
out.writeString(alias);
}
} else {
out.writeVInt(0);
}
out.writeVLong(nowInMillis);
}
} | 0true
| src_main_java_org_elasticsearch_action_count_ShardCountRequest.java |
1,194 | public class OQueryOperatorTraverse extends OQueryOperatorEqualityNotNulls {
private int startDeepLevel = 0; // FIRST
private int endDeepLevel = -1; // INFINITE
private String[] cfgFields;
public OQueryOperatorTraverse() {
super("TRAVERSE", 5, false, 1, true);
}
public OQueryOperatorTraverse(final int startDeepLevel, final int endDeepLevel, final String[] iFieldList) {
this();
this.startDeepLevel = startDeepLevel;
this.endDeepLevel = endDeepLevel;
this.cfgFields = iFieldList;
}
@Override
public String getSyntax() {
return "<left> TRAVERSE[(<begin-deep-level> [,<maximum-deep-level> [,<fields>]] )] ( <conditions> )";
}
@Override
protected boolean evaluateExpression(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft,
final Object iRight, final OCommandContext iContext) {
final OSQLFilterCondition condition;
final Object target;
if (iCondition.getLeft() instanceof OSQLFilterCondition) {
condition = (OSQLFilterCondition) iCondition.getLeft();
target = iRight;
} else {
condition = (OSQLFilterCondition) iCondition.getRight();
target = iLeft;
}
final Set<ORID> evaluatedRecords = new HashSet<ORID>();
return traverse(target, condition, 0, evaluatedRecords, iContext);
}
@SuppressWarnings("unchecked")
private boolean traverse(Object iTarget, final OSQLFilterCondition iCondition, final int iLevel,
final Set<ORID> iEvaluatedRecords, final OCommandContext iContext) {
if (endDeepLevel > -1 && iLevel > endDeepLevel)
return false;
if (iTarget instanceof ORID) {
if (iEvaluatedRecords.contains(iTarget))
// ALREADY EVALUATED
return false;
// TRANSFORM THE ORID IN ODOCUMENT
iTarget = new ODocument((ORID) iTarget);
} else if (iTarget instanceof ODocument) {
if (iEvaluatedRecords.contains(((ODocument) iTarget).getIdentity()))
// ALREADY EVALUATED
return false;
}
if (iTarget instanceof ODocument) {
final ODocument target = (ODocument) iTarget;
iEvaluatedRecords.add(target.getIdentity());
if (target.getInternalStatus() == ORecordElement.STATUS.NOT_LOADED)
try {
target.load();
} catch (final ORecordNotFoundException e) {
// INVALID RID
return false;
}
if (iLevel >= startDeepLevel && (Boolean) iCondition.evaluate(target, null, iContext) == Boolean.TRUE)
return true;
// TRAVERSE THE DOCUMENT ITSELF
if (cfgFields != null)
for (final String cfgField : cfgFields) {
if (cfgField.equalsIgnoreCase(OSQLFilterItemFieldAny.FULL_NAME)) {
// ANY
for (final String fieldName : target.fieldNames())
if (traverse(target.rawField(fieldName), iCondition, iLevel + 1, iEvaluatedRecords, iContext))
return true;
} else if (cfgField.equalsIgnoreCase(OSQLFilterItemFieldAny.FULL_NAME)) {
// ALL
for (final String fieldName : target.fieldNames())
if (!traverse(target.rawField(fieldName), iCondition, iLevel + 1, iEvaluatedRecords, iContext))
return false;
return true;
} else {
if (traverse(target.rawField(cfgField), iCondition, iLevel + 1, iEvaluatedRecords, iContext))
return true;
}
}
} else if (iTarget instanceof OQueryRuntimeValueMulti) {
final OQueryRuntimeValueMulti multi = (OQueryRuntimeValueMulti) iTarget;
for (final Object o : multi.getValues()) {
if (traverse(o, iCondition, iLevel + 1, iEvaluatedRecords, iContext) == Boolean.TRUE)
return true;
}
} else if (iTarget instanceof Collection<?>) {
final Collection<Object> collection = (Collection<Object>) iTarget;
for (final Object o : collection) {
if (traverse(o, iCondition, iLevel + 1, iEvaluatedRecords, iContext) == Boolean.TRUE)
return true;
}
} else if (iTarget instanceof Map<?, ?>) {
final Map<Object, Object> map = (Map<Object, Object>) iTarget;
for (final Object o : map.values()) {
if (traverse(o, iCondition, iLevel + 1, iEvaluatedRecords, iContext) == Boolean.TRUE)
return true;
}
}
return false;
}
@Override
public OQueryOperator configure(final List<String> iParams) {
if (iParams == null)
return this;
final int start = !iParams.isEmpty() ? Integer.parseInt(iParams.get(0)) : startDeepLevel;
final int end = iParams.size() > 1 ? Integer.parseInt(iParams.get(1)) : endDeepLevel;
String[] fields = new String[] { "any()" };
if (iParams.size() > 2) {
String f = iParams.get(2);
if (f.startsWith("'") || f.startsWith("\""))
f = f.substring(1, f.length() - 1);
fields = f.split(",");
}
return new OQueryOperatorTraverse(start, end, fields);
}
public int getStartDeepLevel() {
return startDeepLevel;
}
public int getEndDeepLevel() {
return endDeepLevel;
}
public String[] getCfgFields() {
return cfgFields;
}
@Override
public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) {
return OIndexReuseType.NO_INDEX;
}
@Override
public String toString() {
return String.format("%s(%d,%d,%s)", keyword, startDeepLevel, endDeepLevel, Arrays.toString(cfgFields));
}
@Override
public ORID getBeginRidRange(Object iLeft, Object iRight) {
return null;
}
@Override
public ORID getEndRidRange(Object iLeft, Object iRight) {
return null;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryOperatorTraverse.java |
2,590 | public class SocketConnector implements Runnable {
private static final int TIMEOUT = 3000;
private final TcpIpConnectionManager connectionManager;
private final Address address;
private final ILogger logger;
private final boolean silent;
public SocketConnector(TcpIpConnectionManager connectionManager, Address address, boolean silent) {
this.connectionManager = connectionManager;
this.address = address;
this.logger = connectionManager.ioService.getLogger(this.getClass().getName());
this.silent = silent;
}
public void run() {
if (!connectionManager.isLive()) {
if (logger.isFinestEnabled()) {
String message = "ConnectionManager is not live, connection attempt to " + address + " is cancelled!";
log(Level.FINEST, message);
}
return;
}
try {
if (logger.isFinestEnabled()) {
log(Level.FINEST, "Starting to connect to " + address);
}
final Address thisAddress = connectionManager.ioService.getThisAddress();
if (address.isIPv4()) {
// remote is IPv4; connect...
tryToConnect(address.getInetSocketAddress(), 0);
} else if (thisAddress.isIPv6() && thisAddress.getScopeId() != null) {
// Both remote and this addresses are IPv6.
// This is a local IPv6 address and scope id is known.
// find correct inet6 address for remote and connect...
final Inet6Address inetAddress = AddressUtil
.getInetAddressFor((Inet6Address) address.getInetAddress(), thisAddress.getScopeId());
tryToConnect(new InetSocketAddress(inetAddress, address.getPort()), 0);
} else {
// remote is IPv6 and this is either IPv4 or a global IPv6.
// find possible remote inet6 addresses and try each one to connect...
final Collection<Inet6Address> possibleInetAddresses = AddressUtil.getPossibleInetAddressesFor(
(Inet6Address) address.getInetAddress());
final Level level = silent ? Level.FINEST : Level.INFO;
//TODO: collection.toString() will likely not produce any useful output!
if (logger.isLoggable(level)) {
log(level, "Trying to connect possible IPv6 addresses: " + possibleInetAddresses);
}
boolean connected = false;
Exception error = null;
for (Inet6Address inetAddress : possibleInetAddresses) {
try {
tryToConnect(new InetSocketAddress(inetAddress, address.getPort()), TIMEOUT);
connected = true;
break;
} catch (Exception e) {
error = e;
}
}
if (!connected && error != null) {
// could not connect any of addresses
throw error;
}
}
} catch (Throwable e) {
logger.finest(e);
connectionManager.failedConnection(address, e, silent);
}
}
private void tryToConnect(final InetSocketAddress socketAddress, final int timeout)
throws Exception {
final SocketChannel socketChannel = SocketChannel.open();
connectionManager.initSocket(socketChannel.socket());
if (connectionManager.ioService.isSocketBind()) {
bindSocket(socketChannel);
}
final Level level = silent ? Level.FINEST : Level.INFO;
if (logger.isLoggable(level)) {
final String message = "Connecting to " + socketAddress + ", timeout: " + timeout
+ ", bind-any: " + connectionManager.ioService.isSocketBindAny();
log(level, message);
}
try {
socketChannel.configureBlocking(true);
try {
if (timeout > 0) {
socketChannel.socket().connect(socketAddress, timeout);
} else {
socketChannel.connect(socketAddress);
}
} catch (SocketException ex) {
//we want to include the socketAddress in the exception.
SocketException newEx = new SocketException(ex.getMessage() + " to address " + socketAddress);
newEx.setStackTrace(ex.getStackTrace());
throw newEx;
}
if (logger.isFinestEnabled()) {
log(Level.FINEST, "Successfully connected to: " + address + " using socket " + socketChannel.socket());
}
final SocketChannelWrapper socketChannelWrapper = connectionManager.wrapSocketChannel(socketChannel, true);
MemberSocketInterceptor memberSocketInterceptor = connectionManager.getMemberSocketInterceptor();
if (memberSocketInterceptor != null) {
if (logger.isFinestEnabled()) {
log(Level.FINEST, "Calling member socket interceptor: " + memberSocketInterceptor + " for " + socketChannel);
}
memberSocketInterceptor.onConnect(socketChannel.socket());
}
socketChannelWrapper.configureBlocking(false);
TcpIpConnection connection = connectionManager.assignSocketChannel(socketChannelWrapper);
connection.getWriteHandler().setProtocol(Protocols.CLUSTER);
connectionManager.sendBindRequest(connection, address, true);
} catch (Exception e) {
closeSocket(socketChannel);
log(level, "Could not connect to: " + socketAddress + ". Reason: " + e.getClass().getSimpleName()
+ "[" + e.getMessage() + "]");
throw e;
}
}
private void bindSocket(final SocketChannel socketChannel) throws IOException {
final InetAddress inetAddress;
if (connectionManager.ioService.isSocketBindAny()) {
inetAddress = null;
} else {
final Address thisAddress = connectionManager.ioService.getThisAddress();
inetAddress = thisAddress.getInetAddress();
}
final Socket socket = socketChannel.socket();
if (connectionManager.useAnyOutboundPort()) {
final SocketAddress socketAddress = new InetSocketAddress(inetAddress, 0);
socket.bind(socketAddress);
} else {
IOException ex = null;
final int retryCount = connectionManager.getOutboundPortCount() * 2;
for (int i = 0; i < retryCount; i++) {
final int port = connectionManager.acquireOutboundPort();
final SocketAddress socketAddress = new InetSocketAddress(inetAddress, port);
try {
socket.bind(socketAddress);
return;
} catch (IOException e) {
ex = e;
log(Level.FINEST, "Could not bind port[ " + port + "]: " + e.getMessage());
}
}
throw ex;
}
}
private void closeSocket(final SocketChannel socketChannel) {
if (socketChannel != null) {
try {
socketChannel.close();
} catch (final IOException ignored) {
}
}
}
private void log(Level level, String message) {
logger.log(level, message);
connectionManager.ioService.getSystemLogService().logConnection(message);
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_nio_SocketConnector.java |
1,664 | private static class SecureRandomHolder {
// class loading is atomic - this is a lazy & safe singleton
private static final SecureRandom INSTANCE = new SecureRandom();
} | 0true
| src_main_java_org_elasticsearch_common_Strings.java |
3,553 | public class BooleanFieldMapper extends AbstractFieldMapper<Boolean> {
public static final String CONTENT_TYPE = "boolean";
public static class Defaults extends AbstractFieldMapper.Defaults {
public static final FieldType FIELD_TYPE = new FieldType(AbstractFieldMapper.Defaults.FIELD_TYPE);
static {
FIELD_TYPE.setOmitNorms(true);
FIELD_TYPE.setIndexOptions(IndexOptions.DOCS_ONLY);
FIELD_TYPE.setTokenized(false);
FIELD_TYPE.freeze();
}
public static final Boolean NULL_VALUE = null;
}
public static class Values {
public final static BytesRef TRUE = new BytesRef("T");
public final static BytesRef FALSE = new BytesRef("F");
}
public static class Builder extends AbstractFieldMapper.Builder<Builder, BooleanFieldMapper> {
private Boolean nullValue = Defaults.NULL_VALUE;
public Builder(String name) {
super(name, new FieldType(Defaults.FIELD_TYPE));
this.builder = this;
}
public Builder nullValue(boolean nullValue) {
this.nullValue = nullValue;
return this;
}
@Override
public Builder tokenized(boolean tokenized) {
if (tokenized) {
throw new ElasticsearchIllegalArgumentException("bool field can't be tokenized");
}
return super.tokenized(tokenized);
}
@Override
public BooleanFieldMapper build(BuilderContext context) {
return new BooleanFieldMapper(buildNames(context), boost, fieldType, nullValue, postingsProvider,
docValuesProvider, similarity, normsLoading, fieldDataSettings, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo);
}
}
public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
BooleanFieldMapper.Builder builder = booleanField(name);
parseField(builder, name, node, parserContext);
for (Map.Entry<String, Object> entry : node.entrySet()) {
String propName = Strings.toUnderscoreCase(entry.getKey());
Object propNode = entry.getValue();
if (propName.equals("null_value")) {
builder.nullValue(nodeBooleanValue(propNode));
}
}
return builder;
}
}
private Boolean nullValue;
protected BooleanFieldMapper(Names names, float boost, FieldType fieldType, Boolean nullValue, PostingsFormatProvider postingsProvider,
DocValuesFormatProvider docValuesProvider, SimilarityProvider similarity, Loading normsLoading,
@Nullable Settings fieldDataSettings, Settings indexSettings, MultiFields multiFields, CopyTo copyTo) {
super(names, boost, fieldType, null, Lucene.KEYWORD_ANALYZER, Lucene.KEYWORD_ANALYZER, postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings, indexSettings, multiFields, copyTo);
this.nullValue = nullValue;
}
@Override
public FieldType defaultFieldType() {
return Defaults.FIELD_TYPE;
}
@Override
public FieldDataType defaultFieldDataType() {
// TODO have a special boolean type?
return new FieldDataType("string");
}
@Override
public boolean useTermQueryWithQueryString() {
return true;
}
@Override
public Boolean value(Object value) {
if (value == null) {
return Boolean.FALSE;
}
String sValue = value.toString();
if (sValue.length() == 0) {
return Boolean.FALSE;
}
if (sValue.length() == 1 && sValue.charAt(0) == 'F') {
return Boolean.FALSE;
}
if (Booleans.parseBoolean(sValue, false)) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
@Override
public Object valueForSearch(Object value) {
return value(value);
}
@Override
public BytesRef indexedValueForSearch(Object value) {
if (value == null) {
return Values.FALSE;
}
if (value instanceof Boolean) {
return ((Boolean) value) ? Values.TRUE : Values.FALSE;
}
String sValue;
if (value instanceof BytesRef) {
sValue = ((BytesRef) value).utf8ToString();
} else {
sValue = value.toString();
}
if (sValue.length() == 0) {
return Values.FALSE;
}
if (sValue.length() == 1 && sValue.charAt(0) == 'F') {
return Values.FALSE;
}
if (Booleans.parseBoolean(sValue, false)) {
return Values.TRUE;
}
return Values.FALSE;
}
@Override
public Filter nullValueFilter() {
if (nullValue == null) {
return null;
}
return new TermFilter(names().createIndexNameTerm(nullValue ? Values.TRUE : Values.FALSE));
}
@Override
protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException {
if (!fieldType().indexed() && !fieldType().stored()) {
return;
}
XContentParser.Token token = context.parser().currentToken();
String value = null;
if (token == XContentParser.Token.VALUE_NULL) {
if (nullValue != null) {
value = nullValue ? "T" : "F";
}
} else {
value = context.parser().booleanValue() ? "T" : "F";
}
if (value == null) {
return;
}
fields.add(new Field(names.indexName(), value, fieldType));
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
@Override
protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException {
super.doXContentBody(builder, includeDefaults, params);
if (includeDefaults || nullValue != null) {
builder.field("null_value", nullValue);
}
}
@Override
public boolean hasDocValues() {
return false;
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_core_BooleanFieldMapper.java |
179 | public class OByteBufferUtils {
public static final int SIZE_OF_SHORT = 2;
public static final int SIZE_OF_INT = 4;
public static final int SIZE_OF_LONG = 8;
private static final int SIZE_OF_BYTE_IN_BITS = 8;
private static final int MASK = 0x000000FF;
/**
* Merge short value from two byte buffer. First byte of short will be extracted from first byte buffer and second from second
* one.
*
* @param buffer
* to read first part of value
* @param buffer1
* to read second part of value
* @return merged value
*/
public static short mergeShortFromBuffers(final ByteBuffer buffer, final ByteBuffer buffer1) {
short result = 0;
result = (short) (result | (buffer.get() & MASK));
result = (short) (result << SIZE_OF_BYTE_IN_BITS);
result = (short) (result | (buffer1.get() & MASK));
return result;
}
/**
* Merge int value from two byte buffer. First bytes of int will be extracted from first byte buffer and second from second one.
* How many bytes will be read from first buffer determines based on <code>buffer.remaining()</code> value
*
* @param buffer
* to read first part of value
* @param buffer1
* to read second part of value
* @return merged value
*/
public static int mergeIntFromBuffers(final ByteBuffer buffer, final ByteBuffer buffer1) {
int result = 0;
final int remaining = buffer.remaining();
for (int i = 0; i < remaining; ++i) {
result = result | (buffer.get() & MASK);
result = result << SIZE_OF_BYTE_IN_BITS;
}
for (int i = 0; i < SIZE_OF_INT - remaining - 1; ++i) {
result = result | (buffer1.get() & MASK);
result = result << SIZE_OF_BYTE_IN_BITS;
}
result = result | (buffer1.get() & MASK);
return result;
}
/**
* Merge long value from two byte buffer. First bytes of long will be extracted from first byte buffer and second from second one.
* How many bytes will be read from first buffer determines based on <code>buffer.remaining()</code> value
*
* @param buffer
* to read first part of value
* @param buffer1
* to read second part of value
* @return merged value
*/
public static long mergeLongFromBuffers(final ByteBuffer buffer, final ByteBuffer buffer1) {
long result = 0;
final int remaining = buffer.remaining();
for (int i = 0; i < remaining; ++i) {
result = result | (MASK & buffer.get());
result = result << SIZE_OF_BYTE_IN_BITS;
}
for (int i = 0; i < SIZE_OF_LONG - remaining - 1; ++i) {
result = result | (MASK & buffer1.get());
result = result << SIZE_OF_BYTE_IN_BITS;
}
result = result | (MASK & buffer1.get());
return result;
}
/**
* Split short value into two byte buffer. First byte of short will be written to first byte buffer and second to second one.
*
* @param buffer
* to write first part of value
* @param buffer1
* to write second part of value
*/
public static void splitShortToBuffers(final ByteBuffer buffer, final ByteBuffer buffer1, final short iValue) {
buffer.put((byte) (MASK & (iValue >>> SIZE_OF_BYTE_IN_BITS)));
buffer1.put((byte) (MASK & iValue));
}
/**
* Split int value into two byte buffer. First byte of int will be written to first byte buffer and second to second one. How many
* bytes will be written to first buffer determines based on <code>buffer.remaining()</code> value
*
* @param buffer
* to write first part of value
* @param buffer1
* to write second part of value
*/
public static void splitIntToBuffers(final ByteBuffer buffer, final ByteBuffer buffer1, final int iValue) {
final int remaining = buffer.remaining();
int i;
for (i = 0; i < remaining; ++i) {
buffer.put((byte) (MASK & (iValue >>> SIZE_OF_BYTE_IN_BITS * (SIZE_OF_INT - i - 1))));
}
for (int j = 0; j < SIZE_OF_INT - remaining; ++j) {
buffer1.put((byte) (MASK & (iValue >>> SIZE_OF_BYTE_IN_BITS * (SIZE_OF_INT - i - j - 1))));
}
}
/**
* Split long value into two byte buffer. First byte of long will be written to first byte buffer and second to second one. How
* many bytes will be written to first buffer determines based on <code>buffer.remaining()</code> value
*
* @param buffer
* to write first part of value
* @param buffer1
* to write second part of value
*/
public static void splitLongToBuffers(final ByteBuffer buffer, final ByteBuffer buffer1, final long iValue) {
final int remaining = buffer.remaining();
int i;
for (i = 0; i < remaining; ++i) {
buffer.put((byte) (iValue >> SIZE_OF_BYTE_IN_BITS * (SIZE_OF_LONG - i - 1)));
}
for (int j = 0; j < SIZE_OF_LONG - remaining; ++j) {
buffer1.put((byte) (iValue >> SIZE_OF_BYTE_IN_BITS * (SIZE_OF_LONG - i - j - 1)));
}
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_util_OByteBufferUtils.java |
1,895 | public class NearCache {
/**
* Used when caching nonexistent values.
*/
public static final Object NULL_OBJECT = new Object();
private static final int HUNDRED_PERCENT = 100;
private static final int EVICTION_PERCENTAGE = 20;
private static final int CLEANUP_INTERVAL = 5000;
private final int maxSize;
private volatile long lastCleanup;
private final long maxIdleMillis;
private final long timeToLiveMillis;
private final EvictionPolicy evictionPolicy;
private final InMemoryFormat inMemoryFormat;
private final MapService mapService;
private final NodeEngine nodeEngine;
private final AtomicBoolean canCleanUp;
private final AtomicBoolean canEvict;
private final ConcurrentMap<Data, CacheRecord> cache;
private final MapContainer mapContainer;
private final NearCacheStatsImpl nearCacheStats;
/**
* @param mapName
* @param mapService
*/
public NearCache(String mapName, MapService mapService) {
this.mapService = mapService;
this.nodeEngine = mapService.getNodeEngine();
this.mapContainer = mapService.getMapContainer(mapName);
Config config = nodeEngine.getConfig();
NearCacheConfig nearCacheConfig = config.findMapConfig(mapName).getNearCacheConfig();
maxSize = nearCacheConfig.getMaxSize() <= 0 ? Integer.MAX_VALUE : nearCacheConfig.getMaxSize();
maxIdleMillis = TimeUnit.SECONDS.toMillis(nearCacheConfig.getMaxIdleSeconds());
inMemoryFormat = nearCacheConfig.getInMemoryFormat();
timeToLiveMillis = TimeUnit.SECONDS.toMillis(nearCacheConfig.getTimeToLiveSeconds());
evictionPolicy = EvictionPolicy.valueOf(nearCacheConfig.getEvictionPolicy());
cache = new ConcurrentHashMap<Data, CacheRecord>();
canCleanUp = new AtomicBoolean(true);
canEvict = new AtomicBoolean(true);
nearCacheStats = new NearCacheStatsImpl();
lastCleanup = Clock.currentTimeMillis();
}
/**
* EvictionPolicy.
*/
static enum EvictionPolicy {
NONE, LRU, LFU
}
// this operation returns the given value in near-cache memory format (data or object)
public Object put(Data key, Data data) {
fireTtlCleanup();
if (evictionPolicy == EvictionPolicy.NONE && cache.size() >= maxSize) {
// no more space in near-cache -> return given value in near-cache format
if (data == null) {
return null;
} else {
return inMemoryFormat.equals(InMemoryFormat.OBJECT) ? mapService.toObject(data) : data;
}
}
if (evictionPolicy != EvictionPolicy.NONE && cache.size() >= maxSize) {
fireEvictCache();
}
final Object value;
if (data == null) {
value = NULL_OBJECT;
} else {
value = inMemoryFormat.equals(InMemoryFormat.OBJECT) ? mapService.toObject(data) : data;
}
final CacheRecord record = new CacheRecord(key, value);
cache.put(key, record);
updateSizeEstimator(calculateCost(record));
if (NULL_OBJECT.equals(value)) {
return null;
} else {
return value;
}
}
public NearCacheStatsImpl getNearCacheStats() {
return createNearCacheStats();
}
private NearCacheStatsImpl createNearCacheStats() {
long ownedEntryCount = 0;
long ownedEntryMemoryCost = 0;
for (CacheRecord record : cache.values()) {
ownedEntryCount++;
ownedEntryMemoryCost += record.getCost();
}
nearCacheStats.setOwnedEntryCount(ownedEntryCount);
nearCacheStats.setOwnedEntryMemoryCost(ownedEntryMemoryCost);
return nearCacheStats;
}
private void fireEvictCache() {
if (canEvict.compareAndSet(true, false)) {
try {
nodeEngine.getExecutionService().execute("hz:near-cache", new Runnable() {
public void run() {
try {
TreeSet<CacheRecord> records = new TreeSet<CacheRecord>(cache.values());
int evictSize = cache.size() * EVICTION_PERCENTAGE / HUNDRED_PERCENT;
int i = 0;
for (CacheRecord record : records) {
cache.remove(record.key);
updateSizeEstimator(-calculateCost(record));
if (++i > evictSize) {
break;
}
}
} finally {
canEvict.set(true);
}
}
});
} catch (RejectedExecutionException e) {
canEvict.set(true);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
}
private void fireTtlCleanup() {
if (Clock.currentTimeMillis() < (lastCleanup + CLEANUP_INTERVAL)) {
return;
}
if (canCleanUp.compareAndSet(true, false)) {
try {
nodeEngine.getExecutionService().execute("hz:near-cache", new Runnable() {
public void run() {
try {
lastCleanup = Clock.currentTimeMillis();
for (Map.Entry<Data, CacheRecord> entry : cache.entrySet()) {
if (entry.getValue().expired()) {
final Data key = entry.getKey();
final CacheRecord record = cache.remove(key);
//if a mapping exists.
if (record != null) {
updateSizeEstimator(-calculateCost(record));
}
}
}
} finally {
canCleanUp.set(true);
}
}
});
} catch (RejectedExecutionException e) {
canCleanUp.set(true);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
}
public Object get(Data key) {
fireTtlCleanup();
CacheRecord record = cache.get(key);
if (record != null) {
if (record.expired()) {
cache.remove(key);
updateSizeEstimator(-calculateCost(record));
nearCacheStats.incrementMisses();
return null;
}
record.access();
return record.value;
} else {
nearCacheStats.incrementMisses();
return null;
}
}
public void invalidate(Data key) {
final CacheRecord record = cache.remove(key);
// if a mapping exists for the key.
if (record != null) {
updateSizeEstimator(-calculateCost(record));
}
}
public void invalidate(Set<Data> keys) {
if (keys == null || keys.isEmpty()) {
return;
}
for (Data key : keys) {
invalidate(key);
}
}
public int size() {
return cache.size();
}
public void clear() {
cache.clear();
resetSizeEstimator();
}
public Map<Data, CacheRecord> getReadonlyMap() {
return Collections.unmodifiableMap(cache);
}
/**
* CacheRecord.
*/
public class CacheRecord implements Comparable<CacheRecord> {
final Data key;
final Object value;
final long creationTime;
final AtomicInteger hit;
volatile long lastAccessTime;
CacheRecord(Data key, Object value) {
this.key = key;
this.value = value;
long time = Clock.currentTimeMillis();
this.lastAccessTime = time;
this.creationTime = time;
this.hit = new AtomicInteger(0);
}
void access() {
hit.incrementAndGet();
nearCacheStats.incrementHits();
lastAccessTime = Clock.currentTimeMillis();
}
boolean expired() {
long time = Clock.currentTimeMillis();
return (maxIdleMillis > 0 && time > lastAccessTime + maxIdleMillis)
|| (timeToLiveMillis > 0 && time > creationTime + timeToLiveMillis);
}
public int compareTo(CacheRecord o) {
if (EvictionPolicy.LRU.equals(evictionPolicy)) {
return ((Long) this.lastAccessTime).compareTo((o.lastAccessTime));
} else if (EvictionPolicy.LFU.equals(evictionPolicy)) {
return ((Integer) this.hit.get()).compareTo((o.hit.get()));
}
return 0;
}
public boolean equals(Object o) {
if (o != null && o instanceof CacheRecord) {
return this.compareTo((CacheRecord) o) == 0;
}
return false;
}
// If you don't think instances of this class will ever be inserted into a HashMap/HashTable,
// the recommended hashCode implementation to use is:
public int hashCode() {
assert false : "hashCode not designed";
// any arbitrary constant will do.
return 42;
}
public long getCost() {
// todo find object size if not a Data instance.
if (!(value instanceof Data)) {
return 0;
}
final int numberOfLongs = 2;
final int numberOfIntegers = 3;
// value is Data
return key.getHeapCost()
+ ((Data) value).getHeapCost()
+ numberOfLongs * (Long.SIZE / Byte.SIZE)
// sizeof atomic integer
+ (Integer.SIZE / Byte.SIZE)
// object references (key, value, hit)
+ numberOfIntegers * (Integer.SIZE / Byte.SIZE);
}
public Data getKey() {
return key;
}
public Object getValue() {
return value;
}
}
private void resetSizeEstimator() {
mapContainer.getNearCacheSizeEstimator().reset();
}
private void updateSizeEstimator(long size) {
mapContainer.getNearCacheSizeEstimator().add(size);
}
private long calculateCost(CacheRecord record) {
return mapContainer.getNearCacheSizeEstimator().getCost(record);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_map_NearCache.java |
1,369 | public class JDTMethod implements MethodMirror, IBindingProvider {
private WeakReference<MethodBinding> bindingRef;
private Map<String, AnnotationMirror> annotations;
private String name;
private List<VariableMirror> parameters;
private TypeMirror returnType;
private List<TypeParameterMirror> typeParameters;
Boolean isOverriding;
private Boolean isOverloading;
private JDTClass enclosingClass;
private boolean isStatic;
private boolean isPublic;
private boolean isConstructor;
private boolean isStaticInit;
private boolean isAbstract;
private boolean isFinal;
private char[] bindingKey;
private String readableName;
private boolean isProtected;
private boolean isDefaultAccess;
private boolean isDeclaredVoid;
private boolean isVariadic;
private boolean isDefault;
public JDTMethod(JDTClass enclosingClass, MethodBinding method) {
this.enclosingClass = enclosingClass;
bindingRef = new WeakReference<MethodBinding>(method);
name = new String(method.selector);
readableName = new String(method.readableName());
isStatic = method.isStatic();
isPublic = method.isPublic();
isConstructor = method.isConstructor();
isStaticInit = method.selector == TypeConstants.CLINIT; // TODO : check if it is right
isAbstract = method.isAbstract();
isFinal = method.isFinal();
isProtected = method.isProtected();
isDefaultAccess = method.isDefault();
isDeclaredVoid = method.returnType.id == TypeIds.T_void;
isVariadic = method.isVarargs();
isDefault = method.getDefaultValue()!=null;
bindingKey = method.computeUniqueKey();
if (method instanceof ProblemMethodBinding) {
annotations = new HashMap<>();
parameters = Collections.emptyList();
returnType = JDTType.UNKNOWN_TYPE;
typeParameters = Collections.emptyList();
isOverriding = false;
isOverloading = false;
}
}
@Override
public AnnotationMirror getAnnotation(String type) {
if (annotations == null) {
doWithBindings(new ActionOnMethodBinding() {
@Override
public void doWithBinding(IType declaringClassModel,
ReferenceBinding declaringClass,
MethodBinding method) {
annotations = JDTUtils.getAnnotations(method.getAnnotations());
}
});
}
return annotations.get(type);
}
@Override
public String getName() {
return name;
}
@Override
public boolean isStatic() {
return isStatic;
}
@Override
public boolean isPublic() {
return isPublic;
}
@Override
public boolean isConstructor() {
return isConstructor;
}
@Override
public boolean isStaticInit() {
return isStaticInit;
}
@Override
public List<VariableMirror> getParameters() {
if (parameters == null) {
doWithBindings(new ActionOnMethodBinding() {
private String toParameterName(TypeBinding parameterType) {
String typeName = new String(parameterType.sourceName());
StringTokenizer tokens = new StringTokenizer(typeName, "$.[]");
String result = null;
while (tokens.hasMoreTokens()) {
result = tokens.nextToken();
}
if (typeName.endsWith("[]")) {
result = result + "Array";
}
return toLowerCase(result.charAt(0)) +
result.substring(1);
}
@Override
public void doWithBinding(IType declaringClassModel,
ReferenceBinding declaringClassBinding, MethodBinding methodBinding) {
TypeBinding[] parameterBindings;
AnnotationBinding[][] parameterAnnotationBindings;
parameterBindings = ((MethodBinding)methodBinding).parameters;
parameterAnnotationBindings = ((MethodBinding)methodBinding).getParameterAnnotations();
if (parameterAnnotationBindings == null) {
parameterAnnotationBindings = new AnnotationBinding[parameterBindings.length][];
for (int i=0; i<parameterAnnotationBindings.length; i++) {
parameterAnnotationBindings[i] = new AnnotationBinding[0];
}
}
parameters = new ArrayList<VariableMirror>(parameterBindings.length);
List<String> givenNames = new ArrayList<>(parameterBindings.length);
for(int i=0;i<parameterBindings.length;i++) {
Map<String, AnnotationMirror> parameterAnnotations = JDTUtils.getAnnotations(parameterAnnotationBindings[i]);
String parameterName;
AnnotationMirror nameAnnotation = getAnnotation(Name.class.getName());
TypeBinding parameterTypeBinding = parameterBindings[i];
if(nameAnnotation != null) {
parameterName = (String) nameAnnotation.getValue();
} else {
String baseName = toParameterName(parameterTypeBinding);
int count = 0;
String nameToReturn = baseName;
for (String givenName : givenNames) {
if (givenName.equals(nameToReturn)) {
count ++;
nameToReturn = baseName + Integer.toString(count);
}
}
parameterName = nameToReturn;
}
givenNames.add(parameterName);
parameters.add(new JDTVariable(parameterName, new JDTType(parameterTypeBinding), parameterAnnotations));
}
}
});
}
return parameters;
}
@Override
public boolean isAbstract() {
return isAbstract;
}
@Override
public boolean isFinal() {
return isFinal;
}
@Override
public TypeMirror getReturnType() {
if (returnType == null) {
doWithBindings(new ActionOnMethodBinding() {
@Override
public void doWithBinding(IType declaringClassModel,
ReferenceBinding declaringClassBinding, MethodBinding methodBinding) {
returnType = new JDTType(methodBinding.returnType);
}
});
}
return returnType;
}
@Override
public List<TypeParameterMirror> getTypeParameters() {
if (typeParameters == null) {
doWithBindings(new ActionOnMethodBinding() {
@Override
public void doWithBinding(IType declaringClassModel,
ReferenceBinding declaringClassBinding, MethodBinding methodBinding) {
TypeVariableBinding[] jdtTypeParameters = methodBinding.typeVariables();
typeParameters = new ArrayList<TypeParameterMirror>(jdtTypeParameters.length);
for(TypeVariableBinding jdtTypeParameter : jdtTypeParameters)
typeParameters.add(new JDTTypeParameter(jdtTypeParameter));
}
});
}
return typeParameters;
}
public boolean isOverridingMethod() {
if (isOverriding == null) {
isOverriding = false;
doWithBindings(new ActionOnMethodBinding() {
@Override
public void doWithBinding(IType declaringClassModel,
ReferenceBinding declaringClass,
MethodBinding method) {
if (CharOperation.equals(declaringClass.readableName(), "ceylon.language.Identifiable".toCharArray())) {
if ("equals".equals(name)
|| "hashCode".equals(name)) {
isOverriding = true;
return;
}
}
if (CharOperation.equals(declaringClass.readableName(), "ceylon.language.Object".toCharArray())) {
if ("equals".equals(name)
|| "hashCode".equals(name)
|| "toString".equals(name)) {
isOverriding = false;
return;
}
}
// try the superclass first
if (isDefinedInSuperClasses(declaringClass, method)) {
isOverriding = true;
}
if (isDefinedInSuperInterfaces(declaringClass, method)) {
isOverriding = true;
}
}
});
}
return isOverriding.booleanValue();
}
private void doWithBindings(final ActionOnMethodBinding action) {
final IType declaringClassModel = enclosingClass.getType();
if (!JDTModelLoader.doWithMethodBinding(declaringClassModel, bindingRef.get(), action)) {
JDTModelLoader.doWithResolvedType(declaringClassModel, new JDTModelLoader.ActionOnResolvedType() {
@Override
public void doWithBinding(ReferenceBinding declaringClass) {
MethodBinding method = null;
for (MethodBinding m : declaringClass.methods()) {
if (CharOperation.equals(m.computeUniqueKey(), bindingKey)) {
method = m;
break;
}
}
if (method == null) {
throw new ModelResolutionException("Method '" + readableName + "' not found in the binding of class '" + declaringClassModel.getFullyQualifiedName() + "'");
}
bindingRef = new WeakReference<MethodBinding>(method);
action.doWithBinding(declaringClassModel, declaringClass, method);
}
});
}
}
public boolean isOverloadingMethod() {
if (isOverloading == null) {
isOverloading = Boolean.FALSE;
doWithBindings(new ActionOnMethodBinding() {
@Override
public void doWithBinding(IType declaringClassModel,
ReferenceBinding declaringClass,
MethodBinding method) {
// Exception has a pretend supertype of Object, unlike its Java supertype of java.lang.RuntimeException
// so we stop there for it, especially since it does not have any overloading
if(CharOperation.equals(declaringClass.qualifiedSourceName(), "ceylon.language.Exception".toCharArray())) {
isOverloading = false;
return;
}
// try the superclass first
if (isOverloadingInSuperClasses(declaringClass, method)) {
isOverloading = Boolean.TRUE;
}
if (isOverloadingInSuperInterfaces(declaringClass, method)) {
isOverloading = Boolean.TRUE;
}
}
});
}
return isOverloading.booleanValue();
}
private boolean ignoreMethodInAncestorSearch(MethodBinding methodBinding) {
String name = CharOperation.charToString(methodBinding.selector);
if(name.equals("finalize")
|| name.equals("clone")){
if(methodBinding.declaringClass != null && CharOperation.toString(methodBinding.declaringClass.compoundName).equals("java.lang.Object")) {
return true;
}
}
// skip ignored methods too
if(JDTUtils.hasAnnotation(methodBinding, AbstractModelLoader.CEYLON_IGNORE_ANNOTATION)) {
return true;
}
return false;
}
private boolean isDefinedInType(ReferenceBinding superClass, MethodBinding method) {
MethodVerifier methodVerifier = superClass.getPackage().environment.methodVerifier();
for (MethodBinding inheritedMethod : superClass.methods()) {
// skip ignored methods
if(ignoreMethodInAncestorSearch(inheritedMethod)) {
continue;
}
if (methodVerifier.doesMethodOverride(method, inheritedMethod)) {
return true;
}
}
return false;
}
private boolean isOverloadingInType(ReferenceBinding superClass, MethodBinding method) {
MethodVerifier methodVerifier = superClass.getPackage().environment.methodVerifier();
for (MethodBinding inheritedMethod : superClass.methods()) {
if(inheritedMethod.isPrivate()
|| inheritedMethod.isStatic()
|| inheritedMethod.isConstructor()
|| inheritedMethod.isBridge()
|| inheritedMethod.isSynthetic()
|| !Arrays.equals(inheritedMethod.constantPoolName(), method.selector))
continue;
// skip ignored methods
if(ignoreMethodInAncestorSearch(inheritedMethod)) {
continue;
}
// if it does not override it and has the same name, it's overloading
if (!methodVerifier.doesMethodOverride(method, inheritedMethod)) {
return true;
}
}
return false;
}
boolean isDefinedInSuperClasses(ReferenceBinding declaringClass, MethodBinding method) {
ReferenceBinding superClass = declaringClass.superclass();
if (superClass == null) {
return false;
}
superClass = JDTUtils.inferTypeParametersFromSuperClass(declaringClass,
superClass);
if (isDefinedInType(superClass, method)) {
return true;
}
return isDefinedInSuperClasses(superClass, method);
}
boolean isDefinedInSuperInterfaces(ReferenceBinding declaringType, MethodBinding method) {
ReferenceBinding[] superInterfaces = declaringType.superInterfaces();
if (superInterfaces == null) {
return false;
}
for (ReferenceBinding superInterface : superInterfaces) {
if (isDefinedInType(superInterface, method)) {
return true;
}
if (isDefinedInSuperInterfaces(superInterface, method)) {
return true;
}
}
return false;
}
boolean isOverloadingInSuperClasses(ReferenceBinding declaringClass, MethodBinding method) {
ReferenceBinding superClass = declaringClass.superclass();
if (superClass == null) {
return false;
}
// Exception has a pretend supertype of Object, unlike its Java supertype of java.lang.RuntimeException
// so we stop there for it, especially since it does not have any overloading
if(CharOperation.equals(superClass.qualifiedSourceName(), "ceylon.language.Exception".toCharArray()))
return false;
superClass = JDTUtils.inferTypeParametersFromSuperClass(declaringClass,
superClass);
if (isOverloadingInType(superClass, method)) {
return true;
}
return isOverloadingInSuperClasses(superClass, method);
}
boolean isOverloadingInSuperInterfaces(ReferenceBinding declaringType, MethodBinding method) {
ReferenceBinding[] superInterfaces = declaringType.superInterfaces();
if (superInterfaces == null) {
return false;
}
for (ReferenceBinding superInterface : superInterfaces) {
if (isOverloadingInType(superInterface, method)) {
return true;
}
if (isOverloadingInSuperInterfaces(superInterface, method)) {
return true;
}
}
return false;
}
@Override
public boolean isProtected() {
return isProtected;
}
@Override
public boolean isDefaultAccess() {
return isDefaultAccess;
}
@Override
public boolean isDeclaredVoid() {
return isDeclaredVoid;
}
@Override
public boolean isVariadic() {
return isVariadic;
}
@Override
public boolean isDefault() {
return isDefault;
}
@Override
public char[] getBindingKey() {
return bindingKey;
}
@Override
public ClassMirror getEnclosingClass() {
return enclosingClass;
}
} | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_model_mirror_JDTMethod.java |
1,255 | @Deprecated
public interface TaxModule {
public String getName();
public void setName(String name);
public Order calculateTaxForOrder(Order order) throws TaxException;
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_service_module_TaxModule.java |
1,591 | private class DefaultLogger implements ILogger {
final String name;
final ILogger logger;
final boolean addToLoggingService;
DefaultLogger(String name) {
this.name = name;
this.logger = loggerFactory.getLogger(name);
addToLoggingService = (name.equals(ClusterServiceImpl.class.getName()));
}
@Override
public void finest(String message) {
log(Level.FINEST, message);
}
@Override
public void finest(String message, Throwable thrown) {
log(Level.FINEST, message, thrown);
}
@Override
public void finest(Throwable thrown) {
log(Level.FINEST, thrown.getMessage(), thrown);
}
@Override
public boolean isFinestEnabled() {
return isLoggable(Level.FINEST);
}
@Override
public void info(String message) {
log(Level.INFO, message);
}
@Override
public void severe(String message) {
log(Level.SEVERE, message);
}
@Override
public void severe(Throwable thrown) {
log(Level.SEVERE, thrown.getMessage(), thrown);
}
@Override
public void severe(String message, Throwable thrown) {
log(Level.SEVERE, message, thrown);
}
@Override
public void warning(String message) {
log(Level.WARNING, message);
}
@Override
public void warning(Throwable thrown) {
log(Level.WARNING, thrown.getMessage(), thrown);
}
@Override
public void warning(String message, Throwable thrown) {
log(Level.WARNING, message, thrown);
}
@Override
public void log(Level level, String message) {
log(level, message, null);
}
@Override
public void log(Level level, String message, Throwable thrown) {
if (addToLoggingService) {
systemLogService.logNode(message + ((thrown == null) ? "" : ": " + thrown.getMessage()));
}
boolean loggable = logger.isLoggable(level);
if (loggable || level.intValue() >= minLevel.intValue()) {
String logRecordMessage = thisAddressString + " [" + groupName + "] "
+ "[" + buildInfo.getVersion() + "] " + message;
LogRecord logRecord = new LogRecord(level, logRecordMessage);
logRecord.setThrown(thrown);
logRecord.setLoggerName(name);
logRecord.setSourceClassName(name);
LogEvent logEvent = new LogEvent(logRecord, groupName, thisMember);
if (loggable) {
logger.log(logEvent);
}
if (listeners.size() > 0) {
handleLogEvent(logEvent);
}
}
}
@Override
public void log(LogEvent logEvent) {
handleLogEvent(logEvent);
}
@Override
public Level getLevel() {
return logger.getLevel();
}
@Override
public boolean isLoggable(Level level) {
return logger.isLoggable(level);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_logging_LoggingServiceImpl.java |
1,125 | public static class Factory implements NativeScriptFactory {
@Override
public ExecutableScript newScript(@Nullable Map<String, Object> params) {
return new NativeConstantForLoopScoreScript(params);
}
} | 0true
| src_test_java_org_elasticsearch_benchmark_scripts_score_script_NativeConstantForLoopScoreScript.java |
254 | public class OCaseInsensitiveCollate extends ODefaultComparator implements OCollate {
public String getName() {
return "ci";
}
public Object transform(final Object obj) {
if (obj instanceof String)
return ((String) obj).toLowerCase();
return obj;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_collate_OCaseInsensitiveCollate.java |
159 | public abstract class BackendException extends Exception {
private static final long serialVersionUID = 4056436257763972423L;
/**
* @param msg Exception message
*/
public BackendException(String msg) {
super(msg);
}
/**
* @param msg Exception message
* @param cause Cause of the exception
*/
public BackendException(String msg, Throwable cause) {
super(msg, cause);
}
/**
* Constructs an exception with a generic message
*
* @param cause Cause of the exception
*/
public BackendException(Throwable cause) {
this("Exception in storage backend.", cause);
}
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_BackendException.java |
293 | {
@Override
public NodeRecord newUnused( Long key, Void additionalData )
{
return new NodeRecord( key, Record.NO_NEXT_RELATIONSHIP.intValue(),
Record.NO_NEXT_PROPERTY.intValue() );
}
@Override
public NodeRecord load( Long key, Void additionalData )
{
return getNodeStore().getRecord( key );
}
@Override
public void ensureHeavy( NodeRecord record )
{
getNodeStore().ensureHeavy( record );
}
@Override
public NodeRecord clone(NodeRecord nodeRecord)
{
return nodeRecord.clone();
}
}, true ); | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_nioneo_xa_NeoStoreTransaction.java |
1,838 | injector.callInContext(new ContextualCallable<Void>() {
Dependency<?> dependency = Dependency.get(binding.getKey());
public Void call(InternalContext context) {
context.setDependency(dependency);
Errors errorsForBinding = errors.withSource(dependency);
try {
binding.getInternalFactory().get(errorsForBinding, context, dependency);
} catch (ErrorsException e) {
errorsForBinding.merge(e.getErrors());
} finally {
context.setDependency(null);
}
return null;
}
}); | 0true
| src_main_java_org_elasticsearch_common_inject_InjectorBuilder.java |
3,379 | public class PackedArrayIndexFieldData extends AbstractIndexFieldData<AtomicNumericFieldData> implements IndexNumericFieldData<AtomicNumericFieldData> {
public static class Builder implements IndexFieldData.Builder {
private NumericType numericType;
public Builder setNumericType(NumericType numericType) {
this.numericType = numericType;
return this;
}
@Override
public IndexFieldData<AtomicNumericFieldData> build(Index index, @IndexSettings Settings indexSettings, FieldMapper<?> mapper,
IndexFieldDataCache cache, CircuitBreakerService breakerService) {
return new PackedArrayIndexFieldData(index, indexSettings, mapper.names(), mapper.fieldDataType(), cache, numericType, breakerService);
}
}
private final NumericType numericType;
private final CircuitBreakerService breakerService;
public PackedArrayIndexFieldData(Index index, @IndexSettings Settings indexSettings, FieldMapper.Names fieldNames,
FieldDataType fieldDataType, IndexFieldDataCache cache, NumericType numericType,
CircuitBreakerService breakerService) {
super(index, indexSettings, fieldNames, fieldDataType, cache);
Preconditions.checkNotNull(numericType);
Preconditions.checkArgument(EnumSet.of(NumericType.BYTE, NumericType.SHORT, NumericType.INT, NumericType.LONG).contains(numericType), getClass().getSimpleName() + " only supports integer types, not " + numericType);
this.numericType = numericType;
this.breakerService = breakerService;
}
@Override
public NumericType getNumericType() {
return numericType;
}
@Override
public boolean valuesOrdered() {
// because we might have single values? we can dynamically update a flag to reflect that
// based on the atomic field data loaded
return false;
}
@Override
public AtomicNumericFieldData loadDirect(AtomicReaderContext context) throws Exception {
AtomicReader reader = context.reader();
Terms terms = reader.terms(getFieldNames().indexName());
PackedArrayAtomicFieldData data = null;
PackedArrayEstimator estimator = new PackedArrayEstimator(breakerService.getBreaker(), getNumericType());
if (terms == null) {
data = PackedArrayAtomicFieldData.empty(reader.maxDoc());
estimator.adjustForNoTerms(data.getMemorySizeInBytes());
return data;
}
// TODO: how can we guess the number of terms? numerics end up creating more terms per value...
// Lucene encodes numeric data so that the lexicographical (encoded) order matches the integer order so we know the sequence of
// longs is going to be monotonically increasing
final MonotonicAppendingLongBuffer values = new MonotonicAppendingLongBuffer();
final float acceptableTransientOverheadRatio = fieldDataType.getSettings().getAsFloat("acceptable_transient_overhead_ratio", OrdinalsBuilder.DEFAULT_ACCEPTABLE_OVERHEAD_RATIO);
OrdinalsBuilder builder = new OrdinalsBuilder(-1, reader.maxDoc(), acceptableTransientOverheadRatio);
TermsEnum termsEnum = estimator.beforeLoad(terms);
boolean success = false;
try {
BytesRefIterator iter = builder.buildFromTerms(termsEnum);
BytesRef term;
assert !getNumericType().isFloatingPoint();
final boolean indexedAsLong = getNumericType().requiredBits() > 32;
while ((term = iter.next()) != null) {
final long value = indexedAsLong
? NumericUtils.prefixCodedToLong(term)
: NumericUtils.prefixCodedToInt(term);
assert values.size() == 0 || value > values.get(values.size() - 1);
values.add(value);
}
Ordinals build = builder.build(fieldDataType.getSettings());
if (!build.isMultiValued() && CommonSettings.removeOrdsOnSingleValue(fieldDataType)) {
Docs ordinals = build.ordinals();
final FixedBitSet set = builder.buildDocsWithValuesSet();
long minValue, maxValue;
minValue = maxValue = 0;
if (values.size() > 0) {
minValue = values.get(0);
maxValue = values.get(values.size() - 1);
}
// Encode document without a value with a special value
long missingValue = 0;
if (set != null) {
if ((maxValue - minValue + 1) == values.size()) {
// values are dense
if (minValue > Long.MIN_VALUE) {
missingValue = --minValue;
} else {
assert maxValue != Long.MAX_VALUE;
missingValue = ++maxValue;
}
} else {
for (long i = 1; i < values.size(); ++i) {
if (values.get(i) > values.get(i - 1) + 1) {
missingValue = values.get(i - 1) + 1;
break;
}
}
}
missingValue -= minValue; // delta
}
final long delta = maxValue - minValue;
final int bitsRequired = delta < 0 ? 64 : PackedInts.bitsRequired(delta);
final float acceptableOverheadRatio = fieldDataType.getSettings().getAsFloat("acceptable_overhead_ratio", PackedInts.DEFAULT);
final PackedInts.FormatAndBits formatAndBits = PackedInts.fastestFormatAndBits(reader.maxDoc(), bitsRequired, acceptableOverheadRatio);
// there's sweet spot where due to low unique value count, using ordinals will consume less memory
final long singleValuesSize = formatAndBits.format.longCount(PackedInts.VERSION_CURRENT, reader.maxDoc(), formatAndBits.bitsPerValue) * 8L;
final long uniqueValuesSize = values.ramBytesUsed();
final long ordinalsSize = build.getMemorySizeInBytes();
if (uniqueValuesSize + ordinalsSize < singleValuesSize) {
data = new PackedArrayAtomicFieldData.WithOrdinals(values, reader.maxDoc(), build);
} else {
final PackedInts.Mutable sValues = PackedInts.getMutable(reader.maxDoc(), bitsRequired, acceptableOverheadRatio);
if (missingValue != 0) {
sValues.fill(0, sValues.size(), missingValue);
}
for (int i = 0; i < reader.maxDoc(); i++) {
final long ord = ordinals.getOrd(i);
if (ord != Ordinals.MISSING_ORDINAL) {
sValues.set(i, values.get(ord - 1) - minValue);
}
}
if (set == null) {
data = new PackedArrayAtomicFieldData.Single(sValues, minValue, reader.maxDoc(), ordinals.getNumOrds());
} else {
data = new PackedArrayAtomicFieldData.SingleSparse(sValues, minValue, reader.maxDoc(), missingValue, ordinals.getNumOrds());
}
}
} else {
data = new PackedArrayAtomicFieldData.WithOrdinals(values, reader.maxDoc(), build);
}
success = true;
return data;
} finally {
if (!success) {
// If something went wrong, unwind any current estimations we've made
estimator.afterLoad(termsEnum, 0);
} else {
// Adjust as usual, based on the actual size of the field data
estimator.afterLoad(termsEnum, data.getMemorySizeInBytes());
}
builder.close();
}
}
@Override
public XFieldComparatorSource comparatorSource(@Nullable Object missingValue, SortMode sortMode) {
return new LongValuesComparatorSource(this, missingValue, sortMode);
}
/**
* Estimator that wraps numeric field data loading in a
* RamAccountingTermsEnum, adjusting the breaker after data has been
* loaded
*/
public class PackedArrayEstimator implements PerValueEstimator {
private final MemoryCircuitBreaker breaker;
private final NumericType type;
public PackedArrayEstimator(MemoryCircuitBreaker breaker, NumericType type) {
this.breaker = breaker;
this.type = type;
}
/**
* @return number of bytes per term, based on the NumericValue.requiredBits()
*/
@Override
public long bytesPerValue(BytesRef term) {
// Estimate about about 0.8 (8 / 10) compression ratio for
// numbers, but at least 4 bytes
return Math.max(type.requiredBits() / 10, 4);
}
/**
* @return A TermsEnum wrapped in a RamAccountingTermsEnum
* @throws IOException
*/
@Override
public TermsEnum beforeLoad(Terms terms) throws IOException {
return new RamAccountingTermsEnum(type.wrapTermsEnum(terms.iterator(null)), breaker, this);
}
/**
* Adjusts the breaker based on the aggregated value from the RamAccountingTermsEnum
*
* @param termsEnum terms that were wrapped and loaded
* @param actualUsed actual field data memory usage
*/
@Override
public void afterLoad(TermsEnum termsEnum, long actualUsed) {
assert termsEnum instanceof RamAccountingTermsEnum;
long estimatedBytes = ((RamAccountingTermsEnum) termsEnum).getTotalBytes();
breaker.addWithoutBreaking(-(estimatedBytes - actualUsed));
}
/**
* Adjust the breaker when no terms were actually loaded, but the field
* data takes up space regardless. For instance, when ordinals are
* used.
* @param actualUsed bytes actually used
*/
public void adjustForNoTerms(long actualUsed) {
breaker.addWithoutBreaking(actualUsed);
}
}
} | 0true
| src_main_java_org_elasticsearch_index_fielddata_plain_PackedArrayIndexFieldData.java |
3,119 | static final class Fields {
static final XContentBuilderString SEGMENTS = new XContentBuilderString("segments");
static final XContentBuilderString COUNT = new XContentBuilderString("count");
static final XContentBuilderString MEMORY = new XContentBuilderString("memory");
static final XContentBuilderString MEMORY_IN_BYTES = new XContentBuilderString("memory_in_bytes");
} | 0true
| src_main_java_org_elasticsearch_index_engine_SegmentsStats.java |
1,159 | public class BenchmarkMessageRequest extends TransportRequest {
long id;
byte[] payload;
public BenchmarkMessageRequest(long id, byte[] payload) {
this.id = id;
this.payload = payload;
}
public BenchmarkMessageRequest() {
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
id = in.readLong();
payload = new byte[in.readVInt()];
in.readFully(payload);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeLong(id);
out.writeVInt(payload.length);
out.writeBytes(payload);
}
} | 0true
| src_test_java_org_elasticsearch_benchmark_transport_BenchmarkMessageRequest.java |
469 | public interface ClientClusterService {
MemberImpl getMember(Address address);
MemberImpl getMember(String uuid);
Collection<MemberImpl> getMemberList();
Address getMasterAddress();
int getSize();
long getClusterTime();
} | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_spi_ClientClusterService.java |
233 | return new PassageFormatter() {
PassageFormatter defaultFormatter = new DefaultPassageFormatter();
@Override
public String[] format(Passage passages[], String content) {
// Just turns the String snippet into a length 2
// array of String
return new String[] {"blah blah", defaultFormatter.format(passages, content).toString()};
}
}; | 0true
| src_test_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighterTests.java |
674 | OHashFunction<Integer> hashFunction = new OHashFunction<Integer>() {
@Override
public long hashCode(Integer value) {
return Long.MAX_VALUE / 2 + value;
}
}; | 0true
| core_src_test_java_com_orientechnologies_orient_core_index_hashindex_local_LocalHashTableIterationTest.java |
495 | public interface SiteDao {
/**
* Finds a site by its id.
* @param id
* @return
*/
public Site retrieve(Long id);
/**
* Finds a site by its domain or domain prefix.
* @param domain
* @param prefix
* @return
*/
public Site retrieveSiteByDomainOrDomainPrefix(String domain, String prefix);
/**
* Persists the site changes.
* @param site
* @return
*/
public Site save(Site site);
/**
* Returns a default site. This method returns null in the out of box implementation of Broadleaf.
* Extend for implementation specific behavior.
*
* @return
*/
public Site retrieveDefaultSite();
/**
* @return a List of all sites in the system
*/
public List<Site> readAllActiveSites();
} | 0true
| common_src_main_java_org_broadleafcommerce_common_site_dao_SiteDao.java |
748 | public class TxnListAddRequest extends TxnCollectionRequest {
public TxnListAddRequest() {
}
public TxnListAddRequest(String name, Data value) {
super(name, value);
}
@Override
public Object innerCall() throws Exception {
return getEndpoint().getTransactionContext(txnId).getList(name).add(value);
}
@Override
public String getServiceName() {
return ListService.SERVICE_NAME;
}
@Override
public int getClassId() {
return CollectionPortableHook.TXN_LIST_ADD;
}
@Override
public Permission getRequiredPermission() {
return new ListPermission(name, ActionConstants.ACTION_ADD);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_client_TxnListAddRequest.java |
120 | public interface OLAPResult<S> {
/**
* Returns an {@link Iterable} over all final vertex states.
*
* @return
*/
public Iterable<S> values();
/**
* Returns an {@link Iterable} over all final (vertex-id,vertex-state) pairs resulting from a job's execution.
* @return
*/
public Iterable<Map.Entry<Long,S>> entries();
/**
* Returns the number of vertices in the result
* @return
*/
public long size();
/**
* Returns the final vertex state for a given vertex identified by its id.
*
* @param vertexid
* @return
*/
public S get(long vertexid);
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_core_olap_OLAPResult.java |
154 | public class JMSArchivedStructuredContentPublisher implements ArchivedStructuredContentPublisher {
private JmsTemplate archiveStructuredContentTemplate;
private Destination archiveStructuredContentDestination;
@Override
public void processStructuredContentArchive(final StructuredContent sc, final String baseNameKey, final String baseTypeKey) {
archiveStructuredContentTemplate.send(archiveStructuredContentDestination, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
HashMap<String, String> objectMap = new HashMap<String,String>(2);
objectMap.put("nameKey", baseNameKey);
objectMap.put("typeKey", baseTypeKey);
return session.createObjectMessage(objectMap);
}
});
}
public JmsTemplate getArchiveStructuredContentTemplate() {
return archiveStructuredContentTemplate;
}
public void setArchiveStructuredContentTemplate(JmsTemplate archiveStructuredContentTemplate) {
this.archiveStructuredContentTemplate = archiveStructuredContentTemplate;
}
public Destination getArchiveStructuredContentDestination() {
return archiveStructuredContentDestination;
}
public void setArchiveStructuredContentDestination(Destination archiveStructuredContentDestination) {
this.archiveStructuredContentDestination = archiveStructuredContentDestination;
}
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_message_jms_JMSArchivedStructuredContentPublisher.java |
1,766 | map.addEntryListener(new EntryAdapter() {
public void entryEvicted(EntryEvent event) {
latch.countDown();
}
}, false); | 0true
| hazelcast_src_test_java_com_hazelcast_map_EvictionTest.java |
875 | private class AsyncAction extends BaseAsyncAction<QuerySearchResult> {
final AtomicArray<FetchSearchResult> fetchResults;
final AtomicArray<IntArrayList> docIdsToLoad;
private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) {
super(request, listener);
fetchResults = new AtomicArray<FetchSearchResult>(firstResults.length());
docIdsToLoad = new AtomicArray<IntArrayList>(firstResults.length());
}
@Override
protected String firstPhaseName() {
return "query";
}
@Override
protected void sendExecuteFirstPhase(DiscoveryNode node, ShardSearchRequest request, SearchServiceListener<QuerySearchResult> listener) {
searchService.sendExecuteQuery(node, request, listener);
}
@Override
protected void moveToSecondPhase() {
sortedShardList = searchPhaseController.sortDocs(firstResults);
searchPhaseController.fillDocIdsToLoad(docIdsToLoad, sortedShardList);
if (docIdsToLoad.asList().isEmpty()) {
finishHim();
return;
}
final AtomicInteger counter = new AtomicInteger(docIdsToLoad.asList().size());
int localOperations = 0;
for (AtomicArray.Entry<IntArrayList> entry : docIdsToLoad.asList()) {
QuerySearchResult queryResult = firstResults.get(entry.index);
DiscoveryNode node = nodes.get(queryResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
localOperations++;
} else {
FetchSearchRequest fetchSearchRequest = new FetchSearchRequest(request, queryResult.id(), entry.value);
executeFetch(entry.index, queryResult.shardTarget(), counter, fetchSearchRequest, node);
}
}
if (localOperations > 0) {
if (request.operationThreading() == SearchOperationThreading.SINGLE_THREAD) {
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
for (AtomicArray.Entry<IntArrayList> entry : docIdsToLoad.asList()) {
QuerySearchResult queryResult = firstResults.get(entry.index);
DiscoveryNode node = nodes.get(queryResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
FetchSearchRequest fetchSearchRequest = new FetchSearchRequest(request, queryResult.id(), entry.value);
executeFetch(entry.index, queryResult.shardTarget(), counter, fetchSearchRequest, node);
}
}
}
});
} else {
boolean localAsync = request.operationThreading() == SearchOperationThreading.THREAD_PER_SHARD;
for (final AtomicArray.Entry<IntArrayList> entry : docIdsToLoad.asList()) {
final QuerySearchResult queryResult = firstResults.get(entry.index);
final DiscoveryNode node = nodes.get(queryResult.shardTarget().nodeId());
if (node.id().equals(nodes.localNodeId())) {
final FetchSearchRequest fetchSearchRequest = new FetchSearchRequest(request, queryResult.id(), entry.value);
try {
if (localAsync) {
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() {
@Override
public void run() {
executeFetch(entry.index, queryResult.shardTarget(), counter, fetchSearchRequest, node);
}
});
} else {
executeFetch(entry.index, queryResult.shardTarget(), counter, fetchSearchRequest, node);
}
} catch (Throwable t) {
onFetchFailure(t, fetchSearchRequest, entry.index, queryResult.shardTarget(), counter);
}
}
}
}
}
}
void executeFetch(final int shardIndex, final SearchShardTarget shardTarget, final AtomicInteger counter, final FetchSearchRequest fetchSearchRequest, DiscoveryNode node) {
searchService.sendExecuteFetch(node, fetchSearchRequest, new SearchServiceListener<FetchSearchResult>() {
@Override
public void onResult(FetchSearchResult result) {
result.shardTarget(shardTarget);
fetchResults.set(shardIndex, result);
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
@Override
public void onFailure(Throwable t) {
onFetchFailure(t, fetchSearchRequest, shardIndex, shardTarget, counter);
}
});
}
void onFetchFailure(Throwable t, FetchSearchRequest fetchSearchRequest, int shardIndex, SearchShardTarget shardTarget, AtomicInteger counter) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] Failed to execute fetch phase", t, fetchSearchRequest.id());
}
this.addShardFailure(shardIndex, shardTarget, t);
successulOps.decrementAndGet();
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
void finishHim() {
try {
innerFinishHim();
} catch (Throwable e) {
ReduceSearchPhaseException failure = new ReduceSearchPhaseException("fetch", "", e, buildShardFailures());
if (logger.isDebugEnabled()) {
logger.debug("failed to reduce search", failure);
}
listener.onFailure(failure);
} finally {
releaseIrrelevantSearchContexts(firstResults, docIdsToLoad);
}
}
void innerFinishHim() throws Exception {
InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, firstResults, fetchResults);
String scrollId = null;
if (request.scroll() != null) {
scrollId = TransportSearchHelper.buildScrollId(request.searchType(), firstResults, null);
}
listener.onResponse(new SearchResponse(internalResponse, scrollId, expectedSuccessfulOps, successulOps.get(), buildTookInMillis(), buildShardFailures()));
}
} | 1no label
| src_main_java_org_elasticsearch_action_search_type_TransportSearchQueryThenFetchAction.java |
2,017 | @RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class WriteBehindQueueTest extends HazelcastTestSupport {
@Test
public void smoke() {
final WriteBehindQueue<DelayedEntry> queue = WriteBehindQueues.createDefaultWriteBehindQueue(true);
assertEquals(0, queue.size());
}
@Test
public void testOffer() {
final WriteBehindQueue<DelayedEntry> queue = WriteBehindQueues.createDefaultWriteBehindQueue(true);
fillQueue(queue);
assertEquals(3, queue.size());
}
@Test
public void testRemoveEmpty() {
final WriteBehindQueue<DelayedEntry> queue = WriteBehindQueues.createDefaultWriteBehindQueue(true);
queue.removeFirst();
assertEquals(0, queue.size());
}
@Test
public void testClear() {
final WriteBehindQueue<DelayedEntry> queue = WriteBehindQueues.createDefaultWriteBehindQueue(true);
queue.clear();
assertEquals(0, queue.size());
}
@Test
public void testContains() {
final WriteBehindQueue<DelayedEntry> queue = WriteBehindQueues.createDefaultWriteBehindQueue(true);
fillQueue(queue);
assertEquals(false, queue.contains(DelayedEntry.createEmpty()));
}
@Test
public void testClearFull() {
final WriteBehindQueue<DelayedEntry> queue = WriteBehindQueues.createDefaultWriteBehindQueue(true);
fillQueue(queue);
queue.clear();
assertEquals(0, queue.size());
}
@Test
public void testRemoveAll() {
final WriteBehindQueue<DelayedEntry> queue = WriteBehindQueues.createDefaultWriteBehindQueue(true);
final DelayedEntry<Object, Object> e1 = DelayedEntry.createEmpty();
final DelayedEntry<Object, Object> e2 = DelayedEntry.createEmpty();
final DelayedEntry<Object, Object> e3 = DelayedEntry.createEmpty();
queue.offer(e1);
queue.offer(e2);
queue.offer(e3);
queue.removeFirst();
queue.removeFirst();
queue.removeFirst();
assertEquals(0, queue.size());
}
private void fillQueue(WriteBehindQueue queue){
final DelayedEntry<Object, Object> e1 = DelayedEntry.createEmpty();
final DelayedEntry<Object, Object> e2 = DelayedEntry.createEmpty();
final DelayedEntry<Object, Object> e3 = DelayedEntry.createEmpty();
queue.offer(e1);
queue.offer(e2);
queue.offer(e3);
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_map_mapstore_WriteBehindQueueTest.java |
2,657 | class UnicastPingRequestHandler extends BaseTransportRequestHandler<UnicastPingRequest> {
static final String ACTION = "discovery/zen/unicast";
@Override
public UnicastPingRequest newInstance() {
return new UnicastPingRequest();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void messageReceived(UnicastPingRequest request, TransportChannel channel) throws Exception {
channel.sendResponse(handlePingRequest(request));
}
} | 0true
| src_main_java_org_elasticsearch_discovery_zen_ping_unicast_UnicastZenPing.java |
51 | public final class RefinementCompletionProposal extends CompletionProposal {
final class ReturnValueContextInfo implements IContextInformation {
@Override
public String getInformationDisplayString() {
if (declaration instanceof TypedDeclaration) {
return getType().getProducedTypeName(getUnit());
}
else {
return null;
}
}
@Override
public Image getImage() {
return getImageForDeclaration(declaration);
}
@Override
public String getContextDisplayString() {
return "Return value of '" + declaration.getName() + "'";
}
}
public static Image DEFAULT_REFINEMENT = CeylonPlugin.getInstance()
.getImageRegistry().get(CEYLON_DEFAULT_REFINEMENT);
public static Image FORMAL_REFINEMENT = CeylonPlugin.getInstance()
.getImageRegistry().get(CEYLON_FORMAL_REFINEMENT);
static void addRefinementProposal(int offset, final Declaration dec,
ClassOrInterface ci, Node node, Scope scope, String prefix,
CeylonParseController cpc, IDocument doc,
List<ICompletionProposal> result, boolean preamble) {
boolean isInterface = scope instanceof Interface;
ProducedReference pr = getRefinedProducedReference(scope, dec);
Unit unit = node.getUnit();
result.add(new RefinementCompletionProposal(offset, prefix, pr,
getRefinementDescriptionFor(dec, pr, unit),
getRefinementTextFor(dec, pr, unit, isInterface, ci,
getDefaultLineDelimiter(doc) + getIndent(node, doc),
true, preamble),
cpc, dec, scope, false, true));
}
static void addNamedArgumentProposal(int offset, String prefix,
CeylonParseController cpc, List<ICompletionProposal> result,
Declaration dec, Scope scope) {
//TODO: type argument substitution using the ProducedReference of the primary node
Unit unit = cpc.getRootNode().getUnit();
result.add(new RefinementCompletionProposal(offset, prefix,
dec.getReference(), //TODO: this needs to do type arg substitution
getDescriptionFor(dec, unit),
getTextFor(dec, unit) + " = nothing;",
cpc, dec, scope, true, false));
}
static void addInlineFunctionProposal(int offset, Declaration dec,
Scope scope, Node node, String prefix, CeylonParseController cpc,
IDocument doc, List<ICompletionProposal> result) {
//TODO: type argument substitution using the ProducedReference of the primary node
if (dec.isParameter()) {
Parameter p = ((MethodOrValue) dec).getInitializerParameter();
Unit unit = node.getUnit();
result.add(new RefinementCompletionProposal(offset, prefix,
dec.getReference(), //TODO: this needs to do type arg substitution
getInlineFunctionDescriptionFor(p, null, unit),
getInlineFunctionTextFor(p, null, unit,
getDefaultLineDelimiter(doc) + getIndent(node, doc)),
cpc, dec, scope, false, false));
}
}
public static ProducedReference getRefinedProducedReference(Scope scope,
Declaration d) {
return refinedProducedReference(scope.getDeclaringType(d), d);
}
public static ProducedReference getRefinedProducedReference(ProducedType superType,
Declaration d) {
if (superType.getDeclaration() instanceof IntersectionType) {
for (ProducedType pt: superType.getDeclaration().getSatisfiedTypes()) {
ProducedReference result = getRefinedProducedReference(pt, d);
if (result!=null) return result;
}
return null; //never happens?
}
else {
ProducedType declaringType =
superType.getDeclaration().getDeclaringType(d);
if (declaringType==null) return null;
ProducedType outerType =
superType.getSupertype(declaringType.getDeclaration());
return refinedProducedReference(outerType, d);
}
}
private static ProducedReference refinedProducedReference(ProducedType outerType,
Declaration d) {
List<ProducedType> params = new ArrayList<ProducedType>();
if (d instanceof Generic) {
for (TypeParameter tp: ((Generic) d).getTypeParameters()) {
params.add(tp.getType());
}
}
return d.getProducedReference(outerType, params);
}
private final CeylonParseController cpc;
private final Declaration declaration;
private final ProducedReference pr;
private final boolean fullType;
private final Scope scope;
private boolean explicitReturnType;
private RefinementCompletionProposal(int offset, String prefix,
ProducedReference pr, String desc, String text,
CeylonParseController cpc, Declaration dec, Scope scope,
boolean fullType, boolean explicitReturnType) {
super(offset, prefix, getRefinementIcon(dec), desc, text);
this.cpc = cpc;
this.declaration = dec;
this.pr = pr;
this.fullType = fullType;
this.scope = scope;
this.explicitReturnType = explicitReturnType;
}
private Unit getUnit() {
return cpc.getRootNode().getUnit();
}
@Override
public StyledString getStyledDisplayString() {
StyledString result = new StyledString();
String string = getDisplayString();
if (string.startsWith("shared actual")) {
result.append(string.substring(0,13), Highlights.ANN_STYLER);
string=string.substring(13);
}
Highlights.styleProposal(result, string, false);
return result;
}
private ProducedType getType() {
return fullType ?
pr.getFullType() :
pr.getType();
}
@Override
public Point getSelection(IDocument document) {
int loc = text.indexOf("nothing;");
int length;
int start;
if (loc<0) {
start = offset + text.length()-prefix.length();
if (text.endsWith("{}")) start--;
length = 0;
}
else {
start = offset + loc-prefix.length();
length = 7;
}
return new Point(start, length);
}
@Override
public void apply(IDocument document) {
try {
createChange(document).perform(new NullProgressMonitor());
}
catch (Exception e) {
e.printStackTrace();
}
if (EditorsUI.getPreferenceStore()
.getBoolean(LINKED_MODE)) {
enterLinkedMode(document);
}
}
private DocumentChange createChange(IDocument document)
throws BadLocationException {
DocumentChange change =
new DocumentChange("Complete Refinement", document);
change.setEdit(new MultiTextEdit());
HashSet<Declaration> decs = new HashSet<Declaration>();
Tree.CompilationUnit cu = cpc.getRootNode();
if (explicitReturnType) {
importSignatureTypes(declaration, cu, decs);
}
else {
importParameterTypes(declaration, cu, decs);
}
int il=applyImports(change, decs, cu, document);
change.addEdit(createEdit(document));
offset+=il;
return change;
}
public String getAdditionalProposalInfo() {
return getDocumentationFor(cpc, declaration);
}
public void enterLinkedMode(IDocument document) {
try {
final int loc = offset-prefix.length();
int pos = text.indexOf("nothing");
if (pos>0) {
final LinkedModeModel linkedModeModel =
new LinkedModeModel();
List<ICompletionProposal> props =
new ArrayList<ICompletionProposal>();
addProposals(loc+pos, props, prefix);
ProposalPosition linkedPosition =
new ProposalPosition(document,
loc+pos, 7, 0,
props.toArray(NO_COMPLETIONS));
LinkedMode.addLinkedPosition(linkedModeModel, linkedPosition);
LinkedMode.installLinkedMode((CeylonEditor) EditorUtil.getCurrentEditor(),
document, linkedModeModel, this, new LinkedMode.NullExitPolicy(),
1, loc+text.length());
}
}
catch (Exception e) {
e.printStackTrace();
}
}
@Override
public IContextInformation getContextInformation() {
return new ReturnValueContextInfo();
}
@Override
public boolean validate(IDocument document, int offset, DocumentEvent event) {
if (offset<this.offset) {
return false;
}
try {
int start = this.offset-prefix.length();
String typedText = document.get(start, offset-start);
return isNameMatching(typedText, declaration.getName());
}
catch (BadLocationException e) {
return false;
}
}
private void addProposals(final int loc,
List<ICompletionProposal> props, String prefix) {
ProducedType type = getType();
if (type==null) return;
TypeDeclaration td = type.getDeclaration();
for (DeclarationWithProximity dwp:
getSortedProposedValues(scope, getUnit())) {
if (dwp.isUnimported()) {
//don't propose unimported stuff b/c adding
//imports drops us out of linked mode and
//because it results in a pause
continue;
}
Declaration d = dwp.getDeclaration();
final String name = d.getName();
String[] split = prefix.split("\\s+");
if (split.length>0 &&
name.equals(split[split.length-1])) {
continue;
}
if (d instanceof Value && !d.equals(declaration)) {
Value value = (Value) d;
if (d.getUnit().getPackage().getNameAsString()
.equals(Module.LANGUAGE_MODULE_NAME)) {
if (isIgnoredLanguageModuleValue(value)) {
continue;
}
}
ProducedType vt = value.getType();
if (vt!=null && !vt.isNothing() &&
((td instanceof TypeParameter) &&
isInBounds(((TypeParameter)td).getSatisfiedTypes(), vt) ||
vt.isSubtypeOf(type))) {
props.add(new NestedCompletionProposal(d, loc));
}
}
if (d instanceof Method && !d.equals(declaration)) {
if (!d.isAnnotation()) {
Method method = (Method) d;
if (d.getUnit().getPackage().getNameAsString()
.equals(Module.LANGUAGE_MODULE_NAME)) {
if (isIgnoredLanguageModuleMethod(method)) {
continue;
}
}
ProducedType mt = method.getType();
if (mt!=null && !mt.isNothing() &&
((td instanceof TypeParameter) &&
isInBounds(((TypeParameter)td).getSatisfiedTypes(), mt) ||
mt.isSubtypeOf(type))) {
props.add(new NestedCompletionProposal(d, loc));
}
}
}
if (d instanceof Class) {
Class clazz = (Class) d;
if (!clazz.isAbstract() && !d.isAnnotation()) {
if (d.getUnit().getPackage().getNameAsString()
.equals(Module.LANGUAGE_MODULE_NAME)) {
if (isIgnoredLanguageModuleClass(clazz)) {
continue;
}
}
ProducedType ct = clazz.getType();
if (ct!=null && !ct.isNothing() &&
((td instanceof TypeParameter) &&
isInBounds(((TypeParameter)td).getSatisfiedTypes(), ct) ||
ct.getDeclaration().equals(type.getDeclaration()) ||
ct.isSubtypeOf(type))) {
props.add(new NestedCompletionProposal(d, loc));
}
}
}
}
}
final class NestedCompletionProposal implements ICompletionProposal,
ICompletionProposalExtension2 {
private final Declaration dec;
private final int offset;
public NestedCompletionProposal(Declaration dec, int offset) {
super();
this.dec = dec;
this.offset = offset;
}
@Override
public void apply(IDocument document) {
try {
int len = 0;
while (isJavaIdentifierPart(document.getChar(offset+len))) {
len++;
}
document.replace(offset, len, getText(false));
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public String getDisplayString() {
return getText(true);
}
@Override
public Image getImage() {
return getImageForDeclaration(dec);
}
@Override
public IContextInformation getContextInformation() {
return null;
}
private String getText(boolean description) {
StringBuilder sb = new StringBuilder()
.append(dec.getName());
if (dec instanceof Functional) {
appendPositionalArgs(dec, getUnit(),
sb, false, description);
}
return sb.toString();
}
@Override
public void apply(ITextViewer viewer, char trigger,
int stateMask, int offset) {
apply(viewer.getDocument());
}
@Override
public void selected(ITextViewer viewer, boolean smartToggle) {}
@Override
public void unselected(ITextViewer viewer) {}
@Override
public boolean validate(IDocument document, int currentOffset,
DocumentEvent event) {
if (event==null) {
return true;
}
else {
try {
String content = document.get(offset,
currentOffset-offset);
String filter = content.trim().toLowerCase();
if ((dec.getName().toLowerCase())
.startsWith(filter)) {
return true;
}
}
catch (BadLocationException e) {
// ignore concurrently modified document
}
return false;
}
}
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_RefinementCompletionProposal.java |
1,738 | map.executeOnKeys(keys, new AbstractEntryProcessor() {
@Override
public Object process(Map.Entry entry) {
entry.setValue("newValue");
return 5;
}
}); | 0true
| hazelcast_src_test_java_com_hazelcast_map_EntryProcessorTest.java |
641 | @Component("blResourceBundleProcessor")
public class ResourceBundleProcessor extends AbstractElementProcessor {
@Resource(name = "blResourceBundlingService")
protected ResourceBundlingService bundlingService;
@Value("${bundle.enabled}")
protected boolean bundleEnabled;
public ResourceBundleProcessor() {
super("bundle");
}
@Override
public int getPrecedence() {
return 10000;
}
@Override
protected ProcessorResult processElement(Arguments arguments, Element element) {
String name = element.getAttributeValue("name");
String mappingPrefix = element.getAttributeValue("mapping-prefix");
NestableNode parent = element.getParent();
List<String> files = new ArrayList<String>();
for (String file : element.getAttributeValue("files").split(",")) {
files.add(file.trim());
}
if (bundleEnabled) {
String versionedBundle = bundlingService.getVersionedBundleName(name);
if (StringUtils.isBlank(versionedBundle)) {
BroadleafResourceHttpRequestHandler reqHandler = getRequestHandler(name, arguments);
try {
versionedBundle = bundlingService.registerBundle(name, files, reqHandler);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
String value = (String) StandardExpressionProcessor.processExpression(arguments, "@{'" + mappingPrefix + versionedBundle + "'}");
Element e = getElement(value);
parent.insertAfter(element, e);
} else {
List<String> additionalBundleFiles = bundlingService.getAdditionalBundleFiles(name);
if (additionalBundleFiles != null) {
files.addAll(additionalBundleFiles);
}
for (String file : files) {
file = file.trim();
String value = (String) StandardExpressionProcessor.processExpression(arguments, "@{'" + mappingPrefix + file + "'}");
Element e = getElement(value);
parent.insertBefore(element, e);
}
}
parent.removeChild(element);
return ProcessorResult.OK;
}
protected Element getScriptElement(String src) {
Element e = new Element("script");
e.setAttribute("type", "text/javascript");
e.setAttribute("src", src);
return e;
}
protected Element getLinkElement(String src) {
Element e = new Element("link");
e.setAttribute("rel", "stylesheet");
e.setAttribute("href", src);
return e;
}
protected Element getElement(String src) {
if (src.contains(";")) {
src = src.substring(0, src.indexOf(';'));
}
if (src.endsWith(".js")) {
return getScriptElement(src);
} else if (src.endsWith(".css")) {
return getLinkElement(src);
} else {
throw new IllegalArgumentException("Unknown extension for: " + src + " - only .js and .css are supported");
}
}
protected BroadleafResourceHttpRequestHandler getRequestHandler(String name, Arguments arguments) {
BroadleafResourceHttpRequestHandler handler = null;
if (name.endsWith(".js")) {
handler = ProcessorUtils.getJsRequestHandler(arguments);
} else if (name.endsWith(".css")) {
handler = ProcessorUtils.getCssRequestHandler(arguments);
}
if (handler == null) {
throw new IllegalArgumentException("Unknown extension for: " + name + " - only .js and .css are supported");
}
return handler;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_web_processor_ResourceBundleProcessor.java |
1,520 | public class OJPAEntityManagerFactory implements EntityManagerFactory {
/** the log used by this class. */
private static Logger logger = Logger.getLogger(OJPAPersistenceProvider.class.getName());
private boolean opened = true;
private final List<OJPAEntityManager> instances = new ArrayList<OJPAEntityManager>();
private final OJPAProperties properties;
public OJPAEntityManagerFactory(final OJPAProperties properties) {
this.properties = properties;
if (logger.isLoggable(Level.INFO)) {
logger.info("EntityManagerFactory created. " + toString());
}
}
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public EntityManager createEntityManager(final Map map) {
return createEntityManager(new OJPAProperties(map));
}
@Override
public EntityManager createEntityManager() {
return createEntityManager(properties);
}
private EntityManager createEntityManager(final OJPAProperties properties) {
final OJPAEntityManager newInstance = new OJPAEntityManager(this, properties);
instances.add(newInstance);
return newInstance;
}
@Override
public void close() {
for (OJPAEntityManager instance : instances) {
instance.close();
}
instances.clear();
opened = false;
if (logger.isLoggable(Level.INFO)) {
logger.info("EntityManagerFactory closed. " + toString());
}
}
@Override
public boolean isOpen() {
return opened;
}
@Override
public CriteriaBuilder getCriteriaBuilder() {
throw new UnsupportedOperationException("getCriteriaBuilder");
}
@Override
public Metamodel getMetamodel() {
throw new UnsupportedOperationException("getMetamodel");
}
@Override
public Map<String, Object> getProperties() {
return properties.getUnmodifiableProperties();
}
@Override
public Cache getCache() {
throw new UnsupportedOperationException("getCache");
}
@Override
public PersistenceUnitUtil getPersistenceUnitUtil() {
throw new UnsupportedOperationException("getPersistenceUnitUtil");
}
} | 0true
| object_src_main_java_com_orientechnologies_orient_object_jpa_OJPAEntityManagerFactory.java |
1,057 | public class ListenerConfig {
protected String className = null;
protected EventListener implementation = null;
private ListenerConfigReadOnly readOnly;
/**
* Creates a ListenerConfig without className/implementation.
*/
public ListenerConfig() {
}
/**
* Creates a ListenerConfig with the given className.
*
* @param className the name of the EventListener class.
* @throws IllegalArgumentException if className is null or an empty String.
*/
public ListenerConfig(String className) {
setClassName(className);
}
public ListenerConfig(ListenerConfig config) {
implementation = config.getImplementation();
className = config.getClassName();
}
/**
* Creates a ListenerConfig with the given implementation.
*
* @param implementation the implementation to use as EventListener.
* @throws IllegalArgumentException if the implementation is null.
*/
public ListenerConfig(EventListener implementation) {
this.implementation = isNotNull(implementation,"implementation");
}
public ListenerConfig getAsReadOnly() {
if (readOnly == null) {
readOnly = new ListenerConfigReadOnly(this);
}
return readOnly;
}
/**
* Returns the name of the class of the EventListener. If no class is specified, null is returned.
*
* @return the class name of the EventListener.
* @see #setClassName(String)
*/
public String getClassName() {
return className;
}
/**
* Sets the class name of the EventListener.
*
* If a implementation was set, it will be removed.
*
* @param className the name of the class of the EventListener.
* @return the updated ListenerConfig.
* @throws IllegalArgumentException if className is null or an empty String.
* @see #setImplementation(java.util.EventListener)
* @see #getClassName()
*/
public ListenerConfig setClassName(String className) {
this.className = hasText(className, "className");
this.implementation = null;
return this;
}
/**
* Returns the EventListener implementation. If none has been specified, null is returned.
*
* @return the EventListener implementation.
* @see #setImplementation(java.util.EventListener)
*/
public EventListener getImplementation() {
return implementation;
}
/**
* Sets the EventListener implementation.
*
* If a className was set, it will be removed.
*
* @param implementation the EventListener implementation.
* @return the updated ListenerConfig.
* @throws IllegalArgumentException the implementation is null.
* @see #setClassName(String)
* @see #getImplementation()
*/
public ListenerConfig setImplementation(EventListener implementation) {
this.implementation = isNotNull(implementation,"implementation");
this.className = null;
return this;
}
public boolean isIncludeValue() {
return true;
}
public boolean isLocal() {
return false;
}
@Override
public String toString() {
return "ListenerConfig [className=" + className + ", implementation=" + implementation + ", includeValue="
+ isIncludeValue() + ", local=" + isLocal() + "]";
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_config_ListenerConfig.java |
1,425 | public abstract class AbstractDynamicSkuPricingFilter implements DynamicSkuPricingFilter {
public void destroy() {
//do nothing
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
SkuPricingConsiderationContext.setSkuPricingConsiderationContext(getPricingConsiderations(request));
SkuPricingConsiderationContext.setSkuPricingService(getDynamicSkuPricingService(request));
filterChain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
//do nothing
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_catalog_AbstractDynamicSkuPricingFilter.java |
1,616 | public class OFixUpdateRecordTask extends OAbstractRemoteTask {
private static final long serialVersionUID = 1L;
private ORecordId rid;
private byte[] content;
private ORecordVersion version;
public OFixUpdateRecordTask() {
}
public OFixUpdateRecordTask(final ORecordId iRid, final byte[] iContent, final ORecordVersion iVersion) {
rid = iRid;
content = iContent;
version = iVersion;
}
@Override
public Object execute(final OServer iServer, ODistributedServerManager iManager, final ODatabaseDocumentTx database)
throws Exception {
ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN,
"fixing update record %s/%s v.%s", database.getName(), rid.toString(), version.toString());
final ORecordInternal<?> record = rid.getRecord();
if (record == null)
// DELETED, CANNOT FIX IT
return Boolean.FALSE;
final ORecordInternal<?> newRecord = Orient.instance().getRecordFactoryManager().newInstance(record.getRecordType());
newRecord.fill(rid, version, content, true);
((ODocument) record).merge((ODocument) newRecord, false, false);
database.save(record);
ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN,
"+-> fixed update record %s/%s v.%s", database.getName(), record.getIdentity().toString(), record.getRecordVersion()
.toString());
return Boolean.TRUE;
}
public QUORUM_TYPE getQuorumType() {
return QUORUM_TYPE.NONE;
}
@Override
public void writeExternal(final ObjectOutput out) throws IOException {
out.writeUTF(rid.toString());
out.writeInt(content.length);
out.write(content);
if (version == null)
version = OVersionFactory.instance().createUntrackedVersion();
version.getSerializer().writeTo(out, version);
}
@Override
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
rid = new ORecordId(in.readUTF());
final int contentSize = in.readInt();
content = new byte[contentSize];
in.readFully(content);
if (version == null)
version = OVersionFactory.instance().createUntrackedVersion();
version.getSerializer().readFrom(in, version);
}
@Override
public String getName() {
return "fix_record_update";
}
} | 0true
| server_src_main_java_com_orientechnologies_orient_server_distributed_task_OFixUpdateRecordTask.java |
1,119 | @Deprecated
public class LegacyMergeCartServiceImpl implements MergeCartService {
@Resource(name = "blOfferDao")
private OfferDao offerDao;
@Resource(name = "blOrderService")
private OrderService orderService;
@Resource(name = "blOrderItemService")
private OrderItemService orderItemService;
@Resource(name = "blOfferService")
private OfferService offerService;
@Resource(name = "blFulfillmentGroupService")
protected FulfillmentGroupService fulfillmentGroupService;
@Override
public MergeCartResponse mergeCart(Customer customer, Order anonymousCart) throws PricingException {
return mergeCart(customer, anonymousCart, true);
}
@Override
public ReconstructCartResponse reconstructCart(Customer customer) throws PricingException {
return reconstructCart(customer, true);
}
@Override
public MergeCartResponse mergeCart(Customer customer, Order anonymousCart, boolean priceOrder) throws PricingException {
MergeCartResponse mergeCartResponse = new MergeCartResponse();
// reconstruct cart items (make sure they are valid)
ReconstructCartResponse reconstructCartResponse = reconstructCart(customer, false);
mergeCartResponse.setRemovedItems(reconstructCartResponse.getRemovedItems());
Order customerCart = reconstructCartResponse.getOrder();
if (anonymousCart != null && customerCart != null && anonymousCart.getId().equals(customerCart.getId())) {
/*
* Set merged to false if the cart ids are equal (cookied customer
* logs in).
*/
mergeCartResponse.setMerged(false);
} else {
/*
* Set the response to merged if the saved cart has any items
* available to merge in.
*/
mergeCartResponse.setMerged(customerCart != null && customerCart.getOrderItems().size() > 0);
}
// add anonymous cart items (make sure they are valid)
if (anonymousCart != null && (customerCart == null || !customerCart.getId().equals(anonymousCart.getId()))) {
if (anonymousCart != null && anonymousCart.getOrderItems() != null && !anonymousCart.getOrderItems().isEmpty()) {
if (customerCart == null) {
customerCart = orderService.createNewCartForCustomer(customer);
}
Map<OrderItem, OrderItem> oldNewItemMap = new HashMap<OrderItem, OrderItem>();
customerCart = mergeRegularOrderItems(anonymousCart, mergeCartResponse, customerCart, oldNewItemMap);
customerCart = mergeOfferCodes(anonymousCart, customerCart);
customerCart = removeExpiredGiftWrapOrderItems(mergeCartResponse, customerCart, oldNewItemMap);
customerCart = mergeGiftWrapOrderItems(mergeCartResponse, customerCart, oldNewItemMap);
orderService.cancelOrder(anonymousCart);
}
}
// copy the customer's email to this order, overriding any previously set email
if (customerCart != null && StringUtils.isNotBlank(customer.getEmailAddress())) {
customerCart.setEmailAddress(customer.getEmailAddress());
customerCart = orderService.save(customerCart, priceOrder);
}
mergeCartResponse.setOrder(customerCart);
return mergeCartResponse;
}
@Override
public ReconstructCartResponse reconstructCart(Customer customer, boolean priceOrder) throws PricingException {
ReconstructCartResponse reconstructCartResponse = new ReconstructCartResponse();
Order customerCart = orderService.findCartForCustomer(customer);
if (customerCart != null) {
List<OrderItem> itemsToRemove = new ArrayList<OrderItem>();
for (OrderItem orderItem : customerCart.getOrderItems()) {
if (orderItem instanceof DiscreteOrderItem) {
DiscreteOrderItem discreteOrderItem = (DiscreteOrderItem) orderItem;
if (discreteOrderItem.getSku().getActiveStartDate() != null) {
if (!discreteOrderItem.getSku().isActive(
discreteOrderItem.getProduct(),
orderItem.getCategory())) {
itemsToRemove.add(orderItem);
}
} else {
if (!discreteOrderItem.getProduct().isActive() || !orderItem.getCategory().isActive()) {
itemsToRemove.add(orderItem);
}
}
} else if (orderItem instanceof BundleOrderItem) {
BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItem;
boolean removeBundle = false;
for (DiscreteOrderItem discreteOrderItem : bundleOrderItem
.getDiscreteOrderItems()) {
if (discreteOrderItem.getSku().getActiveStartDate() != null) {
if (!discreteOrderItem.getSku().isActive(
discreteOrderItem.getProduct(),
orderItem.getCategory())) {
/*
* Bundle has an inactive item in it -- remove the
* whole bundle
*/
removeBundle = true;
break;
}
} else {
if (!discreteOrderItem.getProduct().isActive() || !orderItem.getCategory().isActive()) {
removeBundle = true;
break;
}
}
}
if (removeBundle) {
itemsToRemove.add(orderItem);
}
}
}
//Remove any giftwrap items who have one or more wrapped item members that have been removed
for (OrderItem orderItem : customerCart.getOrderItems()) {
if (orderItem instanceof GiftWrapOrderItem) {
for (OrderItem wrappedItem : ((GiftWrapOrderItem) orderItem).getWrappedItems()) {
if (itemsToRemove.contains(wrappedItem)) {
itemsToRemove.add(orderItem);
break;
}
}
}
}
for (OrderItem item : itemsToRemove) {
removeItemFromOrder(customerCart, item, priceOrder);
}
reconstructCartResponse.setRemovedItems(itemsToRemove);
}
reconstructCartResponse.setOrder(customerCart);
return reconstructCartResponse;
}
protected Order mergeGiftWrapOrderItems(MergeCartResponse mergeCartResponse, Order customerCart, Map<OrderItem, OrderItem> oldNewItemMap) throws PricingException {
//update any remaining gift wrap items with their cloned wrapped item values, instead of the originals
Iterator<OrderItem> addedItems = mergeCartResponse.getAddedItems().iterator();
while (addedItems.hasNext()) {
OrderItem addedItem = addedItems.next();
if (addedItem instanceof GiftWrapOrderItem) {
GiftWrapOrderItem giftItem = (GiftWrapOrderItem) addedItem;
List<OrderItem> itemsToAdd = new ArrayList<OrderItem>();
Iterator<OrderItem> wrappedItems = giftItem.getWrappedItems().iterator();
while (wrappedItems.hasNext()) {
OrderItem wrappedItem = wrappedItems.next();
if (oldNewItemMap.containsKey(wrappedItem)) {
OrderItem newItem = oldNewItemMap.get(wrappedItem);
newItem.setGiftWrapOrderItem(giftItem);
itemsToAdd.add(newItem);
wrappedItem.setGiftWrapOrderItem(null);
wrappedItems.remove();
}
}
giftItem.getWrappedItems().addAll(itemsToAdd);
} else if (addedItem instanceof BundleOrderItem) {
//a GiftWrapOrderItem inside a BundleOrderItem can only wrap other members of that bundle
//or root members of the order - not members of an entirely different bundle
boolean isValidBundle = true;
Map<String, DiscreteOrderItem> newItemsMap = new HashMap<String, DiscreteOrderItem>();
for (DiscreteOrderItem newItem : ((BundleOrderItem) addedItem).getDiscreteOrderItems()){
newItemsMap.put(newItem.getSku().getId() + "_" + newItem.getPrice(), newItem);
}
checkBundle: {
for (DiscreteOrderItem itemFromBundle : ((BundleOrderItem) addedItem).getDiscreteOrderItems()) {
if (itemFromBundle instanceof GiftWrapOrderItem) {
GiftWrapOrderItem giftItem = (GiftWrapOrderItem) itemFromBundle;
List<OrderItem> itemsToAdd = new ArrayList<OrderItem>();
Iterator<OrderItem> wrappedItems = giftItem.getWrappedItems().iterator();
while (wrappedItems.hasNext()) {
OrderItem wrappedItem = wrappedItems.next();
if (oldNewItemMap.containsKey(wrappedItem)) {
OrderItem newItem = oldNewItemMap.get(wrappedItem);
newItem.setGiftWrapOrderItem(giftItem);
itemsToAdd.add(newItem);
wrappedItem.setGiftWrapOrderItem(null);
wrappedItems.remove();
} else if (wrappedItem instanceof DiscreteOrderItem) {
DiscreteOrderItem discreteWrappedItem = (DiscreteOrderItem) wrappedItem;
String itemKey = discreteWrappedItem.getSku().getId() + "_" + discreteWrappedItem.getPrice();
if (newItemsMap.containsKey(itemKey)) {
OrderItem newItem = newItemsMap.get(itemKey);
newItem.setGiftWrapOrderItem(giftItem);
itemsToAdd.add(newItem);
discreteWrappedItem.setGiftWrapOrderItem(null);
wrappedItems.remove();
} else {
isValidBundle = false;
break checkBundle;
}
} else {
isValidBundle = false;
break checkBundle;
}
}
giftItem.getWrappedItems().addAll(itemsToAdd);
}
}
}
if (!isValidBundle) {
customerCart = removeItemFromOrder(customerCart, addedItem, false);
addedItems.remove();
mergeCartResponse.getRemovedItems().add(addedItem);
}
}
}
//Go through any remaining bundles and check their DiscreteOrderItem instances for GiftWrapOrderItem references without a local GiftWrapOrderItem
//If found, remove, because this is invalid. A GiftWrapOrderItem cannot wrap OrderItems located in an entirely different bundle.
for (OrderItem addedItem : mergeCartResponse.getAddedItems()) {
if (addedItem instanceof BundleOrderItem) {
boolean containsGiftWrap = false;
for (DiscreteOrderItem discreteOrderItem : ((BundleOrderItem) addedItem).getDiscreteOrderItems()) {
if (discreteOrderItem instanceof GiftWrapOrderItem) {
containsGiftWrap = true;
break;
}
}
if (!containsGiftWrap) {
for (DiscreteOrderItem discreteOrderItem : ((BundleOrderItem) addedItem).getDiscreteOrderItems()) {
discreteOrderItem.setGiftWrapOrderItem(null);
}
}
}
}
return customerCart;
}
protected Order removeExpiredGiftWrapOrderItems(MergeCartResponse mergeCartResponse, Order customerCart, Map<OrderItem, OrderItem> oldNewItemMap) throws PricingException {
//clear out any Gift Wrap items that contain one or more removed wrapped items
Iterator<OrderItem> addedItems = mergeCartResponse.getAddedItems().iterator();
while (addedItems.hasNext()) {
OrderItem addedItem = addedItems.next();
if (addedItem instanceof GiftWrapOrderItem) {
GiftWrapOrderItem giftWrapOrderItem = (GiftWrapOrderItem) addedItem;
boolean removeItem = false;
for (OrderItem wrappedItem : giftWrapOrderItem.getWrappedItems()) {
if (mergeCartResponse.getRemovedItems().contains(wrappedItem)) {
removeItem = true;
break;
}
}
if (removeItem) {
for (OrderItem wrappedItem : giftWrapOrderItem.getWrappedItems()) {
wrappedItem.setGiftWrapOrderItem(null);
}
giftWrapOrderItem.getWrappedItems().clear();
for (OrderItem cartItem : customerCart.getOrderItems()) {
if (cartItem.getGiftWrapOrderItem() != null && oldNewItemMap.containsKey(cartItem.getGiftWrapOrderItem())) {
cartItem.setGiftWrapOrderItem(null);
}
}
customerCart = removeItemFromOrder(customerCart, giftWrapOrderItem, false);
addedItems.remove();
mergeCartResponse.getRemovedItems().add(giftWrapOrderItem);
}
}
}
return customerCart;
}
protected Order mergeOfferCodes(Order anonymousCart, Order customerCart) {
// add all offers from anonymous order
Map<String, OfferCode> customerOffersMap = new HashMap<String, OfferCode>();
for (OfferCode customerOffer : customerCart.getAddedOfferCodes()) {
customerOffersMap.put(customerOffer.getOfferCode(), customerOffer);
}
for (OfferCode anonymousOffer : anonymousCart.getAddedOfferCodes()) {
if (!customerOffersMap.containsKey(anonymousOffer.getOfferCode())) {
OfferCode transferredCode = offerService.lookupOfferCodeByCode(anonymousOffer.getOfferCode());
OfferInfo info = anonymousCart.getAdditionalOfferInformation().get(anonymousOffer.getOffer());
OfferInfo offerInfo = offerDao.createOfferInfo();
for (String key : info.getFieldValues().keySet()) {
offerInfo.getFieldValues().put(key, info.getFieldValues().get(key));
}
customerCart.getAdditionalOfferInformation().put(transferredCode.getOffer(), offerInfo);
customerCart.addOfferCode(transferredCode);
}
}
return customerCart;
}
protected Order mergeRegularOrderItems(Order anonymousCart, MergeCartResponse mergeCartResponse, Order customerCart, Map<OrderItem, OrderItem> oldNewItemMap) throws PricingException {
// currently we'll just add items
for (OrderItem orderItem : anonymousCart.getOrderItems()) {
if (orderItem instanceof DiscreteOrderItem) {
orderItem.removeAllAdjustments();
orderItem.removeAllCandidateItemOffers();
DiscreteOrderItem discreteOrderItem = (DiscreteOrderItem) orderItem;
if (discreteOrderItem.getSku().getActiveStartDate() != null) {
if (discreteOrderItem.getSku().isActive(discreteOrderItem.getProduct(), orderItem.getCategory())) {
OrderItem newItem = addOrderItemToOrder(customerCart, discreteOrderItem.clone(), false);
mergeCartResponse.getAddedItems().add(newItem);
oldNewItemMap.put(orderItem, newItem);
} else {
mergeCartResponse.getRemovedItems().add(orderItem);
}
} else {
if (discreteOrderItem.getProduct().isActive() && orderItem.getCategory().isActive()) {
OrderItem newItem = addOrderItemToOrder(customerCart, discreteOrderItem.clone(), false);
mergeCartResponse.getAddedItems().add(newItem);
oldNewItemMap.put(orderItem, newItem);
} else {
mergeCartResponse.getRemovedItems().add(orderItem);
}
}
} else if (orderItem instanceof BundleOrderItem) {
BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItem;
orderItem.removeAllAdjustments();
orderItem.removeAllCandidateItemOffers();
boolean removeBundle = false;
for (DiscreteOrderItem discreteOrderItem : bundleOrderItem.getDiscreteOrderItems()){
discreteOrderItem.removeAllAdjustments();
discreteOrderItem.removeAllCandidateItemOffers();
if (discreteOrderItem.getSku().getActiveStartDate() != null) {
if (!discreteOrderItem.getSku().isActive(discreteOrderItem.getProduct(), orderItem.getCategory())) {
/*
* Bundle has an inactive item in it -- remove the whole bundle
*/
removeBundle = true;
}
} else {
if (!discreteOrderItem.getProduct().isActive() || !orderItem.getCategory().isActive()) {
removeBundle = true;
}
}
}
if (!removeBundle) {
OrderItem newItem = addOrderItemToOrder(customerCart, bundleOrderItem.clone(), false);
mergeCartResponse.getAddedItems().add(newItem);
oldNewItemMap.put(orderItem, newItem);
} else {
mergeCartResponse.getRemovedItems().add(orderItem);
}
}
}
return customerCart;
}
protected OrderItem addOrderItemToOrder(Order order, OrderItem newOrderItem, Boolean priceOrder) throws PricingException {
List<OrderItem> orderItems = order.getOrderItems();
newOrderItem.setOrder(order);
newOrderItem = orderItemService.saveOrderItem(newOrderItem);
orderItems.add(newOrderItem);
order = orderService.save(order, priceOrder);
return newOrderItem;
}
protected Order removeItemFromOrder(Order order, OrderItem item, boolean priceOrder) throws PricingException {
fulfillmentGroupService.removeOrderItemFromFullfillmentGroups(order, item);
OrderItem itemFromOrder = order.getOrderItems().remove(order.getOrderItems().indexOf(item));
itemFromOrder.setOrder(null);
orderItemService.delete(itemFromOrder);
order = orderService.save(order, priceOrder);
return order;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_legacy_LegacyMergeCartServiceImpl.java |
591 | public interface StatusHandler {
public void handleStatus(String serviceName, ServiceStatusType status);
} | 0true
| common_src_main_java_org_broadleafcommerce_common_vendor_service_monitor_StatusHandler.java |
1,721 | public static class Builder<KType, VType> implements ObjectObjectMap<KType, VType> {
private ObjectObjectOpenHashMap<KType, VType> map;
public Builder() {
//noinspection unchecked
this(EMPTY);
}
public Builder(int size) {
this.map = new ObjectObjectOpenHashMap<KType, VType>(size);
}
public Builder(ImmutableOpenMap<KType, VType> map) {
this.map = map.map.clone();
}
/**
* Builds a new instance of the
*/
public ImmutableOpenMap<KType, VType> build() {
ObjectObjectOpenHashMap<KType, VType> map = this.map;
this.map = null; // nullify the map, so any operation post build will fail! (hackish, but safest)
return new ImmutableOpenMap<KType, VType>(map);
}
/**
* Puts all the entries in the map to the builder.
*/
public Builder<KType, VType> putAll(Map<KType, VType> map) {
for (Map.Entry<KType, VType> entry : map.entrySet()) {
this.map.put(entry.getKey(), entry.getValue());
}
return this;
}
/**
* A put operation that can be used in the fluent pattern.
*/
public Builder<KType, VType> fPut(KType key, VType value) {
map.put(key, value);
return this;
}
@Override
public VType put(KType key, VType value) {
return map.put(key, value);
}
@Override
public VType get(KType key) {
return map.get(key);
}
@Override
public VType getOrDefault(KType kType, VType vType) {
return map.getOrDefault(kType, vType);
}
@Override
public int putAll(ObjectObjectAssociativeContainer<? extends KType, ? extends VType> container) {
return map.putAll(container);
}
@Override
public int putAll(Iterable<? extends ObjectObjectCursor<? extends KType, ? extends VType>> iterable) {
return map.putAll(iterable);
}
/**
* Remove that can be used in the fluent pattern.
*/
public Builder<KType, VType> fRemove(KType key) {
map.remove(key);
return this;
}
@Override
public VType remove(KType key) {
return map.remove(key);
}
@Override
public Iterator<ObjectObjectCursor<KType, VType>> iterator() {
return map.iterator();
}
@Override
public boolean containsKey(KType key) {
return map.containsKey(key);
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public int removeAll(ObjectContainer<? extends KType> container) {
return map.removeAll(container);
}
@Override
public int removeAll(ObjectPredicate<? super KType> predicate) {
return map.removeAll(predicate);
}
@Override
public <T extends ObjectObjectProcedure<? super KType, ? super VType>> T forEach(T procedure) {
return map.forEach(procedure);
}
@Override
public void clear() {
map.clear();
}
@Override
public ObjectCollection<KType> keys() {
return map.keys();
}
@Override
public ObjectContainer<VType> values() {
return map.values();
}
@SuppressWarnings("unchecked")
public <K, V> Builder<K, V> cast() {
return (Builder) this;
}
} | 0true
| src_main_java_org_elasticsearch_common_collect_ImmutableOpenMap.java |
1,082 | class MyServiceConfig {
String stringProp;
int intProp;
boolean boolProp;
} | 0true
| hazelcast_src_test_java_com_hazelcast_config_MyServiceConfig.java |
402 | public class AccountNumberMask {
private List<UnmaskRange> ranges;
private char maskCharacter;
public AccountNumberMask(List<UnmaskRange> ranges, char maskCharacter) {
this.ranges = ranges;
this.maskCharacter = maskCharacter;
}
public String mask (String accountNumber) {
if (accountNumber == null) {
throw new RuntimeException("account number is null");
}
char[] characters = accountNumber.toCharArray();
char[] newCharacters = new char[characters.length];
//do mask phase
Arrays.fill(newCharacters, 0, newCharacters.length, maskCharacter);
for (UnmaskRange range : ranges) {
if (range.getPositionType() == UnmaskRange.BEGINNINGTYPE) {
System.arraycopy(characters, 0, newCharacters, 0, range.getLength());
} else {
System.arraycopy(characters, characters.length - range.getLength(), newCharacters, newCharacters.length - range.getLength(), range.getLength());
}
}
return new String(newCharacters);
}
public static void main( String[] args ) {
ArrayList<UnmaskRange> ranges = new ArrayList<UnmaskRange>();
ranges.add(new UnmaskRange(UnmaskRange.BEGINNINGTYPE, 4));
ranges.add(new UnmaskRange(UnmaskRange.ENDTYPE, 4));
AccountNumberMask mask = new AccountNumberMask(ranges, 'X');
System.out.println("Card: " + mask.mask( "1111111111111111" ) );
System.out.println("Card: " + mask.mask( "111111111111111" ) );
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_payment_AccountNumberMask.java |
1,720 | return new UnmodifiableIterator<VType>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public VType next() {
return iterator.next().value;
}
}; | 0true
| src_main_java_org_elasticsearch_common_collect_ImmutableOpenMap.java |
2,264 | public static final class TcpSettings {
public static final String TCP_NO_DELAY = "network.tcp.no_delay";
public static final String TCP_KEEP_ALIVE = "network.tcp.keep_alive";
public static final String TCP_REUSE_ADDRESS = "network.tcp.reuse_address";
public static final String TCP_SEND_BUFFER_SIZE = "network.tcp.send_buffer_size";
public static final String TCP_RECEIVE_BUFFER_SIZE = "network.tcp.receive_buffer_size";
public static final String TCP_BLOCKING = "network.tcp.blocking";
public static final String TCP_BLOCKING_SERVER = "network.tcp.blocking_server";
public static final String TCP_BLOCKING_CLIENT = "network.tcp.blocking_client";
public static final String TCP_CONNECT_TIMEOUT = "network.tcp.connect_timeout";
public static final ByteSizeValue TCP_DEFAULT_SEND_BUFFER_SIZE = null;
public static final ByteSizeValue TCP_DEFAULT_RECEIVE_BUFFER_SIZE = null;
public static final TimeValue TCP_DEFAULT_CONNECT_TIMEOUT = new TimeValue(30, TimeUnit.SECONDS);
} | 0true
| src_main_java_org_elasticsearch_common_network_NetworkService.java |
359 | public class HBaseCompat0_96 implements HBaseCompat {
@Override
public void setCompression(HColumnDescriptor cd, String algo) {
cd.setCompressionType(Compression.Algorithm.valueOf(algo));
}
@Override
public HTableDescriptor newTableDescriptor(String tableName) {
TableName tn = TableName.valueOf(tableName);
return new HTableDescriptor(tn);
}
} | 0true
| titan-hbase-parent_titan-hbase-096_src_main_java_com_thinkaurelius_titan_diskstorage_hbase_HBaseCompat0_96.java |
314 | LOG_FILE_LEVEL("log.file.level", "File logging level", String.class, "fine", new OConfigurationChangeCallback() {
public void change(final Object iCurrentValue, final Object iNewValue) {
OLogManager.instance().setLevel((String) iNewValue, FileHandler.class);
}
}), | 0true
| core_src_main_java_com_orientechnologies_orient_core_config_OGlobalConfiguration.java |
479 | listener.onMessage("\n--- DB2: " + makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<String>() {
public String call() {
return indexTwoValue.toString();
}
})); | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java |
3,608 | final class TransactionContextImpl implements TransactionContext {
private final NodeEngineImpl nodeEngine;
private final TransactionImpl transaction;
private final TransactionManagerServiceImpl transactionManager;
private final Map<TransactionalObjectKey, TransactionalObject> txnObjectMap
= new HashMap<TransactionalObjectKey, TransactionalObject>(2);
private XAResourceImpl xaResource;
TransactionContextImpl(TransactionManagerServiceImpl transactionManagerService, NodeEngineImpl nodeEngine,
TransactionOptions options, String ownerUuid) {
this.transactionManager = transactionManagerService;
this.nodeEngine = nodeEngine;
this.transaction = new TransactionImpl(transactionManagerService, nodeEngine, options, ownerUuid);
}
@Override
public XAResourceImpl getXaResource() {
if (xaResource == null) {
xaResource = new XAResourceImpl(transactionManager, this, nodeEngine);
}
return xaResource;
}
@Override
public boolean isXAManaged() {
return transaction.getXid() != null;
}
@Override
public String getTxnId() {
return transaction.getTxnId();
}
@Override
public void beginTransaction() {
transaction.begin();
}
@Override
public void commitTransaction() throws TransactionException {
if (transaction.getTransactionType().equals(TransactionOptions.TransactionType.TWO_PHASE)) {
transaction.prepare();
}
transaction.commit();
}
@Override
public void rollbackTransaction() {
transaction.rollback();
}
@SuppressWarnings("unchecked")
@Override
public <K, V> TransactionalMap<K, V> getMap(String name) {
return (TransactionalMap<K, V>) getTransactionalObject(MapService.SERVICE_NAME, name);
}
@SuppressWarnings("unchecked")
@Override
public <E> TransactionalQueue<E> getQueue(String name) {
return (TransactionalQueue<E>) getTransactionalObject(QueueService.SERVICE_NAME, name);
}
@SuppressWarnings("unchecked")
@Override
public <K, V> TransactionalMultiMap<K, V> getMultiMap(String name) {
return (TransactionalMultiMap<K, V>) getTransactionalObject(MultiMapService.SERVICE_NAME, name);
}
@SuppressWarnings("unchecked")
@Override
public <E> TransactionalList<E> getList(String name) {
return (TransactionalList<E>) getTransactionalObject(ListService.SERVICE_NAME, name);
}
@SuppressWarnings("unchecked")
@Override
public <E> TransactionalSet<E> getSet(String name) {
return (TransactionalSet<E>) getTransactionalObject(SetService.SERVICE_NAME, name);
}
@SuppressWarnings("unchecked")
@Override
public TransactionalObject getTransactionalObject(String serviceName, String name) {
if (transaction.getState() != Transaction.State.ACTIVE) {
throw new TransactionNotActiveException("No transaction is found while accessing "
+ "transactional object -> " + serviceName + "[" + name + "]!");
}
TransactionalObjectKey key = new TransactionalObjectKey(serviceName, name);
TransactionalObject obj = txnObjectMap.get(key);
if (obj != null) {
return obj;
}
final Object service = nodeEngine.getService(serviceName);
if (service instanceof TransactionalService) {
nodeEngine.getProxyService().initializeDistributedObject(serviceName, name);
obj = ((TransactionalService) service).createTransactionalObject(name, transaction);
txnObjectMap.put(key, obj);
} else {
if (service == null) {
if (!nodeEngine.isActive()) {
throw new HazelcastInstanceNotActiveException();
}
throw new IllegalArgumentException("Unknown Service[" + serviceName + "]!");
}
throw new IllegalArgumentException("Service[" + serviceName + "] is not transactional!");
}
return obj;
}
Transaction getTransaction() {
return transaction;
}
private static class TransactionalObjectKey {
private final String serviceName;
private final String name;
TransactionalObjectKey(String serviceName, String name) {
this.serviceName = serviceName;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TransactionalObjectKey)) {
return false;
}
TransactionalObjectKey that = (TransactionalObjectKey) o;
if (!name.equals(that.name)) {
return false;
}
if (!serviceName.equals(that.serviceName)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = serviceName.hashCode();
result = 31 * result + name.hashCode();
return result;
}
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_transaction_impl_TransactionContextImpl.java |
1,418 | METRIC_TYPE.COUNTER, new OProfilerHookValue() {
public Object getValue() {
return metricFlushes;
}
}, dictProfilerMetric + ".flushes"); | 0true
| enterprise_src_main_java_com_orientechnologies_orient_enterprise_channel_OChannel.java |
2,932 | public class RussianStemTokenFilterFactory extends AbstractTokenFilterFactory {
@Inject
public RussianStemTokenFilterFactory(Index index, @IndexSettings Settings indexSettings, @Assisted String name, @Assisted Settings settings) {
super(index, indexSettings, name, settings);
}
@Override
public TokenStream create(TokenStream tokenStream) {
return new SnowballFilter(tokenStream, "Russian");
}
} | 0true
| src_main_java_org_elasticsearch_index_analysis_RussianStemTokenFilterFactory.java |
3,529 | public class UidTests extends ElasticsearchTestCase {
@Test
public void testCreateAndSplitId() {
BytesRef createUid = Uid.createUidAsBytes("foo", "bar");
HashedBytesArray[] splitUidIntoTypeAndId = Uid.splitUidIntoTypeAndId(createUid);
assertThat("foo", equalTo(splitUidIntoTypeAndId[0].toUtf8()));
assertThat("bar", equalTo(splitUidIntoTypeAndId[1].toUtf8()));
// split also with an offset
BytesRef ref = new BytesRef(createUid.length+10);
ref.offset = 9;
ref.length = createUid.length;
System.arraycopy(createUid.bytes, createUid.offset, ref.bytes, ref.offset, ref.length);
splitUidIntoTypeAndId = Uid.splitUidIntoTypeAndId(ref);
assertThat("foo", equalTo(splitUidIntoTypeAndId[0].toUtf8()));
assertThat("bar", equalTo(splitUidIntoTypeAndId[1].toUtf8()));
}
} | 0true
| src_test_java_org_elasticsearch_index_mapper_UidTests.java |
136 | @RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class ClientTimeoutTest {
@Test(timeout = 20000, expected = IllegalStateException.class)
public void testTimeoutToOutsideNetwork() throws Exception {
ClientConfig clientConfig = new ClientConfig();
clientConfig.getGroupConfig().setName( "dev" ).setPassword( "dev-pass" );
clientConfig.getNetworkConfig().addAddress( "8.8.8.8:5701" );
HazelcastInstance client = HazelcastClient.newHazelcastClient( clientConfig );
IList<Object> list = client.getList( "test" );
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_ClientTimeoutTest.java |
353 | public abstract class AbstractClientMapReduceJobTest {
protected ClientConfig buildClientConfig()
{
ClientConfig config = new XmlClientConfigBuilder().build();
return config;
}
protected Config buildConfig() {
Config config = new XmlConfigBuilder().build();
config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true).addMember("127.0.0.1");
return config;
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_AbstractClientMapReduceJobTest.java |
1,088 | @Service("blOrderServiceExtensionManager")
public class OrderServiceExtensionManager extends ExtensionManager<OrderServiceExtensionHandler> {
public OrderServiceExtensionManager() {
super(OrderServiceExtensionHandler.class);
}
/**
* By default,this extension manager will continue on handled allowing multiple handlers to interact with the order.
*/
public boolean continueOnHandled() {
return true;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_OrderServiceExtensionManager.java |
2,583 | private class NewClusterStateListener implements PublishClusterStateAction.NewClusterStateListener {
@Override
public void onNewClusterState(ClusterState clusterState, NewStateProcessed newStateProcessed) {
handleNewClusterStateFromMaster(clusterState, newStateProcessed);
}
} | 0true
| src_main_java_org_elasticsearch_discovery_zen_ZenDiscovery.java |
77 | @Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_STATIC_ASSET_DESC")
@EntityListeners(value = { AdminAuditableListener.class })
@Cache(usage= CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blCMSElements")
public class StaticAssetDescriptionImpl implements StaticAssetDescription {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "StaticAssetDescriptionId")
@GenericGenerator(
name="StaticAssetDescriptionId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="StaticAssetDescriptionImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.cms.file.domain.StaticAssetDescriptionImpl")
}
)
@Column(name = "STATIC_ASSET_DESC_ID")
protected Long id;
@Embedded
@AdminPresentation(excluded = true)
protected AdminAuditable auditable = new AdminAuditable();
@Column (name = "DESCRIPTION")
@AdminPresentation(friendlyName = "StaticAssetDescriptionImpl_Description", prominent = true)
protected String description;
@Column (name = "LONG_DESCRIPTION")
@AdminPresentation(friendlyName = "StaticAssetDescriptionImpl_Long_Description", largeEntry = true, visibility = VisibilityEnum.GRID_HIDDEN)
protected String longDescription;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getDescription() {
return description;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public String getLongDescription() {
return longDescription;
}
@Override
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
@Override
public StaticAssetDescription cloneEntity() {
StaticAssetDescriptionImpl newAssetDescription = new StaticAssetDescriptionImpl();
newAssetDescription.description = description;
newAssetDescription.longDescription = longDescription;
return newAssetDescription;
}
@Override
public AdminAuditable getAuditable() {
return auditable;
}
@Override
public void setAuditable(AdminAuditable auditable) {
this.auditable = auditable;
}
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_domain_StaticAssetDescriptionImpl.java |
2,587 | clusterService.submitStateUpdateTask("received a request to rejoin the cluster from [" + request.fromNodeId + "]", Priority.URGENT, new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
try {
channel.sendResponse(TransportResponse.Empty.INSTANCE);
} catch (Exception e) {
logger.warn("failed to send response on rejoin cluster request handling", e);
}
return rejoin(currentState, "received a request to rejoin the cluster from [" + request.fromNodeId + "]");
}
@Override
public void onFailure(String source, Throwable t) {
logger.error("unexpected failure during [{}]", t, source);
}
}); | 1no label
| src_main_java_org_elasticsearch_discovery_zen_ZenDiscovery.java |
1,439 | public class LocalGraphDbTest {
private static String DB_URL = "plocal:target/databases/tinkerpop";
public static void main(String[] args) throws IOException {
new LocalGraphDbTest().multipleDatabasesSameThread();
}
private boolean oldStorageOpen;
public LocalGraphDbTest() {
OGremlinHelper.global().create();
}
@BeforeClass
public void before() {
oldStorageOpen = OGlobalConfiguration.STORAGE_KEEP_OPEN.getValueAsBoolean();
OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(false);
}
@AfterClass
public void after() {
OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(oldStorageOpen);
}
@Test
public void multipleDatabasesSameThread() throws IOException {
OGraphDatabase db1 = OGraphDatabasePool.global().acquire(DB_URL, "admin", "admin");
ODocument doc1 = db1.createVertex();
doc1.field("key", "value");
doc1.save();
db1.close();
OGraphDatabase db2 = OGraphDatabasePool.global().acquire(DB_URL, "admin", "admin");
ODocument doc2 = db2.createVertex();
doc2.field("key", "value");
doc2.save();
db2.close();
db1 = OGraphDatabasePool.global().acquire(DB_URL, "admin", "admin");
final List<?> result = db1.query(new OSQLSynchQuery<ODocument>("select out[weight=3].size() from V where out.size() > 0"));
doc1 = db1.createVertex();
doc1.field("newkey", "newvalue");
doc1.save();
db1.close();
}
} | 0true
| graphdb_src_test_java_com_orientechnologies_orient_graph_blueprints_LocalGraphDbTest.java |
634 | final String registrationId = service.addMembershipListener(new MembershipListener() {
@Override
public void memberAdded(MembershipEvent membershipEvent) {
if (endpoint.live()) {
final MemberImpl member = (MemberImpl) membershipEvent.getMember();
endpoint.sendEvent(new ClientMembershipEvent(member, MembershipEvent.MEMBER_ADDED), getCallId());
}
}
@Override
public void memberRemoved(MembershipEvent membershipEvent) {
if (endpoint.live()) {
final MemberImpl member = (MemberImpl) membershipEvent.getMember();
endpoint.sendEvent(new ClientMembershipEvent(member, MembershipEvent.MEMBER_REMOVED), getCallId());
}
}
public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) {
if (endpoint.live()) {
final MemberImpl member = (MemberImpl) memberAttributeEvent.getMember();
final String uuid = member.getUuid();
final MemberAttributeOperationType op = memberAttributeEvent.getOperationType();
final String key = memberAttributeEvent.getKey();
final Object value = memberAttributeEvent.getValue();
final MemberAttributeChange memberAttributeChange = new MemberAttributeChange(uuid, op, key, value);
endpoint.sendEvent(new ClientMembershipEvent(member, memberAttributeChange), getCallId());
}
}
}); | 0true
| hazelcast_src_main_java_com_hazelcast_cluster_client_AddMembershipListenerRequest.java |
2,320 | static class UTCIntervalTimeZoneRounding extends TimeZoneRounding {
final static byte ID = 4;
private long interval;
UTCIntervalTimeZoneRounding() { // for serialization
}
UTCIntervalTimeZoneRounding(long interval) {
this.interval = interval;
}
@Override
public byte id() {
return ID;
}
@Override
public long roundKey(long utcMillis) {
return Rounding.Interval.roundKey(utcMillis, interval);
}
@Override
public long valueForKey(long key) {
return Rounding.Interval.roundValue(key, interval);
}
@Override
public long nextRoundingValue(long value) {
return value + interval;
}
@Override
public void readFrom(StreamInput in) throws IOException {
interval = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVLong(interval);
}
} | 0true
| src_main_java_org_elasticsearch_common_rounding_TimeZoneRounding.java |
1,204 | public interface OAutoshardedStorage extends OStorage {
/**
* Storage unique id
*
* @return storage unique id
*/
long getStorageId();
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_OAutoshardedStorage.java |
1,388 | public static class Timestamp {
public static String parseStringTimestamp(String timestampAsString, FormatDateTimeFormatter dateTimeFormatter) throws TimestampParsingException {
long ts;
try {
// if we manage to parse it, its a millisecond timestamp, just return the string as is
ts = Long.parseLong(timestampAsString);
return timestampAsString;
} catch (NumberFormatException e) {
try {
ts = dateTimeFormatter.parser().parseMillis(timestampAsString);
} catch (RuntimeException e1) {
throw new TimestampParsingException(timestampAsString);
}
}
return Long.toString(ts);
}
public static final Timestamp EMPTY = new Timestamp(false, null, TimestampFieldMapper.DEFAULT_DATE_TIME_FORMAT);
private final boolean enabled;
private final String path;
private final String format;
private final String[] pathElements;
private final FormatDateTimeFormatter dateTimeFormatter;
public Timestamp(boolean enabled, String path, String format) {
this.enabled = enabled;
this.path = path;
if (path == null) {
pathElements = Strings.EMPTY_ARRAY;
} else {
pathElements = Strings.delimitedListToStringArray(path, ".");
}
this.format = format;
this.dateTimeFormatter = Joda.forPattern(format);
}
public boolean enabled() {
return enabled;
}
public boolean hasPath() {
return path != null;
}
public String path() {
return this.path;
}
public String[] pathElements() {
return this.pathElements;
}
public String format() {
return this.format;
}
public FormatDateTimeFormatter dateTimeFormatter() {
return this.dateTimeFormatter;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Timestamp timestamp = (Timestamp) o;
if (enabled != timestamp.enabled) return false;
if (dateTimeFormatter != null ? !dateTimeFormatter.equals(timestamp.dateTimeFormatter) : timestamp.dateTimeFormatter != null)
return false;
if (format != null ? !format.equals(timestamp.format) : timestamp.format != null) return false;
if (path != null ? !path.equals(timestamp.path) : timestamp.path != null) return false;
if (!Arrays.equals(pathElements, timestamp.pathElements)) return false;
return true;
}
@Override
public int hashCode() {
int result = (enabled ? 1 : 0);
result = 31 * result + (path != null ? path.hashCode() : 0);
result = 31 * result + (format != null ? format.hashCode() : 0);
result = 31 * result + (pathElements != null ? Arrays.hashCode(pathElements) : 0);
result = 31 * result + (dateTimeFormatter != null ? dateTimeFormatter.hashCode() : 0);
return result;
}
} | 1no label
| src_main_java_org_elasticsearch_cluster_metadata_MappingMetaData.java |
1,480 | @Component("blUpdateAccountValidator")
public class UpdateAccountValidator implements Validator {
@Resource(name="blCustomerService")
protected CustomerService customerService;
public void validate(UpdateAccountForm form, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "emailAddress", "emailAddress.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "firstName.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "lastName.required");
if (!errors.hasErrors()) {
//is this a valid email address?
if (!GenericValidator.isEmail(form.getEmailAddress())) {
errors.rejectValue("emailAddress", "emailAddress.invalid");
}
//check email address to see if it is already in use by another customer
Customer customerMatchingNewEmail = customerService.readCustomerByEmail(form.getEmailAddress());
if (customerMatchingNewEmail != null && CustomerState.getCustomer().getId() != customerMatchingNewEmail.getId()) {
//customer found with new email entered, and it is not the current customer
errors.rejectValue("emailAddress", "emailAddress.used");
}
}
}
@Override
public boolean supports(Class<?> clazz) {
return false;
}
@Override
public void validate(Object target, Errors errors) {
}
} | 1no label
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_account_validator_UpdateAccountValidator.java |
1,098 | public class FulfillmentGroupItemRequest {
protected Order order;
protected FulfillmentGroup fulfillmentGroup;
protected OrderItem orderItem;
protected int quantity;
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public FulfillmentGroup getFulfillmentGroup() {
return fulfillmentGroup;
}
public void setFulfillmentGroup(FulfillmentGroup fulfillmentGroup) {
this.fulfillmentGroup = fulfillmentGroup;
}
public OrderItem getOrderItem() {
return orderItem;
}
public void setOrderItem(OrderItem orderItem) {
this.orderItem = orderItem;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_call_FulfillmentGroupItemRequest.java |
464 | public interface StoreFeatures {
/**
* Equivalent to calling {@link #hasUnorderedScan()} {@code ||}
* {@link #hasOrderedScan()}.
*/
public boolean hasScan();
/**
* Whether this storage backend supports global key scans via
* {@link KeyColumnValueStore#getKeys(SliceQuery, StoreTransaction)}.
*/
public boolean hasUnorderedScan();
/**
* Whether this storage backend supports global key scans via
* {@link KeyColumnValueStore#getKeys(KeyRangeQuery, StoreTransaction)}.
*/
public boolean hasOrderedScan();
/**
* Whether this storage backend supports query operations on multiple keys
* via
* {@link KeyColumnValueStore#getSlice(java.util.List, SliceQuery, StoreTransaction)}
*/
public boolean hasMultiQuery();
/**
* Whether this store supports locking via
* {@link KeyColumnValueStore#acquireLock(com.thinkaurelius.titan.diskstorage.StaticBuffer, com.thinkaurelius.titan.diskstorage.StaticBuffer, com.thinkaurelius.titan.diskstorage.StaticBuffer, StoreTransaction)}
*
*/
public boolean hasLocking();
/**
* Whether this storage backend supports batch mutations via
* {@link KeyColumnValueStoreManager#mutateMany(java.util.Map, StoreTransaction)}.
*
*/
public boolean hasBatchMutation();
/**
* Whether this storage backend preserves key locality. This affects Titan's
* use of vertex ID partitioning.
*
*/
public boolean isKeyOrdered();
/**
* Whether this storage backend writes and reads data from more than one
* machine.
*/
public boolean isDistributed();
/**
* Whether this storage backend's transactions support isolation.
*/
public boolean hasTxIsolation();
/**
*
*/
public boolean hasLocalKeyPartition();
/**
* Whether this storage backend provides strong consistency within each
* key/row. This property is weaker than general strong consistency, since
* reads and writes to different keys need not obey strong consistency.
* "Key consistency" is shorthand for
* "strong consistency at the key/row level".
*
* @return true if the backend supports key-level strong consistency
*/
public boolean isKeyConsistent();
/**
* Returns true if column-value entries in this storage backend are annotated with a timestamp,
* else false. It is assumed that the timestamp matches the one set during the committing transaction.
*
* @return
*/
public boolean hasTimestamps();
/**
* If this storage backend supports one particular type of data
* timestamp/version better than others. For example, HBase server-side TTLs
* assume row timestamps are in milliseconds; some Cassandra client utils
* assume timestamps in microseconds. This method should return null if the
* backend has no preference for a specific timestamp resolution.
*
* This method will be ignored by Titan if {@link #hasTimestamps()} is
* false.
*
* @return null or a Timestamps enum value
*/
public Timestamps getPreferredTimestamps();
/**
* Returns true if this storage backend support time-to-live (TTL) settings for column-value entries. If such a value
* is provided as a meta-data annotation on the {@link com.thinkaurelius.titan.diskstorage.Entry}, the entry will
* disappear from the storage backend after the given amount of time.
*
* @return true if the storage backend supports TTL, else false
*/
public boolean hasCellTTL();
/**
* Returns true if this storage backend supports time-to-live (TTL) settings on a per-store basis. That means, that
* entries added to such a store will require after a configured amount of time.
*
* @return
*/
public boolean hasStoreTTL();
/**
* Returns true if this storage backend supports entry-level visibility by attaching a visibility or authentication
* token to each column-value entry in the data store and limited retrievals to "visible" entries.
*
* @return
*/
public boolean hasVisibility();
/**
* Get a transaction configuration that enforces key consistency. This
* method has undefined behavior when {@link #isKeyConsistent()} is
* false.
*
* @return a key-consistent tx config
*/
public Configuration getKeyConsistentTxConfig();
/**
* Get a transaction configuration that enforces local key consistency.
* "Local" has flexible meaning depending on the backend implementation. An
* example is Cassandra's notion of LOCAL_QUORUM, which provides strong
* consistency among all replicas in the same datacenter as the node
* handling the request, but not nodes at other datacenters. This method has
* undefined behavior when {@link #isKeyConsistent()} is false.
*
* Backends which don't support the notion of "local" strong consistency may
* return the same configuration returned by
* {@link #getKeyConsistencyTxConfig()}.
*
* @return a locally (or globally) key-consistent tx config
*/
public Configuration getLocalKeyConsistentTxConfig();
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_StoreFeatures.java |
83 | final Map<Method, Object> consoleMethods = new TreeMap<Method, Object>(new Comparator<Method>() {
public int compare(Method o1, Method o2) {
int res = o1.getName().compareTo(o2.getName());
if (res == 0)
res = o1.toString().compareTo(o2.toString());
return res;
}
}); | 0true
| commons_src_main_java_com_orientechnologies_common_console_OConsoleApplication.java |
802 | public class ApplyRequest extends ReadRequest {
private Data function;
public ApplyRequest() {
}
public ApplyRequest(String name, Data function) {
super(name);
this.function = function;
}
@Override
protected Operation prepareOperation() {
SerializationService serializationService = getClientEngine().getSerializationService();
IFunction f = serializationService.toObject(function);
//noinspection unchecked
return new ApplyOperation(name, f);
}
@Override
public int getClassId() {
return AtomicLongPortableHook.APPLY;
}
@Override
public void write(PortableWriter writer) throws IOException {
super.write(writer);
ObjectDataOutput out = writer.getRawDataOutput();
writeNullableData(out, function);
}
@Override
public void read(PortableReader reader) throws IOException {
super.read(reader);
ObjectDataInput in = reader.getRawDataInput();
function = readNullableData(in);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_client_ApplyRequest.java |
695 | public static interface Listener {
/**
* Callback before the bulk is executed.
*/
void beforeBulk(long executionId, BulkRequest request);
/**
* Callback after a successful execution of bulk request.
*/
void afterBulk(long executionId, BulkRequest request, BulkResponse response);
/**
* Callback after a failed execution of bulk request.
*/
void afterBulk(long executionId, BulkRequest request, Throwable failure);
} | 0true
| src_main_java_org_elasticsearch_action_bulk_BulkProcessor.java |
920 | makeDbCall(iOtherDb, new ODbRelatedCall<Object>() {
public Object call() {
if (iOther.getInternalStatus() == STATUS.NOT_LOADED)
iOther.reload();
return null;
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocumentHelper.java |
1,307 | public class OClusterPositionMap extends OSharedResourceAdaptive {
public static final String DEF_EXTENSION = ".cpm";
private final ODiskCache diskCache;
private String name;
private long fileId;
private final OWriteAheadLog writeAheadLog;
public OClusterPositionMap(ODiskCache diskCache, String name, OWriteAheadLog writeAheadLog) {
acquireExclusiveLock();
try {
this.diskCache = diskCache;
this.name = name;
this.writeAheadLog = writeAheadLog;
} finally {
releaseExclusiveLock();
}
}
public void open() throws IOException {
acquireExclusiveLock();
try {
fileId = diskCache.openFile(name + DEF_EXTENSION);
} finally {
releaseExclusiveLock();
}
}
public void create() throws IOException {
acquireExclusiveLock();
try {
fileId = diskCache.openFile(name + DEF_EXTENSION);
} finally {
releaseExclusiveLock();
}
}
public void flush() throws IOException {
acquireSharedLock();
try {
diskCache.flushFile(fileId);
} finally {
releaseSharedLock();
}
}
public void close() throws IOException {
acquireExclusiveLock();
try {
diskCache.closeFile(fileId);
} finally {
releaseExclusiveLock();
}
}
public void truncate() throws IOException {
acquireExclusiveLock();
try {
diskCache.truncateFile(fileId);
} finally {
releaseExclusiveLock();
}
}
public void delete() throws IOException {
acquireExclusiveLock();
try {
diskCache.deleteFile(fileId);
} finally {
releaseExclusiveLock();
}
}
public void rename(String newName) throws IOException {
acquireExclusiveLock();
try {
diskCache.renameFile(fileId, this.name, newName);
name = newName;
} finally {
releaseExclusiveLock();
}
}
public OClusterPosition add(long pageIndex, int recordPosition, OOperationUnitId unitId, OLogSequenceNumber startLSN,
ODurablePage.TrackMode trackMode) throws IOException {
acquireExclusiveLock();
try {
long lastPage = diskCache.getFilledUpTo(fileId) - 1;
boolean isNewPage = false;
if (lastPage < 0) {
lastPage = 0;
isNewPage = true;
}
OCacheEntry cacheEntry = diskCache.load(fileId, lastPage, false);
OCachePointer cachePointer = cacheEntry.getCachePointer();
cachePointer.acquireExclusiveLock();
try {
OClusterPositionMapBucket bucket = new OClusterPositionMapBucket(cachePointer.getDataPointer(), trackMode);
if (bucket.isFull()) {
cachePointer.releaseExclusiveLock();
diskCache.release(cacheEntry);
isNewPage = true;
cacheEntry = diskCache.allocateNewPage(fileId);
cachePointer = cacheEntry.getCachePointer();
cachePointer.acquireExclusiveLock();
bucket = new OClusterPositionMapBucket(cachePointer.getDataPointer(), trackMode);
}
final long index = bucket.add(pageIndex, recordPosition);
final OClusterPosition result = OClusterPositionFactory.INSTANCE.valueOf(index + cacheEntry.getPageIndex()
* OClusterPositionMapBucket.MAX_ENTRIES);
logPageChanges(bucket, fileId, cacheEntry.getPageIndex(), isNewPage, unitId, startLSN);
cacheEntry.markDirty();
return result;
} finally {
cachePointer.releaseExclusiveLock();
diskCache.release(cacheEntry);
}
} finally {
releaseExclusiveLock();
}
}
public OClusterPositionMapBucket.PositionEntry get(OClusterPosition clusterPosition) throws IOException {
acquireSharedLock();
try {
final long position = clusterPosition.longValue();
long pageIndex = position / OClusterPositionMapBucket.MAX_ENTRIES;
int index = (int) (position % OClusterPositionMapBucket.MAX_ENTRIES);
final OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
final OCachePointer cachePointer = cacheEntry.getCachePointer();
try {
final OClusterPositionMapBucket bucket = new OClusterPositionMapBucket(cachePointer.getDataPointer(),
ODurablePage.TrackMode.NONE);
return bucket.get(index);
} finally {
diskCache.release(cacheEntry);
}
} finally {
releaseSharedLock();
}
}
public OClusterPositionMapBucket.PositionEntry remove(OClusterPosition clusterPosition, OOperationUnitId unitId,
OLogSequenceNumber startLSN, ODurablePage.TrackMode trackMode) throws IOException {
acquireExclusiveLock();
try {
final long position = clusterPosition.longValue();
long pageIndex = position / OClusterPositionMapBucket.MAX_ENTRIES;
int index = (int) (position % OClusterPositionMapBucket.MAX_ENTRIES);
final OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
final OCachePointer cachePointer = cacheEntry.getCachePointer();
cachePointer.acquireExclusiveLock();
try {
final OClusterPositionMapBucket bucket = new OClusterPositionMapBucket(cachePointer.getDataPointer(), trackMode);
OClusterPositionMapBucket.PositionEntry positionEntry = bucket.remove(index);
if (positionEntry == null)
return null;
cacheEntry.markDirty();
logPageChanges(bucket, fileId, pageIndex, false, unitId, startLSN);
return positionEntry;
} finally {
cachePointer.releaseExclusiveLock();
diskCache.release(cacheEntry);
}
} finally {
releaseExclusiveLock();
}
}
public OClusterPosition[] higherPositions(OClusterPosition clusterPosition) throws IOException {
acquireSharedLock();
try {
final long position = clusterPosition.longValue();
if (position == Long.MAX_VALUE)
return new OClusterPosition[0];
return ceilingPositions(OClusterPositionFactory.INSTANCE.valueOf(position + 1));
} finally {
releaseSharedLock();
}
}
public OClusterPosition[] ceilingPositions(OClusterPosition clusterPosition) throws IOException {
acquireSharedLock();
try {
long position = clusterPosition.longValue();
if (position < 0)
position = 0;
long pageIndex = position / OClusterPositionMapBucket.MAX_ENTRIES;
int index = (int) (position % OClusterPositionMapBucket.MAX_ENTRIES);
final long filledUpTo = diskCache.getFilledUpTo(fileId);
if (pageIndex >= filledUpTo)
return new OClusterPosition[0];
OClusterPosition[] result = null;
do {
OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
OCachePointer cachePointer = cacheEntry.getCachePointer();
OClusterPositionMapBucket bucket = new OClusterPositionMapBucket(cachePointer.getDataPointer(), ODurablePage.TrackMode.NONE);
int resultSize = bucket.getSize() - index;
if (resultSize <= 0) {
diskCache.release(cacheEntry);
pageIndex++;
} else {
int entriesCount = 0;
long startIndex = cacheEntry.getPageIndex() * OClusterPositionMapBucket.MAX_ENTRIES + index;
result = new OClusterPosition[resultSize];
for (int i = 0; i < resultSize; i++) {
if (bucket.exists(i + index)) {
result[entriesCount] = OClusterPositionFactory.INSTANCE.valueOf(startIndex + i);
entriesCount++;
}
}
if (entriesCount == 0) {
result = null;
pageIndex++;
index = 0;
} else
result = Arrays.copyOf(result, entriesCount);
diskCache.release(cacheEntry);
}
} while (result == null && pageIndex < filledUpTo);
if (result == null)
result = new OClusterPosition[0];
return result;
} finally {
releaseSharedLock();
}
}
public OClusterPosition[] lowerPositions(OClusterPosition clusterPosition) throws IOException {
acquireSharedLock();
try {
final long position = clusterPosition.longValue();
if (position == 0)
return new OClusterPosition[0];
return floorPositions(OClusterPositionFactory.INSTANCE.valueOf(position - 1));
} finally {
releaseSharedLock();
}
}
public OClusterPosition[] floorPositions(OClusterPosition clusterPosition) throws IOException {
acquireSharedLock();
try {
final long position = clusterPosition.longValue();
if (position < 0)
return new OClusterPosition[0];
long pageIndex = position / OClusterPositionMapBucket.MAX_ENTRIES;
int index = (int) (position % OClusterPositionMapBucket.MAX_ENTRIES);
final long filledUpTo = diskCache.getFilledUpTo(fileId);
OClusterPosition[] result;
if (pageIndex >= filledUpTo) {
pageIndex = filledUpTo - 1;
index = Integer.MIN_VALUE;
}
do {
OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
OCachePointer cachePointer = cacheEntry.getCachePointer();
OClusterPositionMapBucket bucket = new OClusterPositionMapBucket(cachePointer.getDataPointer(), ODurablePage.TrackMode.NONE);
if (index == Integer.MIN_VALUE)
index = bucket.getSize() - 1;
int resultSize = index + 1;
int entriesCount = 0;
long startPosition = cacheEntry.getPageIndex() * OClusterPositionMapBucket.MAX_ENTRIES;
result = new OClusterPosition[resultSize];
for (int i = 0; i < resultSize; i++) {
if (bucket.exists(i)) {
result[entriesCount] = OClusterPositionFactory.INSTANCE.valueOf(startPosition + i);
entriesCount++;
}
}
if (entriesCount == 0) {
result = null;
pageIndex--;
index = Integer.MIN_VALUE;
} else
result = Arrays.copyOf(result, entriesCount);
diskCache.release(cacheEntry);
} while (result == null && pageIndex >= 0);
if (result == null)
result = new OClusterPosition[0];
return result;
} finally {
releaseSharedLock();
}
}
public OClusterPosition getFirstPosition() throws IOException {
acquireSharedLock();
try {
final long filledUpTo = diskCache.getFilledUpTo(fileId);
for (long pageIndex = 0; pageIndex < filledUpTo; pageIndex++) {
OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
OCachePointer cachePointer = cacheEntry.getCachePointer();
try {
OClusterPositionMapBucket bucket = new OClusterPositionMapBucket(cachePointer.getDataPointer(),
ODurablePage.TrackMode.NONE);
int bucketSize = bucket.getSize();
for (int index = 0; index < bucketSize; index++) {
if (bucket.exists(index))
return OClusterPositionFactory.INSTANCE.valueOf(pageIndex * OClusterPositionMapBucket.MAX_ENTRIES + index);
}
} finally {
diskCache.release(cacheEntry);
}
}
return OClusterPosition.INVALID_POSITION;
} finally {
releaseSharedLock();
}
}
public OClusterPosition getLastPosition() throws IOException {
acquireSharedLock();
try {
final long filledUpTo = diskCache.getFilledUpTo(fileId);
for (long pageIndex = filledUpTo - 1; pageIndex >= 0; pageIndex--) {
OCacheEntry cacheEntry = diskCache.load(fileId, pageIndex, false);
OCachePointer cachePointer = cacheEntry.getCachePointer();
try {
OClusterPositionMapBucket bucket = new OClusterPositionMapBucket(cachePointer.getDataPointer(),
ODurablePage.TrackMode.NONE);
final int bucketSize = bucket.getSize();
for (int index = bucketSize - 1; index >= 0; index--) {
if (bucket.exists(index))
return OClusterPositionFactory.INSTANCE.valueOf(pageIndex * OClusterPositionMapBucket.MAX_ENTRIES + index);
}
} finally {
diskCache.release(cacheEntry);
}
}
return OClusterPosition.INVALID_POSITION;
} finally {
releaseSharedLock();
}
}
public boolean wasSoftlyClosed() throws IOException {
acquireSharedLock();
try {
return diskCache.wasSoftlyClosed(fileId);
} finally {
releaseSharedLock();
}
}
private void logPageChanges(ODurablePage localPage, long fileId, long pageIndex, boolean isNewPage, OOperationUnitId unitId,
OLogSequenceNumber startLSN) throws IOException {
if (writeAheadLog != null) {
OPageChanges pageChanges = localPage.getPageChanges();
if (pageChanges.isEmpty())
return;
OLogSequenceNumber prevLsn;
if (isNewPage)
prevLsn = startLSN;
else
prevLsn = localPage.getLsn();
OLogSequenceNumber lsn = writeAheadLog.log(new OUpdatePageRecord(pageIndex, fileId, unitId, pageChanges, prevLsn));
localPage.setLsn(lsn);
}
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_OClusterPositionMap.java |
2,901 | public class NumericFloatTokenizer extends NumericTokenizer {
public NumericFloatTokenizer(Reader reader, int precisionStep, char[] buffer) throws IOException {
super(reader, new NumericTokenStream(precisionStep), buffer, null);
}
@Override
protected void setValue(NumericTokenStream tokenStream, String value) {
tokenStream.setFloatValue(Float.parseFloat(value));
}
} | 0true
| src_main_java_org_elasticsearch_index_analysis_NumericFloatTokenizer.java |
746 | @Service("blCheckoutService")
public class CheckoutServiceImpl implements CheckoutService {
@Resource(name="blCheckoutWorkflow")
protected SequenceProcessor checkoutWorkflow;
@Resource(name="blOrderService")
protected OrderService orderService;
/* (non-Javadoc)
* @see org.broadleafcommerce.core.checkout.service.CheckoutService#performCheckout(org.broadleafcommerce.core.order.domain.Order, java.util.Map)
*/
public CheckoutResponse performCheckout(Order order, final Map<PaymentInfo, Referenced> payments) throws CheckoutException {
if (payments != null) {
/*
* TODO add validation that checks the order and payment information for validity.
*/
/*
* TODO remove this simple validation and encapsulate using our real validation strategy
*/
for (PaymentInfo info : payments.keySet()) {
if (info.getReferenceNumber() == null) {
throw new CheckoutException("PaymentInfo reference number cannot be null", null);
}
}
for (Referenced referenced : payments.values()) {
if (referenced.getReferenceNumber() == null) {
throw new CheckoutException("Referenced reference number cannot be null", null);
}
}
}
CheckoutSeed seed = null;
try {
order = orderService.save(order, false);
seed = new CheckoutSeed(order, payments, new HashMap<String, Object>());
checkoutWorkflow.doActivities(seed);
// We need to pull the order off the seed and save it here in case any activity modified the order.
order = orderService.save(seed.getOrder(), false);
seed.setOrder(order);
return seed;
} catch (PricingException e) {
throw new CheckoutException("Unable to checkout order -- id: " + order.getId(), e, seed);
} catch (WorkflowException e) {
throw new CheckoutException("Unable to checkout order -- id: " + order.getId(), e.getRootCause(), seed);
}
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.checkout.service.CheckoutService#performCheckout(org.broadleafcommerce.core.order.domain.Order)
*/
public CheckoutResponse performCheckout(final Order order) throws CheckoutException {
return performCheckout(order, null);
}
} | 1no label
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_checkout_service_CheckoutServiceImpl.java |
436 | EventHandler<PortableMessage> handler = new EventHandler<PortableMessage>() {
@Override
public void handle(PortableMessage event) {
SerializationService serializationService = getContext().getSerializationService();
ClientClusterService clusterService = getContext().getClusterService();
E messageObject = serializationService.toObject(event.getMessage());
Member member = clusterService.getMember(event.getUuid());
Message<E> message = new Message<E>(name, messageObject, event.getPublishTime(), member);
listener.onMessage(message);
}
@Override
public void onListenerRegister() {
}
}; | 1no label
| hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientTopicProxy.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.