Unnamed: 0
int64 0
6.45k
| func
stringlengths 37
161k
| target
class label 2
classes | project
stringlengths 33
167
|
---|---|---|---|
486 |
class ExecutionCallbackNode {
final ExecutionCallback callback;
final Executor executor;
ExecutionCallbackNode(ExecutionCallback callback, Executor executor) {
this.callback = callback;
this.executor = executor;
}
}
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_spi_impl_ClientCallFuture.java
|
416 |
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
firedEvents.add(event);
}
});
| 0true
|
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedListTest.java
|
19 |
@Component("blAdminProductTranslationExtensionListener")
public class AdminProductTranslationExtensionListener implements AdminTranslationControllerExtensionListener {
@Resource(name = "blCatalogService")
protected CatalogService catalogService;
/**
* If we are trying to translate a field on Product that starts with "defaultSku.", we really want to associate the
* translation with Sku, its associated id, and the property name without "defaultSku."
*/
@Override
public boolean applyTransformation(TranslationForm form) {
if (form.getCeilingEntity().equals(Product.class.getName()) && form.getPropertyName().startsWith("defaultSku.")) {
Product p = catalogService.findProductById(Long.parseLong(form.getEntityId()));
form.setCeilingEntity(Sku.class.getName());
form.setEntityId(String.valueOf(p.getDefaultSku().getId()));
form.setPropertyName(form.getPropertyName().substring("defaultSku.".length()));
return true;
}
return false;
}
}
| 1no label
|
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_web_controller_AdminProductTranslationExtensionListener.java
|
365 |
public class TranslatedEntity implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, TranslatedEntity> TYPES = new LinkedHashMap<String, TranslatedEntity>();
public static final TranslatedEntity PRODUCT = new TranslatedEntity("org.broadleafcommerce.core.catalog.domain.Product", "Product");
public static final TranslatedEntity SKU = new TranslatedEntity("org.broadleafcommerce.core.catalog.domain.Sku", "Sku");
public static final TranslatedEntity CATEGORY = new TranslatedEntity("org.broadleafcommerce.core.catalog.domain.Category", "Category");
public static final TranslatedEntity PRODUCT_OPTION = new TranslatedEntity("org.broadleafcommerce.core.catalog.domain.ProductOption", "ProdOption");
public static final TranslatedEntity PRODUCT_OPTION_VALUE = new TranslatedEntity("org.broadleafcommerce.core.catalog.domain.ProductOptionValue", "ProdOptionVal");
public static final TranslatedEntity STATIC_ASSET = new TranslatedEntity("org.broadleafcommerce.cms.file.domain.StaticAsset", "StaticAsset");
public static final TranslatedEntity SEARCH_FACET = new TranslatedEntity("org.broadleafcommerce.core.search.domain.SearchFacet", "SearchFacet");
public static final TranslatedEntity FULFILLMENT_OPTION = new TranslatedEntity("org.broadleafcommerce.core.order.domain.FulfillmentOption", "FulfillmentOption");
public static final TranslatedEntity OFFER = new TranslatedEntity("org.broadleafcommerce.core.offer.domain.Offer", "Offer");
public static TranslatedEntity getInstance(final String type) {
return TYPES.get(type);
}
public static TranslatedEntity getInstanceFromFriendlyType(final String friendlyType) {
for (Entry<String, TranslatedEntity> entry : TYPES.entrySet()) {
if (entry.getValue().getFriendlyType().equals(friendlyType)) {
return entry.getValue();
}
}
return null;
}
private String type;
private String friendlyType;
public TranslatedEntity() {
//do nothing
}
public TranslatedEntity(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
public String getType() {
return type;
}
public String getFriendlyType() {
return friendlyType;
}
public static Map<String, TranslatedEntity> getTypes() {
return TYPES;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TranslatedEntity other = (TranslatedEntity) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_i18n_domain_TranslatedEntity.java
|
916 |
public final class DestructiveOperations implements NodeSettingsService.Listener {
/**
* Setting which controls whether wildcard usage (*, prefix*, _all) is allowed.
*/
public static final String REQUIRES_NAME = "action.destructive_requires_name";
private final ESLogger logger;
private volatile boolean destructiveRequiresName;
// TODO: Turn into a component that can be reused and wired up into all the transport actions where
// this helper logic is required. Note: also added the logger as argument, otherwise the same log
// statement is printed several times, this can removed once this becomes a component.
public DestructiveOperations(ESLogger logger, Settings settings, NodeSettingsService nodeSettingsService) {
this.logger = logger;
destructiveRequiresName = settings.getAsBoolean(DestructiveOperations.REQUIRES_NAME, false);
nodeSettingsService.addListener(this);
}
/**
* Fail if there is wildcard usage in indices and the named is required for destructive operations.
*/
public void failDestructive(String[] aliasesOrIndices) {
if (!destructiveRequiresName) {
return;
}
if (aliasesOrIndices == null || aliasesOrIndices.length == 0) {
throw new ElasticsearchIllegalArgumentException("Wildcard expressions or all indices are not allowed");
} else if (aliasesOrIndices.length == 1) {
if (hasWildcardUsage(aliasesOrIndices[0])) {
throw new ElasticsearchIllegalArgumentException("Wildcard expressions or all indices are not allowed");
}
} else {
for (String aliasesOrIndex : aliasesOrIndices) {
if (hasWildcardUsage(aliasesOrIndex)) {
throw new ElasticsearchIllegalArgumentException("Wildcard expressions or all indices are not allowed");
}
}
}
}
@Override
public void onRefreshSettings(Settings settings) {
boolean newValue = settings.getAsBoolean("action.destructive_requires_name", destructiveRequiresName);
if (destructiveRequiresName != newValue) {
logger.info("updating [action.operate_all_indices] from [{}] to [{}]", destructiveRequiresName, newValue);
this.destructiveRequiresName = newValue;
}
}
private static boolean hasWildcardUsage(String aliasOrIndex) {
return "_all".equals(aliasOrIndex) || aliasOrIndex.indexOf('*') != -1;
}
}
| 0true
|
src_main_java_org_elasticsearch_action_support_DestructiveOperations.java
|
193 |
public class ClientSecurityConfig {
private Credentials credentials;
private String credentialsClassname;
public Credentials getCredentials() {
return credentials;
}
public void setCredentials(Credentials credentials) {
this.credentials = credentials;
}
public String getCredentialsClassname() {
return credentialsClassname;
}
public void setCredentialsClassname(String credentialsClassname) {
this.credentialsClassname = credentialsClassname;
}
}
| 1no label
|
hazelcast-client_src_main_java_com_hazelcast_client_config_ClientSecurityConfig.java
|
2,367 |
public class ReducerTask<Key, Chunk>
implements Runnable {
private final AtomicBoolean cancelled = new AtomicBoolean();
private final JobSupervisor supervisor;
private final Queue<ReducerChunk<Key, Chunk>> reducerQueue;
private final String name;
private final String jobId;
private AtomicBoolean active = new AtomicBoolean();
public ReducerTask(String name, String jobId, JobSupervisor supervisor) {
this.name = name;
this.jobId = jobId;
this.supervisor = supervisor;
this.reducerQueue = new ConcurrentLinkedQueue<ReducerChunk<Key, Chunk>>();
}
public String getName() {
return name;
}
public String getJobId() {
return jobId;
}
public void cancel() {
cancelled.set(true);
}
public void processChunk(Map<Key, Chunk> chunk) {
processChunk(-1, null, chunk);
}
public void processChunk(int partitionId, Address sender, Map<Key, Chunk> chunk) {
if (cancelled.get()) {
return;
}
reducerQueue.offer(new ReducerChunk<Key, Chunk>(chunk, partitionId, sender));
if (active.compareAndSet(false, true)) {
MapReduceService mapReduceService = supervisor.getMapReduceService();
ExecutorService es = mapReduceService.getExecutorService(name);
es.submit(this);
}
}
@Override
public void run() {
try {
ReducerChunk<Key, Chunk> reducerChunk;
while ((reducerChunk = reducerQueue.poll()) != null) {
if (cancelled.get()) {
return;
}
reduceChunk(reducerChunk.chunk);
processProcessedState(reducerChunk);
}
} catch (Throwable t) {
notifyRemoteException(supervisor, t);
if (t instanceof Error) {
ExceptionUtil.sneakyThrow(t);
}
} finally {
active.compareAndSet(true, false);
}
}
private void reduceChunk(Map<Key, Chunk> chunk) {
for (Map.Entry<Key, Chunk> entry : chunk.entrySet()) {
Reducer reducer = supervisor.getReducerByKey(entry.getKey());
if (reducer != null) {
Chunk chunkValue = entry.getValue();
if (chunkValue instanceof List) {
for (Object value : (List) chunkValue) {
reducer.reduce(value);
}
} else {
reducer.reduce(chunkValue);
}
}
}
}
private void processProcessedState(ReducerChunk<Key, Chunk> reducerChunk) {
// If partitionId is set this was the last chunk for this partition
if (reducerChunk.partitionId != -1) {
MapReduceService mapReduceService = supervisor.getMapReduceService();
ReducingFinishedNotification notification = new ReducingFinishedNotification(mapReduceService.getLocalAddress(), name,
jobId, reducerChunk.partitionId);
mapReduceService.sendNotification(reducerChunk.sender, notification);
}
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_mapreduce_impl_task_ReducerTask.java
|
4,518 |
public class IndicesTTLService extends AbstractLifecycleComponent<IndicesTTLService> {
public static final String INDICES_TTL_INTERVAL = "indices.ttl.interval";
public static final String INDEX_TTL_DISABLE_PURGE = "index.ttl.disable_purge";
private final ClusterService clusterService;
private final IndicesService indicesService;
private final Client client;
private volatile TimeValue interval;
private final int bulkSize;
private PurgerThread purgerThread;
@Inject
public IndicesTTLService(Settings settings, ClusterService clusterService, IndicesService indicesService, NodeSettingsService nodeSettingsService, Client client) {
super(settings);
this.clusterService = clusterService;
this.indicesService = indicesService;
this.client = client;
this.interval = componentSettings.getAsTime("interval", TimeValue.timeValueSeconds(60));
this.bulkSize = componentSettings.getAsInt("bulk_size", 10000);
nodeSettingsService.addListener(new ApplySettings());
}
@Override
protected void doStart() throws ElasticsearchException {
this.purgerThread = new PurgerThread(EsExecutors.threadName(settings, "[ttl_expire]"));
this.purgerThread.start();
}
@Override
protected void doStop() throws ElasticsearchException {
this.purgerThread.doStop();
this.purgerThread.interrupt();
}
@Override
protected void doClose() throws ElasticsearchException {
}
private class PurgerThread extends Thread {
volatile boolean running = true;
public PurgerThread(String name) {
super(name);
setDaemon(true);
}
public void doStop() {
running = false;
}
public void run() {
while (running) {
try {
List<IndexShard> shardsToPurge = getShardsToPurge();
purgeShards(shardsToPurge);
} catch (Throwable e) {
if (running) {
logger.warn("failed to execute ttl purge", e);
}
}
try {
Thread.sleep(interval.millis());
} catch (InterruptedException e) {
// ignore, if we are interrupted because we are shutting down, running will be false
}
}
}
/**
* Returns the shards to purge, i.e. the local started primary shards that have ttl enabled and disable_purge to false
*/
private List<IndexShard> getShardsToPurge() {
List<IndexShard> shardsToPurge = new ArrayList<IndexShard>();
MetaData metaData = clusterService.state().metaData();
for (IndexService indexService : indicesService) {
// check the value of disable_purge for this index
IndexMetaData indexMetaData = metaData.index(indexService.index().name());
if (indexMetaData == null) {
continue;
}
boolean disablePurge = indexMetaData.settings().getAsBoolean(INDEX_TTL_DISABLE_PURGE, false);
if (disablePurge) {
continue;
}
// should be optimized with the hasTTL flag
FieldMappers ttlFieldMappers = indexService.mapperService().name(TTLFieldMapper.NAME);
if (ttlFieldMappers == null) {
continue;
}
// check if ttl is enabled for at least one type of this index
boolean hasTTLEnabled = false;
for (FieldMapper ttlFieldMapper : ttlFieldMappers) {
if (((TTLFieldMapper) ttlFieldMapper).enabled()) {
hasTTLEnabled = true;
break;
}
}
if (hasTTLEnabled) {
for (IndexShard indexShard : indexService) {
if (indexShard.state() == IndexShardState.STARTED && indexShard.routingEntry().primary() && indexShard.routingEntry().started()) {
shardsToPurge.add(indexShard);
}
}
}
}
return shardsToPurge;
}
}
private void purgeShards(List<IndexShard> shardsToPurge) {
for (IndexShard shardToPurge : shardsToPurge) {
Query query = NumericRangeQuery.newLongRange(TTLFieldMapper.NAME, null, System.currentTimeMillis(), false, true);
Engine.Searcher searcher = shardToPurge.acquireSearcher("indices_ttl");
try {
logger.debug("[{}][{}] purging shard", shardToPurge.routingEntry().index(), shardToPurge.routingEntry().id());
ExpiredDocsCollector expiredDocsCollector = new ExpiredDocsCollector(shardToPurge.routingEntry().index());
searcher.searcher().search(query, expiredDocsCollector);
List<DocToPurge> docsToPurge = expiredDocsCollector.getDocsToPurge();
BulkRequestBuilder bulkRequest = client.prepareBulk();
for (DocToPurge docToPurge : docsToPurge) {
bulkRequest.add(new DeleteRequest().index(shardToPurge.routingEntry().index()).type(docToPurge.type).id(docToPurge.id).version(docToPurge.version).routing(docToPurge.routing));
bulkRequest = processBulkIfNeeded(bulkRequest, false);
}
processBulkIfNeeded(bulkRequest, true);
} catch (Exception e) {
logger.warn("failed to purge", e);
} finally {
searcher.release();
}
}
}
private static class DocToPurge {
public final String type;
public final String id;
public final long version;
public final String routing;
public DocToPurge(String type, String id, long version, String routing) {
this.type = type;
this.id = id;
this.version = version;
this.routing = routing;
}
}
private class ExpiredDocsCollector extends Collector {
private final MapperService mapperService;
private AtomicReaderContext context;
private List<DocToPurge> docsToPurge = new ArrayList<DocToPurge>();
public ExpiredDocsCollector(String index) {
mapperService = indicesService.indexService(index).mapperService();
}
public void setScorer(Scorer scorer) {
}
public boolean acceptsDocsOutOfOrder() {
return true;
}
public void collect(int doc) {
try {
UidAndRoutingFieldsVisitor fieldsVisitor = new UidAndRoutingFieldsVisitor();
context.reader().document(doc, fieldsVisitor);
Uid uid = fieldsVisitor.uid();
final long version = Versions.loadVersion(context.reader(), new Term(UidFieldMapper.NAME, uid.toBytesRef()));
docsToPurge.add(new DocToPurge(uid.type(), uid.id(), version, fieldsVisitor.routing()));
} catch (Exception e) {
logger.trace("failed to collect doc", e);
}
}
public void setNextReader(AtomicReaderContext context) throws IOException {
this.context = context;
}
public List<DocToPurge> getDocsToPurge() {
return this.docsToPurge;
}
}
private BulkRequestBuilder processBulkIfNeeded(BulkRequestBuilder bulkRequest, boolean force) {
if ((force && bulkRequest.numberOfActions() > 0) || bulkRequest.numberOfActions() >= bulkSize) {
try {
bulkRequest.execute(new ActionListener<BulkResponse>() {
@Override
public void onResponse(BulkResponse bulkResponse) {
logger.trace("bulk took " + bulkResponse.getTookInMillis() + "ms");
}
@Override
public void onFailure(Throwable e) {
logger.warn("failed to execute bulk");
}
});
} catch (Exception e) {
logger.warn("failed to process bulk", e);
}
bulkRequest = client.prepareBulk();
}
return bulkRequest;
}
class ApplySettings implements NodeSettingsService.Listener {
@Override
public void onRefreshSettings(Settings settings) {
TimeValue interval = settings.getAsTime(INDICES_TTL_INTERVAL, IndicesTTLService.this.interval);
if (!interval.equals(IndicesTTLService.this.interval)) {
logger.info("updating indices.ttl.interval from [{}] to [{}]", IndicesTTLService.this.interval, interval);
IndicesTTLService.this.interval = interval;
}
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_indices_ttl_IndicesTTLService.java
|
15 |
static final class AsyncSupply<U> extends Async {
final Generator<U> fn;
final CompletableFuture<U> dst;
AsyncSupply(Generator<U> fn, CompletableFuture<U> dst) {
this.fn = fn; this.dst = dst;
}
public final boolean exec() {
CompletableFuture<U> d; U u; Throwable ex;
if ((d = this.dst) != null && d.result == null) {
try {
u = fn.get();
ex = null;
} catch (Throwable rex) {
ex = rex;
u = null;
}
d.internalComplete(u, ex);
}
return true;
}
private static final long serialVersionUID = 5232453952276885070L;
}
| 0true
|
src_main_java_jsr166e_CompletableFuture.java
|
1,229 |
QUEUE {
@Override
<T> Recycler<T> build(Recycler.C<T> c, int limit, int estimatedThreadPoolSize, int availableProcessors) {
return concurrentDeque(c, limit);
}
},
| 0true
|
src_main_java_org_elasticsearch_cache_recycler_PageCacheRecycler.java
|
172 |
public abstract class OSoftThread extends Thread implements OService {
private volatile boolean shutdownFlag;
public OSoftThread() {
}
public OSoftThread(final ThreadGroup iThreadGroup) {
super(iThreadGroup, OSoftThread.class.getSimpleName());
setDaemon(true);
}
public OSoftThread(final String name) {
super(name);
setDaemon(true);
}
public OSoftThread(final ThreadGroup group, final String name) {
super(group, name);
setDaemon(true);
}
protected abstract void execute() throws Exception;
public void startup() {
}
public void shutdown() {
}
public void sendShutdown() {
shutdownFlag = true;
}
@Override
public void run() {
startup();
while (!shutdownFlag && !isInterrupted()) {
try {
beforeExecution();
execute();
afterExecution();
} catch (Throwable t) {
t.printStackTrace();
}
}
shutdown();
}
/**
* Pauses current thread until iTime timeout or a wake up by another thread.
*
* @param iTime
* @return true if timeout has reached, otherwise false. False is the case of wake-up by another thread.
*/
public static boolean pauseCurrentThread(long iTime) {
try {
if (iTime <= 0)
iTime = Long.MAX_VALUE;
Thread.sleep(iTime);
return true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
protected void beforeExecution() throws InterruptedException {
return;
}
protected void afterExecution() throws InterruptedException {
return;
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_thread_OSoftThread.java
|
740 |
public class ProductBundlePricingModelType implements Serializable, BroadleafEnumerationType {
private static final long serialVersionUID = 1L;
private static final Map<String, ProductBundlePricingModelType> TYPES = new LinkedHashMap<String, ProductBundlePricingModelType>();
public static final ProductBundlePricingModelType ITEM_SUM = new ProductBundlePricingModelType("ITEM_SUM","Item Sum");
public static final ProductBundlePricingModelType BUNDLE = new ProductBundlePricingModelType("BUNDLE","Bundle");
public static ProductBundlePricingModelType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public ProductBundlePricingModelType() {
//do nothing
}
public ProductBundlePricingModelType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
public String getType() {
return type;
}
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProductBundlePricingModelType other = (ProductBundlePricingModelType) obj;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_service_type_ProductBundlePricingModelType.java
|
599 |
interface ValuesTransformer<V> {
Collection<OIdentifiable> transformFromValue(V value);
V transformToValue(Collection<OIdentifiable> collection);
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_index_OIndexEngine.java
|
2,047 |
public class DeleteOperation extends BaseRemoveOperation {
boolean success = false;
public DeleteOperation(String name, Data dataKey) {
super(name, dataKey);
}
public DeleteOperation() {
}
public void run() {
success = recordStore.remove(dataKey) != null;
}
@Override
public Object getResponse() {
return success;
}
public void afterRun() {
if (success)
super.afterRun();
}
public boolean shouldBackup() {
return success;
}
@Override
public void onWaitExpire() {
getResponseHandler().sendResponse(false);
}
@Override
public String toString() {
return "DeleteOperation{" + name + "}";
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_map_operation_DeleteOperation.java
|
1,079 |
public class CacheProperty extends AbstractProperty {
public CacheProperty(long id, PropertyKey key, InternalVertex start, Object value, Entry data) {
super(id, key, start.it(), value);
this.data = data;
}
//############## Similar code as CacheEdge but be careful when copying #############################
private final Entry data;
@Override
public InternalRelation it() {
InternalRelation it = null;
InternalVertex startVertex = getVertex(0);
if (startVertex.hasAddedRelations() && startVertex.hasRemovedRelations()) {
//Test whether this relation has been replaced
final long id = super.getLongId();
it = Iterables.getOnlyElement(startVertex.getAddedRelations(new Predicate<InternalRelation>() {
@Override
public boolean apply(@Nullable InternalRelation internalRelation) {
return (internalRelation instanceof StandardProperty) && ((StandardProperty) internalRelation).getPreviousID() == id;
}
}), null);
}
return (it != null) ? it : super.it();
}
private void copyProperties(InternalRelation to) {
for (LongObjectCursor<Object> entry : getPropertyMap()) {
to.setPropertyDirect(tx().getExistingRelationType(entry.key), entry.value);
}
}
private synchronized InternalRelation update() {
StandardProperty copy = new StandardProperty(super.getLongId(), getPropertyKey(), getVertex(0), getValue(), ElementLifeCycle.Loaded);
copyProperties(copy);
copy.remove();
StandardProperty u = (StandardProperty) tx().addProperty(getVertex(0), getPropertyKey(), getValue());
if (type.getConsistencyModifier()!= ConsistencyModifier.FORK) u.setId(super.getLongId());
u.setPreviousID(super.getLongId());
copyProperties(u);
return u;
}
@Override
public long getLongId() {
InternalRelation it = it();
return (it == this) ? super.getLongId() : it.getLongId();
}
private RelationCache getPropertyMap() {
RelationCache map = data.getCache();
if (map == null || !map.hasProperties()) {
map = RelationConstructor.readRelationCache(data, tx());
}
return map;
}
@Override
public <O> O getPropertyDirect(RelationType type) {
return getPropertyMap().get(type.getLongId());
}
@Override
public Iterable<RelationType> getPropertyKeysDirect() {
RelationCache map = getPropertyMap();
List<RelationType> types = new ArrayList<RelationType>(map.numProperties());
for (LongObjectCursor<Object> entry : map) {
types.add(tx().getExistingRelationType(entry.key));
}
return types;
}
@Override
public void setPropertyDirect(RelationType type, Object value) {
update().setPropertyDirect(type, value);
}
@Override
public <O> O removePropertyDirect(RelationType type) {
return update().removePropertyDirect(type);
}
@Override
public byte getLifeCycle() {
if ((getVertex(0).hasRemovedRelations() || getVertex(0).isRemoved()) && tx().isRemovedRelation(super.getLongId()))
return ElementLifeCycle.Removed;
else return ElementLifeCycle.Loaded;
}
@Override
public void remove() {
if (!tx().isRemovedRelation(super.getLongId())) {
tx().removeRelation(this);
}// else throw InvalidElementException.removedException(this);
}
}
| 1no label
|
titan-core_src_main_java_com_thinkaurelius_titan_graphdb_relations_CacheProperty.java
|
388 |
public class ClusterUpdateSettingsResponse extends AcknowledgedResponse {
Settings transientSettings;
Settings persistentSettings;
ClusterUpdateSettingsResponse() {
this.persistentSettings = ImmutableSettings.EMPTY;
this.transientSettings = ImmutableSettings.EMPTY;
}
ClusterUpdateSettingsResponse(boolean acknowledged, Settings transientSettings, Settings persistentSettings) {
super(acknowledged);
this.persistentSettings = persistentSettings;
this.transientSettings = transientSettings;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
transientSettings = ImmutableSettings.readSettingsFromStream(in);
persistentSettings = ImmutableSettings.readSettingsFromStream(in);
readAcknowledged(in);
}
public Settings getTransientSettings() {
return transientSettings;
}
public Settings getPersistentSettings() {
return persistentSettings;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
ImmutableSettings.writeSettingsToStream(transientSettings, out);
ImmutableSettings.writeSettingsToStream(persistentSettings, out);
writeAcknowledged(out);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_settings_ClusterUpdateSettingsResponse.java
|
657 |
public interface CategoryXrefDao {
/**
* Retrieve all the category relationships for which the passed in
* {@code Category} primary key is a parent
*
* @param categoryId the parent {@code Category} primary key
* @return the list of child category relationships for the parent primary key
*/
@Nonnull
public List<CategoryXrefImpl> readXrefsByCategoryId(@Nonnull Long categoryId);
/**
* Retrieve all the category relationships for which the passed in
* {@code Category} primary key is a sub category (or child)
*
* @param subCategoryId the sub-categories primary key
* @return the list of category relationships for the sub-category primary key
*/
@Nonnull
public List<CategoryXrefImpl> readXrefsBySubCategoryId(@Nonnull Long subCategoryId);
/**
* Find a specific relationship between a parent categoy and sub-category (child)
*
* @param categoryId The primary key of the parent category
* @param subCategoryId The primary key of the sub-category
* @return The relationship between the parent and child categories
*/
@Nonnull
public CategoryXref readXrefByIds(@Nonnull Long categoryId, @Nonnull Long subCategoryId);
/**
* Persist the passed in category relationship to the datastore
*
* @param categoryXref the relationship between a parent and child category
* @return the persisted relationship between a parent and child category
*/
@Nonnull
public CategoryXref save(@Nonnull CategoryXrefImpl categoryXref);
/**
* Remove the passed in category relationship from the datastore
*
* @param categoryXref the category relationship to remove
*/
public void delete(@Nonnull CategoryXrefImpl categoryXref);
/**
* Persist the passed in category/product relationship to the datastore
*
* @param categoryProductXref the relationship between a category and product
* @return the persisted relationship between a category and product
*/
@Nonnull
public CategoryProductXrefImpl save(CategoryProductXrefImpl categoryProductXref);
}
| 0true
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_dao_CategoryXrefDao.java
|
767 |
public class IndexAction extends Action<IndexRequest, IndexResponse, IndexRequestBuilder> {
public static final IndexAction INSTANCE = new IndexAction();
public static final String NAME = "index";
private IndexAction() {
super(NAME);
}
@Override
public IndexResponse newResponse() {
return new IndexResponse();
}
@Override
public IndexRequestBuilder newRequestBuilder(Client client) {
return new IndexRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_index_IndexAction.java
|
533 |
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class ClientTxnSetTest {
static HazelcastInstance client;
static HazelcastInstance server1;
static HazelcastInstance server2;
@BeforeClass
public static void init(){
server1 = Hazelcast.newHazelcastInstance();
client = HazelcastClient.newHazelcastClient();
}
@AfterClass
public static void destroy() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test
public void testAdd_withinTxn() throws Exception {
final String element = "item1";
final String setName = randomString();
final ISet set = client.getSet(setName);
final TransactionContext context = client.newTransactionContext();
context.beginTransaction();
final TransactionalSet<Object> txnSet = context.getSet(setName);
assertTrue(txnSet.add(element));
assertEquals(1, txnSet.size());
context.commitTransaction();
}
@Test
public void testSetSizeAfterAdd_withinTxn() throws Exception {
final String element = "item1";
final String setName = randomString();
final ISet set = client.getSet(setName);
final TransactionContext context = client.newTransactionContext();
context.beginTransaction();
final TransactionalSet<Object> txnSet = context.getSet(setName);
txnSet.add(element);
context.commitTransaction();
assertEquals(1, set.size());
}
@Test
public void testRemove_withinTxn() throws Exception {
final String element = "item1";
final String setName = randomString();
final ISet set = client.getSet(setName);
set.add(element);
final TransactionContext context = client.newTransactionContext();
context.beginTransaction();
final TransactionalSet<Object> txnSet = context.getSet(setName);
assertTrue(txnSet.remove(element));
assertFalse(txnSet.remove("NOT_THERE"));
context.commitTransaction();
}
@Test
public void testSetSizeAfterRemove_withinTxn() throws Exception {
final String element = "item1";
final String setName = randomString();
final ISet set = client.getSet(setName);
set.add(element);
final TransactionContext context = client.newTransactionContext();
context.beginTransaction();
final TransactionalSet<Object> txnSet = context.getSet(setName);
txnSet.remove(element);
context.commitTransaction();
assertEquals(0, set.size());
}
@Test
public void testAddDuplicateElement_withinTxn() throws Exception {
final String element = "item1";
final String setName = randomString();
final TransactionContext context = client.newTransactionContext();
context.beginTransaction();
final TransactionalSet<Object> txnSet = context.getSet(setName);
assertTrue(txnSet.add(element));
assertFalse(txnSet.add(element));
context.commitTransaction();
assertEquals(1, client.getSet(setName).size());
}
@Test
public void testAddExistingElement_withinTxn() throws Exception {
final String element = "item1";
final String setName = randomString();
final ISet set = client.getSet(setName);
set.add(element);
final TransactionContext context = client.newTransactionContext();
context.beginTransaction();
final TransactionalSet<Object> txnSet = context.getSet(setName);
assertFalse(txnSet.add(element));
context.commitTransaction();
assertEquals(1,set.size());
}
@Test
public void testSetSizeAfterAddingDuplicateElement_withinTxn() throws Exception {
final String element = "item1";
final String setName = randomString();
final ISet set = client.getSet(setName);
set.add(element);
final TransactionContext context = client.newTransactionContext();
context.beginTransaction();
final TransactionalSet<Object> txnSet = context.getSet(setName);
txnSet.add(element);
context.commitTransaction();
assertEquals(1, set.size());
}
@Test
public void testAddRollBack() throws Exception {
final String setName = randomString();
final ISet set = client.getSet(setName);
set.add("item1");
final TransactionContext context = client.newTransactionContext();
context.beginTransaction();
final TransactionalSet<Object> setTxn = context.getSet(setName);
setTxn.add("item2");
context.rollbackTransaction();
assertEquals(1, set.size());
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_txn_ClientTxnSetTest.java
|
1,996 |
@Entity
@EntityListeners(value = { TemporalTimestampListener.class })
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_ROLE")
public class RoleImpl implements Role {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "RoleId")
@GenericGenerator(
name="RoleId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="RoleImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.profile.core.domain.RoleImpl")
}
)
@Column(name = "ROLE_ID")
protected Long id;
@Column(name = "ROLE_NAME", nullable = false)
@Index(name="ROLE_NAME_INDEX", columnNames={"ROLE_NAME"})
protected String roleName;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getRoleName() {
return roleName;
}
@Override
public void setRoleName(String roleName) {
this.roleName = roleName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((roleName == null) ? 0 : roleName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RoleImpl other = (RoleImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (roleName == null) {
if (other.roleName != null)
return false;
} else if (!roleName.equals(other.roleName))
return false;
return true;
}
}
| 1no label
|
core_broadleaf-profile_src_main_java_org_broadleafcommerce_profile_core_domain_RoleImpl.java
|
158 |
public class TestUpgradeOneDotFourToFiveIT
{
private static final File PATH = new File( "target/test-data/upgrade-1.4-5" );
@BeforeClass
public static void doBefore() throws Exception
{
deleteRecursively( PATH );
}
@Test( expected=IllegalLogFormatException.class )
public void cannotRecoverNoncleanShutdownDbWithOlderLogFormat() throws Exception
{
copyRecursively( findDatabaseDirectory( getClass(), "non-clean-1.4.2-db" ), PATH );
KernelHealth kernelHealth = mock( KernelHealth.class );
XaLogicalLog log = new XaLogicalLog( resourceFile(), null, null, null,
defaultFileSystemAbstraction(), new Monitors(), new DevNullLoggingService(), LogPruneStrategies.NO_PRUNING,
TransactionStateFactory.noStateFactory( new DevNullLoggingService() ), kernelHealth, 25 * 1024 * 1024, ALLOW_ALL );
log.open();
fail( "Shouldn't be able to start" );
}
protected File resourceFile()
{
return new File( PATH, "nioneo_logical.log" );
}
}
| 0true
|
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestUpgradeOneDotFourToFiveIT.java
|
5,838 |
public class ContextIndexSearcher extends IndexSearcher {
public static enum Stage {
NA,
MAIN_QUERY
}
/** The wrapped {@link IndexSearcher}. The reason why we sometimes prefer delegating to this searcher instead of <tt>super</tt> is that
* this instance may have more assertions, for example if it comes from MockInternalEngine which wraps the IndexSearcher into an
* AssertingIndexSearcher. */
private final IndexSearcher in;
private final SearchContext searchContext;
private CachedDfSource dfSource;
private List<Collector> queryCollectors;
private Stage currentState = Stage.NA;
private boolean enableMainDocIdSetCollector;
private DocIdSetCollector mainDocIdSetCollector;
public ContextIndexSearcher(SearchContext searchContext, Engine.Searcher searcher) {
super(searcher.reader());
in = searcher.searcher();
this.searchContext = searchContext;
setSimilarity(searcher.searcher().getSimilarity());
}
public void release() {
if (mainDocIdSetCollector != null) {
mainDocIdSetCollector.release();
}
}
public void dfSource(CachedDfSource dfSource) {
this.dfSource = dfSource;
}
/**
* Adds a query level collector that runs at {@link Stage#MAIN_QUERY}. Note, supports
* {@link org.elasticsearch.common.lucene.search.XCollector} allowing for a callback
* when collection is done.
*/
public void addMainQueryCollector(Collector collector) {
if (queryCollectors == null) {
queryCollectors = new ArrayList<Collector>();
}
queryCollectors.add(collector);
}
public DocIdSetCollector mainDocIdSetCollector() {
return this.mainDocIdSetCollector;
}
public void enableMainDocIdSetCollector() {
this.enableMainDocIdSetCollector = true;
}
public void inStage(Stage stage) {
this.currentState = stage;
}
public void finishStage(Stage stage) {
assert currentState == stage : "Expected stage " + stage + " but was stage " + currentState;
this.currentState = Stage.NA;
}
@Override
public Query rewrite(Query original) throws IOException {
if (original == searchContext.query() || original == searchContext.parsedQuery().query()) {
// optimize in case its the top level search query and we already rewrote it...
if (searchContext.queryRewritten()) {
return searchContext.query();
}
Query rewriteQuery = in.rewrite(original);
searchContext.updateRewriteQuery(rewriteQuery);
return rewriteQuery;
} else {
return in.rewrite(original);
}
}
@Override
public Weight createNormalizedWeight(Query query) throws IOException {
try {
// if its the main query, use we have dfs data, only then do it
if (dfSource != null && (query == searchContext.query() || query == searchContext.parsedQuery().query())) {
return dfSource.createNormalizedWeight(query);
}
return in.createNormalizedWeight(query);
} catch (Throwable t) {
searchContext.clearReleasables();
throw new RuntimeException(t);
}
}
@Override
public void search(List<AtomicReaderContext> leaves, Weight weight, Collector collector) throws IOException {
if (searchContext.timeoutInMillis() != -1) {
// TODO: change to use our own counter that uses the scheduler in ThreadPool
collector = new TimeLimitingCollector(collector, TimeLimitingCollector.getGlobalCounter(), searchContext.timeoutInMillis());
}
if (currentState == Stage.MAIN_QUERY) {
if (enableMainDocIdSetCollector) {
// TODO should we create a cache of segment->docIdSets so we won't create one each time?
collector = this.mainDocIdSetCollector = new DocIdSetCollector(searchContext.docSetCache(), collector);
}
if (searchContext.parsedPostFilter() != null) {
// this will only get applied to the actual search collector and not
// to any scoped collectors, also, it will only be applied to the main collector
// since that is where the filter should only work
collector = new FilteredCollector(collector, searchContext.parsedPostFilter().filter());
}
if (queryCollectors != null && !queryCollectors.isEmpty()) {
collector = new MultiCollector(collector, queryCollectors.toArray(new Collector[queryCollectors.size()]));
}
// apply the minimum score after multi collector so we filter facets as well
if (searchContext.minimumScore() != null) {
collector = new MinimumScoreCollector(collector, searchContext.minimumScore());
}
}
// we only compute the doc id set once since within a context, we execute the same query always...
try {
if (searchContext.timeoutInMillis() != -1) {
try {
super.search(leaves, weight, collector);
} catch (TimeLimitingCollector.TimeExceededException e) {
searchContext.queryResult().searchTimedOut(true);
}
} else {
super.search(leaves, weight, collector);
}
if (currentState == Stage.MAIN_QUERY) {
if (enableMainDocIdSetCollector) {
enableMainDocIdSetCollector = false;
mainDocIdSetCollector.postCollection();
}
if (queryCollectors != null && !queryCollectors.isEmpty()) {
for (Collector queryCollector : queryCollectors) {
if (queryCollector instanceof XCollector) {
((XCollector) queryCollector).postCollection();
}
}
}
}
} finally {
searchContext.clearReleasables();
}
}
@Override
public Explanation explain(Query query, int doc) throws IOException {
try {
if (searchContext.aliasFilter() == null) {
return super.explain(query, doc);
}
XFilteredQuery filteredQuery = new XFilteredQuery(query, searchContext.aliasFilter());
return super.explain(filteredQuery, doc);
} finally {
searchContext.clearReleasables();
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_search_internal_ContextIndexSearcher.java
|
342 |
static class TestMapStore extends MapStoreAdapter<Long, String> {
public volatile CountDownLatch latch;
@Override
public void store(Long key, String value) {
if (latch != null) {
latch.countDown();
}
}
@Override
public void storeAll(Map<Long, String> map) {
if (latch != null) {
latch.countDown();
}
}
@Override
public void deleteAll(Collection<Long> keys) {
if (latch != null) {
latch.countDown();
}
}
@Override
public void delete(Long key) {
if (latch != null) {
latch.countDown();
}
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java
|
45 |
public enum Multiplicity {
/**
* The given edge label specifies a multi-graph, meaning that the multiplicity is not constrained and that
* there may be multiple edges of this label between any given pair of vertices.
*
* @link http://en.wikipedia.org/wiki/Multigraph
*/
MULTI,
/**
* The given edge label specifies a simple graph, meaning that the multiplicity is not constrained but that there
* can only be at most a single edge of this label between a given pair of vertices.
*/
SIMPLE,
/**
* There can only be a single in-edge of this label for a given vertex but multiple out-edges (i.e. in-unique)
*/
ONE2MANY,
/**
* There can only be a single out-edge of this label for a given vertex but multiple in-edges (i.e. out-unique)
*/
MANY2ONE,
/**
* There can be only a single in and out-edge of this label for a given vertex (i.e. unique in both directions).
*/
ONE2ONE;
/**
* Whether this multiplicity imposes any constraint on the number of edges that may exist between a pair of vertices.
*
* @return
*/
public boolean isConstrained() {
return this!=MULTI;
}
public boolean isConstrained(Direction direction) {
if (direction==Direction.BOTH) return isConstrained();
if (this==MULTI) return false;
if (this==SIMPLE) return true;
return isUnique(direction);
}
/**
* If this multiplicity implies edge uniqueness in the given direction for any given vertex.
*
* @param direction
* @return
*/
public boolean isUnique(Direction direction) {
switch (direction) {
case IN:
return this==ONE2MANY || this==ONE2ONE;
case OUT:
return this==MANY2ONE || this==ONE2ONE;
case BOTH:
return this==ONE2ONE;
default: throw new AssertionError("Unknown direction: " + direction);
}
}
//######### CONVERTING MULTIPLICITY <-> CARDINALITY ########
public static Multiplicity convert(Cardinality cardinality) {
Preconditions.checkNotNull(cardinality);
switch(cardinality) {
case LIST: return MULTI;
case SET: return SIMPLE;
case SINGLE: return MANY2ONE;
default: throw new AssertionError("Unknown cardinality: " + cardinality);
}
}
public Cardinality getCardinality() {
switch (this) {
case MULTI: return Cardinality.LIST;
case SIMPLE: return Cardinality.SET;
case MANY2ONE: return Cardinality.SINGLE;
default: throw new AssertionError("Invalid multiplicity: " + this);
}
}
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_Multiplicity.java
|
64 |
class TransactionImpl implements Transaction
{
private static final int RS_ENLISTED = 0;
private static final int RS_SUSPENDED = 1;
private static final int RS_DELISTED = 2;
private static final int RS_READONLY = 3; // set in prepare
private final byte globalId[];
private boolean globalStartRecordWritten = false;
private final LinkedList<ResourceElement> resourceList = new LinkedList<>();
private int status = Status.STATUS_ACTIVE;
// volatile since at least toString is unsynchronized and reads it,
// but all logical operations are guarded with synchronization
private volatile boolean active = true;
private List<Synchronization> syncHooks = new ArrayList<>();
private final int eventIdentifier;
private final TxManager txManager;
private final StringLogger logger;
private final ForceMode forceMode;
private Thread owner;
private final TransactionState state;
TransactionImpl( byte[] xidGlobalId, TxManager txManager, ForceMode forceMode, TransactionStateFactory stateFactory,
StringLogger logger )
{
this.txManager = txManager;
this.logger = logger;
this.state = stateFactory.create( this );
globalId = xidGlobalId;
eventIdentifier = txManager.getNextEventIdentifier();
this.forceMode = forceMode;
owner = Thread.currentThread();
}
/**
* @return The event identifier for this transaction, a unique per database
* run identifier among all transactions initiated by the
* transaction manager. Currently an increasing natural number.
*/
Integer getEventIdentifier()
{
return eventIdentifier;
}
byte[] getGlobalId()
{
return globalId;
}
public TransactionState getState()
{
return state;
}
private String getStatusAsString()
{
return txManager.getTxStatusAsString( status ) + (active ? "" : " (suspended)");
}
@Override
public String toString()
{
return String.format( "Transaction(%d, owner:\"%s\")[%s,Resources=%d]",
eventIdentifier, owner.getName(), getStatusAsString(), resourceList.size() );
}
@Override
public synchronized void commit() throws RollbackException,
HeuristicMixedException, HeuristicRollbackException,
IllegalStateException, SystemException
{
txManager.commit();
}
boolean isGlobalStartRecordWritten()
{
return globalStartRecordWritten;
}
@Override
public synchronized void rollback() throws IllegalStateException,
SystemException
{
txManager.rollback();
}
@Override
public synchronized boolean enlistResource( XAResource xaRes )
throws RollbackException, IllegalStateException, SystemException
{
if ( xaRes == null )
{
throw new IllegalArgumentException( "Null xa resource" );
}
if ( status == Status.STATUS_ACTIVE || status == Status.STATUS_PREPARING )
{
try
{
if ( resourceList.size() == 0 )
{ // This is the first enlisted resource
ensureGlobalTxStartRecordWritten();
registerAndStartResource( xaRes );
}
else
{ // There are other enlisted resources. We have to check if any of them have the same Xid
Pair<Xid,ResourceElement> similarResource = findAlreadyRegisteredSimilarResource( xaRes );
if ( similarResource.other() != null )
{ // This exact resource is already enlisted
ResourceElement resource = similarResource.other();
// TODO either enlisted or delisted. is TMJOIN correct then?
xaRes.start( resource.getXid(), resource.getStatus() == RS_SUSPENDED ?
XAResource.TMRESUME : XAResource.TMJOIN );
resource.setStatus( RS_ENLISTED );
}
else if ( similarResource.first() != null )
{ // A similar resource, but not the exact same instance is already registered
Xid xid = similarResource.first();
addResourceToList( xid, xaRes );
xaRes.start( xid, XAResource.TMJOIN );
}
else
{
registerAndStartResource( xaRes );
}
}
return true;
}
catch ( XAException e )
{
logger.error( "Unable to enlist resource[" + xaRes + "]", e );
status = Status.STATUS_MARKED_ROLLBACK;
return false;
}
}
else if ( status == Status.STATUS_ROLLING_BACK ||
status == Status.STATUS_ROLLEDBACK ||
status == Status.STATUS_MARKED_ROLLBACK )
{
throw new RollbackException( "Tx status is: " + txManager.getTxStatusAsString( status ) );
}
throw new IllegalStateException( "Tx status is: " + txManager.getTxStatusAsString( status ) );
}
private Pair<Xid, ResourceElement> findAlreadyRegisteredSimilarResource( XAResource xaRes ) throws XAException
{
Xid sameXid = null;
ResourceElement sameResource = null;
for ( ResourceElement re : resourceList )
{
if ( sameXid == null && re.getResource().isSameRM( xaRes ) )
{
sameXid = re.getXid();
}
if ( xaRes == re.getResource() )
{
sameResource = re;
}
}
return sameXid == null && sameResource == null ?
Pair.<Xid,ResourceElement>empty() : Pair.of( sameXid, sameResource );
}
private void registerAndStartResource( XAResource xaRes ) throws XAException, SystemException
{
byte branchId[] = txManager.getBranchId( xaRes );
Xid xid = new XidImpl( globalId, branchId );
addResourceToList( xid, xaRes );
xaRes.start( xid, XAResource.TMNOFLAGS );
try
{
txManager.getTxLog().addBranch( globalId, branchId );
}
catch ( IOException e )
{
logger.error( "Error writing transaction log", e );
txManager.setTmNotOk( e );
throw Exceptions.withCause( new SystemException( "TM encountered a problem, "
+ " error writing transaction log" ), e );
}
}
private void ensureGlobalTxStartRecordWritten() throws SystemException
{
if ( !globalStartRecordWritten )
{
txManager.writeStartRecord( globalId );
globalStartRecordWritten = true;
}
}
private void addResourceToList( Xid xid, XAResource xaRes )
{
ResourceElement element = new ResourceElement( xid, xaRes );
if ( Arrays.equals( NeoStoreXaDataSource.BRANCH_ID, xid.getBranchQualifier() ) )
{
resourceList.addFirst( element );
}
else
{
resourceList.add( element );
}
}
@Override
public synchronized boolean delistResource( XAResource xaRes, int flag )
throws IllegalStateException
{
if ( xaRes == null )
{
throw new IllegalArgumentException( "Null xa resource" );
}
if ( flag != XAResource.TMSUCCESS && flag != XAResource.TMSUSPEND &&
flag != XAResource.TMFAIL )
{
throw new IllegalArgumentException( "Illegal flag: " + flag );
}
ResourceElement re = null;
for ( ResourceElement reMatch : resourceList )
{
if ( reMatch.getResource() == xaRes )
{
re = reMatch;
break;
}
}
if ( re == null )
{
return false;
}
if ( status == Status.STATUS_ACTIVE ||
status == Status.STATUS_MARKED_ROLLBACK )
{
try
{
xaRes.end( re.getXid(), flag );
if ( flag == XAResource.TMSUSPEND || flag == XAResource.TMFAIL )
{
re.setStatus( RS_SUSPENDED );
}
else
{
re.setStatus( RS_DELISTED );
}
return true;
}
catch ( XAException e )
{
logger.error( "Unable to delist resource[" + xaRes + "]", e );
status = Status.STATUS_MARKED_ROLLBACK;
return false;
}
}
throw new IllegalStateException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
// TODO: figure out if this needs synchronization or make status volatile
@Override
public int getStatus() // throws SystemException
{
return status;
}
void setStatus( int status )
{
this.status = status;
}
private boolean beforeCompletionRunning = false;
private List<Synchronization> syncHooksAdded = new ArrayList<>();
@Override
public synchronized void registerSynchronization( Synchronization s )
throws RollbackException, IllegalStateException
{
if ( s == null )
{
throw new IllegalArgumentException( "Null parameter" );
}
if ( status == Status.STATUS_ACTIVE ||
status == Status.STATUS_PREPARING ||
status == Status.STATUS_MARKED_ROLLBACK )
{
if ( !beforeCompletionRunning )
{
syncHooks.add( s );
}
else
{
// avoid CME if synchronization is added in before completion
syncHooksAdded.add( s );
}
}
else if ( status == Status.STATUS_ROLLING_BACK ||
status == Status.STATUS_ROLLEDBACK )
{
throw new RollbackException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
else
{
throw new IllegalStateException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
}
synchronized void doBeforeCompletion()
{
beforeCompletionRunning = true;
try
{
for ( Synchronization s : syncHooks )
{
try
{
s.beforeCompletion();
}
catch ( Throwable t )
{
addRollbackCause( t );
}
}
// execute any hooks added since we entered doBeforeCompletion
while ( !syncHooksAdded.isEmpty() )
{
List<Synchronization> addedHooks = syncHooksAdded;
syncHooksAdded = new ArrayList<>();
for ( Synchronization s : addedHooks )
{
s.beforeCompletion();
syncHooks.add( s );
}
}
}
finally
{
beforeCompletionRunning = false;
}
}
synchronized void doAfterCompletion()
{
if ( syncHooks != null )
{
for ( Synchronization s : syncHooks )
{
try
{
s.afterCompletion( status );
}
catch ( Throwable t )
{
logger.warn( "Caught exception from tx syncronization[" + s
+ "] afterCompletion()", t );
}
}
syncHooks = null; // help gc
}
}
@Override
public void setRollbackOnly() throws IllegalStateException
{
if ( status == Status.STATUS_ACTIVE ||
status == Status.STATUS_PREPARING ||
status == Status.STATUS_PREPARED ||
status == Status.STATUS_MARKED_ROLLBACK ||
status == Status.STATUS_ROLLING_BACK )
{
status = Status.STATUS_MARKED_ROLLBACK;
}
else
{
throw new IllegalStateException( "Tx status is: "
+ txManager.getTxStatusAsString( status ) );
}
}
@Override
public boolean equals( Object o )
{
if ( !(o instanceof TransactionImpl) )
{
return false;
}
TransactionImpl other = (TransactionImpl) o;
return this.eventIdentifier == other.eventIdentifier;
}
private volatile int hashCode = 0;
private Throwable rollbackCause;
@Override
public int hashCode()
{
if ( hashCode == 0 )
{
hashCode = 3217 * eventIdentifier;
}
return hashCode;
}
int getResourceCount()
{
return resourceList.size();
}
private boolean isOnePhase()
{
if ( resourceList.size() == 0 )
{
logger.warn( "Detected zero resources in resourceList" );
return true;
}
// check for more than one unique xid
Iterator<ResourceElement> itr = resourceList.iterator();
Xid xid = itr.next().getXid();
while ( itr.hasNext() )
{
if ( !xid.equals( itr.next().getXid() ) )
{
return false;
}
}
return true;
}
void doCommit() throws XAException, SystemException
{
boolean onePhase = isOnePhase();
boolean readOnly = true;
if ( !onePhase )
{
// prepare
status = Status.STATUS_PREPARING;
LinkedList<Xid> preparedXids = new LinkedList<>();
for ( ResourceElement re : resourceList )
{
if ( !preparedXids.contains( re.getXid() ) )
{
preparedXids.add( re.getXid() );
int vote = re.getResource().prepare( re.getXid() );
if ( vote == XAResource.XA_OK )
{
readOnly = false;
}
else if ( vote == XAResource.XA_RDONLY )
{
re.setStatus( RS_READONLY );
}
else
{
// rollback tx
status = Status.STATUS_MARKED_ROLLBACK;
return;
}
}
else
{
// set it to readonly, only need to commit once
re.setStatus( RS_READONLY );
}
}
if ( readOnly )
{
status = Status.STATUS_COMMITTED;
return;
}
else
{
status = Status.STATUS_PREPARED;
}
// everyone has prepared - mark as committing
try
{
txManager.getTxLog().markAsCommitting( getGlobalId(), forceMode );
}
catch ( IOException e )
{
logger.error( "Error writing transaction log", e );
txManager.setTmNotOk( e );
throw Exceptions.withCause( new SystemException( "TM encountered a problem, "
+ " error writing transaction log" ), e );
}
}
// commit
status = Status.STATUS_COMMITTING;
RuntimeException benignException = null;
for ( ResourceElement re : resourceList )
{
if ( re.getStatus() != RS_READONLY )
{
try
{
re.getResource().commit( re.getXid(), onePhase );
}
catch ( XAException e )
{
throw e;
}
catch ( CommitNotificationFailedException e )
{
benignException = e;
}
catch( Throwable e )
{
throw Exceptions.withCause( new XAException( XAException.XAER_RMERR ), e );
}
}
}
status = Status.STATUS_COMMITTED;
if ( benignException != null )
{
throw benignException;
}
}
void doRollback() throws XAException
{
status = Status.STATUS_ROLLING_BACK;
LinkedList<Xid> rolledbackXids = new LinkedList<>();
for ( ResourceElement re : resourceList )
{
if ( !rolledbackXids.contains( re.getXid() ) )
{
rolledbackXids.add( re.getXid() );
re.getResource().rollback( re.getXid() );
}
}
status = Status.STATUS_ROLLEDBACK;
}
private static class ResourceElement
{
private Xid xid = null;
private XAResource resource = null;
private int status;
ResourceElement( Xid xid, XAResource resource )
{
this.xid = xid;
this.resource = resource;
status = RS_ENLISTED;
}
Xid getXid()
{
return xid;
}
XAResource getResource()
{
return resource;
}
int getStatus()
{
return status;
}
void setStatus( int status )
{
this.status = status;
}
@Override
public String toString()
{
String statusString;
switch ( status )
{
case RS_ENLISTED:
statusString = "ENLISTED";
break;
case RS_DELISTED:
statusString = "DELISTED";
break;
case RS_SUSPENDED:
statusString = "SUSPENDED";
break;
case RS_READONLY:
statusString = "READONLY";
break;
default:
statusString = "UNKNOWN";
}
return "Xid[" + xid + "] XAResource[" + resource + "] Status["
+ statusString + "]";
}
}
boolean isActive()
{
return active;
}
synchronized void markAsActive()
{
if ( active )
{
throw new IllegalStateException( "Transaction[" + this
+ "] already active" );
}
owner = Thread.currentThread();
active = true;
}
synchronized void markAsSuspended()
{
if ( !active )
{
throw new IllegalStateException( "Transaction[" + this
+ "] already suspended" );
}
active = false;
}
public ForceMode getForceMode()
{
return forceMode;
}
public Throwable getRollbackCause()
{
return rollbackCause;
}
private void addRollbackCause( Throwable cause )
{
if ( rollbackCause == null )
{
rollbackCause = cause;
}
else
{
if ( !(rollbackCause instanceof MultipleCauseException) )
{
rollbackCause = new MultipleCauseException(
"Multiple exceptions occurred, stack traces of all of them available below, " +
"or via #getCauses().",
rollbackCause );
}
((MultipleCauseException) rollbackCause).addCause( cause );
}
}
public void finish( boolean successful )
{
if ( state.isRemotelyInitialized() )
{
getState().getTxHook().remotelyFinishTransaction( eventIdentifier, successful );
}
}
}
| 0true
|
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TransactionImpl.java
|
62 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_FLD_ENUM")
@Cache(usage= CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blCMSElements")
public class FieldEnumerationImpl implements FieldEnumeration {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "FieldEnumerationId")
@GenericGenerator(
name="FieldEnumerationId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="FieldEnumerationImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.cms.field.domain.FieldEnumerationImpl")
}
)
@Column(name = "FLD_ENUM_ID")
protected Long id;
@Column (name = "NAME")
protected String name;
@OneToMany(mappedBy = "fieldEnumeration", targetEntity = FieldEnumerationItemImpl.class, cascade = {CascadeType.ALL})
@Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blCMSElements")
@OrderBy("fieldOrder")
@BatchSize(size = 20)
protected List<FieldEnumerationItem> enumerationItems;
@Override
public List<FieldEnumerationItem> getEnumerationItems() {
return enumerationItems;
}
@Override
public void setEnumerationItems(List<FieldEnumerationItem> enumerationItems) {
this.enumerationItems = enumerationItems;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_field_domain_FieldEnumerationImpl.java
|
830 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_ORDER_ITEM_ADJUSTMENT")
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements")
@AdminPresentationMergeOverrides(
{
@AdminPresentationMergeOverride(name = "", mergeEntries =
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.READONLY,
booleanOverrideValue = true))
}
)
@AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "OrderItemAdjustmentImpl_baseOrderItemAdjustment")
public class OrderItemAdjustmentImpl implements OrderItemAdjustment, CurrencyCodeIdentifiable {
public static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator= "OrderItemAdjustmentId")
@GenericGenerator(
name="OrderItemAdjustmentId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="OrderItemAdjustmentImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.offer.domain.OrderItemAdjustmentImpl")
}
)
@Column(name = "ORDER_ITEM_ADJUSTMENT_ID")
protected Long id;
@ManyToOne(targetEntity = OrderItemImpl.class)
@JoinColumn(name = "ORDER_ITEM_ID")
@Index(name="OIADJUST_ITEM_INDEX", columnNames={"ORDER_ITEM_ID"})
@AdminPresentation(excluded = true)
protected OrderItem orderItem;
@ManyToOne(targetEntity = OfferImpl.class, optional=false)
@JoinColumn(name = "OFFER_ID")
@Index(name="OIADJUST_OFFER_INDEX", columnNames={"OFFER_ID"})
@AdminPresentation(friendlyName = "OrderItemAdjustmentImpl_Offer", order=1000,
group = "OrderItemAdjustmentImpl_Description", prominent = true, gridOrder = 1000)
@AdminPresentationToOneLookup()
protected Offer offer;
@Column(name = "ADJUSTMENT_REASON", nullable=false)
@AdminPresentation(friendlyName = "OrderItemAdjustmentImpl_Item_Adjustment_Reason", order=2000)
protected String reason;
@Column(name = "ADJUSTMENT_VALUE", nullable=false, precision=19, scale=5)
@AdminPresentation(friendlyName = "OrderItemAdjustmentImpl_Item_Adjustment_Value", order=3000,
fieldType = SupportedFieldType.MONEY, prominent = true,
gridOrder = 2000)
protected BigDecimal value = Money.ZERO.getAmount();
@Column(name = "APPLIED_TO_SALE_PRICE")
@AdminPresentation(friendlyName = "OrderItemAdjustmentImpl_Apply_To_Sale_Price", order=4000)
protected boolean appliedToSalePrice;
@Transient
protected Money retailValue;
@Transient
protected Money salesValue;
@Override
public void init(OrderItem orderItem, Offer offer, String reason){
this.orderItem = orderItem;
this.offer = offer;
this.reason = reason;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public OrderItem getOrderItem() {
return orderItem;
}
@Override
public Offer getOffer() {
return offer;
}
@Override
public String getReason() {
return reason;
}
@Override
public void setReason(String reason) {
this.reason = reason;
}
@Override
public void setOrderItem(OrderItem orderItem) {
this.orderItem = orderItem;
}
public void setOffer(Offer offer) {
this.offer = offer;
}
@Override
public Money getValue() {
return value == null ? null : BroadleafCurrencyUtils.getMoney(value, getOrderItem().getOrder().getCurrency());
}
@Override
public void setValue(Money value) {
this.value = value.getAmount();
}
@Override
public boolean isAppliedToSalePrice() {
return appliedToSalePrice;
}
@Override
public void setAppliedToSalePrice(boolean appliedToSalePrice) {
this.appliedToSalePrice = appliedToSalePrice;
}
@Override
public Money getRetailPriceValue() {
if (retailValue == null) {
return BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, getOrderItem().getOrder().getCurrency());
}
return this.retailValue;
}
@Override
public void setRetailPriceValue(Money retailPriceValue) {
this.retailValue = retailPriceValue;
}
@Override
public Money getSalesPriceValue() {
if (salesValue == null) {
return BroadleafCurrencyUtils.getMoney(BigDecimal.ZERO, getOrderItem().getOrder().getCurrency());
}
return salesValue;
}
@Override
public void setSalesPriceValue(Money salesPriceValue) {
this.salesValue = salesPriceValue;
}
@Override
public String getCurrencyCode() {
return ((CurrencyCodeIdentifiable) orderItem).getCurrencyCode();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((offer == null) ? 0 : offer.hashCode());
result = prime * result + ((orderItem == null) ? 0 : orderItem.hashCode());
result = prime * result + ((reason == null) ? 0 : reason.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
OrderItemAdjustmentImpl other = (OrderItemAdjustmentImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (offer == null) {
if (other.offer != null) {
return false;
}
} else if (!offer.equals(other.offer)) {
return false;
}
if (orderItem == null) {
if (other.orderItem != null) {
return false;
}
} else if (!orderItem.equals(other.orderItem)) {
return false;
}
if (reason == null) {
if (other.reason != null) {
return false;
}
} else if (!reason.equals(other.reason)) {
return false;
}
if (value == null) {
if (other.value != null) {
return false;
}
} else if (!value.equals(other.value)) {
return false;
}
return true;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_OrderItemAdjustmentImpl.java
|
1,639 |
new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()) {
String senderNode = null;
ODistributedResponse message = null;
try {
message = nodeResponseQueue.take();
if (message != null) {
senderNode = message.getSenderNodeName();
dispatchResponseToThread(message);
}
} catch (InterruptedException e) {
// EXIT CURRENT THREAD
Thread.interrupted();
break;
} catch (Throwable e) {
ODistributedServerLog.error(this, manager.getLocalNodeName(), senderNode, DIRECTION.IN,
"error on reading distributed response", e, message != null ? message.getPayload() : "-");
}
}
}
}).start();
| 1no label
|
distributed_src_main_java_com_orientechnologies_orient_server_hazelcast_OHazelcastDistributedMessageService.java
|
3,726 |
public class DynamicTemplate {
public static enum MatchType {
SIMPLE,
REGEX;
public static MatchType fromString(String value) {
if ("simple".equals(value)) {
return SIMPLE;
} else if ("regex".equals(value)) {
return REGEX;
}
throw new ElasticsearchIllegalArgumentException("No matching pattern matched on [" + value + "]");
}
}
public static DynamicTemplate parse(String name, Map<String, Object> conf) throws MapperParsingException {
String match = null;
String pathMatch = null;
String unmatch = null;
String pathUnmatch = null;
Map<String, Object> mapping = null;
String matchMappingType = null;
String matchPattern = "simple";
for (Map.Entry<String, Object> entry : conf.entrySet()) {
String propName = Strings.toUnderscoreCase(entry.getKey());
if ("match".equals(propName)) {
match = entry.getValue().toString();
} else if ("path_match".equals(propName)) {
pathMatch = entry.getValue().toString();
} else if ("unmatch".equals(propName)) {
unmatch = entry.getValue().toString();
} else if ("path_unmatch".equals(propName)) {
pathUnmatch = entry.getValue().toString();
} else if ("match_mapping_type".equals(propName)) {
matchMappingType = entry.getValue().toString();
} else if ("match_pattern".equals(propName)) {
matchPattern = entry.getValue().toString();
} else if ("mapping".equals(propName)) {
mapping = (Map<String, Object>) entry.getValue();
}
}
if (match == null && pathMatch == null && matchMappingType == null) {
throw new MapperParsingException("template must have match, path_match or match_mapping_type set");
}
if (mapping == null) {
throw new MapperParsingException("template must have mapping set");
}
return new DynamicTemplate(name, conf, pathMatch, pathUnmatch, match, unmatch, matchMappingType, MatchType.fromString(matchPattern), mapping);
}
private final String name;
private final Map<String, Object> conf;
private final String pathMatch;
private final String pathUnmatch;
private final String match;
private final String unmatch;
private final MatchType matchType;
private final String matchMappingType;
private final Map<String, Object> mapping;
public DynamicTemplate(String name, Map<String, Object> conf, String pathMatch, String pathUnmatch, String match, String unmatch, String matchMappingType, MatchType matchType, Map<String, Object> mapping) {
this.name = name;
this.conf = new TreeMap<String, Object>(conf);
this.pathMatch = pathMatch;
this.pathUnmatch = pathUnmatch;
this.match = match;
this.unmatch = unmatch;
this.matchType = matchType;
this.matchMappingType = matchMappingType;
this.mapping = mapping;
}
public String name() {
return this.name;
}
public Map<String, Object> conf() {
return this.conf;
}
public boolean match(ContentPath path, String name, String dynamicType) {
if (pathMatch != null && !patternMatch(pathMatch, path.fullPathAsText(name))) {
return false;
}
if (match != null && !patternMatch(match, name)) {
return false;
}
if (pathUnmatch != null && patternMatch(pathUnmatch, path.fullPathAsText(name))) {
return false;
}
if (unmatch != null && patternMatch(unmatch, name)) {
return false;
}
if (matchMappingType != null) {
if (dynamicType == null) {
return false;
}
if (!patternMatch(matchMappingType, dynamicType)) {
return false;
}
}
return true;
}
public boolean hasType() {
return mapping.containsKey("type");
}
public String mappingType(String dynamicType) {
return mapping.containsKey("type") ? mapping.get("type").toString() : dynamicType;
}
private boolean patternMatch(String pattern, String str) {
if (matchType == MatchType.SIMPLE) {
return Regex.simpleMatch(pattern, str);
}
return str.matches(pattern);
}
public Map<String, Object> mappingForName(String name, String dynamicType) {
return processMap(mapping, name, dynamicType);
}
private Map<String, Object> processMap(Map<String, Object> map, String name, String dynamicType) {
Map<String, Object> processedMap = Maps.newHashMap();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey().replace("{name}", name).replace("{dynamic_type}", dynamicType).replace("{dynamicType}", dynamicType);
Object value = entry.getValue();
if (value instanceof Map) {
value = processMap((Map<String, Object>) value, name, dynamicType);
} else if (value instanceof List) {
value = processList((List) value, name, dynamicType);
} else if (value instanceof String) {
value = value.toString().replace("{name}", name).replace("{dynamic_type}", dynamicType).replace("{dynamicType}", dynamicType);
}
processedMap.put(key, value);
}
return processedMap;
}
private List processList(List list, String name, String dynamicType) {
List processedList = new ArrayList();
for (Object value : list) {
if (value instanceof Map) {
value = processMap((Map<String, Object>) value, name, dynamicType);
} else if (value instanceof List) {
value = processList((List) value, name, dynamicType);
} else if (value instanceof String) {
value = value.toString().replace("{name}", name).replace("{dynamic_type}", dynamicType).replace("{dynamicType}", dynamicType);
}
processedList.add(value);
}
return processedList;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DynamicTemplate that = (DynamicTemplate) o;
// check if same matching, if so, replace the mapping
if (match != null ? !match.equals(that.match) : that.match != null) {
return false;
}
if (matchMappingType != null ? !matchMappingType.equals(that.matchMappingType) : that.matchMappingType != null) {
return false;
}
if (matchType != that.matchType) {
return false;
}
if (unmatch != null ? !unmatch.equals(that.unmatch) : that.unmatch != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
// check if same matching, if so, replace the mapping
int result = match != null ? match.hashCode() : 0;
result = 31 * result + (unmatch != null ? unmatch.hashCode() : 0);
result = 31 * result + (matchType != null ? matchType.hashCode() : 0);
result = 31 * result + (matchMappingType != null ? matchMappingType.hashCode() : 0);
return result;
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_mapper_object_DynamicTemplate.java
|
349 |
public interface ODatabaseSchemaAware<T extends Object> extends ODatabaseComplex<T> {
/**
* Creates a new entity instance. Each database implementation will return the right type.
*
* @return The new instance.
*/
public <RET extends Object> RET newInstance(String iClassName);
/**
* Counts the entities contained in the specified class.
*
* @param iClassName
* Class name
* @return Total entities
*/
public long countClass(String iClassName);
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_ODatabaseSchemaAware.java
|
3,746 |
public class SessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
}
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
WebFilter.destroyOriginalSession(httpSessionEvent.getSession());
}
}
| 1no label
|
hazelcast-wm_src_main_java_com_hazelcast_web_SessionListener.java
|
150 |
public class OCharSerializer implements OBinarySerializer<Character> {
private static final OBinaryConverter BINARY_CONVERTER = OBinaryConverterFactory.getConverter();
/**
* size of char value in bytes
*/
public static final int CHAR_SIZE = 2;
public static OCharSerializer INSTANCE = new OCharSerializer();
public static final byte ID = 3;
public int getObjectSize(final Character object, Object... hints) {
return CHAR_SIZE;
}
public void serialize(final Character object, final byte[] stream, final int startPosition, Object... hints) {
stream[startPosition] = (byte) (object >>> 8);
stream[startPosition + 1] = (byte) (object.charValue());
}
public Character deserialize(final byte[] stream, final int startPosition) {
return (char) (((stream[startPosition] & 0xFF) << 8) + (stream[startPosition + 1] & 0xFF));
}
public int getObjectSize(final byte[] stream, final int startPosition) {
return CHAR_SIZE;
}
public byte getId() {
return ID;
}
public int getObjectSizeNative(byte[] stream, int startPosition) {
return CHAR_SIZE;
}
public void serializeNative(Character object, byte[] stream, int startPosition, Object... hints) {
BINARY_CONVERTER.putChar(stream, startPosition, object, ByteOrder.nativeOrder());
}
public Character deserializeNative(byte[] stream, int startPosition) {
return BINARY_CONVERTER.getChar(stream, startPosition, ByteOrder.nativeOrder());
}
@Override
public void serializeInDirectMemory(Character object, ODirectMemoryPointer pointer, long offset, Object... hints) {
pointer.setChar(offset, object);
}
@Override
public Character deserializeFromDirectMemory(ODirectMemoryPointer pointer, long offset) {
return pointer.getChar(offset);
}
@Override
public int getObjectSizeInDirectMemory(ODirectMemoryPointer pointer, long offset) {
return CHAR_SIZE;
}
public boolean isFixedLength() {
return true;
}
public int getFixedLength() {
return CHAR_SIZE;
}
@Override
public Character preprocess(Character value, Object... hints) {
return value;
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_serialization_types_OCharSerializer.java
|
173 |
public interface Entry extends StaticBuffer, MetaAnnotated {
public int getValuePosition();
public boolean hasValue();
public StaticBuffer getColumn();
public<T> T getColumnAs(Factory<T> factory);
public StaticBuffer getValue();
public<T> T getValueAs(Factory<T> factory);
/**
* Returns the cached parsed representation of this Entry if it exists, else NULL
*
* @return
*/
public RelationCache getCache();
/**
* Sets the cached parsed representation of this Entry. This method does not synchronize,
* so a previously set representation would simply be overwritten.
*
* @param cache
*/
public void setCache(RelationCache cache);
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_Entry.java
|
561 |
public class PutMappingAction extends IndicesAction<PutMappingRequest, PutMappingResponse, PutMappingRequestBuilder> {
public static final PutMappingAction INSTANCE = new PutMappingAction();
public static final String NAME = "indices/mapping/put";
private PutMappingAction() {
super(NAME);
}
@Override
public PutMappingResponse newResponse() {
return new PutMappingResponse();
}
@Override
public PutMappingRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new PutMappingRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_mapping_put_PutMappingAction.java
|
700 |
public class BulkShardRequest extends ShardReplicationOperationRequest<BulkShardRequest> {
private int shardId;
private BulkItemRequest[] items;
private boolean refresh;
BulkShardRequest() {
}
BulkShardRequest(String index, int shardId, boolean refresh, BulkItemRequest[] items) {
this.index = index;
this.shardId = shardId;
this.items = items;
this.refresh = refresh;
}
boolean refresh() {
return this.refresh;
}
int shardId() {
return shardId;
}
BulkItemRequest[] items() {
return items;
}
/**
* Before we fork on a local thread, make sure we copy over the bytes if they are unsafe
*/
@Override
public void beforeLocalFork() {
for (BulkItemRequest item : items) {
if (item.request() instanceof InstanceShardOperationRequest) {
((InstanceShardOperationRequest) item.request()).beforeLocalFork();
} else {
((ShardReplicationOperationRequest) item.request()).beforeLocalFork();
}
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVInt(shardId);
out.writeVInt(items.length);
for (BulkItemRequest item : items) {
if (item != null) {
out.writeBoolean(true);
item.writeTo(out);
} else {
out.writeBoolean(false);
}
}
out.writeBoolean(refresh);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
shardId = in.readVInt();
items = new BulkItemRequest[in.readVInt()];
for (int i = 0; i < items.length; i++) {
if (in.readBoolean()) {
items[i] = BulkItemRequest.readBulkItem(in);
}
}
refresh = in.readBoolean();
}
}
| 0true
|
src_main_java_org_elasticsearch_action_bulk_BulkShardRequest.java
|
334 |
public class NodesRestartAction extends ClusterAction<NodesRestartRequest, NodesRestartResponse, NodesRestartRequestBuilder> {
public static final NodesRestartAction INSTANCE = new NodesRestartAction();
public static final String NAME = "cluster/nodes/restart";
private NodesRestartAction() {
super(NAME);
}
@Override
public NodesRestartResponse newResponse() {
return new NodesRestartResponse();
}
@Override
public NodesRestartRequestBuilder newRequestBuilder(ClusterAdminClient client) {
return new NodesRestartRequestBuilder(client);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_node_restart_NodesRestartAction.java
|
4 |
public interface Action<A> { void accept(A a); }
| 0true
|
src_main_java_jsr166e_CompletableFuture.java
|
1,049 |
public class ItemListenerConfig extends ListenerConfig {
private boolean includeValue = true;
private ItemListenerConfigReadOnly readOnly;
public ItemListenerConfig() {
super();
}
public ItemListenerConfig(String className, boolean includeValue) {
super(className);
this.includeValue = includeValue;
}
public ItemListenerConfig(ItemListener implementation, boolean includeValue) {
super(implementation);
this.includeValue = includeValue;
}
public ItemListenerConfig(ItemListenerConfig config) {
includeValue = config.isIncludeValue();
implementation = config.getImplementation();
className = config.getClassName();
}
public ItemListenerConfigReadOnly getAsReadOnly() {
if (readOnly == null ){
readOnly = new ItemListenerConfigReadOnly(this);
}
return readOnly;
}
public ItemListener getImplementation() {
return (ItemListener) implementation;
}
public ItemListenerConfig setImplementation(final ItemListener implementation) {
super.setImplementation(implementation);
return this;
}
public boolean isIncludeValue() {
return includeValue;
}
public ItemListenerConfig setIncludeValue(boolean includeValue) {
this.includeValue = includeValue;
return this;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("ItemListenerConfig");
sb.append("{includeValue=").append(includeValue);
sb.append('}');
return sb.toString();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_config_ItemListenerConfig.java
|
52 |
static final class EntrySpliterator<K,V> extends Traverser<K,V>
implements ConcurrentHashMapSpliterator<Map.Entry<K,V>> {
final ConcurrentHashMapV8<K,V> map; // To export MapEntry
long est; // size estimate
EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
long est, ConcurrentHashMapV8<K,V> map) {
super(tab, size, index, limit);
this.map = map;
this.est = est;
}
public ConcurrentHashMapSpliterator<Map.Entry<K,V>> trySplit() {
int i, f, h;
return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
f, est >>>= 1, map);
}
public void forEachRemaining(Action<? super Map.Entry<K,V>> action) {
if (action == null) throw new NullPointerException();
for (Node<K,V> p; (p = advance()) != null; )
action.apply(new MapEntry<K,V>(p.key, p.val, map));
}
public boolean tryAdvance(Action<? super Map.Entry<K,V>> action) {
if (action == null) throw new NullPointerException();
Node<K,V> p;
if ((p = advance()) == null)
return false;
action.apply(new MapEntry<K,V>(p.key, p.val, map));
return true;
}
public long estimateSize() { return est; }
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
3,374 |
final class BasicOperationService implements InternalOperationService {
private final AtomicLong executedOperationsCount = new AtomicLong();
private final NodeEngineImpl nodeEngine;
private final Node node;
private final ILogger logger;
private final AtomicLong callIdGen = new AtomicLong(1);
private final Map<RemoteCallKey, RemoteCallKey> executingCalls;
final ConcurrentMap<Long, BasicInvocation> invocations;
private final long defaultCallTimeout;
private final ExecutionService executionService;
final BasicOperationScheduler scheduler;
BasicOperationService(NodeEngineImpl nodeEngine) {
this.nodeEngine = nodeEngine;
this.node = nodeEngine.getNode();
this.logger = node.getLogger(OperationService.class);
this.defaultCallTimeout = node.getGroupProperties().OPERATION_CALL_TIMEOUT_MILLIS.getLong();
this.executionService = nodeEngine.getExecutionService();
int coreSize = Runtime.getRuntime().availableProcessors();
boolean reallyMultiCore = coreSize >= 8;
int concurrencyLevel = reallyMultiCore ? coreSize * 4 : 16;
this.executingCalls = new ConcurrentHashMap<RemoteCallKey, RemoteCallKey>(1000, 0.75f, concurrencyLevel);
this.invocations = new ConcurrentHashMap<Long, BasicInvocation>(1000, 0.75f, concurrencyLevel);
this.scheduler = new BasicOperationScheduler(node, executionService, new BasicOperationProcessorImpl());
}
@Override
public int getPartitionOperationThreadCount() {
return scheduler.partitionOperationThreads.length;
}
@Override
public int getGenericOperationThreadCount() {
return scheduler.genericOperationThreads.length;
}
@Override
public int getRunningOperationsCount() {
return executingCalls.size();
}
@Override
public long getExecutedOperationCount() {
return executedOperationsCount.get();
}
@Override
public int getRemoteOperationsCount() {
return invocations.size();
}
@Override
public int getResponseQueueSize() {
return scheduler.getResponseQueueSize();
}
@Override
public int getOperationExecutorQueueSize() {
return scheduler.getOperationExecutorQueueSize();
}
@Override
public int getPriorityOperationExecutorQueueSize() {
return scheduler.getPriorityOperationExecutorQueueSize();
}
@Override
public InvocationBuilder createInvocationBuilder(String serviceName, Operation op, int partitionId) {
if (partitionId < 0) {
throw new IllegalArgumentException("Partition id cannot be negative!");
}
return new BasicInvocationBuilder(nodeEngine, serviceName, op, partitionId);
}
@Override
public InvocationBuilder createInvocationBuilder(String serviceName, Operation op, Address target) {
if (target == null) {
throw new IllegalArgumentException("Target cannot be null!");
}
return new BasicInvocationBuilder(nodeEngine, serviceName, op, target);
}
@PrivateApi
@Override
public void receive(final Packet packet) {
scheduler.execute(packet);
}
/**
* Runs operation in calling thread.
*
* @param op
*/
@Override
//todo: move to BasicOperationScheduler
public void runOperationOnCallingThread(Operation op) {
if (scheduler.isAllowedToRunInCurrentThread(op)) {
processOperation(op);
} else {
throw new IllegalThreadStateException("Operation: " + op + " cannot be run in current thread! -> " +
Thread.currentThread());
}
}
/**
* Executes operation in operation executor pool.
*
* @param op
*/
@Override
public void executeOperation(final Operation op) {
scheduler.execute(op);
}
@Override
@SuppressWarnings("unchecked")
public <E> InternalCompletableFuture<E> invokeOnPartition(String serviceName, Operation op, int partitionId) {
return new BasicPartitionInvocation(nodeEngine, serviceName, op, partitionId, InvocationBuilder.DEFAULT_REPLICA_INDEX,
InvocationBuilder.DEFAULT_TRY_COUNT, InvocationBuilder.DEFAULT_TRY_PAUSE_MILLIS,
InvocationBuilder.DEFAULT_CALL_TIMEOUT, null, null, InvocationBuilder.DEFAULT_DESERIALIZE_RESULT).invoke();
}
@Override
@SuppressWarnings("unchecked")
public <E> InternalCompletableFuture<E> invokeOnTarget(String serviceName, Operation op, Address target) {
return new BasicTargetInvocation(nodeEngine, serviceName, op, target, InvocationBuilder.DEFAULT_TRY_COUNT,
InvocationBuilder.DEFAULT_TRY_PAUSE_MILLIS,
InvocationBuilder.DEFAULT_CALL_TIMEOUT, null, null, InvocationBuilder.DEFAULT_DESERIALIZE_RESULT).invoke();
}
// =============================== processing response ===============================
private void processResponsePacket(Packet packet) {
try {
final Data data = packet.getData();
final Response response = (Response) nodeEngine.toObject(data);
if (response instanceof NormalResponse) {
notifyRemoteCall((NormalResponse) response);
} else if (response instanceof BackupResponse) {
notifyBackupCall(response.getCallId());
} else {
throw new IllegalStateException("Unrecognized response type: " + response);
}
} catch (Throwable e) {
logger.severe("While processing response...", e);
}
}
// TODO: @mm - operations those do not return response can cause memory leaks! Call->Invocation->Operation->Data
private void notifyRemoteCall(NormalResponse response) {
BasicInvocation invocation = invocations.get(response.getCallId());
if (invocation == null) {
throw new HazelcastException("No invocation for response:" + response);
}
invocation.notify(response);
}
@Override
public void notifyBackupCall(long callId) {
try {
final BasicInvocation invocation = invocations.get(callId);
if (invocation != null) {
invocation.signalOneBackupComplete();
}
} catch (Exception e) {
ReplicaErrorLogger.log(e, logger);
}
}
// =============================== processing operation ===============================
private void processOperationPacket(Packet packet) {
final Connection conn = packet.getConn();
try {
final Address caller = conn.getEndPoint();
final Data data = packet.getData();
final Object object = nodeEngine.toObject(data);
final Operation op = (Operation) object;
op.setNodeEngine(nodeEngine);
OperationAccessor.setCallerAddress(op, caller);
OperationAccessor.setConnection(op, conn);
ResponseHandlerFactory.setRemoteResponseHandler(nodeEngine, op);
if (!isJoinOperation(op) && node.clusterService.getMember(op.getCallerAddress()) == null) {
final Exception error = new CallerNotMemberException(op.getCallerAddress(), op.getPartitionId(),
op.getClass().getName(), op.getServiceName());
handleOperationError(op, error);
} else {
String executorName = op.getExecutorName();
if (executorName == null) {
processOperation(op);
} else {
ExecutorService executor = executionService.getExecutor(executorName);
if (executor == null) {
throw new IllegalStateException("Could not found executor with name: " + executorName);
}
executor.execute(new LocalOperationProcessor(op));
}
}
} catch (Throwable e) {
logger.severe(e);
}
}
/**
* Runs operation in calling thread.
*/
private void processOperation(final Operation op) {
executedOperationsCount.incrementAndGet();
RemoteCallKey callKey = null;
try {
if (isCallTimedOut(op)) {
Object response = new CallTimeoutException(op.getClass().getName(), op.getInvocationTime(), op.getCallTimeout());
op.getResponseHandler().sendResponse(response);
return;
}
callKey = beforeCallExecution(op);
final int partitionId = op.getPartitionId();
if (op instanceof PartitionAwareOperation) {
if (partitionId < 0) {
throw new IllegalArgumentException("Partition id cannot be negative! -> " + partitionId);
}
final InternalPartition internalPartition = nodeEngine.getPartitionService().getPartition(partitionId);
if (retryDuringMigration(op) && internalPartition.isMigrating()) {
throw new PartitionMigratingException(node.getThisAddress(), partitionId,
op.getClass().getName(), op.getServiceName());
}
final Address owner = internalPartition.getReplicaAddress(op.getReplicaIndex());
if (op.validatesTarget() && !node.getThisAddress().equals(owner)) {
throw new WrongTargetException(node.getThisAddress(), owner, partitionId, op.getReplicaIndex(),
op.getClass().getName(), op.getServiceName());
}
}
OperationAccessor.setStartTime(op, Clock.currentTimeMillis());
op.beforeRun();
if (op instanceof WaitSupport) {
WaitSupport waitSupport = (WaitSupport) op;
if (waitSupport.shouldWait()) {
nodeEngine.waitNotifyService.await(waitSupport);
return;
}
}
op.run();
final boolean returnsResponse = op.returnsResponse();
Object response = null;
if (op instanceof BackupAwareOperation) {
final BackupAwareOperation backupAwareOp = (BackupAwareOperation) op;
int syncBackupCount = 0;
if (backupAwareOp.shouldBackup()) {
syncBackupCount = sendBackups(backupAwareOp);
}
if (returnsResponse) {
response = new NormalResponse(op.getResponse(), op.getCallId(), syncBackupCount, op.isUrgent());
}
}
if (returnsResponse) {
if (response == null) {
response = op.getResponse();
}
final ResponseHandler responseHandler = op.getResponseHandler();
if (responseHandler == null) {
throw new IllegalStateException("ResponseHandler should not be null!");
}
responseHandler.sendResponse(response);
}
try {
op.afterRun();
if (op instanceof Notifier) {
final Notifier notifier = (Notifier) op;
if (notifier.shouldNotify()) {
nodeEngine.waitNotifyService.notify(notifier);
}
}
} catch (Throwable e) {
// passed the response phase
// `afterRun` and `notifier` errors cannot be sent to the caller anymore
// just log the error
logOperationError(op, e);
}
} catch (Throwable e) {
handleOperationError(op, e);
} finally {
afterCallExecution(op, callKey);
}
}
private static boolean retryDuringMigration(Operation op) {
return !(op instanceof ReadonlyOperation || OperationAccessor.isMigrationOperation(op));
}
@PrivateApi
public boolean isCallTimedOut(Operation op) {
if (op.returnsResponse() && op.getCallId() != 0) {
final long callTimeout = op.getCallTimeout();
final long invocationTime = op.getInvocationTime();
final long expireTime = invocationTime + callTimeout;
if (expireTime > 0 && expireTime < Long.MAX_VALUE) {
final long now = nodeEngine.getClusterTime();
if (expireTime < now) {
return true;
}
}
}
return false;
}
private RemoteCallKey beforeCallExecution(Operation op) {
RemoteCallKey callKey = null;
if (op.getCallId() != 0 && op.returnsResponse()) {
callKey = new RemoteCallKey(op);
RemoteCallKey current;
if ((current = executingCalls.put(callKey, callKey)) != null) {
logger.warning("Duplicate Call record! -> " + callKey + " / " + current + " == " + op.getClass().getName());
}
}
return callKey;
}
private void afterCallExecution(Operation op, RemoteCallKey callKey) {
if (callKey != null && op.getCallId() != 0 && op.returnsResponse()) {
if (executingCalls.remove(callKey) == null) {
logger.severe("No Call record has been found: -> " + callKey + " == " + op.getClass().getName());
}
}
}
private int sendBackups(BackupAwareOperation backupAwareOp) throws Exception {
Operation op = (Operation) backupAwareOp;
boolean returnsResponse = op.returnsResponse();
InternalPartitionService partitionService = nodeEngine.getPartitionService();
int maxBackupCount = InternalPartition.MAX_BACKUP_COUNT;
int maxPossibleBackupCount = Math.min(partitionService.getMemberGroupsSize() - 1, maxBackupCount);
int requestedSyncBackupCount = backupAwareOp.getSyncBackupCount() > 0
? Math.min(maxBackupCount, backupAwareOp.getSyncBackupCount()) : 0;
int requestedAsyncBackupCount = backupAwareOp.getAsyncBackupCount() > 0
? Math.min(maxBackupCount - requestedSyncBackupCount, backupAwareOp.getAsyncBackupCount()) : 0;
int totalRequestedBackupCount = requestedSyncBackupCount + requestedAsyncBackupCount;
if (totalRequestedBackupCount == 0) {
return 0;
}
int partitionId = op.getPartitionId();
long[] replicaVersions = partitionService.incrementPartitionReplicaVersions(partitionId, totalRequestedBackupCount);
int syncBackupCount = Math.min(maxPossibleBackupCount, requestedSyncBackupCount);
int asyncBackupCount = Math.min(maxPossibleBackupCount - syncBackupCount, requestedAsyncBackupCount);
if (!returnsResponse) {
asyncBackupCount += syncBackupCount;
syncBackupCount = 0;
}
int totalBackupCount = syncBackupCount + asyncBackupCount;
if (totalBackupCount == 0) {
return 0;
}
int sentSyncBackupCount = 0;
String serviceName = op.getServiceName();
InternalPartition partition = partitionService.getPartition(partitionId);
for (int replicaIndex = 1; replicaIndex <= totalBackupCount; replicaIndex++) {
Address target = partition.getReplicaAddress(replicaIndex);
if (target != null) {
if (target.equals(node.getThisAddress())) {
throw new IllegalStateException("Normally shouldn't happen! Owner node and backup node " +
"are the same! " + partition);
} else {
Operation backupOp = backupAwareOp.getBackupOperation();
if (backupOp == null) {
throw new IllegalArgumentException("Backup operation should not be null!");
}
backupOp.setPartitionId(partitionId).setReplicaIndex(replicaIndex).setServiceName(serviceName);
Data backupOpData = nodeEngine.getSerializationService().toData(backupOp);
boolean isSyncBackup = replicaIndex <= syncBackupCount;
Backup backup = new Backup(backupOpData, op.getCallerAddress(), replicaVersions, isSyncBackup);
backup.setPartitionId(partitionId).setReplicaIndex(replicaIndex).setServiceName(serviceName)
.setCallerUuid(nodeEngine.getLocalMember().getUuid());
OperationAccessor.setCallId(backup, op.getCallId());
send(backup, target);
if (isSyncBackup) {
sentSyncBackupCount++;
}
}
}
}
return sentSyncBackupCount;
}
private void handleOperationError(Operation op, Throwable e) {
if (e instanceof OutOfMemoryError) {
OutOfMemoryErrorDispatcher.onOutOfMemory((OutOfMemoryError) e);
}
op.logError(e);
ResponseHandler responseHandler = op.getResponseHandler();
if (op.returnsResponse() && responseHandler != null) {
try {
if (node.isActive()) {
responseHandler.sendResponse(e);
} else if (responseHandler.isLocal()) {
responseHandler.sendResponse(new HazelcastInstanceNotActiveException());
}
} catch (Throwable t) {
logger.warning("While sending op error... op: " + op + ", error: " + e, t);
}
}
}
private void logOperationError(Operation op, Throwable e) {
if (e instanceof OutOfMemoryError) {
OutOfMemoryErrorDispatcher.onOutOfMemory((OutOfMemoryError) e);
}
op.logError(e);
}
@Override
public Map<Integer, Object> invokeOnAllPartitions(String serviceName, OperationFactory operationFactory) throws Exception {
Map<Address, List<Integer>> memberPartitions = nodeEngine.getPartitionService().getMemberPartitionsMap();
return invokeOnPartitions(serviceName, operationFactory, memberPartitions);
}
@Override
public Map<Integer, Object> invokeOnPartitions(String serviceName, OperationFactory operationFactory,
Collection<Integer> partitions) throws Exception {
final Map<Address, List<Integer>> memberPartitions = new HashMap<Address, List<Integer>>(3);
for (int partition : partitions) {
Address owner = nodeEngine.getPartitionService().getPartitionOwner(partition);
if (!memberPartitions.containsKey(owner)) {
memberPartitions.put(owner, new ArrayList<Integer>());
}
memberPartitions.get(owner).add(partition);
}
return invokeOnPartitions(serviceName, operationFactory, memberPartitions);
}
private Map<Integer, Object> invokeOnPartitions(String serviceName, OperationFactory operationFactory,
Map<Address, List<Integer>> memberPartitions) throws Exception {
final Thread currentThread = Thread.currentThread();
if (currentThread instanceof BasicOperationScheduler.OperationThread) {
throw new IllegalThreadStateException(currentThread + " cannot make invocation on multiple partitions!");
}
final Map<Address, Future> responses = new HashMap<Address, Future>(memberPartitions.size());
for (Map.Entry<Address, List<Integer>> mp : memberPartitions.entrySet()) {
final Address address = mp.getKey();
final List<Integer> partitions = mp.getValue();
final PartitionIteratingOperation pi = new PartitionIteratingOperation(partitions, operationFactory);
Future future = createInvocationBuilder(serviceName, pi, address).setTryCount(10).setTryPauseMillis(300).invoke();
responses.put(address, future);
}
Map<Integer, Object> partitionResults = new HashMap<Integer, Object>(
nodeEngine.getPartitionService().getPartitionCount());
int x = 0;
for (Map.Entry<Address, Future> response : responses.entrySet()) {
try {
Future future = response.getValue();
PartitionResponse result = (PartitionResponse) nodeEngine.toObject(future.get());
partitionResults.putAll(result.asMap());
} catch (Throwable t) {
if (logger.isFinestEnabled()) {
logger.finest(t);
} else {
logger.warning(t.getMessage());
}
List<Integer> partitions = memberPartitions.get(response.getKey());
for (Integer partition : partitions) {
partitionResults.put(partition, t);
}
}
x++;
}
final List<Integer> failedPartitions = new LinkedList<Integer>();
for (Map.Entry<Integer, Object> partitionResult : partitionResults.entrySet()) {
int partitionId = partitionResult.getKey();
Object result = partitionResult.getValue();
if (result instanceof Throwable) {
failedPartitions.add(partitionId);
}
}
for (Integer failedPartition : failedPartitions) {
Future f = createInvocationBuilder(serviceName,
operationFactory.createOperation(), failedPartition).invoke();
partitionResults.put(failedPartition, f);
}
for (Integer failedPartition : failedPartitions) {
Future f = (Future) partitionResults.get(failedPartition);
Object result = f.get();
partitionResults.put(failedPartition, result);
}
return partitionResults;
}
@Override
public boolean send(final Operation op, final Address target) {
if (target == null) {
throw new IllegalArgumentException("Target is required!");
}
if (nodeEngine.getThisAddress().equals(target)) {
throw new IllegalArgumentException("Target is this node! -> " + target + ", op: " + op);
}
return send(op, node.getConnectionManager().getOrConnect(target));
}
@Override
public boolean send(Response response, Address target) {
if (target == null) {
throw new IllegalArgumentException("Target is required!");
}
if (nodeEngine.getThisAddress().equals(target)) {
throw new IllegalArgumentException("Target is this node! -> " + target + ", response: " + response);
}
Data data = nodeEngine.toData(response);
Packet packet = new Packet(data, nodeEngine.getSerializationContext());
packet.setHeader(Packet.HEADER_OP);
packet.setHeader(Packet.HEADER_RESPONSE);
if (response.isUrgent()) {
packet.setHeader(Packet.HEADER_URGENT);
}
return nodeEngine.send(packet, node.getConnectionManager().getOrConnect(target));
}
private boolean send(final Operation op, final Connection connection) {
Data data = nodeEngine.toData(op);
//enable this line to get some logging of sizes of operations.
//System.out.println(op.getClass()+" "+data.bufferSize());
final int partitionId = scheduler.getPartitionIdForExecution(op);
Packet packet = new Packet(data, partitionId, nodeEngine.getSerializationContext());
packet.setHeader(Packet.HEADER_OP);
if (op instanceof UrgentSystemOperation) {
packet.setHeader(Packet.HEADER_URGENT);
}
return nodeEngine.send(packet, connection);
}
public long registerInvocation(BasicInvocation invocation) {
long callId = callIdGen.getAndIncrement();
Operation op = invocation.op;
if (op.getCallId() != 0) {
invocations.remove(op.getCallId());
}
invocations.put(callId, invocation);
setCallId(invocation.op, callId);
return callId;
}
public void deregisterInvocation(long id) {
invocations.remove(id);
}
@PrivateApi
long getDefaultCallTimeout() {
return defaultCallTimeout;
}
@PrivateApi
boolean isOperationExecuting(Address callerAddress, String callerUuid, long operationCallId) {
return executingCalls.containsKey(new RemoteCallKey(callerAddress, callerUuid, operationCallId));
}
@PrivateApi
boolean isOperationExecuting(Address callerAddress, String callerUuid, String serviceName, Object identifier) {
Object service = nodeEngine.getService(serviceName);
if (service == null) {
logger.severe("Not able to find operation execution info. Invalid service: " + serviceName);
return false;
}
if (service instanceof ExecutionTracingService) {
return ((ExecutionTracingService) service).isOperationExecuting(callerAddress, callerUuid, identifier);
}
logger.severe("Not able to find operation execution info. Invalid service: " + service);
return false;
}
@Override
public void onMemberLeft(final MemberImpl member) {
// postpone notifying calls since real response may arrive in the mean time.
nodeEngine.getExecutionService().schedule(new Runnable() {
public void run() {
final Iterator<BasicInvocation> iter = invocations.values().iterator();
while (iter.hasNext()) {
final BasicInvocation invocation = iter.next();
if (invocation.isCallTarget(member)) {
iter.remove();
invocation.notify(new MemberLeftException(member));
}
}
}
}, 1111, TimeUnit.MILLISECONDS);
}
@Override
public void shutdown() {
logger.finest("Stopping operation threads...");
final Object response = new HazelcastInstanceNotActiveException();
for (BasicInvocation invocation : invocations.values()) {
invocation.notify(response);
}
invocations.clear();
scheduler.shutdown();
}
public class BasicOperationProcessorImpl implements BasicOperationProcessor {
@Override
public void process(Object o) {
if (o == null) {
throw new IllegalArgumentException();
} else if (o instanceof Operation) {
processOperation((Operation) o);
} else if (o instanceof Packet) {
Packet packet = (Packet) o;
if (packet.isHeaderSet(Packet.HEADER_RESPONSE)) {
processResponsePacket(packet);
} else {
processOperationPacket(packet);
}
} else if (o instanceof Runnable) {
((Runnable) o).run();
} else {
throw new IllegalArgumentException("Unrecognized task:" + o);
}
}
}
/**
* Process the operation that has been send locally to this OperationService.
*/
private class LocalOperationProcessor implements Runnable {
private final Operation op;
private LocalOperationProcessor(Operation op) {
this.op = op;
}
@Override
public void run() {
processOperation(op);
}
}
private static class RemoteCallKey {
private final long time = Clock.currentTimeMillis();
private final Address callerAddress; // human readable caller
private final String callerUuid;
private final long callId;
private RemoteCallKey(Address callerAddress, String callerUuid, long callId) {
if (callerUuid == null) {
throw new IllegalArgumentException("Caller UUID is required!");
}
this.callerAddress = callerAddress;
if (callerAddress == null) {
throw new IllegalArgumentException("Caller address is required!");
}
this.callerUuid = callerUuid;
this.callId = callId;
}
private RemoteCallKey(final Operation op) {
callerUuid = op.getCallerUuid();
if (callerUuid == null) {
throw new IllegalArgumentException("Caller UUID is required! -> " + op);
}
callerAddress = op.getCallerAddress();
if (callerAddress == null) {
throw new IllegalArgumentException("Caller address is required! -> " + op);
}
callId = op.getCallId();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RemoteCallKey callKey = (RemoteCallKey) o;
if (callId != callKey.callId) return false;
if (!callerUuid.equals(callKey.callerUuid)) return false;
return true;
}
@Override
public int hashCode() {
int result = callerUuid.hashCode();
result = 31 * result + (int) (callId ^ (callId >>> 32));
return result;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("RemoteCallKey");
sb.append("{callerAddress=").append(callerAddress);
sb.append(", callerUuid=").append(callerUuid);
sb.append(", callId=").append(callId);
sb.append(", time=").append(time);
sb.append('}');
return sb.toString();
}
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_spi_impl_BasicOperationService.java
|
772 |
public class CollectionPrepareOperation extends CollectionBackupAwareOperation {
boolean removeOperation;
String transactionId;
private long itemId = -1;
public CollectionPrepareOperation() {
}
public CollectionPrepareOperation(String name, long itemId, String transactionId, boolean removeOperation) {
super(name);
this.itemId = itemId;
this.removeOperation = removeOperation;
this.transactionId = transactionId;
}
@Override
public boolean shouldBackup() {
return true;
}
@Override
public Operation getBackupOperation() {
return new CollectionPrepareBackupOperation(name, itemId, transactionId, removeOperation);
}
@Override
public int getId() {
return CollectionDataSerializerHook.COLLECTION_PREPARE;
}
@Override
public void beforeRun() throws Exception {
}
@Override
public void run() throws Exception {
getOrCreateContainer().ensureReserve(itemId);
}
@Override
public void afterRun() throws Exception {
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeLong(itemId);
out.writeBoolean(removeOperation);
out.writeUTF(transactionId);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
itemId = in.readLong();
removeOperation = in.readBoolean();
transactionId = in.readUTF();
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_txn_CollectionPrepareOperation.java
|
100 |
{
@Override
public void beforeCompletion()
{
throw firstException;
}
@Override
public void afterCompletion( int status )
{
}
};
| 0true
|
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestTransactionImpl.java
|
624 |
indexEngine.getEntriesMajor(iRangeFrom, isInclusive, null, new OIndexEngine.EntriesResultListener() {
@Override
public boolean addResult(ODocument entry) {
return entriesResultListener.addResult(entry);
}
});
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_index_OIndexOneValue.java
|
54 |
public class TypeArgumentListCompletions {
public static void addTypeArgumentListProposal(final int offset,
final CeylonParseController cpc, final Node node,
final Scope scope, final IDocument document,
final List<ICompletionProposal> result) {
final Integer startIndex2 = node.getStartIndex();
final Integer stopIndex2 = node.getStopIndex();
final String typeArgText;
try {
typeArgText = document.get(startIndex2, stopIndex2-startIndex2+1);
}
catch (BadLocationException e) {
e.printStackTrace();
return;
}
new Visitor() {
@Override
public void visit(Tree.StaticMemberOrTypeExpression that) {
Tree.TypeArguments tal = that.getTypeArguments();
Integer startIndex = tal==null ?
null : that.getTypeArguments().getStartIndex();
if (startIndex!=null && startIndex2!=null &&
startIndex.intValue()==startIndex2.intValue()) {
ProducedReference pr = that.getTarget();
Declaration d = that.getDeclaration();
if (d instanceof Functional && pr!=null) {
try {
String pref = document.get(that.getStartIndex(),
that.getStopIndex()-that.getStartIndex()+1);
addInvocationProposals(offset, pref, cpc, result, d,
pr, scope, null, typeArgText, false);
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
}
super.visit(that);
}
public void visit(Tree.SimpleType that) {
Tree.TypeArgumentList tal = that.getTypeArgumentList();
Integer startIndex = tal==null ? null : tal.getStartIndex();
if (startIndex!=null && startIndex2!=null &&
startIndex.intValue()==startIndex2.intValue()) {
Declaration d = that.getDeclarationModel();
if (d instanceof Functional) {
try {
String pref = document.get(that.getStartIndex(),
that.getStopIndex()-that.getStartIndex()+1);
addInvocationProposals(offset, pref, cpc, result, d,
that.getTypeModel(), scope, null, typeArgText,
false);
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
}
super.visit(that);
}
}.visit(cpc.getRootNode());
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_TypeArgumentListCompletions.java
|
369 |
@RunWith(HazelcastSerialClassRunner.class)
@Category(NightlyTest.class)
@SuppressWarnings("unused")
public class DistributedMapperClientMapReduceTest extends AbstractClientMapReduceJobTest {
private static final String MAP_NAME = "default";
@After
public void shutdown() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Test(timeout = 30000)
public void testMapperReducer()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Map<String, Integer>> future =
job.mapper(new GroupingTestMapper())
.combiner(new TestCombinerFactory())
.reducer(new TestReducerFactory())
.submit();
Map<String, Integer> result = future.get();
// Precalculate results
int[] expectedResults = new int[4];
for (int i = 0; i < 100; i++) {
int index = i % 4;
expectedResults[index] += i;
}
for (int i = 0; i < 4; i++) {
assertEquals(expectedResults[i], (int) result.get(String.valueOf(i)));
}
}
@Test(timeout = 30000)
public void testMapperReducerCollator()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Integer> future =
job.mapper(new GroupingTestMapper())
.combiner(new TestCombinerFactory())
.reducer(new TestReducerFactory())
.submit(new TestCollator());
int result = future.get();
// Precalculate result
int expectedResult = 0;
for (int i = 0; i < 100; i++) {
expectedResult += i;
}
for (int i = 0; i < 4; i++) {
assertEquals(expectedResult, result);
}
}
@Test(timeout = 30000)
public void testAsyncMapperReducer()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
final Map<String, Integer> listenerResults = new HashMap<String, Integer>();
final Semaphore semaphore = new Semaphore(1);
semaphore.acquire();
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Map<String, Integer>> future =
job.mapper(new GroupingTestMapper())
.combiner(new TestCombinerFactory())
.reducer(new TestReducerFactory())
.submit();
future.andThen(new ExecutionCallback<Map<String, Integer>>() {
@Override
public void onResponse(Map<String, Integer> response) {
try {
listenerResults.putAll(response);
} finally {
semaphore.release();
}
}
@Override
public void onFailure(Throwable t) {
semaphore.release();
}
});
// Precalculate results
int[] expectedResults = new int[4];
for (int i = 0; i < 100; i++) {
int index = i % 4;
expectedResults[index] += i;
}
semaphore.acquire();
for (int i = 0; i < 4; i++) {
assertEquals(expectedResults[i], (int) listenerResults.get(String.valueOf(i)));
}
}
@Test(timeout = 30000)
public void testAsyncMapperReducerCollator()
throws Exception {
Config config = buildConfig();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h3 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance client = HazelcastClient.newHazelcastClient(null);
IMap<Integer, Integer> m1 = client.getMap(MAP_NAME);
for (int i = 0; i < 100; i++) {
m1.put(i, i);
}
final int[] result = new int[1];
final Semaphore semaphore = new Semaphore(1);
semaphore.acquire();
JobTracker tracker = client.getJobTracker("default");
Job<Integer, Integer> job = tracker.newJob(KeyValueSource.fromMap(m1));
ICompletableFuture<Integer> future =
job.mapper(new GroupingTestMapper())
.combiner(new TestCombinerFactory())
.reducer(new TestReducerFactory())
.submit(new TestCollator());
future.andThen(new ExecutionCallback<Integer>() {
@Override
public void onResponse(Integer response) {
try {
result[0] = response.intValue();
} finally {
semaphore.release();
}
}
@Override
public void onFailure(Throwable t) {
semaphore.release();
}
});
// Precalculate result
int expectedResult = 0;
for (int i = 0; i < 100; i++) {
expectedResult += i;
}
semaphore.acquire();
for (int i = 0; i < 4; i++) {
assertEquals(expectedResult, result[0]);
}
}
public static class TestCombiner
extends Combiner<String, Integer, Integer> {
private transient int sum;
@Override
public void combine(String key, Integer value) {
sum += value;
}
@Override
public Integer finalizeChunk() {
int v = sum;
sum = 0;
return v;
}
}
public static class TestCombinerFactory
implements CombinerFactory<String, Integer, Integer> {
public TestCombinerFactory() {
}
@Override
public Combiner<String, Integer, Integer> newCombiner(String key) {
return new TestCombiner();
}
}
public static class GroupingTestMapper
implements Mapper<Integer, Integer, String, Integer> {
@Override
public void map(Integer key, Integer value, Context<String, Integer> collector) {
collector.emit(String.valueOf(key % 4), value);
}
}
public static class TestReducer
extends Reducer<String, Integer, Integer> {
private transient int sum;
@Override
public void reduce(Integer value) {
sum += value;
}
@Override
public Integer finalizeReduce() {
return sum;
}
}
public static class TestReducerFactory
implements ReducerFactory<String, Integer, Integer> {
@Override
public Reducer<String, Integer, Integer> newReducer(String key) {
return new TestReducer();
}
}
public static class TestCollator
implements Collator<Map.Entry<String, Integer>, Integer> {
@Override
public Integer collate(Iterable<Map.Entry<String, Integer>> values) {
int sum = 0;
for (Map.Entry<String, Integer> entry : values) {
sum += entry.getValue();
}
return sum;
}
}
}
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_DistributedMapperClientMapReduceTest.java
|
437 |
public final class PartitionServiceProxy implements PartitionService {
private final ClientPartitionService partitionService;
private final Random random = new Random();
public PartitionServiceProxy(ClientPartitionService partitionService) {
this.partitionService = partitionService;
}
@Override
public String randomPartitionKey() {
return Integer.toString(random.nextInt(partitionService.getPartitionCount()));
}
@Override
public Set<Partition> getPartitions() {
final int partitionCount = partitionService.getPartitionCount();
Set<Partition> partitions = new LinkedHashSet<Partition>(partitionCount);
for (int i = 0; i < partitionCount; i++) {
final Partition partition = partitionService.getPartition(i);
partitions.add(partition);
}
return partitions;
}
@Override
public Partition getPartition(Object key) {
final int partitionId = partitionService.getPartitionId(key);
return partitionService.getPartition(partitionId);
}
@Override
public String addMigrationListener(MigrationListener migrationListener) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeMigrationListener(String registrationId) {
throw new UnsupportedOperationException();
}
}
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_proxy_PartitionServiceProxy.java
|
840 |
private class Async {
final DiscoveryNodes nodes;
final CountDown expectedOps;
final ClearScrollRequest request;
final List<Tuple<String, Long>[]> contexts = new ArrayList<Tuple<String, Long>[]>();
final AtomicReference<Throwable> expHolder;
final ActionListener<ClearScrollResponse> listener;
private Async(ClearScrollRequest request, ActionListener<ClearScrollResponse> listener, ClusterState clusterState) {
int expectedOps = 0;
this.nodes = clusterState.nodes();
if (request.getScrollIds().size() == 1 && "_all".equals(request.getScrollIds().get(0))) {
expectedOps = nodes.size();
} else {
for (String parsedScrollId : request.getScrollIds()) {
Tuple<String, Long>[] context = parseScrollId(parsedScrollId).getContext();
expectedOps += context.length;
this.contexts.add(context);
}
}
this.request = request;
this.listener = listener;
this.expHolder = new AtomicReference<Throwable>();
this.expectedOps = new CountDown(expectedOps);
}
public void run() {
if (expectedOps.isCountedDown()) {
listener.onResponse(new ClearScrollResponse(true));
return;
}
if (contexts.isEmpty()) {
for (final DiscoveryNode node : nodes) {
searchServiceTransportAction.sendClearAllScrollContexts(node, request, new ActionListener<Boolean>() {
@Override
public void onResponse(Boolean success) {
onFreedContext();
}
@Override
public void onFailure(Throwable e) {
onFailedFreedContext(e, node);
}
});
}
} else {
for (Tuple<String, Long>[] context : contexts) {
for (Tuple<String, Long> target : context) {
final DiscoveryNode node = nodes.get(target.v1());
if (node == null) {
onFreedContext();
continue;
}
searchServiceTransportAction.sendFreeContext(node, target.v2(), request, new ActionListener<Boolean>() {
@Override
public void onResponse(Boolean success) {
onFreedContext();
}
@Override
public void onFailure(Throwable e) {
onFailedFreedContext(e, node);
}
});
}
}
}
}
void onFreedContext() {
if (expectedOps.countDown()) {
boolean succeeded = expHolder.get() == null;
listener.onResponse(new ClearScrollResponse(succeeded));
}
}
void onFailedFreedContext(Throwable e, DiscoveryNode node) {
logger.warn("Clear SC failed on node[{}]", e, node);
if (expectedOps.countDown()) {
listener.onResponse(new ClearScrollResponse(false));
} else {
expHolder.set(e);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_search_TransportClearScrollAction.java
|
3,256 |
public abstract class InstancePermission extends ClusterPermission {
protected static final int NONE = 0x0;
protected static final int CREATE = 0x1;
protected static final int DESTROY = 0x2;
protected final int mask;
protected final String actions;
public InstancePermission(String name, String... actions) {
super(name);
if (name == null || "".equals(name)) {
throw new IllegalArgumentException("Permission name is mamdatory!");
}
mask = initMask(actions);
final StringBuilder s = new StringBuilder();
for (String action : actions) {
s.append(action).append(" ");
}
this.actions = s.toString();
}
/**
* init mask
*/
protected abstract int initMask(String[] actions);
@Override
public boolean implies(Permission permission) {
if (this.getClass() != permission.getClass()) {
return false;
}
InstancePermission that = (InstancePermission) permission;
boolean maskTest = ((this.mask & that.mask) == that.mask);
if (!maskTest) {
return false;
}
if (!Config.nameMatches(that.getName(), this.getName())) {
return false;
}
return true;
}
@Override
public String getActions() {
return actions;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + mask;
result = 31 * result + actions.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
InstancePermission other = (InstancePermission) obj;
if (getName() == null && other.getName() != null) {
return false;
}
if (!getName().equals(other.getName())) {
return false;
}
if (mask != other.mask) {
return false;
}
return true;
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_security_permission_InstancePermission.java
|
116 |
public interface Gather<S,M> {
/**
* Gathers the adjacent vertex's state and the connecting edge's properties into a single object
* to be combined by a corresponding {@link Combiner} as configured in {@link OLAPQueryBuilder#edges(Gather, Combiner)}.
*
* @param state State of the adjacent vertex
* @param edge Edge connecting to the adjacent vertex
* @param dir Direction of the edge from the perspective of the current/central vertex
* @return An object of type M which gathers the state and edge properties
*/
public M apply(S state, TitanEdge edge, Direction dir);
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_olap_Gather.java
|
10 |
@SuppressWarnings("serial")
public class OLimitedMap<K, V> extends LinkedHashMap<K, V> {
protected final int limit;
public OLimitedMap(final int initialCapacity, final float loadFactor, final int limit) {
super(initialCapacity, loadFactor, true);
this.limit = limit;
}
@Override
protected boolean removeEldestEntry(final Map.Entry<K, V> eldest) {
return limit > 0 ? size() - limit > 0 : false;
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_collection_OLimitedMap.java
|
3,262 |
public class QueuePermission extends InstancePermission {
private static final int ADD = 0x4;
private static final int READ = 0x8;
private static final int REMOVE = 0x16;
private static final int LISTEN = 0x32;
private static final int ALL = ADD | REMOVE | READ | CREATE | DESTROY | LISTEN;
public QueuePermission(String name, String... actions) {
super(name, actions);
}
@Override
protected int initMask(String[] actions) {
int mask = NONE;
for (String action : actions) {
if (ActionConstants.ACTION_ALL.equals(action)) {
return ALL;
}
if (ActionConstants.ACTION_CREATE.equals(action)) {
mask |= CREATE;
} else if (ActionConstants.ACTION_DESTROY.equals(action)) {
mask |= DESTROY;
} else if (ActionConstants.ACTION_ADD.equals(action)) {
mask |= ADD;
} else if (ActionConstants.ACTION_READ.equals(action)) {
mask |= READ;
} else if (ActionConstants.ACTION_REMOVE.equals(action)) {
mask |= REMOVE;
} else if (ActionConstants.ACTION_LISTEN.equals(action)) {
mask |= LISTEN;
}
}
return mask;
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_security_permission_QueuePermission.java
|
1,186 |
public class OQueryOperatorMajor extends OQueryOperatorEqualityNotNulls {
public OQueryOperatorMajor() {
super(">", 5, false);
}
@Override
@SuppressWarnings("unchecked")
protected boolean evaluateExpression(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft,
final Object iRight, OCommandContext iContext) {
final Object right = OType.convert(iRight, iLeft.getClass());
if (right == null)
return false;
return ((Comparable<Object>) iLeft).compareTo(right) > 0;
}
@Override
public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) {
if (iRight == null || iLeft == null)
return OIndexReuseType.NO_INDEX;
return OIndexReuseType.INDEX_METHOD;
}
@Override
public Object executeIndexQuery(OCommandContext iContext, OIndex<?> index, INDEX_OPERATION_TYPE iOperationType,
List<Object> keyParams, IndexResultListener resultListener, int fetchLimit) {
final OIndexDefinition indexDefinition = index.getDefinition();
final OIndexInternal<?> internalIndex = index.getInternal();
if (!internalIndex.canBeUsedInEqualityOperators() || !internalIndex.hasRangeQuerySupport())
return null;
final Object result;
if (indexDefinition.getParamCount() == 1) {
final Object key;
if (indexDefinition instanceof OIndexDefinitionMultiValue)
key = ((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(keyParams.get(0));
else
key = indexDefinition.createValue(keyParams);
if (key == null)
return null;
if (INDEX_OPERATION_TYPE.COUNT.equals(iOperationType))
result = index.count(key, false, null, false, fetchLimit);
else if (resultListener != null) {
index.getValuesMajor(key, false, resultListener);
result = resultListener.getResult();
} else
result = index.getValuesMajor(key, false);
} else {
// if we have situation like "field1 = 1 AND field2 > 2"
// then we fetch collection which left not included boundary is the smallest composite key in the
// index that contains keys with values field1=1 and field2=2 and which right included boundary
// is the biggest composite key in the index that contains key with value field1=1.
final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition;
final Object keyOne = compositeIndexDefinition.createSingleValue(keyParams);
if (keyOne == null)
return null;
final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams.subList(0, keyParams.size() - 1));
if (keyTwo == null)
return null;
if (INDEX_OPERATION_TYPE.COUNT.equals(iOperationType))
result = index.count(keyOne, false, keyTwo, true, fetchLimit);
else if (resultListener != null) {
index.getValuesBetween(keyOne, false, keyTwo, true, resultListener);
result = resultListener.getResult();
} else
result = index.getValuesBetween(keyOne, false, keyTwo, true);
}
updateProfiler(iContext, index, keyParams, indexDefinition);
return result;
}
@Override
public ORID getBeginRidRange(final Object iLeft, final Object iRight) {
if (iLeft instanceof OSQLFilterItemField && ODocumentHelper.ATTRIBUTE_RID.equals(((OSQLFilterItemField) iLeft).getRoot()))
if (iRight instanceof ORID)
return new ORecordId(((ORID) iRight).next());
else {
if (iRight instanceof OSQLFilterItemParameter && ((OSQLFilterItemParameter) iRight).getValue(null, null) instanceof ORID)
return new ORecordId(((ORID) ((OSQLFilterItemParameter) iRight).getValue(null, null)).next());
}
return null;
}
@Override
public ORID getEndRidRange(Object iLeft, Object iRight) {
return null;
}
}
| 1no label
|
core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryOperatorMajor.java
|
79 |
EQUAL {
@Override
public boolean isValidValueType(Class<?> clazz) {
return true;
}
@Override
public boolean isValidCondition(Object condition) {
return true;
}
@Override
public boolean evaluate(Object value, Object condition) {
if (condition==null) {
return value==null;
} else {
return condition.equals(value);
}
}
@Override
public String toString() {
return "=";
}
@Override
public TitanPredicate negate() {
return NOT_EQUAL;
}
},
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java
|
467 |
@Repository("blSandBoxDao")
public class SandBoxDaoImpl implements SandBoxDao {
@PersistenceContext(unitName = "blPU")
protected EntityManager sandBoxEntityManager;
@Resource(name = "blTransactionManager")
JpaTransactionManager transactionManager;
@Override
public SandBox retrieve(Long id) {
return sandBoxEntityManager.find(SandBoxImpl.class, id);
}
@Override
public SandBox retrieveSandBoxByType(Site site, SandBoxType sandboxType) {
TypedQuery<SandBox> query = sandBoxEntityManager.createNamedQuery("BC_READ_SANDBOX_BY_TYPE", SandBox.class);
//query.setParameter("site", site);
query.setParameter("sandboxType", sandboxType.getType());
SandBox response = null;
try {
response = query.getSingleResult();
} catch (NoResultException e) {
//do nothing - there is no sandbox
}
return response;
}
@Override
public SandBox retrieveNamedSandBox(Site site, SandBoxType sandboxType, String sandboxName) {
Query query = sandBoxEntityManager.createNamedQuery("BC_READ_SANDBOX_BY_TYPE_AND_NAME");
//query.setParameter("site", site);
query.setParameter("sandboxType", sandboxType.getType());
query.setParameter("sandboxName", sandboxName);
SandBox response = null;
try {
response = (SandBox) query.getSingleResult();
} catch (NoResultException e) {
//do nothing - there is no sandbox
}
return response;
}
@Override
public SandBox persist(SandBox entity) {
sandBoxEntityManager.persist(entity);
sandBoxEntityManager.flush();
return entity;
}
public SandBox createSandBox(Site site, String sandBoxName, SandBoxType sandBoxType) {
TransactionStatus status = TransactionUtils.createTransaction("createSandBox",
TransactionDefinition.PROPAGATION_REQUIRES_NEW, transactionManager);
try {
SandBox approvalSandbox = retrieveNamedSandBox(site, sandBoxType, sandBoxName);
if (approvalSandbox == null) {
approvalSandbox = new SandBoxImpl();
approvalSandbox.setSite(site);
approvalSandbox.setName(sandBoxName);
approvalSandbox.setSandBoxType(sandBoxType);
approvalSandbox = persist(approvalSandbox);
}
TransactionUtils.finalizeTransaction(status, transactionManager, false);
return approvalSandbox;
} catch (Exception ex) {
TransactionUtils.finalizeTransaction(status, transactionManager, true);
throw new RuntimeException(ex);
}
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_sandbox_dao_SandBoxDaoImpl.java
|
380 |
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_LOCALE")
@Cache(usage= CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blCMSElements")
@AdminPresentationClass(friendlyName = "LocaleImpl_baseLocale")
public class LocaleImpl implements Locale {
private static final long serialVersionUID = 1L;
@Id
@Column (name = "LOCALE_CODE")
@AdminPresentation(friendlyName = "LocaleImpl_Locale_Code", order = 1,
group = "LocaleImpl_Details",
prominent = true, gridOrder = 2)
protected String localeCode;
@Column (name = "FRIENDLY_NAME")
@AdminPresentation(friendlyName = "LocaleImpl_Name", order = 2,
group = "LocaleImpl_Details",
prominent = true, gridOrder = 1)
protected String friendlyName;
@Column (name = "DEFAULT_FLAG")
@AdminPresentation(friendlyName = "LocaleImpl_Is_Default", order = 3,
group = "LocaleImpl_Details",
prominent = true, gridOrder = 3)
protected Boolean defaultFlag = false;
@ManyToOne(targetEntity = BroadleafCurrencyImpl.class)
@JoinColumn(name = "CURRENCY_CODE")
@AdminPresentation(friendlyName = "LocaleImpl_Currency", order = 4,
group = "LocaleImpl_Details",
prominent = true)
protected BroadleafCurrency defaultCurrency;
@Column (name = "USE_IN_SEARCH_INDEX")
@AdminPresentation(friendlyName = "LocaleImpl_Use_In_Search_Index", order = 5,
group = "LocaleImpl_Details",
prominent = true, gridOrder = 3)
protected Boolean useInSearchIndex = false;
@Override
public String getLocaleCode() {
return localeCode;
}
@Override
public void setLocaleCode(String localeCode) {
this.localeCode = localeCode;
}
@Override
public String getFriendlyName() {
return friendlyName;
}
@Override
public void setFriendlyName(String friendlyName) {
this.friendlyName = friendlyName;
}
@Override
public void setDefaultFlag(Boolean defaultFlag) {
this.defaultFlag = defaultFlag;
}
@Override
public Boolean getDefaultFlag() {
if (defaultFlag == null) {
return Boolean.FALSE;
} else {
return defaultFlag;
}
}
@Override
public BroadleafCurrency getDefaultCurrency() {
return defaultCurrency;
}
@Override
public void setDefaultCurrency(BroadleafCurrency defaultCurrency) {
this.defaultCurrency = defaultCurrency;
}
@Override
public Boolean getUseInSearchIndex() {
return useInSearchIndex == null ? false : useInSearchIndex;
}
@Override
public void setUseInSearchIndex(Boolean useInSearchIndex) {
this.useInSearchIndex = useInSearchIndex;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Locale)) {
return false;
}
LocaleImpl locale = (LocaleImpl) o;
if (localeCode != null ? !localeCode.equals(locale.localeCode) : locale.localeCode != null) {
return false;
}
if (friendlyName != null ? !friendlyName.equals(locale.friendlyName) : locale.friendlyName != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = localeCode != null ? localeCode.hashCode() : 0;
result = 31 * result + (friendlyName != null ? friendlyName.hashCode() : 0);
return result;
}
}
| 1no label
|
common_src_main_java_org_broadleafcommerce_common_locale_domain_LocaleImpl.java
|
41 |
public interface EdgeLabel extends RelationType {
/**
* Checks whether this labels is defined as directed.
*
* @return true, if this label is directed, else false.
*/
public boolean isDirected();
/**
* Checks whether this labels is defined as unidirected.
*
* @return true, if this label is unidirected, else false.
*/
public boolean isUnidirected();
/**
* The {@link Multiplicity} for this edge label.
*
* @return
*/
public Multiplicity getMultiplicity();
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_EdgeLabel.java
|
884 |
public class PromotableCandidateItemOfferImpl extends AbstractPromotionRounding implements PromotableCandidateItemOffer, OfferHolder {
private static final long serialVersionUID = 1L;
protected Offer offer;
protected PromotableOrder promotableOrder;
protected Money potentialSavings;
protected int uses = 0;
protected HashMap<OfferItemCriteria, List<PromotableOrderItem>> candidateQualifiersMap =
new HashMap<OfferItemCriteria, List<PromotableOrderItem>>();
protected HashMap<OfferItemCriteria, List<PromotableOrderItem>> candidateTargetsMap =
new HashMap<OfferItemCriteria, List<PromotableOrderItem>>();
protected List<PromotableOrderItem> legacyCandidateTargets = new ArrayList<PromotableOrderItem>();
public PromotableCandidateItemOfferImpl(PromotableOrder promotableOrder, Offer offer) {
assert (offer != null);
assert (promotableOrder != null);
this.offer = offer;
this.promotableOrder = promotableOrder;
}
@Override
public BroadleafCurrency getCurrency() {
return promotableOrder.getOrderCurrency();
}
@Override
public Money calculateSavingsForOrderItem(PromotableOrderItem orderItem, int qtyToReceiveSavings) {
Money savings = new Money(promotableOrder.getOrderCurrency());
Money price = orderItem.getPriceBeforeAdjustments(getOffer().getApplyDiscountToSalePrice());
BigDecimal offerUnitValue = PromotableOfferUtility.determineOfferUnitValue(offer, this);
savings = PromotableOfferUtility.computeAdjustmentValue(price, offerUnitValue, this, this);
return savings.multiply(qtyToReceiveSavings);
}
/**
* Returns the number of items that potentially could be targets for the offer. Due to combination or bogo
* logic, they may not all get the tiered offer price.
*/
@Override
public int calculateTargetQuantityForTieredOffer() {
int returnQty = 0;
for (OfferItemCriteria itemCriteria : getCandidateQualifiersMap().keySet()) {
List<PromotableOrderItem> candidateTargets = getCandidateTargetsMap().get(itemCriteria);
for (PromotableOrderItem promotableOrderItem : candidateTargets) {
returnQty += promotableOrderItem.getQuantity();
}
}
return returnQty;
}
@Override
public Money getPotentialSavings() {
if (potentialSavings == null) {
return new Money(promotableOrder.getOrderCurrency());
}
return potentialSavings;
}
@Override
public void setPotentialSavings(Money potentialSavings) {
this.potentialSavings = potentialSavings;
}
@Override
public boolean hasQualifyingItemCriteria() {
return (offer.getQualifyingItemCriteria() != null && !offer.getQualifyingItemCriteria().isEmpty());
}
/**
* Determines the maximum number of times this promotion can be used based on the
* ItemCriteria and promotion's maxQty setting.
*/
@Override
public int calculateMaximumNumberOfUses() {
int maxMatchesFound = 9999; // set arbitrarily high / algorithm will adjust down
//iterate through the target criteria and find the least amount of max uses. This will be the overall
//max usage, since the target criteria are grouped together in "and" style.
int numberOfUsesForThisItemCriteria = maxMatchesFound;
for (OfferItemCriteria targetCriteria : getOffer().getTargetItemCriteria()) {
int temp = calculateMaxUsesForItemCriteria(targetCriteria, getOffer());
numberOfUsesForThisItemCriteria = Math.min(numberOfUsesForThisItemCriteria, temp);
}
maxMatchesFound = Math.min(maxMatchesFound, numberOfUsesForThisItemCriteria);
int offerMaxUses = getOffer().isUnlimitedUsePerOrder() ? maxMatchesFound : getOffer().getMaxUsesPerOrder();
return Math.min(maxMatchesFound, offerMaxUses);
}
@Override
public int calculateMaxUsesForItemCriteria(OfferItemCriteria itemCriteria, Offer promotion) {
int numberOfTargets = 0;
int numberOfUsesForThisItemCriteria = 9999;
if (itemCriteria != null) {
List<PromotableOrderItem> candidateTargets = getCandidateTargetsMap().get(itemCriteria);
for(PromotableOrderItem potentialTarget : candidateTargets) {
numberOfTargets += potentialTarget.getQuantity();
}
numberOfUsesForThisItemCriteria = numberOfTargets / itemCriteria.getQuantity();
}
return numberOfUsesForThisItemCriteria;
}
@Override
public HashMap<OfferItemCriteria, List<PromotableOrderItem>> getCandidateQualifiersMap() {
return candidateQualifiersMap;
}
@Override
public void setCandidateQualifiersMap(HashMap<OfferItemCriteria, List<PromotableOrderItem>> candidateItemsMap) {
this.candidateQualifiersMap = candidateItemsMap;
}
@Override
public HashMap<OfferItemCriteria, List<PromotableOrderItem>> getCandidateTargetsMap() {
return candidateTargetsMap;
}
@Override
public void setCandidateTargetsMap(HashMap<OfferItemCriteria, List<PromotableOrderItem>> candidateItemsMap) {
this.candidateTargetsMap = candidateItemsMap;
}
@Override
public int getPriority() {
return offer.getPriority();
}
@Override
public Offer getOffer() {
return offer;
}
@Override
public int getUses() {
return uses;
}
@Override
public void addUse() {
uses++;
}
@Override
public void resetUses() {
uses = 0;
}
@Override
public boolean isLegacyOffer() {
return offer.getQualifyingItemCriteria().isEmpty() && offer.getTargetItemCriteria().isEmpty();
}
@Override
public List<PromotableOrderItem> getLegacyCandidateTargets() {
return legacyCandidateTargets;
}
@Override
public void setLegacyCandidateTargets(List<PromotableOrderItem> candidateTargets) {
this.legacyCandidateTargets = candidateTargets;
}
}
| 1no label
|
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_domain_PromotableCandidateItemOfferImpl.java
|
311 |
new Thread() {
public void run() {
beforeLock.countDown();
map.lock(key);
afterLock.countDown();
}
}.start();
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapLockTest.java
|
552 |
public static class FieldMappingMetaData implements ToXContent {
public static final FieldMappingMetaData NULL = new FieldMappingMetaData("", BytesArray.EMPTY);
private String fullName;
private BytesReference source;
public FieldMappingMetaData(String fullName, BytesReference source) {
this.fullName = fullName;
this.source = source;
}
public String fullName() {
return fullName;
}
/** Returns the mappings as a map. Note that the returned map has a single key which is always the field's {@link Mapper#name}. */
public Map<String, Object> sourceAsMap() {
return XContentHelper.convertToMap(source.array(), source.arrayOffset(), source.length(), true).v2();
}
public boolean isNull() {
return NULL.fullName().equals(fullName) && NULL.source.length() == source.length();
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.field("full_name", fullName);
XContentHelper.writeRawField("mapping", source, builder, params);
return builder;
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_admin_indices_mapping_get_GetFieldMappingsResponse.java
|
195 |
public class MemoryLocker {
/**
* This method disables to using JNA installed in system. Instead of locally installed bundled JNA will be used.
*/
private static void disableUsingSystemJNA() {
if (System.getProperty("jna.nosys") == null || !System.getProperty("jna.nosys").equals("true")) {
System.setProperty("jna.nosys", "true");
}
}
/**
* This method locks memory to prevent swapping. This method provide information about success or problems with locking memory.
* You can reed console output to know if memory locked successfully or not. If system error occurred such as permission any
* specific exception will be thrown.
*
* @param useSystemJNADisabled
* if this parameter is true only bundled JNA will be used.
*/
public static void lockMemory(boolean useSystemJNADisabled) {
if (useSystemJNADisabled)
disableUsingSystemJNA();
try {
int errorCode = MemoryLockerLinux.INSTANCE.mlockall(MemoryLockerLinux.LOCK_CURRENT_MEMORY);
if (errorCode != 0) {
final String errorMessage;
int lastError = Native.getLastError();
switch (lastError) {
case MemoryLockerLinux.EPERM:
errorMessage = "The calling process does not have the appropriate privilege to perform the requested operation(EPERM).";
break;
case MemoryLockerLinux.EAGAIN:
errorMessage = "Some or all of the memory identified by the operation could not be locked when the call was made(EAGAIN).";
break;
case MemoryLockerLinux.ENOMEM:
errorMessage = "Unable to lock JVM memory. This can result in part of the JVM being swapped out, especially if mmapping of files enabled. Increase RLIMIT_MEMLOCK or run OrientDB server as root(ENOMEM).";
break;
case MemoryLockerLinux.EINVAL:
errorMessage = "The flags argument is zero, or includes unimplemented flags(EINVAL).";
break;
case MemoryLockerLinux.ENOSYS:
errorMessage = "The implementation does not support this memory locking interface(ENOSYS).";
break;
default:
errorMessage = "Unexpected exception with code " + lastError + ".";
break;
}
OLogManager.instance().config(null, "[MemoryLocker.lockMemory] Error occurred while locking memory: %s", errorMessage);
} else {
OLogManager.instance().info(null, "[MemoryLocker.lockMemory] Memory locked successfully!");
}
} catch (UnsatisfiedLinkError e) {
OLogManager.instance().config(null,
"[MemoryLocker.lockMemory] Cannot lock virtual memory. It seems that you OS (%s) doesn't support this feature",
System.getProperty("os.name"));
}
}
}
| 0true
|
nativeos_src_main_java_com_orientechnologies_nio_MemoryLocker.java
|
89 |
RenameRefactoring refactoring = new RenameRefactoring(editor) {
@Override
public String getName() {
return "Convert method to getter";
};
@Override
protected void renameNode(TextChange tfc, Node node, Tree.CompilationUnit root) {
Integer startIndex = null;
Integer stopIndex = null;
if (node instanceof Tree.AnyMethod) {
ParameterList parameterList = ((Tree.AnyMethod) node).getParameterLists().get(0);
startIndex = parameterList.getStartIndex();
stopIndex = parameterList.getStopIndex();
} else {
FindInvocationVisitor fiv = new FindInvocationVisitor(node);
fiv.visit(root);
if (fiv.result != null && fiv.result.getPrimary() == node) {
startIndex = fiv.result.getPositionalArgumentList().getStartIndex();
stopIndex = fiv.result.getPositionalArgumentList().getStopIndex();
}
}
if (startIndex != null && stopIndex != null) {
tfc.addEdit(new DeleteEdit(startIndex, stopIndex - startIndex + 1));
}
}
};
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertMethodToGetterProposal.java
|
2,588 |
public class ZenDiscoveryModule extends AbstractModule {
private final List<Class<? extends UnicastHostsProvider>> unicastHostProviders = Lists.newArrayList();
/**
* Adds a custom unicast hosts provider to build a dynamic list of unicast hosts list when doing unicast discovery.
*/
public ZenDiscoveryModule addUnicastHostProvider(Class<? extends UnicastHostsProvider> unicastHostProvider) {
unicastHostProviders.add(unicastHostProvider);
return this;
}
@Override
protected void configure() {
bind(ZenPingService.class).asEagerSingleton();
Multibinder<UnicastHostsProvider> unicastHostsProviderMultibinder = Multibinder.newSetBinder(binder(), UnicastHostsProvider.class);
for (Class<? extends UnicastHostsProvider> unicastHostProvider : unicastHostProviders) {
unicastHostsProviderMultibinder.addBinding().to(unicastHostProvider);
}
bindDiscovery();
}
protected void bindDiscovery() {
bind(Discovery.class).to(ZenDiscovery.class).asEagerSingleton();
}
}
| 1no label
|
src_main_java_org_elasticsearch_discovery_zen_ZenDiscoveryModule.java
|
442 |
static final class Fields {
static final XContentBuilderString VERSIONS = new XContentBuilderString("versions");
static final XContentBuilderString VERSION = new XContentBuilderString("version");
static final XContentBuilderString VM_NAME = new XContentBuilderString("vm_name");
static final XContentBuilderString VM_VERSION = new XContentBuilderString("vm_version");
static final XContentBuilderString VM_VENDOR = new XContentBuilderString("vm_vendor");
static final XContentBuilderString COUNT = new XContentBuilderString("count");
static final XContentBuilderString THREADS = new XContentBuilderString("threads");
static final XContentBuilderString MAX_UPTIME = new XContentBuilderString("max_uptime");
static final XContentBuilderString MAX_UPTIME_IN_MILLIS = new XContentBuilderString("max_uptime_in_millis");
static final XContentBuilderString MEM = new XContentBuilderString("mem");
static final XContentBuilderString HEAP_USED = new XContentBuilderString("heap_used");
static final XContentBuilderString HEAP_USED_IN_BYTES = new XContentBuilderString("heap_used_in_bytes");
static final XContentBuilderString HEAP_MAX = new XContentBuilderString("heap_max");
static final XContentBuilderString HEAP_MAX_IN_BYTES = new XContentBuilderString("heap_max_in_bytes");
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsNodes.java
|
55 |
public class TitanConfigurationException extends TitanException {
private static final long serialVersionUID = 4056436257763972423L;
/**
* @param msg Exception message
*/
public TitanConfigurationException(String msg) {
super(msg);
}
/**
* @param msg Exception message
* @param cause Cause of the exception
*/
public TitanConfigurationException(String msg, Throwable cause) {
super(msg, cause);
}
/**
* Constructs an exception with a generic message
*
* @param cause Cause of the exception
*/
public TitanConfigurationException(Throwable cause) {
this("Exception in graph database configuration", cause);
}
}
| 0true
|
titan-core_src_main_java_com_thinkaurelius_titan_core_TitanConfigurationException.java
|
3,717 |
public final class EntryTaskSchedulerFactory {
private EntryTaskSchedulerFactory() {
}
/**
* Creates a new EntryTaskScheduler that will run all second operations in bulk.
* Imagine a write-behind map where dirty entries will be stored in bulk.
* Note that each key can be only once; meaning you cannot delay the execution
* Once an entry is marked as dirty for example, it will run in write-delay-seconds,
* even if the entry is updated again within write-delay-seconds.
* So two things to
* remember:
* 1. a key cannot be re-scheduled (postponing its execution).
* 2. all entries scheduled for a given second will be executed in once by your
* SecondBulkExecutor implementation.
* Once a key is executed, it can be re-scheduled for another execution.
* <p/>
* EntryTaskScheduler implementation is thread-safe.
*
* @param scheduledExecutorService ScheduledExecutorService instance to execute the second
* @param entryProcessor bulk processor
* @return EntryTaskScheduler
*/
public static <K, V> EntryTaskScheduler<K, V> newScheduler(ScheduledExecutorService scheduledExecutorService,
ScheduledEntryProcessor entryProcessor,
ScheduleType scheduleType) {
return new SecondsBasedEntryTaskScheduler<K, V>(scheduledExecutorService, entryProcessor, scheduleType);
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_util_scheduler_EntryTaskSchedulerFactory.java
|
8 |
private class OutgoingMessageHolder implements MessageHolder
{
private Deque<Message<? extends MessageType>> outgoingMessages = new ArrayDeque<Message<? extends MessageType>>();
@Override
public synchronized void offer( Message<? extends MessageType> message )
{
outgoingMessages.addFirst( message );
}
public synchronized Message<? extends MessageType> nextOutgoingMessage()
{
return outgoingMessages.pollFirst();
}
}
| 1no label
|
enterprise_cluster_src_main_java_org_neo4j_cluster_StateMachines.java
|
820 |
public class MultiSearchRequest extends ActionRequest<MultiSearchRequest> {
private List<SearchRequest> requests = Lists.newArrayList();
private IndicesOptions indicesOptions = IndicesOptions.strict();
/**
* Add a search request to execute. Note, the order is important, the search response will be returned in the
* same order as the search requests.
*/
public MultiSearchRequest add(SearchRequestBuilder request) {
requests.add(request.request());
return this;
}
/**
* Add a search request to execute. Note, the order is important, the search response will be returned in the
* same order as the search requests.
*/
public MultiSearchRequest add(SearchRequest request) {
requests.add(request);
return this;
}
public MultiSearchRequest add(byte[] data, int from, int length, boolean contentUnsafe,
@Nullable String[] indices, @Nullable String[] types, @Nullable String searchType) throws Exception {
return add(new BytesArray(data, from, length), contentUnsafe, indices, types, searchType, null, IndicesOptions.strict(), true);
}
public MultiSearchRequest add(BytesReference data, boolean contentUnsafe, @Nullable String[] indices, @Nullable String[] types, @Nullable String searchType, IndicesOptions indicesOptions) throws Exception {
return add(data, contentUnsafe, indices, types, searchType, null, indicesOptions, true);
}
public MultiSearchRequest add(BytesReference data, boolean contentUnsafe, @Nullable String[] indices, @Nullable String[] types, @Nullable String searchType, @Nullable String routing, IndicesOptions indicesOptions, boolean allowExplicitIndex) throws Exception {
XContent xContent = XContentFactory.xContent(data);
int from = 0;
int length = data.length();
byte marker = xContent.streamSeparator();
while (true) {
int nextMarker = findNextMarker(marker, from, data, length);
if (nextMarker == -1) {
break;
}
// support first line with \n
if (nextMarker == 0) {
from = nextMarker + 1;
continue;
}
SearchRequest searchRequest = new SearchRequest();
if (indices != null) {
searchRequest.indices(indices);
}
if (indicesOptions != null) {
searchRequest.indicesOptions(indicesOptions);
}
if (types != null && types.length > 0) {
searchRequest.types(types);
}
if (routing != null) {
searchRequest.routing(routing);
}
searchRequest.searchType(searchType);
boolean ignoreUnavailable = IndicesOptions.strict().ignoreUnavailable();
boolean allowNoIndices = IndicesOptions.strict().allowNoIndices();
boolean expandWildcardsOpen = IndicesOptions.strict().expandWildcardsOpen();
boolean expandWildcardsClosed = IndicesOptions.strict().expandWildcardsClosed();
// now parse the action
if (nextMarker - from > 0) {
XContentParser parser = xContent.createParser(data.slice(from, nextMarker - from));
try {
// Move to START_OBJECT, if token is null, its an empty data
XContentParser.Token token = parser.nextToken();
if (token != null) {
assert token == XContentParser.Token.START_OBJECT;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if ("index".equals(currentFieldName) || "indices".equals(currentFieldName)) {
if (!allowExplicitIndex) {
throw new ElasticsearchIllegalArgumentException("explicit index in multi search is not allowed");
}
searchRequest.indices(Strings.splitStringByCommaToArray(parser.text()));
} else if ("type".equals(currentFieldName) || "types".equals(currentFieldName)) {
searchRequest.types(Strings.splitStringByCommaToArray(parser.text()));
} else if ("search_type".equals(currentFieldName) || "searchType".equals(currentFieldName)) {
searchRequest.searchType(parser.text());
} else if ("preference".equals(currentFieldName)) {
searchRequest.preference(parser.text());
} else if ("routing".equals(currentFieldName)) {
searchRequest.routing(parser.text());
} else if ("ignore_unavailable".equals(currentFieldName) || "ignoreUnavailable".equals(currentFieldName)) {
ignoreUnavailable = parser.booleanValue();
} else if ("allow_no_indices".equals(currentFieldName) || "allowNoIndices".equals(currentFieldName)) {
allowNoIndices = parser.booleanValue();
} else if ("expand_wildcards".equals(currentFieldName) || "expandWildcards".equals(currentFieldName)) {
String[] wildcards = Strings.splitStringByCommaToArray(parser.text());
for (String wildcard : wildcards) {
if ("open".equals(wildcard)) {
expandWildcardsOpen = true;
} else if ("closed".equals(wildcard)) {
expandWildcardsClosed = true;
} else {
throw new ElasticsearchIllegalArgumentException("No valid expand wildcard value [" + wildcard + "]");
}
}
}
} else if (token == XContentParser.Token.START_ARRAY) {
if ("index".equals(currentFieldName) || "indices".equals(currentFieldName)) {
if (!allowExplicitIndex) {
throw new ElasticsearchIllegalArgumentException("explicit index in multi search is not allowed");
}
searchRequest.indices(parseArray(parser));
} else if ("type".equals(currentFieldName) || "types".equals(currentFieldName)) {
searchRequest.types(parseArray(parser));
} else if ("expand_wildcards".equals(currentFieldName) || "expandWildcards".equals(currentFieldName)) {
String[] wildcards = parseArray(parser);
for (String wildcard : wildcards) {
if ("open".equals(wildcard)) {
expandWildcardsOpen = true;
} else if ("closed".equals(wildcard)) {
expandWildcardsClosed = true;
} else {
throw new ElasticsearchIllegalArgumentException("No valid expand wildcard value [" + wildcard + "]");
}
}
} else {
throw new ElasticsearchParseException(currentFieldName + " doesn't support arrays");
}
}
}
}
} finally {
parser.close();
}
}
searchRequest.indicesOptions(IndicesOptions.fromOptions(ignoreUnavailable, allowNoIndices, expandWildcardsOpen, expandWildcardsClosed));
// move pointers
from = nextMarker + 1;
// now for the body
nextMarker = findNextMarker(marker, from, data, length);
if (nextMarker == -1) {
break;
}
searchRequest.source(data.slice(from, nextMarker - from), contentUnsafe);
// move pointers
from = nextMarker + 1;
add(searchRequest);
}
return this;
}
private String[] parseArray(XContentParser parser) throws IOException {
final List<String> list = new ArrayList<String>();
assert parser.currentToken() == XContentParser.Token.START_ARRAY;
while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
list.add(parser.text());
}
return list.toArray(new String[list.size()]);
}
private int findNextMarker(byte marker, int from, BytesReference data, int length) {
for (int i = from; i < length; i++) {
if (data.get(i) == marker) {
return i;
}
}
return -1;
}
public List<SearchRequest> requests() {
return this.requests;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (requests.isEmpty()) {
validationException = addValidationError("no requests added", validationException);
}
for (int i = 0; i < requests.size(); i++) {
ActionRequestValidationException ex = requests.get(i).validate();
if (ex != null) {
if (validationException == null) {
validationException = new ActionRequestValidationException();
}
validationException.addValidationErrors(ex.validationErrors());
}
}
return validationException;
}
public IndicesOptions indicesOptions() {
return indicesOptions;
}
public MultiSearchRequest indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = indicesOptions;
return this;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
int size = in.readVInt();
for (int i = 0; i < size; i++) {
SearchRequest request = new SearchRequest();
request.readFrom(in);
requests.add(request);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeVInt(requests.size());
for (SearchRequest request : requests) {
request.writeTo(out);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_action_search_MultiSearchRequest.java
|
448 |
public class ClusterStatsRequest extends NodesOperationRequest<ClusterStatsRequest> {
/**
* Get stats from nodes based on the nodes ids specified. If none are passed, stats
* based on all nodes will be returned.
*/
public ClusterStatsRequest(String... nodesIds) {
super(nodesIds);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsRequest.java
|
128 |
public interface StructuredContentDao {
/**
* Returns the <code>StructuredContent</code> item that matches
* the passed in Id.
* @param contentId
* @return the found item or null if it does not exist
*/
public StructuredContent findStructuredContentById(Long contentId);
/**
* Returns the <code>StructuredContentType</code> that matches
* the passed in contentTypeId.
* @param contentTypeId
* @return the found item or null if it does not exist
*/
public StructuredContentType findStructuredContentTypeById(Long contentTypeId);
/**
* Returns the list of all <code>StructuredContentType</code>s.
*
* @return the list of found items
*/
public List<StructuredContentType> retrieveAllStructuredContentTypes();
/**
* Finds all content regardless of the {@link Sandbox} they are a member of
* @return the list of {@link StructuredContent}, an empty list of none are found
*/
public List<StructuredContent> findAllContentItems();
public Map<String,StructuredContentField> readFieldsForStructuredContentItem(StructuredContent sc);
/**
* Persists the changes or saves a new content item.
*
* @param content
* @return the newly saved or persisted item
*/
public StructuredContent addOrUpdateContentItem(StructuredContent content);
/**
* Removes the passed in item from the underlying storage.
*
* @param content
*/
public void delete(StructuredContent content);
/**
* Saves the given <b>type</b> and returns the merged instance
*/
public StructuredContentType saveStructuredContentType(StructuredContentType type);
/**
* Pass through function for backwards compatibility to get a list of structured content.
*
* @param sandBox to search for the content
* @param type of content to search for
* @param locale to restrict the search to
* @return a list of all matching content
* @see org.broadleafcommerce.cms.web.structure.DisplayContentTag
*/
public List<StructuredContent> findActiveStructuredContentByType(SandBox sandBox, StructuredContentType type, Locale locale);
/**
* Called by the <code>DisplayContentTag</code> to locate content based
* on the current SandBox, StructuredContentType, fullLocale and/or languageOnlyLocale.
*
* @param sandBox to search for the content
* @param type of content to search for
* @param fullLocale to restrict the search to
* @param languageOnlyLocale locale based only on a language specified
* @return a list of all matching content
* @see org.broadleafcommerce.cms.web.structure.DisplayContentTag
*/
public List<StructuredContent> findActiveStructuredContentByType(SandBox sandBox, StructuredContentType type, Locale fullLocale, Locale languageOnlyLocale);
/**
* Pass through function for backwards compatibility to get a list of structured content.
*
* @param sandBox
* @param type
* @param name
* @param locale
* @return
*/
public List<StructuredContent> findActiveStructuredContentByNameAndType(SandBox sandBox, StructuredContentType type, String name, Locale locale);
/**
* Called by the <code>DisplayContentTag</code> to locate content based
* on the current SandBox, StructuredContentType, Name, fullLocale and/or languageOnlyLocale.
*
* @param sandBox
* @param type
* @param name
* @param fullLocale
* @param languageOnlyLocale
* @return
*/
public List<StructuredContent> findActiveStructuredContentByNameAndType(SandBox sandBox, StructuredContentType type, String name, Locale fullLocale, Locale languageOnlyLocale);
/**
* Pass through function for backwards compatibility to get a list of structured content.
*
* @param sandBox
* @param name
* @param locale
* @return
*/
public List<StructuredContent> findActiveStructuredContentByName(SandBox sandBox, String name, Locale locale);
/**
* Called by the <code>DisplayContentTag</code> to locate content based
* on the current SandBox, StructuredContentType, Name, fullLocale and/or languageOnlyLocale.
*
* @param sandBox
* @param name
* @param fullLocale
* @param languageOnlyLocale
* @return
*/
public List<StructuredContent> findActiveStructuredContentByName(SandBox sandBox, String name, Locale fullLocale, Locale languageOnlyLocale);
/**
* Used to lookup the StructuredContentType by name.
*
* @param name
* @return
*/
public StructuredContentType findStructuredContentTypeByName(String name);
/**
* Detaches the item from the JPA session. This is intended for internal
* use by the CMS system. It supports the need to clone an item as part
* of the editing process.
*
* @param sc - the item to detach
*/
public void detach(StructuredContent sc);
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_dao_StructuredContentDao.java
|
98 |
final Thread thread = new Thread() {
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
hz1.getLifecycleService().terminate();
}
};
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_ClientIssueTest.java
|
117 |
public class ExportModuleImportProposal implements ICompletionProposal,
ICompletionProposalExtension6 {
private final IProject project;
private final Unit unit;
private final String name;
ExportModuleImportProposal(IProject project, Unit unit, String name) {
this.project = project;
this.unit = unit;
this.name = name;
}
@Override
public void apply(IDocument document) {
ModuleImportUtil.exportModuleImports(project,
unit.getPackage().getModule(),
name);
}
@Override
public Point getSelection(IDocument document) {
return null;
}
@Override
public String getAdditionalProposalInfo() {
return null;
}
@Override
public String getDisplayString() {
return "Export 'import " + name + "' to clients of module";
}
@Override
public Image getImage() {
return IMPORT;
}
@Override
public IContextInformation getContextInformation() {
return null;
}
@Override
public StyledString getStyledDisplayString() {
return Highlights.styleProposal(getDisplayString(), true);
}
static void addExportModuleImportProposalForSupertypes(Collection<ICompletionProposal> proposals,
IProject project, Node node, Tree.CompilationUnit rootNode) {
Unit unit = node.getUnit();
if (node instanceof Tree.InitializerParameter) {
node = getReferencedNode(getReferencedModel(node), rootNode);
}
if (node instanceof Tree.TypedDeclaration) {
node = ((Tree.TypedDeclaration) node).getType();
}
if (node instanceof Tree.ClassOrInterface) {
Tree.ClassOrInterface c = (Tree.ClassOrInterface) node;
ProducedType extendedType =
c.getDeclarationModel().getExtendedType();
if (extendedType!=null) {
addExportModuleImportProposal(proposals, project,
unit, extendedType.getDeclaration());
for (ProducedType typeArgument:
extendedType.getTypeArgumentList()) {
addExportModuleImportProposal(proposals, project,
unit, typeArgument.getDeclaration());
}
}
List<ProducedType> satisfiedTypes =
c.getDeclarationModel().getSatisfiedTypes();
if (satisfiedTypes!=null) {
for (ProducedType satisfiedType: satisfiedTypes) {
addExportModuleImportProposal(proposals, project,
unit, satisfiedType.getDeclaration());
for (ProducedType typeArgument:
satisfiedType.getTypeArgumentList()) {
addExportModuleImportProposal(proposals, project,
unit, typeArgument.getDeclaration());
}
}
}
}
else if (node instanceof Tree.Type) {
ProducedType type = ((Tree.Type) node).getTypeModel();
addExportModuleImportProposal(proposals, project,
unit, type.getDeclaration());
for (ProducedType typeArgument:
type.getTypeArgumentList()) {
addExportModuleImportProposal(proposals, project,
unit, typeArgument.getDeclaration());
}
}
}
static void addExportModuleImportProposal(Collection<ICompletionProposal> proposals,
IProject project, Node node) {
if (node instanceof Tree.SimpleType) {
Declaration dec = ((Tree.SimpleType) node).getDeclarationModel();
addExportModuleImportProposal(proposals, project, node.getUnit(), dec);
}
}
private static void addExportModuleImportProposal(Collection<ICompletionProposal> proposals,
IProject project, Unit unit, Declaration dec) {
Module decModule = dec.getUnit().getPackage().getModule();
for (ModuleImport mi: unit.getPackage().getModule().getImports()) {
if (mi.getModule().equals(decModule)) {
if (mi.isExport()) {
return;
}
}
}
proposals.add(new ExportModuleImportProposal(project, unit,
decModule.getNameAsString()));
}
}
| 0true
|
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ExportModuleImportProposal.java
|
371 |
@Service("blTranslationService")
public class TranslationServiceImpl implements TranslationService {
protected static final Log LOG = LogFactory.getLog(TranslationServiceImpl.class);
@Resource(name = "blTranslationDao")
protected TranslationDao dao;
protected Cache cache;
@Override
@Transactional("blTransactionManager")
public Translation save(Translation translation) {
return dao.save(translation);
}
@Override
@Transactional("blTransactionManager")
public Translation save(String entityType, String entityId, String fieldName, String localeCode,
String translatedValue) {
TranslatedEntity te = getEntityType(entityType);
Translation translation = getTranslation(te, entityId, fieldName, localeCode);
if (translation == null) {
translation = dao.create();
translation.setEntityType(te);
translation.setEntityId(entityId);
translation.setFieldName(fieldName);
translation.setLocaleCode(localeCode);
}
translation.setTranslatedValue(translatedValue);
return save(translation);
}
@Override
public Translation findTranslationById(Long id) {
return dao.readTranslationById(id);
}
@Override
@Transactional("blTransactionManager")
public Translation update(Long translationId, String localeCode, String translatedValue) {
Translation t = dao.readTranslationById(translationId);
// Check to see if there is another translation that matches this updated one. We'll remove it if it exists
Translation t2 = dao.readTranslation(t.getEntityType(), t.getEntityId(), t.getFieldName(), localeCode);
if (t2 != null && t != t2) {
dao.delete(t2);
}
t.setLocaleCode(localeCode);
t.setTranslatedValue(translatedValue);
return save(t);
}
@Override
@Transactional("blTransactionManager")
public void deleteTranslationById(Long translationId) {
Translation t = dao.readTranslationById(translationId);
dao.delete(t);
}
@Override
public Translation getTranslation(TranslatedEntity entity, String entityId, String fieldName, String localeCode) {
return dao.readTranslation(entity, entityId, fieldName, localeCode);
}
@Override
public List<Translation> getTranslations(String ceilingEntityClassname, String entityId, String property) {
TranslatedEntity entityType = getEntityType(ceilingEntityClassname);
return dao.readTranslations(entityType, entityId, property);
}
@Override
public String getTranslatedValue(Object entity, String property, Locale locale) {
// Attempt to get a translated value for this property to override the default value
TranslatedEntity entityType = getEntityType(entity);
String entityId = getEntityId(entity, entityType);
String localeCode = locale.getLanguage();
String localeCountryCode = localeCode;
if (StringUtils.isNotBlank(locale.getCountry())) {
localeCountryCode += "_" + locale.getCountry();
}
Translation translation;
// First, we'll try to look up a country language combo (en_GB), utilizing the cache
String countryCacheKey = getCacheKey(entityType, entityId, property, localeCountryCode);
Element countryValue = getCache().get(countryCacheKey);
if (countryValue != null) {
translation = (Translation) countryValue.getObjectValue();
} else {
translation = getTranslation(entityType, entityId, property, localeCountryCode);
if (translation == null) {
translation = new TranslationImpl();
}
getCache().put(new Element(countryCacheKey, translation));
}
// If we don't find one, let's try just the language (en), again utilizing the cache
if (translation.getTranslatedValue()==null) {
String nonCountryCacheKey = getCacheKey(entityType, entityId, property, localeCode);
Element nonCountryValue = getCache().get(nonCountryCacheKey);
if (nonCountryValue != null) {
translation = (Translation) nonCountryValue.getObjectValue();
} else {
translation = getTranslation(entityType, entityId, property, localeCode);
if (translation == null) {
translation = new TranslationImpl();
}
getCache().put(new Element(nonCountryCacheKey, translation));
}
}
// If we have a match on a translation, use that instead of what we found on the entity.
if (StringUtils.isNotBlank(translation.getTranslatedValue())) {
return translation.getTranslatedValue();
}
return null;
}
protected TranslatedEntity getEntityType(Class<?> entityClass) {
for (Entry<String, TranslatedEntity> entry : TranslatedEntity.getTypes().entrySet()) {
try {
Class<?> clazz = Class.forName(entry.getKey());
if (clazz.isAssignableFrom(entityClass)) {
return entry.getValue();
}
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("TranslatedEntity type was not set to a known class", e);
}
}
throw new IllegalArgumentException(entityClass.getName() + " is not a known translatable class");
}
protected TranslatedEntity getEntityType(Object entity) {
return getEntityType(entity.getClass());
}
protected TranslatedEntity getEntityType(String className) {
try {
Class<?> clazz = Class.forName(className);
return getEntityType(clazz);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(className + " is not a known translatable class");
}
}
protected String getEntityId(Object entity, TranslatedEntity entityType) {
Map<String, Object> idMetadata = dao.getIdPropertyMetadata(entityType);
String idProperty = (String) idMetadata.get("name");
Type idType = (Type) idMetadata.get("type");
if (!(idType instanceof LongType || idType instanceof StringType)) {
throw new UnsupportedOperationException("Only ID types of String and Long are currently supported");
}
Object idValue = null;
try {
idValue = PropertyUtils.getProperty(entity, idProperty);
} catch (Exception e) {
throw new RuntimeException("Error reading id property", e);
}
if (idType instanceof StringType) {
return (String) idValue;
} else if (idType instanceof LongType) {
return String.valueOf(idValue);
}
throw new IllegalArgumentException(String.format("Could not retrieve value for id property. Object: [%s], " +
"ID Property: [%s], ID Type: [%s]", entity, idProperty, idType));
}
protected String getCacheKey(TranslatedEntity entityType, String entityId, String property, String localeCode) {
return StringUtils.join(new String[] { entityType.getFriendlyType(), entityId, property, localeCode }, "|");
}
protected Cache getCache() {
if (cache == null) {
cache = CacheManager.getInstance().getCache("blTranslationElements");
}
return cache;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_i18n_service_TranslationServiceImpl.java
|
1,271 |
return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<Response>>() {
@Override
public ActionFuture<Response> doWithNode(DiscoveryNode node) throws ElasticsearchException {
return proxy.execute(node, request);
}
});
| 1no label
|
src_main_java_org_elasticsearch_client_transport_support_InternalTransportClusterAdminClient.java
|
296 |
public class NoPossibleResultsException extends RuntimeException {
private static final long serialVersionUID = 2422275745139590462L;
// for serialization purposes
protected NoPossibleResultsException() {
super();
}
public NoPossibleResultsException(String message, Throwable cause) {
super(message, cause);
}
public NoPossibleResultsException(String message) {
super(message);
}
public NoPossibleResultsException(Throwable cause) {
super(cause);
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_exception_NoPossibleResultsException.java
|
1,392 |
public static class Builder {
private String uuid;
private long version;
private Settings transientSettings = ImmutableSettings.Builder.EMPTY_SETTINGS;
private Settings persistentSettings = ImmutableSettings.Builder.EMPTY_SETTINGS;
private final ImmutableOpenMap.Builder<String, IndexMetaData> indices;
private final ImmutableOpenMap.Builder<String, IndexTemplateMetaData> templates;
private final ImmutableOpenMap.Builder<String, Custom> customs;
public Builder() {
uuid = "_na_";
indices = ImmutableOpenMap.builder();
templates = ImmutableOpenMap.builder();
customs = ImmutableOpenMap.builder();
}
public Builder(MetaData metaData) {
this.uuid = metaData.uuid;
this.transientSettings = metaData.transientSettings;
this.persistentSettings = metaData.persistentSettings;
this.version = metaData.version;
this.indices = ImmutableOpenMap.builder(metaData.indices);
this.templates = ImmutableOpenMap.builder(metaData.templates);
this.customs = ImmutableOpenMap.builder(metaData.customs);
}
public Builder put(IndexMetaData.Builder indexMetaDataBuilder) {
// we know its a new one, increment the version and store
indexMetaDataBuilder.version(indexMetaDataBuilder.version() + 1);
IndexMetaData indexMetaData = indexMetaDataBuilder.build();
indices.put(indexMetaData.index(), indexMetaData);
return this;
}
public Builder put(IndexMetaData indexMetaData, boolean incrementVersion) {
if (indices.get(indexMetaData.index()) == indexMetaData) {
return this;
}
// if we put a new index metadata, increment its version
if (incrementVersion) {
indexMetaData = IndexMetaData.builder(indexMetaData).version(indexMetaData.version() + 1).build();
}
indices.put(indexMetaData.index(), indexMetaData);
return this;
}
public IndexMetaData get(String index) {
return indices.get(index);
}
public Builder remove(String index) {
indices.remove(index);
return this;
}
public Builder removeAllIndices() {
indices.clear();
return this;
}
public Builder put(IndexTemplateMetaData.Builder template) {
return put(template.build());
}
public Builder put(IndexTemplateMetaData template) {
templates.put(template.name(), template);
return this;
}
public Builder removeTemplate(String templateName) {
templates.remove(templateName);
return this;
}
public Custom getCustom(String type) {
return customs.get(type);
}
public Builder putCustom(String type, Custom custom) {
customs.put(type, custom);
return this;
}
public Builder removeCustom(String type) {
customs.remove(type);
return this;
}
public Builder updateSettings(Settings settings, String... indices) {
if (indices == null || indices.length == 0) {
indices = this.indices.keys().toArray(String.class);
}
for (String index : indices) {
IndexMetaData indexMetaData = this.indices.get(index);
if (indexMetaData == null) {
throw new IndexMissingException(new Index(index));
}
put(IndexMetaData.builder(indexMetaData)
.settings(settingsBuilder().put(indexMetaData.settings()).put(settings)));
}
return this;
}
public Builder updateNumberOfReplicas(int numberOfReplicas, String... indices) {
if (indices == null || indices.length == 0) {
indices = this.indices.keys().toArray(String.class);
}
for (String index : indices) {
IndexMetaData indexMetaData = this.indices.get(index);
if (indexMetaData == null) {
throw new IndexMissingException(new Index(index));
}
put(IndexMetaData.builder(indexMetaData).numberOfReplicas(numberOfReplicas));
}
return this;
}
public Settings transientSettings() {
return this.transientSettings;
}
public Builder transientSettings(Settings settings) {
this.transientSettings = settings;
return this;
}
public Settings persistentSettings() {
return this.persistentSettings;
}
public Builder persistentSettings(Settings settings) {
this.persistentSettings = settings;
return this;
}
public Builder version(long version) {
this.version = version;
return this;
}
public Builder generateUuidIfNeeded() {
if (uuid.equals("_na_")) {
uuid = Strings.randomBase64UUID();
}
return this;
}
public MetaData build() {
return new MetaData(uuid, version, transientSettings, persistentSettings, indices.build(), templates.build(), customs.build());
}
public static String toXContent(MetaData metaData) throws IOException {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.startObject();
toXContent(metaData, builder, ToXContent.EMPTY_PARAMS);
builder.endObject();
return builder.string();
}
public static void toXContent(MetaData metaData, XContentBuilder builder, ToXContent.Params params) throws IOException {
boolean globalPersistentOnly = params.paramAsBoolean(GLOBAL_PERSISTENT_ONLY_PARAM, false);
builder.startObject("meta-data");
builder.field("version", metaData.version());
builder.field("uuid", metaData.uuid);
if (!metaData.persistentSettings().getAsMap().isEmpty()) {
builder.startObject("settings");
for (Map.Entry<String, String> entry : metaData.persistentSettings().getAsMap().entrySet()) {
builder.field(entry.getKey(), entry.getValue());
}
builder.endObject();
}
if (!globalPersistentOnly && !metaData.transientSettings().getAsMap().isEmpty()) {
builder.startObject("transient_settings");
for (Map.Entry<String, String> entry : metaData.transientSettings().getAsMap().entrySet()) {
builder.field(entry.getKey(), entry.getValue());
}
builder.endObject();
}
builder.startObject("templates");
for (ObjectCursor<IndexTemplateMetaData> cursor : metaData.templates().values()) {
IndexTemplateMetaData.Builder.toXContent(cursor.value, builder, params);
}
builder.endObject();
if (!globalPersistentOnly && !metaData.indices().isEmpty()) {
builder.startObject("indices");
for (IndexMetaData indexMetaData : metaData) {
IndexMetaData.Builder.toXContent(indexMetaData, builder, params);
}
builder.endObject();
}
for (ObjectObjectCursor<String, Custom> cursor : metaData.customs()) {
Custom.Factory factory = lookupFactorySafe(cursor.key);
if (!globalPersistentOnly || factory.isPersistent()) {
builder.startObject(cursor.key);
factory.toXContent(cursor.value, builder, params);
builder.endObject();
}
}
builder.endObject();
}
public static MetaData fromXContent(XContentParser parser) throws IOException {
Builder builder = new Builder();
// we might get here after the meta-data element, or on a fresh parser
XContentParser.Token token = parser.currentToken();
String currentFieldName = parser.currentName();
if (!"meta-data".equals(currentFieldName)) {
token = parser.nextToken();
if (token == XContentParser.Token.START_OBJECT) {
// move to the field name (meta-data)
token = parser.nextToken();
// move to the next object
token = parser.nextToken();
}
currentFieldName = parser.currentName();
if (token == null) {
// no data...
return builder.build();
}
}
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("settings".equals(currentFieldName)) {
builder.persistentSettings(ImmutableSettings.settingsBuilder().put(SettingsLoader.Helper.loadNestedFromMap(parser.mapOrdered())).build());
} else if ("indices".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
builder.put(IndexMetaData.Builder.fromXContent(parser), false);
}
} else if ("templates".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
builder.put(IndexTemplateMetaData.Builder.fromXContent(parser));
}
} else {
// check if its a custom index metadata
Custom.Factory<Custom> factory = lookupFactory(currentFieldName);
if (factory == null) {
//TODO warn
parser.skipChildren();
} else {
builder.putCustom(factory.type(), factory.fromXContent(parser));
}
}
} else if (token.isValue()) {
if ("version".equals(currentFieldName)) {
builder.version = parser.longValue();
} else if ("uuid".equals(currentFieldName)) {
builder.uuid = parser.text();
}
}
}
return builder.build();
}
public static MetaData readFrom(StreamInput in) throws IOException {
Builder builder = new Builder();
builder.version = in.readLong();
builder.uuid = in.readString();
builder.transientSettings(readSettingsFromStream(in));
builder.persistentSettings(readSettingsFromStream(in));
int size = in.readVInt();
for (int i = 0; i < size; i++) {
builder.put(IndexMetaData.Builder.readFrom(in), false);
}
size = in.readVInt();
for (int i = 0; i < size; i++) {
builder.put(IndexTemplateMetaData.Builder.readFrom(in));
}
int customSize = in.readVInt();
for (int i = 0; i < customSize; i++) {
String type = in.readString();
Custom customIndexMetaData = lookupFactorySafe(type).readFrom(in);
builder.putCustom(type, customIndexMetaData);
}
return builder.build();
}
public static void writeTo(MetaData metaData, StreamOutput out) throws IOException {
out.writeLong(metaData.version);
out.writeString(metaData.uuid);
writeSettingsToStream(metaData.transientSettings(), out);
writeSettingsToStream(metaData.persistentSettings(), out);
out.writeVInt(metaData.indices.size());
for (IndexMetaData indexMetaData : metaData) {
IndexMetaData.Builder.writeTo(indexMetaData, out);
}
out.writeVInt(metaData.templates.size());
for (ObjectCursor<IndexTemplateMetaData> cursor : metaData.templates.values()) {
IndexTemplateMetaData.Builder.writeTo(cursor.value, out);
}
out.writeVInt(metaData.customs().size());
for (ObjectObjectCursor<String, Custom> cursor : metaData.customs()) {
out.writeString(cursor.key);
lookupFactorySafe(cursor.key).writeTo(cursor.value, out);
}
}
}
| 1no label
|
src_main_java_org_elasticsearch_cluster_metadata_MetaData.java
|
376 |
public interface ODatabaseRecord extends ODatabaseComplex<ORecordInternal<?>> {
/**
* Browses all the records of the specified cluster.
*
* @param iClusterName
* Cluster name to iterate
* @return Iterator of ODocument instances
*/
public <REC extends ORecordInternal<?>> ORecordIteratorCluster<REC> browseCluster(String iClusterName);
public <REC extends ORecordInternal<?>> ORecordIteratorCluster<REC> browseCluster(String iClusterName,
OClusterPosition startClusterPosition, OClusterPosition endClusterPosition, boolean loadTombstones);
/**
* Browses all the records of the specified cluster of the passed record type.
*
* @param iClusterName
* Cluster name to iterate
* @param iRecordClass
* The record class expected
* @return Iterator of ODocument instances
*/
public <REC extends ORecordInternal<?>> ORecordIteratorCluster<REC> browseCluster(String iClusterName, Class<REC> iRecordClass);
public <REC extends ORecordInternal<?>> ORecordIteratorCluster<REC> browseCluster(String iClusterName, Class<REC> iRecordClass,
OClusterPosition startClusterPosition, OClusterPosition endClusterPosition, boolean loadTombstones);
/**
* Returns the record for a OIdentifiable instance. If the argument received already is a ORecord instance, then it's returned as
* is, otherwise a new ORecord is created with the identity received and returned.
*
* @param iIdentifiable
* @return A ORecord instance
*/
public <RET extends ORecordInternal<?>> RET getRecord(OIdentifiable iIdentifiable);
/**
* Returns the default record type for this kind of database.
*/
public byte getRecordType();
/**
* Returns true if current configuration retains objects, otherwise false
*
* @see #setRetainRecords(boolean)
*/
public boolean isRetainRecords();
/**
* Specifies if retain handled objects in memory or not. Setting it to false can improve performance on large inserts. Default is
* enabled.
*
* @param iValue
* True to enable, false to disable it.
* @see #isRetainRecords()
*/
public ODatabaseRecord setRetainRecords(boolean iValue);
/**
* Checks if the operation on a resource is allowed for the current user.
*
* @param iResource
* Resource where to execute the operation
* @param iOperation
* Operation to execute against the resource
* @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <DB extends ODatabaseRecord> DB checkSecurity(String iResource, int iOperation);
/**
* Checks if the operation on a resource is allowed for the current user. The check is made in two steps:
* <ol>
* <li>
* Access to all the resource as *</li>
* <li>
* Access to the specific target resource</li>
* </ol>
*
* @param iResourceGeneric
* Resource where to execute the operation, i.e.: database.clusters
* @param iOperation
* Operation to execute against the resource
* @param iResourceSpecific
* Target resource, i.e.: "employee" to specify the cluster name.
* @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <DB extends ODatabaseRecord> DB checkSecurity(String iResourceGeneric, int iOperation, Object iResourceSpecific);
/**
* Checks if the operation against multiple resources is allowed for the current user. The check is made in two steps:
* <ol>
* <li>
* Access to all the resource as *</li>
* <li>
* Access to the specific target resources</li>
* </ol>
*
* @param iResourceGeneric
* Resource where to execute the operation, i.e.: database.clusters
* @param iOperation
* Operation to execute against the resource
* @param iResourcesSpecific
* Target resources as an array of Objects, i.e.: ["employee", 2] to specify cluster name and id.
* @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <DB extends ODatabaseRecord> DB checkSecurity(String iResourceGeneric, int iOperation, Object... iResourcesSpecific);
/**
* Tells if validation of record is active. Default is true.
*
* @return true if it's active, otherwise false.
*/
public boolean isValidationEnabled();
/**
* Enables or disables the record validation.
*
* @param iEnabled
* True to enable, false to disable
* @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
*/
public <DB extends ODatabaseRecord> DB setValidationEnabled(boolean iEnabled);
public ODataSegmentStrategy getDataSegmentStrategy();
public void setDataSegmentStrategy(ODataSegmentStrategy dataSegmentStrategy);
public OSBTreeCollectionManager getSbTreeCollectionManager();
}
| 0true
|
core_src_main_java_com_orientechnologies_orient_core_db_record_ODatabaseRecord.java
|
596 |
public class IndicesSegmentsRequestBuilder extends BroadcastOperationRequestBuilder<IndicesSegmentsRequest, IndicesSegmentResponse, IndicesSegmentsRequestBuilder> {
public IndicesSegmentsRequestBuilder(IndicesAdminClient indicesClient) {
super((InternalIndicesAdminClient) indicesClient, new IndicesSegmentsRequest());
}
@Override
protected void doExecute(ActionListener<IndicesSegmentResponse> listener) {
((IndicesAdminClient) client).segments(request, listener);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_indices_segments_IndicesSegmentsRequestBuilder.java
|
597 |
@RunWith(HazelcastSerialClassRunner.class)
@Category(NightlyTest.class)
public class JoinStressTest extends HazelcastTestSupport {
@Test
public void testTCPIPJoinWithManyNodes() throws UnknownHostException, InterruptedException {
final int count = 20;
final CountDownLatch latch = new CountDownLatch(count);
final ConcurrentHashMap<Integer, HazelcastInstance> mapOfInstances = new ConcurrentHashMap<Integer, HazelcastInstance>();
final Random random = new Random();
final ExecutorService ex = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
for (int i = 0; i < count; i++) {
final int seed = i;
ex.execute(new Runnable() {
public void run() {
try {
Thread.sleep(random.nextInt(10) * 1000);
final Config config = new Config();
config.setProperty("hazelcast.wait.seconds.before.join", "5");
final NetworkConfig networkConfig = config.getNetworkConfig();
networkConfig.getJoin().getMulticastConfig().setEnabled(false);
TcpIpConfig tcpIpConfig = networkConfig.getJoin().getTcpIpConfig();
tcpIpConfig.setEnabled(true);
int port = 12301;
networkConfig.setPortAutoIncrement(false);
networkConfig.setPort(port + seed);
for (int i = 0; i < count; i++) {
tcpIpConfig.addMember("127.0.0.1:" + (port + i));
}
HazelcastInstance h = Hazelcast.newHazelcastInstance(config);
mapOfInstances.put(seed, h);
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
try {
latch.await(200, TimeUnit.SECONDS);
} finally {
ex.shutdown();
}
for (HazelcastInstance h : mapOfInstances.values()) {
assertEquals(count, h.getCluster().getMembers().size());
}
}
@Test
@Category(ProblematicTest.class)
public void testTCPIPJoinWithManyNodesMultipleGroups() throws UnknownHostException, InterruptedException {
final int count = 20;
final int groupCount = 3;
final CountDownLatch latch = new CountDownLatch(count);
final ConcurrentHashMap<Integer, HazelcastInstance> mapOfInstances = new ConcurrentHashMap<Integer, HazelcastInstance>();
final Random random = new Random();
final Map<String, AtomicInteger> groups = new ConcurrentHashMap<String, AtomicInteger>();
for (int i = 0; i < groupCount; i++) {
groups.put("group" + i, new AtomicInteger(0));
}
final ExecutorService ex = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
for (int i = 0; i < count; i++) {
final int seed = i;
ex.execute(new Runnable() {
public void run() {
try {
Thread.sleep(random.nextInt(10) * 1000);
final Config config = new Config();
config.setProperty("hazelcast.wait.seconds.before.join", "5");
String name = "group" + random.nextInt(groupCount);
groups.get(name).incrementAndGet();
config.getGroupConfig().setName(name);
final NetworkConfig networkConfig = config.getNetworkConfig();
networkConfig.getJoin().getMulticastConfig().setEnabled(false);
TcpIpConfig tcpIpConfig = networkConfig.getJoin().getTcpIpConfig();
tcpIpConfig.setEnabled(true);
int port = 12301;
networkConfig.setPortAutoIncrement(false);
networkConfig.setPort(port + seed);
for (int i = 0; i < count; i++) {
tcpIpConfig.addMember("127.0.0.1:" + (port + i));
}
HazelcastInstance h = Hazelcast.newHazelcastInstance(config);
mapOfInstances.put(seed, h);
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
try {
latch.await(200, TimeUnit.SECONDS);
} finally {
ex.shutdown();
}
for (HazelcastInstance h : mapOfInstances.values()) {
int clusterSize = h.getCluster().getMembers().size();
int shouldBeClusterSize = groups.get(h.getConfig().getGroupConfig().getName()).get();
assertEquals(h.getConfig().getGroupConfig().getName() + ": ", shouldBeClusterSize, clusterSize);
}
}
@Test
@Category(ProblematicTest.class)
public void testMulticastJoinAtTheSameTime() throws InterruptedException {
multicastJoin(10, false);
}
@Test
@Category(ProblematicTest.class)
public void testMulticastJoinWithRandomStartTime() throws InterruptedException {
multicastJoin(10, true);
}
private void multicastJoin(int count, final boolean sleep) throws InterruptedException {
final TestHazelcastInstanceFactory nodeFactory = createHazelcastInstanceFactory(count);
final Config config = new Config();
config.setProperty("hazelcast.wait.seconds.before.join", "5");
config.getNetworkConfig().getJoin().getMulticastConfig().setMulticastTimeoutSeconds(25);
final ConcurrentMap<Integer, HazelcastInstance> map = new ConcurrentHashMap<Integer, HazelcastInstance>();
final CountDownLatch latch = new CountDownLatch(count);
final ExecutorService ex = Executors.newCachedThreadPool();
for (int i = 0; i < count; i++) {
final int index = i;
ex.execute(new Runnable() {
public void run() {
if (sleep) {
try {
Thread.sleep((int) (1000 * Math.random()));
} catch (InterruptedException ignored) {
}
}
HazelcastInstance h = nodeFactory.newHazelcastInstance(config);
map.put(index, h);
latch.countDown();
}
});
}
assertOpenEventually(latch);
for (HazelcastInstance h : map.values()) {
assertEquals(count, h.getCluster().getMembers().size());
}
ex.shutdown();
}
}
| 0true
|
hazelcast_src_test_java_com_hazelcast_cluster_JoinStressTest.java
|
384 |
static class CountDownValueNullListener extends MyEntryListener {
public CountDownValueNullListener(int latchCount){
super(latchCount);
}
public CountDownValueNullListener(int addlatchCount, int removeLatchCount){
super(addlatchCount, removeLatchCount);
}
public void entryAdded(EntryEvent event) {
if(event.getValue() == null){
addLatch.countDown();
}
}
public void entryRemoved(EntryEvent event) {
if(event.getValue() == null){
removeLatch.countDown();
}
}
public void entryUpdated(EntryEvent event) {
if(event.getValue() == null){
updateLatch.countDown();
}
}
public void entryEvicted(EntryEvent event) {
if(event.getValue() == null){
evictLatch.countDown();
}
}
};
| 0true
|
hazelcast-client_src_test_java_com_hazelcast_client_multimap_ClientMultiMapListenersTest.java
|
151 |
public class ItemCriteriaDTO implements Serializable {
private static final long serialVersionUID = 1L;
protected Integer qty;
protected String matchRule;
public Integer getQty() {
return qty;
}
public void setQty(Integer qty) {
this.qty = qty;
}
public String getMatchRule() {
return matchRule;
}
public void setMatchRule(String matchRule) {
this.matchRule = matchRule;
}
}
| 0true
|
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_dto_ItemCriteriaDTO.java
|
23 |
{
@Override
public boolean matchesSafely( LogEntry.Done done )
{
return done != null && done.getIdentifier() == identifier;
}
@Override
public void describeTo( Description description )
{
description.appendText( String.format( "Done[%d]", identifier ) );
}
};
| 1no label
|
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_LogMatchers.java
|
4,198 |
public static class FileInfo {
private final String name;
private final String physicalName;
private final long length;
private final String checksum;
private final ByteSizeValue partSize;
private final long partBytes;
private final long numberOfParts;
/**
* Constructs a new instance of file info
*
* @param name file name as stored in the blob store
* @param physicalName original file name
* @param length total length of the file
* @param partSize size of the single chunk
* @param checksum checksum for the file
*/
public FileInfo(String name, String physicalName, long length, ByteSizeValue partSize, String checksum) {
this.name = name;
this.physicalName = physicalName;
this.length = length;
this.checksum = checksum;
long partBytes = Long.MAX_VALUE;
if (partSize != null) {
partBytes = partSize.bytes();
}
long totalLength = length;
long numberOfParts = totalLength / partBytes;
if (totalLength % partBytes > 0) {
numberOfParts++;
}
if (numberOfParts == 0) {
numberOfParts++;
}
this.numberOfParts = numberOfParts;
this.partSize = partSize;
this.partBytes = partBytes;
}
/**
* Returns the base file name
*
* @return file name
*/
public String name() {
return name;
}
/**
* Returns part name if file is stored as multiple parts
*
* @param part part number
* @return part name
*/
public String partName(long part) {
if (numberOfParts > 1) {
return name + ".part" + part;
} else {
return name;
}
}
/**
* Returns base file name from part name
*
* @param blobName part name
* @return base file name
*/
public static String canonicalName(String blobName) {
if (blobName.contains(".part")) {
return blobName.substring(0, blobName.indexOf(".part"));
}
return blobName;
}
/**
* Returns original file name
*
* @return original file name
*/
public String physicalName() {
return this.physicalName;
}
/**
* File length
*
* @return file length
*/
public long length() {
return length;
}
/**
* Returns part size
*
* @return part size
*/
public ByteSizeValue partSize() {
return partSize;
}
/**
* Return maximum number of bytes in a part
*
* @return maximum number of bytes in a part
*/
public long partBytes() {
return partBytes;
}
/**
* Returns number of parts
*
* @return number of parts
*/
public long numberOfParts() {
return numberOfParts;
}
/**
* Returns file md5 checksum provided by {@link org.elasticsearch.index.store.Store}
*
* @return file checksum
*/
@Nullable
public String checksum() {
return checksum;
}
/**
* Checks if a file in a store is the same file
*
* @param md file in a store
* @return true if file in a store this this file have the same checksum and length
*/
public boolean isSame(StoreFileMetaData md) {
if (checksum == null || md.checksum() == null) {
return false;
}
return length == md.length() && checksum.equals(md.checksum());
}
static final class Fields {
static final XContentBuilderString NAME = new XContentBuilderString("name");
static final XContentBuilderString PHYSICAL_NAME = new XContentBuilderString("physical_name");
static final XContentBuilderString LENGTH = new XContentBuilderString("length");
static final XContentBuilderString CHECKSUM = new XContentBuilderString("checksum");
static final XContentBuilderString PART_SIZE = new XContentBuilderString("part_size");
}
/**
* Serializes file info into JSON
*
* @param file file info
* @param builder XContent builder
* @param params parameters
* @throws IOException
*/
public static void toXContent(FileInfo file, XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.startObject();
builder.field(Fields.NAME, file.name);
builder.field(Fields.PHYSICAL_NAME, file.physicalName);
builder.field(Fields.LENGTH, file.length);
if (file.checksum != null) {
builder.field(Fields.CHECKSUM, file.checksum);
}
if (file.partSize != null) {
builder.field(Fields.PART_SIZE, file.partSize.bytes());
}
builder.endObject();
}
/**
* Parses JSON that represents file info
*
* @param parser parser
* @return file info
* @throws IOException
*/
public static FileInfo fromXContent(XContentParser parser) throws IOException {
XContentParser.Token token = parser.currentToken();
String name = null;
String physicalName = null;
long length = -1;
String checksum = null;
ByteSizeValue partSize = null;
if (token == XContentParser.Token.START_OBJECT) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
String currentFieldName = parser.currentName();
token = parser.nextToken();
if (token.isValue()) {
if ("name".equals(currentFieldName)) {
name = parser.text();
} else if ("physical_name".equals(currentFieldName)) {
physicalName = parser.text();
} else if ("length".equals(currentFieldName)) {
length = parser.longValue();
} else if ("checksum".equals(currentFieldName)) {
checksum = parser.text();
} else if ("part_size".equals(currentFieldName)) {
partSize = new ByteSizeValue(parser.longValue());
} else {
throw new ElasticsearchParseException("unknown parameter [" + currentFieldName + "]");
}
} else {
throw new ElasticsearchParseException("unexpected token [" + token + "]");
}
} else {
throw new ElasticsearchParseException("unexpected token [" + token + "]");
}
}
}
// TODO: Verify???
return new FileInfo(name, physicalName, length, partSize, checksum);
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_snapshots_blobstore_BlobStoreIndexShardSnapshot.java
|
273 |
public class EmailServiceMDP implements MessageListener {
@Resource(name = "blMessageCreator")
private MessageCreator messageCreator;
/*
* (non-Javadoc)
* @see javax.jms.MessageListener#onMessage(javax.jms.Message)
*/
@SuppressWarnings("unchecked")
public void onMessage(Message message) {
try {
HashMap props = (HashMap) ((ObjectMessage) message).getObject();
messageCreator.sendMessage(props);
} catch (MailAuthenticationException e) {
throw new EmailException(e);
} catch (MailPreparationException e) {
throw new EmailException(e);
} catch (MailParseException e) {
throw new EmailException(e);
} catch (MailSendException e) {
/*
* TODO find the specific exception that results from the smtp
* server being down, and throw this as an EmailException.
* Otherwise, log and then swallow this exception, as it may have
* been possible that this email was actually sent.
*/
throw new EmailException(e);
} catch (JMSException e) {
throw new EmailException(e);
}
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_email_service_jms_EmailServiceMDP.java
|
674 |
constructors[COLLECTION_PREPARE_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new CollectionPrepareBackupOperation();
}
};
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
|
692 |
public class CollectionPortableHook implements PortableHook {
public static final int F_ID = FactoryIdHelper.getFactoryId(FactoryIdHelper.COLLECTION_PORTABLE_FACTORY, -20);
public static final int COLLECTION_SIZE = 1;
public static final int COLLECTION_CONTAINS = 2;
public static final int COLLECTION_ADD = 3;
public static final int COLLECTION_REMOVE = 4;
public static final int COLLECTION_ADD_ALL = 5;
public static final int COLLECTION_COMPARE_AND_REMOVE = 6;
public static final int COLLECTION_CLEAR = 7;
public static final int COLLECTION_GET_ALL = 8;
public static final int COLLECTION_ADD_LISTENER = 9;
public static final int LIST_ADD_ALL = 10;
public static final int LIST_GET = 11;
public static final int LIST_SET = 12;
public static final int LIST_ADD = 13;
public static final int LIST_REMOVE = 14;
public static final int LIST_INDEX_OF = 15;
public static final int LIST_SUB = 16;
public static final int TXN_LIST_ADD = 17;
public static final int TXN_LIST_REMOVE = 18;
public static final int TXN_LIST_SIZE = 19;
public static final int TXN_SET_ADD = 20;
public static final int TXN_SET_REMOVE = 21;
public static final int TXN_SET_SIZE = 22;
public static final int COLLECTION_REMOVE_LISTENER = 23;
public int getFactoryId() {
return F_ID;
}
@Override
public PortableFactory createFactory() {
ConstructorFunction<Integer, Portable>[] constructors = new ConstructorFunction[COLLECTION_REMOVE_LISTENER + 1];
constructors[COLLECTION_SIZE] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new CollectionSizeRequest();
}
};
constructors[COLLECTION_CONTAINS] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new CollectionContainsRequest();
}
};
constructors[COLLECTION_ADD] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new CollectionAddRequest();
}
};
constructors[COLLECTION_REMOVE] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new CollectionRemoveRequest();
}
};
constructors[COLLECTION_ADD_ALL] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new CollectionAddAllRequest();
}
};
constructors[COLLECTION_COMPARE_AND_REMOVE] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new CollectionCompareAndRemoveRequest();
}
};
constructors[COLLECTION_CLEAR] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new CollectionClearRequest();
}
};
constructors[COLLECTION_GET_ALL] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new CollectionGetAllRequest();
}
};
constructors[COLLECTION_ADD_LISTENER] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new CollectionAddListenerRequest();
}
};
constructors[LIST_ADD_ALL] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new ListAddAllRequest();
}
};
constructors[LIST_GET] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new ListGetRequest();
}
};
constructors[LIST_SET] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new ListSetRequest();
}
};
constructors[LIST_ADD] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new ListAddRequest();
}
};
constructors[LIST_REMOVE] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new ListRemoveRequest();
}
};
constructors[LIST_INDEX_OF] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new ListIndexOfRequest();
}
};
constructors[LIST_SUB] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new ListSubRequest();
}
};
constructors[TXN_LIST_ADD] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new TxnListAddRequest();
}
};
constructors[TXN_LIST_REMOVE] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new TxnListRemoveRequest();
}
};
constructors[TXN_LIST_SIZE] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new TxnListSizeRequest();
}
};
constructors[TXN_SET_ADD] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new TxnSetAddRequest();
}
};
constructors[TXN_SET_REMOVE] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new TxnSetRemoveRequest();
}
};
constructors[TXN_SET_SIZE] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new TxnSetSizeRequest();
}
};
constructors[COLLECTION_REMOVE_LISTENER] = new ConstructorFunction<Integer, Portable>() {
public Portable createNew(Integer arg) {
return new CollectionRemoveListenerRequest();
}
};
return new ArrayPortableFactory(constructors);
}
@Override
public Collection<ClassDefinition> getBuiltinDefinitions() {
return null;
}
}
| 0true
|
hazelcast_src_main_java_com_hazelcast_collection_CollectionPortableHook.java
|
359 |
public class Filter {
String name;
String condition;
String entityImplementationClassName;
List<String> indexColumnNames;
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEntityImplementationClassName() {
return entityImplementationClassName;
}
public void setEntityImplementationClassName(String entityImplementationClassName) {
this.entityImplementationClassName = entityImplementationClassName;
}
public List<String> getIndexColumnNames() {
return indexColumnNames;
}
public void setIndexColumnNames(List<String> indexColumnNames) {
this.indexColumnNames = indexColumnNames;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_filter_Filter.java
|
3,241 |
class PerSegmentComparator extends NestedWrappableComparator<BytesRef> {
final Ordinals.Docs readerOrds;
final BytesValues.WithOrdinals termsIndex;
public PerSegmentComparator(BytesValues.WithOrdinals termsIndex) {
this.readerOrds = termsIndex.ordinals();
this.termsIndex = termsIndex;
if (readerOrds.getNumOrds() > Long.MAX_VALUE / 4) {
throw new IllegalStateException("Current terms index pretends it has more than " + (Long.MAX_VALUE / 4) + " ordinals, which is unsupported by this impl");
}
}
@Override
public FieldComparator<BytesRef> setNextReader(AtomicReaderContext context) throws IOException {
return BytesRefOrdValComparator.this.setNextReader(context);
}
@Override
public int compare(int slot1, int slot2) {
return BytesRefOrdValComparator.this.compare(slot1, slot2);
}
@Override
public void setBottom(final int bottom) {
BytesRefOrdValComparator.this.setBottom(bottom);
}
@Override
public BytesRef value(int slot) {
return BytesRefOrdValComparator.this.value(slot);
}
@Override
public int compareValues(BytesRef val1, BytesRef val2) {
if (val1 == null) {
if (val2 == null) {
return 0;
}
return -1;
} else if (val2 == null) {
return 1;
}
return val1.compareTo(val2);
}
@Override
public int compareDocToValue(int doc, BytesRef value) {
final long ord = getOrd(doc);
final BytesRef docValue = ord == Ordinals.MISSING_ORDINAL ? missingValue : termsIndex.getValueByOrd(ord);
return compareValues(docValue, value);
}
protected long getOrd(int doc) {
return readerOrds.getOrd(doc);
}
@Override
public int compareBottom(int doc) {
assert bottomSlot != -1;
final long docOrd = getOrd(doc);
final long comparableOrd = docOrd == Ordinals.MISSING_ORDINAL ? missingOrd : docOrd << 2;
return LongValuesComparator.compare(bottomOrd, comparableOrd);
}
@Override
public int compareBottomMissing() {
assert bottomSlot != -1;
return LongValuesComparator.compare(bottomOrd, missingOrd);
}
@Override
public void copy(int slot, int doc) {
final long ord = getOrd(doc);
if (ord == Ordinals.MISSING_ORDINAL) {
ords[slot] = missingOrd;
values[slot] = missingValue;
} else {
assert ord > 0;
ords[slot] = ord << 2;
if (values[slot] == null || values[slot] == missingValue) {
values[slot] = new BytesRef();
}
values[slot].copyBytes(termsIndex.getValueByOrd(ord));
}
readerGen[slot] = currentReaderGen;
}
@Override
public void missing(int slot) {
ords[slot] = missingOrd;
values[slot] = missingValue;
}
}
| 1no label
|
src_main_java_org_elasticsearch_index_fielddata_fieldcomparator_BytesRefOrdValComparator.java
|
73 |
public abstract class OSharedResourceAbstract {
protected final ReadWriteLock lock = new ReentrantReadWriteLock();
protected void acquireSharedLock() {
lock.readLock().lock();
}
protected void releaseSharedLock() {
lock.readLock().unlock();
}
protected void acquireExclusiveLock() {
lock.writeLock().lock();
}
protected void releaseExclusiveLock() {
lock.writeLock().unlock();
}
}
| 0true
|
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResourceAbstract.java
|
953 |
clusterService.add(request.masterNodeTimeout(), new TimeoutClusterStateListener() {
@Override
public void postAdded() {
ClusterState clusterStateV2 = clusterService.state();
if (!clusterState.nodes().masterNodeId().equals(clusterStateV2.nodes().masterNodeId())) {
// master changes while adding the listener, try here
clusterService.remove(this);
innerExecute(request, listener, false);
}
}
@Override
public void onClose() {
clusterService.remove(this);
listener.onFailure(new NodeClosedException(clusterService.localNode()));
}
@Override
public void onTimeout(TimeValue timeout) {
clusterService.remove(this);
listener.onFailure(new MasterNotDiscoveredException());
}
@Override
public void clusterChanged(ClusterChangedEvent event) {
if (event.nodesDelta().masterNodeChanged()) {
clusterService.remove(this);
innerExecute(request, listener, false);
}
}
});
| 1no label
|
src_main_java_org_elasticsearch_action_support_master_TransportMasterNodeOperationAction.java
|
3,411 |
public class NodeEngineImpl
implements NodeEngine {
private final Node node;
private final ILogger logger;
private final ServiceManager serviceManager;
private final TransactionManagerServiceImpl transactionManagerService;
private final ProxyServiceImpl proxyService;
private final WanReplicationService wanReplicationService;
final InternalOperationService operationService;
final ExecutionServiceImpl executionService;
final EventServiceImpl eventService;
final WaitNotifyServiceImpl waitNotifyService;
public NodeEngineImpl(Node node) {
this.node = node;
logger = node.getLogger(NodeEngine.class.getName());
proxyService = new ProxyServiceImpl(this);
serviceManager = new ServiceManager(this);
executionService = new ExecutionServiceImpl(this);
operationService = new BasicOperationService(this);
eventService = new EventServiceImpl(this);
waitNotifyService = new WaitNotifyServiceImpl(this);
transactionManagerService = new TransactionManagerServiceImpl(this);
wanReplicationService = node.initializer.geWanReplicationService();
}
@PrivateApi
public void start() {
serviceManager.start();
proxyService.init();
}
@Override
public Address getThisAddress() {
return node.getThisAddress();
}
@Override
public Address getMasterAddress() {
return node.getMasterAddress();
}
@Override
public MemberImpl getLocalMember() {
return node.getLocalMember();
}
@Override
public Config getConfig() {
return node.getConfig();
}
@Override
public ClassLoader getConfigClassLoader() {
return node.getConfigClassLoader();
}
@Override
public EventService getEventService() {
return eventService;
}
@Override
public SerializationService getSerializationService() {
return node.getSerializationService();
}
public SerializationContext getSerializationContext() {
return node.getSerializationService().getSerializationContext();
}
@Override
public OperationService getOperationService() {
return operationService;
}
@Override
public ExecutionService getExecutionService() {
return executionService;
}
@Override
public InternalPartitionService getPartitionService() {
return node.getPartitionService();
}
@Override
public ClusterService getClusterService() {
return node.getClusterService();
}
public ManagementCenterService getManagementCenterService() {
return node.getManagementCenterService();
}
@Override
public ProxyService getProxyService() {
return proxyService;
}
@Override
public WaitNotifyService getWaitNotifyService() {
return waitNotifyService;
}
@Override
public WanReplicationService getWanReplicationService() {
return wanReplicationService;
}
@Override
public TransactionManagerService getTransactionManagerService() {
return transactionManagerService;
}
@Override
public Data toData(final Object object) {
return node.getSerializationService().toData(object);
}
@Override
public Object toObject(final Object object) {
if (object instanceof Data) {
return node.getSerializationService().toObject((Data) object);
}
return object;
}
@Override
public boolean isActive() {
return node.isActive();
}
@Override
public HazelcastInstance getHazelcastInstance() {
return node.hazelcastInstance;
}
public boolean send(Packet packet, Connection connection) {
if (connection == null || !connection.live()) {
return false;
}
final MemberImpl memberImpl = node.getClusterService().getMember(connection.getEndPoint());
if (memberImpl != null) {
memberImpl.didWrite();
}
return connection.write(packet);
}
/**
* Retries sending packet maximum 5 times until connection to target becomes available.
*/
public boolean send(Packet packet, Address target) {
return send(packet, target, null);
}
private boolean send(Packet packet, Address target, FutureSend futureSend) {
final ConnectionManager connectionManager = node.getConnectionManager();
final Connection connection = connectionManager.getConnection(target);
if (connection != null) {
return send(packet, connection);
} else {
if (futureSend == null) {
futureSend = new FutureSend(packet, target);
}
final int retries = futureSend.retries;
if (retries < 5 && node.isActive()) {
connectionManager.getOrConnect(target, true);
// TODO: Caution: may break the order guarantee of the packets sent from the same thread!
executionService.schedule(futureSend, (retries + 1) * 100, TimeUnit.MILLISECONDS);
return true;
}
return false;
}
}
private class FutureSend
implements Runnable {
private final Packet packet;
private final Address target;
private volatile int retries;
private FutureSend(Packet packet, Address target) {
this.packet = packet;
this.target = target;
}
//retries is incremented by a single thread, but will be read by multiple. So there is no problem.
@edu.umd.cs.findbugs.annotations.SuppressWarnings("VO_VOLATILE_INCREMENT")
@Override
public void run() {
retries++;
if (logger.isFinestEnabled()) {
logger.finest("Retrying[" + retries + "] packet send operation to: " + target);
}
send(packet, target, this);
}
}
@Override
public ILogger getLogger(String name) {
return node.getLogger(name);
}
@Override
public ILogger getLogger(Class clazz) {
return node.getLogger(clazz);
}
@Override
public GroupProperties getGroupProperties() {
return node.getGroupProperties();
}
@PrivateApi
public void handlePacket(Packet packet) {
if (packet.isHeaderSet(Packet.HEADER_OP)) {
operationService.receive(packet);
} else if (packet.isHeaderSet(Packet.HEADER_EVENT)) {
eventService.handleEvent(packet);
} else if (packet.isHeaderSet(Packet.HEADER_WAN_REPLICATION)) {
wanReplicationService.handleEvent(packet);
} else {
logger.severe("Unknown packet type! Header: " + packet.getHeader());
}
}
@PrivateApi
public <T> T getService(String serviceName) {
final ServiceInfo serviceInfo = serviceManager.getServiceInfo(serviceName);
return serviceInfo != null ? (T) serviceInfo.getService() : null;
}
public <T extends SharedService> T getSharedService(String serviceName) {
final Object service = getService(serviceName);
if (service == null) {
return null;
}
if (service instanceof SharedService) {
return (T) service;
}
throw new IllegalArgumentException("No SharedService registered with name: " + serviceName);
}
/**
* Returns a list of services matching provides service class/interface.
* <br></br>
* <b>CoreServices will be placed at the beginning of the list.</b>
*/
@PrivateApi
public <S> Collection<S> getServices(Class<S> serviceClass) {
return serviceManager.getServices(serviceClass);
}
@PrivateApi
public Collection<ServiceInfo> getServiceInfos(Class serviceClass) {
return serviceManager.getServiceInfos(serviceClass);
}
@PrivateApi
public Node getNode() {
return node;
}
@PrivateApi
public void onMemberLeft(MemberImpl member) {
waitNotifyService.onMemberLeft(member);
operationService.onMemberLeft(member);
eventService.onMemberLeft(member);
}
@PrivateApi
public void onClientDisconnected(String clientUuid) {
waitNotifyService.onClientDisconnected(clientUuid);
}
@PrivateApi
public void onPartitionMigrate(MigrationInfo migrationInfo) {
waitNotifyService.onPartitionMigrate(getThisAddress(), migrationInfo);
}
/**
* Post join operations must be lock free; means no locks at all;
* no partition locks, no key-based locks, no service level locks!
* <p/>
* Post join operations should return response, at least a null response.
* <p/>
*/
@PrivateApi
public Operation[] getPostJoinOperations() {
final Collection<Operation> postJoinOps = new LinkedList<Operation>();
Operation eventPostJoinOp = eventService.getPostJoinOperation();
if (eventPostJoinOp != null) {
postJoinOps.add(eventPostJoinOp);
}
Collection<PostJoinAwareService> services = getServices(PostJoinAwareService.class);
for (PostJoinAwareService service : services) {
final Operation pjOp = service.getPostJoinOperation();
if (pjOp != null) {
if (pjOp instanceof PartitionAwareOperation) {
logger.severe(
"Post-join operations cannot implement PartitionAwareOperation! Service: " + service + ", Operation: "
+ pjOp);
continue;
}
postJoinOps.add(pjOp);
}
}
return postJoinOps.isEmpty() ? null : postJoinOps.toArray(new Operation[postJoinOps.size()]);
}
public long getClusterTime() {
return node.getClusterService().getClusterTime();
}
@Override
public Storage<DataRef> getOffHeapStorage() {
return node.initializer.getOffHeapStorage();
}
@PrivateApi
public void shutdown(final boolean terminate) {
logger.finest("Shutting down services...");
waitNotifyService.shutdown();
proxyService.shutdown();
serviceManager.shutdown(terminate);
executionService.shutdown();
eventService.shutdown();
operationService.shutdown();
wanReplicationService.shutdown();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_spi_impl_NodeEngineImpl.java
|
145 |
final class HazelcastClientManagedContext implements ManagedContext {
private final HazelcastInstance instance;
private final ManagedContext externalContext;
private final boolean hasExternalContext;
public HazelcastClientManagedContext(final HazelcastInstance instance, final ManagedContext externalContext) {
this.instance = instance;
this.externalContext = externalContext;
this.hasExternalContext = externalContext != null;
}
@Override
public Object initialize(Object obj) {
if (obj instanceof HazelcastInstanceAware) {
((HazelcastInstanceAware) obj).setHazelcastInstance(instance);
}
if (hasExternalContext) {
obj = externalContext.initialize(obj);
}
return obj;
}
}
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_HazelcastClientManagedContext.java
|
204 |
public abstract class AbstractHydratedCacheManager implements CacheEventListener, HydratedCacheManager, HydratedAnnotationManager {
private static final Log LOG = LogFactory.getLog(AbstractHydratedCacheManager.class);
private Map<String, HydrationDescriptor> hydrationDescriptors = Collections.synchronizedMap(new HashMap(100));
@Override
public HydrationDescriptor getHydrationDescriptor(Object entity) {
if (hydrationDescriptors.containsKey(entity.getClass().getName())) {
return hydrationDescriptors.get(entity.getClass().getName());
}
HydrationDescriptor descriptor = new HydrationDescriptor();
Class<?> topEntityClass = getTopEntityClass(entity);
HydrationScanner scanner = new HydrationScanner(topEntityClass, entity.getClass());
scanner.init();
descriptor.setHydratedMutators(scanner.getCacheMutators());
Map<String, Method[]> mutators = scanner.getIdMutators();
if (mutators.size() != 1) {
throw new RuntimeException("Broadleaf Commerce Hydrated Cache currently only supports entities with a single @Id annotation.");
}
Method[] singleMutators = mutators.values().iterator().next();
descriptor.setIdMutators(singleMutators);
String cacheRegion = scanner.getCacheRegion();
if (cacheRegion == null || "".equals(cacheRegion)) {
cacheRegion = topEntityClass.getName();
}
descriptor.setCacheRegion(cacheRegion);
hydrationDescriptors.put(entity.getClass().getName(), descriptor);
return descriptor;
}
protected Class<?> getTopEntityClass(Object entity) {
Class<?> myClass = entity.getClass();
Class<?> superClass = entity.getClass().getSuperclass();
while (superClass != null && superClass.getName().startsWith("org.broadleaf")) {
myClass = superClass;
superClass = superClass.getSuperclass();
}
return myClass;
}
@Override
public void dispose() {
if (LOG.isInfoEnabled()) {
LOG.info("Disposing of all hydrated cache members");
}
hydrationDescriptors.clear();
}
@Override
public Object clone() throws CloneNotSupportedException {
return this;
}
}
| 0true
|
common_src_main_java_org_broadleafcommerce_common_cache_engine_AbstractHydratedCacheManager.java
|
238 |
XPostingsHighlighter highlighter = new XPostingsHighlighter() {
Iterator<String> valuesIterator = Arrays.asList(firstValue, secondValue, thirdValue).iterator();
Iterator<Integer> offsetsIterator = Arrays.asList(0, firstValue.length() + 1, secondValue.length() + 1).iterator();
@Override
protected String[][] loadFieldValues(IndexSearcher searcher, String[] fields, int[] docids, int maxLength) throws IOException {
return new String[][]{new String[]{valuesIterator.next()}};
}
@Override
protected int getOffsetForCurrentValue(String field, int docId) {
return offsetsIterator.next();
}
@Override
protected BreakIterator getBreakIterator(String field) {
return new WholeBreakIterator();
}
@Override
protected Passage[] getEmptyHighlight(String fieldName, BreakIterator bi, int maxPassages) {
return new Passage[0];
}
};
| 0true
|
src_test_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighterTests.java
|
471 |
public interface ClientExecutionService {
void executeInternal(Runnable command);
<T> ICompletableFuture<T> submitInternal(Callable<T> command);
void execute(Runnable command);
ICompletableFuture<?> submit(Runnable task);
<T> ICompletableFuture<T> submit(Callable<T> task);
ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);
ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long period, TimeUnit unit);
ExecutorService getAsyncExecutor();
}
| 0true
|
hazelcast-client_src_main_java_com_hazelcast_client_spi_ClientExecutionService.java
|
41 |
static class BaseIterator<K,V> extends Traverser<K,V> {
final ConcurrentHashMapV8<K,V> map;
Node<K,V> lastReturned;
BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
ConcurrentHashMapV8<K,V> map) {
super(tab, size, index, limit);
this.map = map;
advance();
}
public final boolean hasNext() { return next != null; }
public final boolean hasMoreElements() { return next != null; }
public final void remove() {
Node<K,V> p;
if ((p = lastReturned) == null)
throw new IllegalStateException();
lastReturned = null;
map.replaceNode(p.key, null, null);
}
}
| 0true
|
src_main_java_jsr166e_ConcurrentHashMapV8.java
|
619 |
public class NodeMulticastListener implements MulticastListener {
final Node node;
final Set<String> trustedInterfaces;
final ILogger logger;
public NodeMulticastListener(Node node) {
this.node = node;
this.trustedInterfaces = node.getConfig().getNetworkConfig()
.getJoin().getMulticastConfig().getTrustedInterfaces();
this.logger = node.getLogger("NodeMulticastListener");
}
@Override
public void onMessage(Object msg) {
if (!isValidJoinMessage(msg)) {
logDroppedMessage(msg);
return;
}
JoinMessage joinMessage = (JoinMessage) msg;
if (node.isActive() && node.joined()) {
handleActiveAndJoined(joinMessage);
} else {
handleNotActiveOrNotJoined(joinMessage);
}
}
private void logDroppedMessage(Object msg) {
if (logger.isFinestEnabled()) {
logger.info("Dropped: " + msg);
}
}
private void handleActiveAndJoined(JoinMessage joinMessage) {
if (!isJoinRequest(joinMessage)) {
logDroppedMessage(joinMessage);
return;
}
if (node.isMaster()) {
JoinRequest request = (JoinRequest) joinMessage;
JoinMessage response = new JoinMessage(request.getPacketVersion(), request.getBuildNumber(),
node.getThisAddress(), request.getUuid(), request.getConfigCheck(),
node.getClusterService().getSize());
node.multicastService.send(response);
} else if (isMasterNode(joinMessage.getAddress()) && !checkMasterUuid(joinMessage.getUuid())) {
logger.warning("New join request has been received from current master. "
+ "Removing " + node.getMasterAddress());
node.getClusterService().removeAddress(node.getMasterAddress());
}
}
private void handleNotActiveOrNotJoined(JoinMessage joinMessage) {
if (isJoinRequest(joinMessage)) {
Joiner joiner = node.getJoiner();
if (joiner instanceof MulticastJoiner) {
MulticastJoiner multicastJoiner = (MulticastJoiner) joiner;
multicastJoiner.onReceivedJoinRequest((JoinRequest) joinMessage);
} else {
logDroppedMessage(joinMessage);
}
} else {
if (!node.joined() && node.getMasterAddress() == null) {
String masterHost = joinMessage.getAddress().getHost();
if (trustedInterfaces.isEmpty() || matchAnyInterface(masterHost, trustedInterfaces)) {
//todo: why are we making a copy here of address?
Address masterAddress = new Address(joinMessage.getAddress());
node.setMasterAddress(masterAddress);
} else {
logJoinMessageDropped(masterHost);
}
} else {
logDroppedMessage(joinMessage);
}
}
}
private boolean isJoinRequest(JoinMessage joinMessage) {
return joinMessage instanceof JoinRequest;
}
private void logJoinMessageDropped(String masterHost) {
if (logger.isFinestEnabled()) {
logger.finest(format(
"JoinMessage from %s is dropped because its sender is not a trusted interface", masterHost));
}
}
private boolean isJoinMessage(Object msg) {
return msg != null && msg instanceof JoinMessage;
}
private boolean isValidJoinMessage(Object msg) {
if (!isJoinMessage(msg)) {
return false;
}
JoinMessage joinMessage = (JoinMessage) msg;
if (isMessageToSelf(joinMessage)) {
return false;
}
try {
return node.getClusterService().validateJoinMessage(joinMessage);
} catch (Exception e) {
return false;
}
}
private boolean isMessageToSelf(JoinMessage joinMessage) {
Address thisAddress = node.getThisAddress();
return thisAddress == null || thisAddress.equals(joinMessage.getAddress());
}
private boolean isMasterNode(Address address) {
return address.equals(node.getMasterAddress());
}
private boolean checkMasterUuid(String uuid) {
Member masterMember = getMasterMember(node.getClusterService().getMembers());
return masterMember == null || masterMember.getUuid().equals(uuid);
}
private Member getMasterMember(Set<Member> members) {
if (members.isEmpty()) {
return null;
}
return members.iterator().next();
}
}
| 1no label
|
hazelcast_src_main_java_com_hazelcast_cluster_NodeMulticastListener.java
|
116 |
public class TestJtaCompliance extends AbstractNeo4jTestCase
{
public class SimpleTxHook implements Synchronization
{
private volatile boolean gotBefore, gotAfter;
@Override
public void beforeCompletion()
{
gotBefore = true;
}
@Override
public void afterCompletion( int status )
{
gotAfter = true;
}
}
// the TransactionManager to use when testing for JTA compliance
private TransactionManager tm;
private XaDataSourceManager xaDsMgr;
private KernelHealth kernelHealth;
@Before
public void setUpFramework()
{
getTransaction().finish();
tm = getGraphDbAPI().getDependencyResolver().resolveDependency( TransactionManager.class );
kernelHealth = getGraphDbAPI().getDependencyResolver().resolveDependency( KernelHealth.class );
xaDsMgr = getGraphDbAPI().getDependencyResolver().resolveDependency( XaDataSourceManager.class );
java.util.Map<String,String> map1 = new java.util.HashMap<String,String>();
map1.put( "store_dir", "target/var" );
java.util.Map<String,String> map2 = new java.util.HashMap<>();
map2.put( "store_dir", "target/var" );
try
{
xaDsMgr.registerDataSource( new OtherDummyXaDataSource( "fakeRes1", UTF8.encode( "0xDDDDDE" ), new FakeXAResource( "XAResource1" ) ));
xaDsMgr.registerDataSource( new OtherDummyXaDataSource( "fakeRes2", UTF8.encode( "0xDDDDDF" ), new FakeXAResource( "XAResource2" ) ));
}
catch ( Exception e )
{
e.printStackTrace();
}
try
{
// make sure were not in transaction
tm.commit();
}
catch ( Exception e )
{
}
Transaction tx = null;
try
{
tx = tm.getTransaction();
}
catch ( Exception e )
{
throw new RuntimeException( "Unknown state of TM" );
}
if ( tx != null )
{
throw new RuntimeException( "We're still in transaction" );
}
}
@After
public void tearDownFramework()
{
xaDsMgr.unregisterDataSource( "fakeRes1" );
xaDsMgr.unregisterDataSource( "fakeRes2" );
try
{
if ( tm.getTransaction() == null )
{
try
{
tm.begin();
}
catch ( Exception e )
{
}
}
}
catch ( SystemException e )
{
e.printStackTrace();
}
}
/**
* o Tests that tm.begin() starts a global transaction and associates the
* calling thread with that transaction. o Tests that after commit is
* invoked transaction is completed and a repeating call to commit/rollback
* results in an exception.
*
* TODO: check if commit is restricted to the thread that started the
* transaction, if not, do some testing.
*/
@Test
public void testBeginCommit() throws Exception
{
tm.begin();
assertTrue( tm.getTransaction() != null );
tm.commit(); // drop current transaction
assertEquals( Status.STATUS_NO_TRANSACTION, tm.getStatus() );
try
{
tm.rollback();
fail( "rollback() should throw an exception -> "
+ "STATUS_NO_TRANSACTION" );
}
catch ( IllegalStateException e )
{
// good
}
try
{
tm.commit();
fail( "commit() should throw an exception -> "
+ "STATUS_NO_TRANSACTION" );
}
catch ( IllegalStateException e )
{
// good
}
}
/**
* o Tests that after rollback is invoked the transaction is completed and a
* repeating call to rollback/commit results in an exception.
*
* TODO: check if rollback is restricted to the thread that started the
* transaction, if not, do some testing.
*/
@Test
public void testBeginRollback() throws Exception
{
tm.begin();
assertTrue( tm.getTransaction() != null );
tm.rollback(); // drop current transaction
assertTrue( tm.getStatus() == Status.STATUS_NO_TRANSACTION );
try
{
tm.commit();
fail( "commit() should throw an exception -> "
+ "STATUS_NO_TRANSACTION" );
}
catch ( IllegalStateException e )
{
// good
}
try
{
tm.rollback();
fail( "rollback() should throw an exception -> "
+ "STATUS_NO_TRANSACTION" );
}
catch ( IllegalStateException e )
{
// good
}
}
/**
* o Tests that suspend temporarily suspends the transaction associated with
* the calling thread. o Tests that resume reinstate the transaction with
* the calling thread. o Tests that an invalid transaction passed to resume
* won't be associated with the calling thread. o Tests that XAResource.end
* is invoked with TMSUSPEND when transaction is suspended. o Tests that
* XAResource.start is invoked with TMRESUME when transaction is resumed.
*
* TODO: o Test that resume throws an exception if the transaction is
* already associated with another thread. o Test if a suspended thread may
* be resumed by another thread.
*/
@Test
public void testSuspendResume() throws Exception
{
tm.begin();
Transaction tx = tm.getTransaction();
FakeXAResource res = new FakeXAResource( "XAResource1" );
tx.enlistResource( res );
// suspend
assertTrue( tm.suspend() == tx );
tx.delistResource( res, XAResource.TMSUSPEND );
MethodCall calls[] = res.getAndRemoveMethodCalls();
assertEquals( 2, calls.length );
assertEquals( "start", calls[0].getMethodName() );
Object args[] = calls[0].getArgs();
assertEquals( XAResource.TMNOFLAGS, ((Integer) args[1]).intValue() );
assertEquals( "end", calls[1].getMethodName() );
args = calls[1].getArgs();
assertEquals( XAResource.TMSUSPEND, ((Integer) args[1]).intValue() );
// resume
tm.resume( tx );
tx.enlistResource( res );
calls = res.getAndRemoveMethodCalls();
assertEquals( 1, calls.length );
assertEquals( "start", calls[0].getMethodName() );
args = calls[0].getArgs();
assertEquals( XAResource.TMRESUME, ((Integer) args[1]).intValue() );
assertTrue( tm.getTransaction() == tx );
tx.delistResource( res, XAResource.TMSUCCESS );
tm.commit();
tm.resume( tx );
assertTrue( tm.getStatus() == Status.STATUS_NO_TRANSACTION );
assertTrue( tm.getTransaction() == null );
// tm.resume( my fake implementation of transaction );
// assertTrue( tm.getStatus() == Status.STATUS_NO_TRANSACTION );
// assertTrue( tm.getTransaction() == null );
}
/**
* o Tests two-phase commits with two different fake XAResource
* implementations so a branch is created within the same global
* transaction.
*/
@Test
public void test2PhaseCommits1() throws Exception
{
tm.begin();
FakeXAResource res1 = new FakeXAResource( "XAResource1" );
FakeXAResource res2 = new FakeXAResource( "XAResource2" );
// enlist two different resources and verify that the start method
// is invoked with correct flags
// res1
tm.getTransaction().enlistResource( res1 );
MethodCall calls1[] = res1.getAndRemoveMethodCalls();
assertEquals( 1, calls1.length );
assertEquals( "start", calls1[0].getMethodName() );
// res2
tm.getTransaction().enlistResource( res2 );
MethodCall calls2[] = res2.getAndRemoveMethodCalls();
assertEquals( 1, calls2.length );
assertEquals( "start", calls2[0].getMethodName() );
// verify Xid
Object args[] = calls1[0].getArgs();
Xid xid1 = (Xid) args[0];
assertEquals( XAResource.TMNOFLAGS, ((Integer) args[1]).intValue() );
args = calls2[0].getArgs();
Xid xid2 = (Xid) args[0];
assertEquals( XAResource.TMNOFLAGS, ((Integer) args[1]).intValue() );
// should have same global transaction id
byte globalTxId1[] = xid1.getGlobalTransactionId();
byte globalTxId2[] = xid2.getGlobalTransactionId();
assertTrue( globalTxId1.length == globalTxId2.length );
for ( int i = 0; i < globalTxId1.length; i++ )
{
assertEquals( globalTxId1[i], globalTxId2[i] );
}
byte branch1[] = xid1.getBranchQualifier();
byte branch2[] = xid2.getBranchQualifier();
// make sure a different branch was created
if ( branch1.length == branch2.length )
{
boolean same = true;
for ( int i = 0; i < branch1.length; i++ )
{
if ( branch1[i] != branch2[i] )
{
same = false;
break;
}
}
assertTrue( !same );
}
// verify delist of resource
tm.getTransaction().delistResource( res2, XAResource.TMSUCCESS );
calls2 = res2.getAndRemoveMethodCalls();
assertEquals( 1, calls2.length );
tm.getTransaction().delistResource( res1, XAResource.TMSUCCESS );
calls1 = res1.getAndRemoveMethodCalls();
// res1
assertEquals( 1, calls1.length );
assertEquals( "end", calls1[0].getMethodName() );
args = calls1[0].getArgs();
assertTrue( ((Xid) args[0]).equals( xid1 ) );
assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() );
// res2
assertEquals( 1, calls2.length );
assertEquals( "end", calls2[0].getMethodName() );
args = calls2[0].getArgs();
assertTrue( ((Xid) args[0]).equals( xid2 ) );
assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() );
// verify proper prepare/commit
tm.commit();
calls1 = res1.getAndRemoveMethodCalls();
calls2 = res2.getAndRemoveMethodCalls();
// res1
assertEquals( 2, calls1.length );
assertEquals( "prepare", calls1[0].getMethodName() );
args = calls1[0].getArgs();
assertTrue( ((Xid) args[0]).equals( xid1 ) );
assertEquals( "commit", calls1[1].getMethodName() );
args = calls1[1].getArgs();
assertTrue( ((Xid) args[0]).equals( xid1 ) );
assertEquals( false, ((Boolean) args[1]).booleanValue() );
// res2
assertEquals( 2, calls2.length );
assertEquals( "prepare", calls2[0].getMethodName() );
args = calls2[0].getArgs();
assertTrue( ((Xid) args[0]).equals( xid2 ) );
assertEquals( "commit", calls2[1].getMethodName() );
args = calls2[1].getArgs();
assertTrue( ((Xid) args[0]).equals( xid2 ) );
assertEquals( false, ((Boolean) args[1]).booleanValue() );
}
/**
* o Tests that two enlistments of same resource (according to the
* isSameRM() method) only receive one set of prepare/commit calls.
*/
@Test
public void test2PhaseCommits2() throws Exception
{
tm.begin();
FakeXAResource res1 = new FakeXAResource( "XAResource1" );
FakeXAResource res2 = new FakeXAResource( "XAResource1" );
// enlist two (same) resources and verify that the start method
// is invoked with correct flags
// res1
tm.getTransaction().enlistResource( res1 );
MethodCall calls1[] = res1.getAndRemoveMethodCalls();
assertEquals( 1, calls1.length );
assertEquals( "start", calls1[0].getMethodName() );
// res2
tm.getTransaction().enlistResource( res2 );
MethodCall calls2[] = res2.getAndRemoveMethodCalls();
assertEquals( 1, calls2.length );
assertEquals( "start", calls2[0].getMethodName() );
// make sure we get a two-phase commit
FakeXAResource res3 = new FakeXAResource( "XAResource2" );
tm.getTransaction().enlistResource( res3 );
// verify Xid and flags
Object args[] = calls1[0].getArgs();
Xid xid1 = (Xid) args[0];
assertEquals( XAResource.TMNOFLAGS, ((Integer) args[1]).intValue() );
args = calls2[0].getArgs();
Xid xid2 = (Xid) args[0];
assertEquals( XAResource.TMJOIN, ((Integer) args[1]).intValue() );
assertTrue( xid1.equals( xid2 ) );
assertTrue( xid2.equals( xid1 ) );
// verify delist of resource
tm.getTransaction().delistResource( res3, XAResource.TMSUCCESS );
tm.getTransaction().delistResource( res2, XAResource.TMSUCCESS );
calls2 = res2.getAndRemoveMethodCalls();
assertEquals( 1, calls2.length );
tm.getTransaction().delistResource( res1, XAResource.TMSUCCESS );
calls1 = res1.getAndRemoveMethodCalls();
// res1
assertEquals( 1, calls1.length );
assertEquals( "end", calls1[0].getMethodName() );
args = calls1[0].getArgs();
assertTrue( ((Xid) args[0]).equals( xid1 ) );
assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() );
// res2
assertEquals( 1, calls2.length );
assertEquals( "end", calls2[0].getMethodName() );
args = calls2[0].getArgs();
assertTrue( ((Xid) args[0]).equals( xid2 ) );
assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() );
// verify proper prepare/commit
tm.commit();
calls1 = res1.getAndRemoveMethodCalls();
calls2 = res2.getAndRemoveMethodCalls();
// res1
assertEquals( 2, calls1.length );
assertEquals( "prepare", calls1[0].getMethodName() );
args = calls1[0].getArgs();
assertTrue( args[0].equals( xid1 ) );
assertEquals( "commit", calls1[1].getMethodName() );
args = calls1[1].getArgs();
assertTrue( args[0].equals( xid1 ) );
assertEquals( false, ((Boolean) args[1]).booleanValue() );
// res2
assertEquals( 0, calls2.length );
}
/**
* o Tests that multiple enlistments receive rollback calls properly.
*/
@Test
public void testRollback1() throws Exception
{
tm.begin();
FakeXAResource res1 = new FakeXAResource( "XAResource1" );
FakeXAResource res2 = new FakeXAResource( "XAResource2" );
// enlist two different resources and verify that the start method
// is invoked with correct flags
// res1
tm.getTransaction().enlistResource( res1 );
MethodCall calls1[] = res1.getAndRemoveMethodCalls();
assertEquals( 1, calls1.length );
assertEquals( "start", calls1[0].getMethodName() );
// res2
tm.getTransaction().enlistResource( res2 );
MethodCall calls2[] = res2.getAndRemoveMethodCalls();
assertEquals( 1, calls2.length );
assertEquals( "start", calls2[0].getMethodName() );
// verify Xid
Object args[] = calls1[0].getArgs();
Xid xid1 = (Xid) args[0];
assertEquals( XAResource.TMNOFLAGS, ((Integer) args[1]).intValue() );
args = calls2[0].getArgs();
Xid xid2 = (Xid) args[0];
assertEquals( XAResource.TMNOFLAGS, ((Integer) args[1]).intValue() );
// should have same global transaction id
byte globalTxId1[] = xid1.getGlobalTransactionId();
byte globalTxId2[] = xid2.getGlobalTransactionId();
assertTrue( globalTxId1.length == globalTxId2.length );
for ( int i = 0; i < globalTxId1.length; i++ )
{
assertEquals( globalTxId1[i], globalTxId2[i] );
}
byte branch1[] = xid1.getBranchQualifier();
byte branch2[] = xid2.getBranchQualifier();
// make sure a different branch was created
if ( branch1.length == branch2.length )
{
boolean same = true;
for ( int i = 0; i < branch1.length; i++ )
{
if ( branch1[i] != branch2[i] )
{
same = false;
break;
}
}
assertTrue( !same );
}
// verify delist of resource
tm.getTransaction().delistResource( res2, XAResource.TMSUCCESS );
calls2 = res2.getAndRemoveMethodCalls();
assertEquals( 1, calls2.length );
tm.getTransaction().delistResource( res1, XAResource.TMSUCCESS );
calls1 = res1.getAndRemoveMethodCalls();
// res1
assertEquals( 1, calls1.length );
assertEquals( "end", calls1[0].getMethodName() );
args = calls1[0].getArgs();
assertTrue( ((Xid) args[0]).equals( xid1 ) );
assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() );
// res2
assertEquals( 1, calls2.length );
assertEquals( "end", calls2[0].getMethodName() );
args = calls2[0].getArgs();
assertTrue( ((Xid) args[0]).equals( xid2 ) );
assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() );
// verify proper rollback
tm.rollback();
calls1 = res1.getAndRemoveMethodCalls();
calls2 = res2.getAndRemoveMethodCalls();
// res1
assertEquals( 1, calls1.length );
assertEquals( "rollback", calls1[0].getMethodName() );
args = calls1[0].getArgs();
assertTrue( ((Xid) args[0]).equals( xid1 ) );
// res2
assertEquals( 1, calls2.length );
assertEquals( "rollback", calls2[0].getMethodName() );
args = calls2[0].getArgs();
assertTrue( ((Xid) args[0]).equals( xid2 ) );
}
/*
* o Tests that multiple enlistments of same (according to isSameRM()
* method) only receive one set of rollback calls.
*/
@Test
public void testRollback2() throws Exception
{
tm.begin();
FakeXAResource res1 = new FakeXAResource( "XAResource1" );
FakeXAResource res2 = new FakeXAResource( "XAResource1" );
// enlist two (same) resources and verify that the start method
// is invoked with correct flags
// res1
tm.getTransaction().enlistResource( res1 );
MethodCall calls1[] = res1.getAndRemoveMethodCalls();
assertEquals( 1, calls1.length );
assertEquals( "start", calls1[0].getMethodName() );
// res2
tm.getTransaction().enlistResource( res2 );
MethodCall calls2[] = res2.getAndRemoveMethodCalls();
assertEquals( 1, calls2.length );
assertEquals( "start", calls2[0].getMethodName() );
// verify Xid and flags
Object args[] = calls1[0].getArgs();
Xid xid1 = (Xid) args[0];
assertEquals( XAResource.TMNOFLAGS, ((Integer) args[1]).intValue() );
args = calls2[0].getArgs();
Xid xid2 = (Xid) args[0];
assertEquals( XAResource.TMJOIN, ((Integer) args[1]).intValue() );
assertTrue( xid1.equals( xid2 ) );
assertTrue( xid2.equals( xid1 ) );
// verify delist of resource
tm.getTransaction().delistResource( res2, XAResource.TMSUCCESS );
calls2 = res2.getAndRemoveMethodCalls();
assertEquals( 1, calls2.length );
tm.getTransaction().delistResource( res1, XAResource.TMSUCCESS );
calls1 = res1.getAndRemoveMethodCalls();
// res1
assertEquals( 1, calls1.length );
assertEquals( "end", calls1[0].getMethodName() );
args = calls1[0].getArgs();
assertTrue( ((Xid) args[0]).equals( xid1 ) );
assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() );
// res2
assertEquals( 1, calls2.length );
assertEquals( "end", calls2[0].getMethodName() );
args = calls2[0].getArgs();
assertTrue( ((Xid) args[0]).equals( xid2 ) );
assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() );
// verify proper prepare/commit
tm.rollback();
calls1 = res1.getAndRemoveMethodCalls();
calls2 = res2.getAndRemoveMethodCalls();
// res1
assertEquals( 1, calls1.length );
assertEquals( "rollback", calls1[0].getMethodName() );
args = calls1[0].getArgs();
assertTrue( ((Xid) args[0]).equals( xid1 ) );
// res2
assertEquals( 0, calls2.length );
}
/**
* o Tests if nested transactions are supported
*
* TODO: if supported, do some testing :)
*/
@Test
public void testNestedTransactions() throws Exception
{
assertTrue( tm.getTransaction() == null );
tm.begin();
Transaction txParent = tm.getTransaction();
assertTrue( txParent != null );
try
{
tm.begin();
// ok supported
// some tests that might be valid for true nested support
// Transaction txChild = tm.getTransaction();
// assertTrue( txChild != txParent );
// tm.commit();
// assertTrue( txParent == tm.getTransaction() );
}
catch ( NotSupportedException e )
{
// well no nested transactions
}
tm.commit();
assertTrue( tm.getStatus() == Status.STATUS_NO_TRANSACTION );
}
private class TxHook implements javax.transaction.Synchronization
{
boolean gotBefore = false;
boolean gotAfter = false;
int statusBefore = -1;
int statusAfter = -1;
Transaction txBefore = null;
Transaction txAfter = null;
public void beforeCompletion()
{
try
{
statusBefore = tm.getStatus();
txBefore = tm.getTransaction();
gotBefore = true;
}
catch ( Exception e )
{
throw new RuntimeException( "" + e );
}
}
public void afterCompletion( int status )
{
try
{
statusAfter = status;
txAfter = tm.getTransaction();
assertTrue( status == tm.getStatus() );
gotAfter = true;
}
catch ( Exception e )
{
throw new RuntimeException( "" + e );
}
}
}
/**
* o Tests that beforeCompletion and afterCompletion are invoked. o Tests
* that the call is made in the same transaction context. o Tests status in
* before and after methods depending on commit/rollback.
*
* NOTE: Not sure if the check of Status is correct according to
* specification.
*/
@Test
public void testTransactionHook() throws Exception
{
// test for commit
tm.begin();
Transaction tx = tm.getTransaction();
TxHook txHook = new TxHook();
tx.registerSynchronization( txHook );
assertEquals( false, txHook.gotBefore );
assertEquals( false, txHook.gotAfter );
tm.commit();
assertEquals( true, txHook.gotBefore );
assertEquals( true, txHook.gotAfter );
assertTrue( tx == txHook.txBefore );
assertTrue( tx == txHook.txAfter );
assertEquals( Status.STATUS_ACTIVE, txHook.statusBefore );
assertEquals( Status.STATUS_COMMITTED, txHook.statusAfter );
// test for rollback
tm.begin();
tx = tm.getTransaction();
txHook = new TxHook();
tx.registerSynchronization( txHook );
assertEquals( false, txHook.gotBefore );
assertEquals( false, txHook.gotAfter );
tm.rollback();
assertEquals( true, txHook.gotBefore );
assertEquals( true, txHook.gotAfter );
assertTrue( tx == txHook.txBefore );
assertTrue( tx == txHook.txAfter );
assertEquals( Status.STATUS_MARKED_ROLLBACK, txHook.statusBefore );
assertEquals( Status.STATUS_ROLLEDBACK, txHook.statusAfter );
}
/**
* Tests that the correct status is returned from TM.
*
* TODO: Implement a FakeXAResource to check: STATUS_COMMITTING
* STATUS_PREPARED STATUS_PREPEARING STATUS_ROLLING_BACK
*/
@Test
public void testStatus() throws Exception
{
assertTrue( tm.getStatus() == Status.STATUS_NO_TRANSACTION );
tm.begin();
assertTrue( tm.getStatus() == Status.STATUS_ACTIVE );
tm.getTransaction().setRollbackOnly();
assertTrue( tm.getStatus() == Status.STATUS_MARKED_ROLLBACK );
tm.rollback();
assertTrue( tm.getStatus() == Status.STATUS_NO_TRANSACTION );
}
@Test
public void shouldCallAfterCompletionsEvenOnCommitWhenTmNotOK() throws Exception
{
shouldCallAfterCompletionsEvenOnCloseWhenTmNotOK( commitTransaction() );
}
@Test
public void shouldCallAfterCompletionsEvenOnRollbackWhenTmNotOK() throws Exception
{
shouldCallAfterCompletionsEvenOnCloseWhenTmNotOK( rollbackTransaction() );
}
private void shouldCallAfterCompletionsEvenOnCloseWhenTmNotOK( WorkerCommand<Void, Object> finish )
throws Exception
{
// GIVEN a transaction T1
SimpleTxHook hook = new SimpleTxHook();
OtherThreadExecutor<Void> t1 = new OtherThreadExecutor<Void>( "T1", null );
t1.execute( beginTransaction( hook ) );
// and a tx manager going in to a bad state
tm.begin();
FakeXAResource resource = new FailingFakeXAResource( "XAResource1", true );
tm.getTransaction().enlistResource( resource );
try
{
tm.commit();
fail( "Should have failed commit" );
}
catch ( Exception e )
{ // YEY
}
// WHEN T1 tries to commit
try
{
t1.execute( finish );
fail( "Should've failed" );
}
catch ( Exception e )
{ // YO
}
// THEN after completions should be called
kernelHealth.healed();
assertTrue( hook.gotAfter );
}
private WorkerCommand<Void, Object> commitTransaction()
{
return new WorkerCommand<Void, Object>()
{
@Override
public Object doWork( Void state )
{
try
{
tm.commit();
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
return null;
}
};
}
private WorkerCommand<Void, Object> rollbackTransaction()
{
return new WorkerCommand<Void, Object>()
{
@Override
public Object doWork( Void state )
{
try
{
tm.rollback();
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
return null;
}
};
}
private WorkerCommand<Void, Object> beginTransaction( final Synchronization hook )
{
return new WorkerCommand<Void, Object>()
{
@Override
public Object doWork( Void state )
{
try
{
tm.begin();
tm.getTransaction().registerSynchronization( hook );
return null;
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
}
};
}
}
| 0true
|
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestJtaCompliance.java
|
1,476 |
public abstract class OSQLFunctionMove extends OSQLFunctionConfigurableAbstract {
public static final String NAME = "move";
public OSQLFunctionMove() {
super(NAME, 1, 2);
}
public OSQLFunctionMove(final String iName, final int iMin, final int iMax) {
super(iName, iMin, iMax);
}
protected abstract Object move(final OrientBaseGraph graph, final OIdentifiable iRecord, final String[] iLabels);
public String getSyntax() {
return "Syntax error: " + name + "([<labels>])";
}
public Object execute(OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParameters,
final OCommandContext iContext) {
final OrientBaseGraph graph = OGraphCommandExecutorSQLFactory.getGraph();
final String[] labels;
if (iParameters != null && iParameters.length > 0 && iParameters[0] != null)
labels = OMultiValue.array(iParameters, String.class, new OCallable<Object, Object>() {
@Override
public Object call(final Object iArgument) {
return OStringSerializerHelper.getStringContent(iArgument);
}
});
else
labels = null;
if (iCurrentRecord == null) {
return OSQLEngine.foreachRecord(new OCallable<Object, OIdentifiable>() {
@Override
public Object call(final OIdentifiable iArgument) {
return move(graph, iArgument, labels);
}
}, iCurrentResult, iContext);
} else
return move(graph, iCurrentRecord.getRecord(), labels);
}
protected Object v2v(final OrientBaseGraph graph, final OIdentifiable iRecord, final Direction iDirection, final String[] iLabels) {
final ODocument rec = iRecord.getRecord();
if (rec.getSchemaClass() != null)
if (rec.getSchemaClass().isSubClassOf(OrientVertex.CLASS_NAME)) {
// VERTEX
final OrientVertex vertex = graph.getVertex(rec);
if (vertex != null)
return vertex.getVertices(iDirection, iLabels);
}
return null;
}
protected Object v2e(final OrientBaseGraph graph, final OIdentifiable iRecord, final Direction iDirection, final String[] iLabels) {
final ODocument rec = iRecord.getRecord();
if (rec.getSchemaClass() != null)
if (rec.getSchemaClass().isSubClassOf(OrientVertex.CLASS_NAME)) {
// VERTEX
final OrientVertex vertex = graph.getVertex(rec);
if (vertex != null)
return vertex.getEdges(iDirection, iLabels);
}
return null;
}
protected Object e2v(final OrientBaseGraph graph, final OIdentifiable iRecord, final Direction iDirection, final String[] iLabels) {
final ODocument rec = iRecord.getRecord();
if (rec.getSchemaClass() != null)
if (rec.getSchemaClass().isSubClassOf(OrientEdge.CLASS_NAME)) {
// EDGE
final OrientEdge edge = graph.getEdge(rec);
if (edge != null) {
final OrientVertex out = (OrientVertex) edge.getVertex(iDirection);
return out;
}
}
return null;
}
}
| 1no label
|
graphdb_src_main_java_com_orientechnologies_orient_graph_sql_functions_OSQLFunctionMove.java
|
430 |
public class TransportClusterStateAction extends TransportMasterNodeReadOperationAction<ClusterStateRequest, ClusterStateResponse> {
private final ClusterName clusterName;
@Inject
public TransportClusterStateAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool,
ClusterName clusterName) {
super(settings, transportService, clusterService, threadPool);
this.clusterName = clusterName;
}
@Override
protected String executor() {
// very lightweight operation in memory, no need to fork to a thread
return ThreadPool.Names.SAME;
}
@Override
protected String transportAction() {
return ClusterStateAction.NAME;
}
@Override
protected ClusterStateRequest newRequest() {
return new ClusterStateRequest();
}
@Override
protected ClusterStateResponse newResponse() {
return new ClusterStateResponse();
}
@Override
protected void masterOperation(final ClusterStateRequest request, final ClusterState state, ActionListener<ClusterStateResponse> listener) throws ElasticsearchException {
ClusterState currentState = clusterService.state();
logger.trace("Serving cluster state request using version {}", currentState.version());
ClusterState.Builder builder = ClusterState.builder();
builder.version(currentState.version());
if (request.nodes()) {
builder.nodes(currentState.nodes());
}
if (request.routingTable()) {
if (request.indices().length > 0) {
RoutingTable.Builder routingTableBuilder = RoutingTable.builder();
for (String filteredIndex : request.indices()) {
if (currentState.routingTable().getIndicesRouting().containsKey(filteredIndex)) {
routingTableBuilder.add(currentState.routingTable().getIndicesRouting().get(filteredIndex));
}
}
builder.routingTable(routingTableBuilder);
} else {
builder.routingTable(currentState.routingTable());
}
builder.allocationExplanation(currentState.allocationExplanation());
}
if (request.blocks()) {
builder.blocks(currentState.blocks());
}
if (request.metaData()) {
MetaData.Builder mdBuilder;
if (request.indices().length == 0 && request.indexTemplates().length == 0) {
mdBuilder = MetaData.builder(currentState.metaData());
} else {
mdBuilder = MetaData.builder();
}
if (request.indices().length > 0) {
String[] indices = currentState.metaData().concreteIndicesIgnoreMissing(request.indices());
for (String filteredIndex : indices) {
IndexMetaData indexMetaData = currentState.metaData().index(filteredIndex);
if (indexMetaData != null) {
mdBuilder.put(indexMetaData, false);
}
}
}
if (request.indexTemplates().length > 0) {
for (String templateName : request.indexTemplates()) {
IndexTemplateMetaData indexTemplateMetaData = currentState.metaData().templates().get(templateName);
if (indexTemplateMetaData != null) {
mdBuilder.put(indexTemplateMetaData);
}
}
}
builder.metaData(mdBuilder);
}
listener.onResponse(new ClusterStateResponse(clusterName, builder.build()));
}
}
| 0true
|
src_main_java_org_elasticsearch_action_admin_cluster_state_TransportClusterStateAction.java
|
776 |
public class MoreLikeThisRequest extends ActionRequest<MoreLikeThisRequest> {
private static final XContentType contentType = Requests.CONTENT_TYPE;
private String index;
private String type;
private String id;
private String routing;
private String[] fields;
private float percentTermsToMatch = -1;
private int minTermFreq = -1;
private int maxQueryTerms = -1;
private String[] stopWords = null;
private int minDocFreq = -1;
private int maxDocFreq = -1;
private int minWordLength = -1;
private int maxWordLength = -1;
private float boostTerms = -1;
private SearchType searchType = SearchType.DEFAULT;
private int searchSize = 0;
private int searchFrom = 0;
private String searchQueryHint;
private String[] searchIndices;
private String[] searchTypes;
private Scroll searchScroll;
private BytesReference searchSource;
private boolean searchSourceUnsafe;
MoreLikeThisRequest() {
}
/**
* Constructs a new more like this request for a document that will be fetch from the provided index.
* Use {@link #type(String)} and {@link #id(String)} to specify the document to load.
*/
public MoreLikeThisRequest(String index) {
this.index = index;
}
/**
* The index to load the document from which the "like" query will run with.
*/
public String index() {
return index;
}
/**
* The type of document to load from which the "like" query will run with.
*/
public String type() {
return type;
}
void index(String index) {
this.index = index;
}
/**
* The type of document to load from which the "like" query will execute with.
*/
public MoreLikeThisRequest type(String type) {
this.type = type;
return this;
}
/**
* The id of document to load from which the "like" query will execute with.
*/
public String id() {
return id;
}
/**
* The id of document to load from which the "like" query will execute with.
*/
public MoreLikeThisRequest id(String id) {
this.id = id;
return this;
}
/**
* @return The routing for this request. This used for the `get` part of the mlt request.
*/
public String routing() {
return routing;
}
public void routing(String routing) {
this.routing = routing;
}
/**
* The fields of the document to use in order to find documents "like" this one. Defaults to run
* against all the document fields.
*/
public String[] fields() {
return this.fields;
}
/**
* The fields of the document to use in order to find documents "like" this one. Defaults to run
* against all the document fields.
*/
public MoreLikeThisRequest fields(String... fields) {
this.fields = fields;
return this;
}
/**
* The percent of the terms to match for each field. Defaults to <tt>0.3f</tt>.
*/
public MoreLikeThisRequest percentTermsToMatch(float percentTermsToMatch) {
this.percentTermsToMatch = percentTermsToMatch;
return this;
}
/**
* The percent of the terms to match for each field. Defaults to <tt>0.3f</tt>.
*/
public float percentTermsToMatch() {
return this.percentTermsToMatch;
}
/**
* The frequency below which terms will be ignored in the source doc. Defaults to <tt>2</tt>.
*/
public MoreLikeThisRequest minTermFreq(int minTermFreq) {
this.minTermFreq = minTermFreq;
return this;
}
/**
* The frequency below which terms will be ignored in the source doc. Defaults to <tt>2</tt>.
*/
public int minTermFreq() {
return this.minTermFreq;
}
/**
* The maximum number of query terms that will be included in any generated query. Defaults to <tt>25</tt>.
*/
public MoreLikeThisRequest maxQueryTerms(int maxQueryTerms) {
this.maxQueryTerms = maxQueryTerms;
return this;
}
/**
* The maximum number of query terms that will be included in any generated query. Defaults to <tt>25</tt>.
*/
public int maxQueryTerms() {
return this.maxQueryTerms;
}
/**
* Any word in this set is considered "uninteresting" and ignored.
* <p/>
* <p>Even if your Analyzer allows stopwords, you might want to tell the MoreLikeThis code to ignore them, as
* for the purposes of document similarity it seems reasonable to assume that "a stop word is never interesting".
* <p/>
* <p>Defaults to no stop words.
*/
public MoreLikeThisRequest stopWords(String... stopWords) {
this.stopWords = stopWords;
return this;
}
/**
* Any word in this set is considered "uninteresting" and ignored.
* <p/>
* <p>Even if your Analyzer allows stopwords, you might want to tell the MoreLikeThis code to ignore them, as
* for the purposes of document similarity it seems reasonable to assume that "a stop word is never interesting".
* <p/>
* <p>Defaults to no stop words.
*/
public String[] stopWords() {
return this.stopWords;
}
/**
* The frequency at which words will be ignored which do not occur in at least this
* many docs. Defaults to <tt>5</tt>.
*/
public MoreLikeThisRequest minDocFreq(int minDocFreq) {
this.minDocFreq = minDocFreq;
return this;
}
/**
* The frequency at which words will be ignored which do not occur in at least this
* many docs. Defaults to <tt>5</tt>.
*/
public int minDocFreq() {
return this.minDocFreq;
}
/**
* The maximum frequency in which words may still appear. Words that appear
* in more than this many docs will be ignored. Defaults to unbounded.
*/
public MoreLikeThisRequest maxDocFreq(int maxDocFreq) {
this.maxDocFreq = maxDocFreq;
return this;
}
/**
* The maximum frequency in which words may still appear. Words that appear
* in more than this many docs will be ignored. Defaults to unbounded.
*/
public int maxDocFreq() {
return this.maxDocFreq;
}
/**
* The minimum word length below which words will be ignored. Defaults to <tt>0</tt>.
*/
public MoreLikeThisRequest minWordLength(int minWordLength) {
this.minWordLength = minWordLength;
return this;
}
/**
* The minimum word length below which words will be ignored. Defaults to <tt>0</tt>.
*/
public int minWordLength() {
return this.minWordLength;
}
/**
* The maximum word length above which words will be ignored. Defaults to unbounded.
*/
public MoreLikeThisRequest maxWordLength(int maxWordLength) {
this.maxWordLength = maxWordLength;
return this;
}
/**
* The maximum word length above which words will be ignored. Defaults to unbounded.
*/
public int maxWordLength() {
return this.maxWordLength;
}
/**
* The boost factor to use when boosting terms. Defaults to <tt>1</tt>.
*/
public MoreLikeThisRequest boostTerms(float boostTerms) {
this.boostTerms = boostTerms;
return this;
}
/**
* The boost factor to use when boosting terms. Defaults to <tt>1</tt>.
*/
public float boostTerms() {
return this.boostTerms;
}
void beforeLocalFork() {
if (searchSourceUnsafe) {
searchSource = searchSource.copyBytesArray();
searchSourceUnsafe = false;
}
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequest searchSource(SearchSourceBuilder sourceBuilder) {
this.searchSource = sourceBuilder.buildAsBytes(Requests.CONTENT_TYPE);
this.searchSourceUnsafe = false;
return this;
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequest searchSource(String searchSource) {
this.searchSource = new BytesArray(searchSource);
this.searchSourceUnsafe = false;
return this;
}
public MoreLikeThisRequest searchSource(Map searchSource) {
try {
XContentBuilder builder = XContentFactory.contentBuilder(contentType);
builder.map(searchSource);
return searchSource(builder);
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + searchSource + "]", e);
}
}
public MoreLikeThisRequest searchSource(XContentBuilder builder) {
this.searchSource = builder.bytes();
this.searchSourceUnsafe = false;
return this;
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequest searchSource(byte[] searchSource) {
return searchSource(searchSource, 0, searchSource.length, false);
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequest searchSource(byte[] searchSource, int offset, int length, boolean unsafe) {
return searchSource(new BytesArray(searchSource, offset, length), unsafe);
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public MoreLikeThisRequest searchSource(BytesReference searchSource, boolean unsafe) {
this.searchSource = searchSource;
this.searchSourceUnsafe = unsafe;
return this;
}
/**
* An optional search source request allowing to control the search request for the
* more like this documents.
*/
public BytesReference searchSource() {
return this.searchSource;
}
public boolean searchSourceUnsafe() {
return searchSourceUnsafe;
}
/**
* The search type of the mlt search query.
*/
public MoreLikeThisRequest searchType(SearchType searchType) {
this.searchType = searchType;
return this;
}
/**
* The search type of the mlt search query.
*/
public MoreLikeThisRequest searchType(String searchType) throws ElasticsearchIllegalArgumentException {
return searchType(SearchType.fromString(searchType));
}
/**
* The search type of the mlt search query.
*/
public SearchType searchType() {
return this.searchType;
}
/**
* The indices the resulting mlt query will run against. If not set, will run
* against the index the document was fetched from.
*/
public MoreLikeThisRequest searchIndices(String... searchIndices) {
this.searchIndices = searchIndices;
return this;
}
/**
* The indices the resulting mlt query will run against. If not set, will run
* against the index the document was fetched from.
*/
public String[] searchIndices() {
return this.searchIndices;
}
/**
* The types the resulting mlt query will run against. If not set, will run
* against the type of the document fetched.
*/
public MoreLikeThisRequest searchTypes(String... searchTypes) {
this.searchTypes = searchTypes;
return this;
}
/**
* The types the resulting mlt query will run against. If not set, will run
* against the type of the document fetched.
*/
public String[] searchTypes() {
return this.searchTypes;
}
/**
* Optional search query hint.
*/
public MoreLikeThisRequest searchQueryHint(String searchQueryHint) {
this.searchQueryHint = searchQueryHint;
return this;
}
/**
* Optional search query hint.
*/
public String searchQueryHint() {
return this.searchQueryHint;
}
/**
* An optional search scroll request to be able to continue and scroll the search
* operation.
*/
public MoreLikeThisRequest searchScroll(Scroll searchScroll) {
this.searchScroll = searchScroll;
return this;
}
/**
* An optional search scroll request to be able to continue and scroll the search
* operation.
*/
public Scroll searchScroll() {
return this.searchScroll;
}
/**
* The number of documents to return, defaults to 10.
*/
public MoreLikeThisRequest searchSize(int size) {
this.searchSize = size;
return this;
}
public int searchSize() {
return this.searchSize;
}
/**
* From which search result set to return.
*/
public MoreLikeThisRequest searchFrom(int from) {
this.searchFrom = from;
return this;
}
public int searchFrom() {
return this.searchFrom;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (index == null) {
validationException = ValidateActions.addValidationError("index is missing", validationException);
}
if (type == null) {
validationException = ValidateActions.addValidationError("type is missing", validationException);
}
if (id == null) {
validationException = ValidateActions.addValidationError("id is missing", validationException);
}
return validationException;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
index = in.readString();
type = in.readString();
id = in.readString();
// no need to pass threading over the network, they are always false when coming throw a thread pool
int size = in.readVInt();
if (size == 0) {
fields = Strings.EMPTY_ARRAY;
} else {
fields = new String[size];
for (int i = 0; i < size; i++) {
fields[i] = in.readString();
}
}
percentTermsToMatch = in.readFloat();
minTermFreq = in.readVInt();
maxQueryTerms = in.readVInt();
size = in.readVInt();
if (size > 0) {
stopWords = new String[size];
for (int i = 0; i < size; i++) {
stopWords[i] = in.readString();
}
}
minDocFreq = in.readVInt();
maxDocFreq = in.readVInt();
minWordLength = in.readVInt();
maxWordLength = in.readVInt();
boostTerms = in.readFloat();
searchType = SearchType.fromId(in.readByte());
if (in.readBoolean()) {
searchQueryHint = in.readString();
}
size = in.readVInt();
if (size == 0) {
searchIndices = null;
} else if (size == 1) {
searchIndices = Strings.EMPTY_ARRAY;
} else {
searchIndices = new String[size - 1];
for (int i = 0; i < searchIndices.length; i++) {
searchIndices[i] = in.readString();
}
}
size = in.readVInt();
if (size == 0) {
searchTypes = null;
} else if (size == 1) {
searchTypes = Strings.EMPTY_ARRAY;
} else {
searchTypes = new String[size - 1];
for (int i = 0; i < searchTypes.length; i++) {
searchTypes[i] = in.readString();
}
}
if (in.readBoolean()) {
searchScroll = readScroll(in);
}
searchSourceUnsafe = false;
searchSource = in.readBytesReference();
searchSize = in.readVInt();
searchFrom = in.readVInt();
routing = in.readOptionalString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(index);
out.writeString(type);
out.writeString(id);
if (fields == null) {
out.writeVInt(0);
} else {
out.writeVInt(fields.length);
for (String field : fields) {
out.writeString(field);
}
}
out.writeFloat(percentTermsToMatch);
out.writeVInt(minTermFreq);
out.writeVInt(maxQueryTerms);
if (stopWords == null) {
out.writeVInt(0);
} else {
out.writeVInt(stopWords.length);
for (String stopWord : stopWords) {
out.writeString(stopWord);
}
}
out.writeVInt(minDocFreq);
out.writeVInt(maxDocFreq);
out.writeVInt(minWordLength);
out.writeVInt(maxWordLength);
out.writeFloat(boostTerms);
out.writeByte(searchType.id());
if (searchQueryHint == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
out.writeString(searchQueryHint);
}
if (searchIndices == null) {
out.writeVInt(0);
} else {
out.writeVInt(searchIndices.length + 1);
for (String index : searchIndices) {
out.writeString(index);
}
}
if (searchTypes == null) {
out.writeVInt(0);
} else {
out.writeVInt(searchTypes.length + 1);
for (String type : searchTypes) {
out.writeString(type);
}
}
if (searchScroll == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
searchScroll.writeTo(out);
}
out.writeBytesReference(searchSource);
out.writeVInt(searchSize);
out.writeVInt(searchFrom);
out.writeOptionalString(routing);
}
}
| 0true
|
src_main_java_org_elasticsearch_action_mlt_MoreLikeThisRequest.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.