Unnamed: 0
int64 0
6.45k
| func
stringlengths 37
161k
| target
class label 2
classes | project
stringlengths 33
167
|
---|---|---|---|
122 | public abstract class AbstractPageRuleProcessor implements PageRuleProcessor {
private static final Log LOG = LogFactory.getLog(AbstractPageRuleProcessor.class);
private Map expressionCache = Collections.synchronizedMap(new LRUMap(1000));
private ParserContext parserContext;
private Map<String, String> contextClassNames = new HashMap<String, String> ();
/**
* Having a parser context that imports the classes speeds MVEL by up to 60%.
* @return
*/
protected ParserContext getParserContext() {
if (parserContext == null) {
parserContext = new ParserContext();
parserContext.addImport("MVEL", MVEL.class);
parserContext.addImport("MvelHelper", MvelHelper.class);
/* Getting errors when the following is in place.
for (String key : contextClassNames.keySet()) {
String className = contextClassNames.get(key);
try {
Class c = Class.forName(className);
parserContext.addImport(key, c);
} catch (ClassNotFoundException e) {
LOG.error("Error resolving classname while setting up MVEL context, rule processing based on the key " + key + " will not be optimized", e);
}
} */
}
return parserContext;
}
/**
* Helpful method for processing a boolean MVEL expression and associated arguments.
*
* Caches the expression in an LRUCache.
* @param expression
* @param vars
* @return the result of the expression
*/
protected Boolean executeExpression(String expression, Map<String, Object> vars) {
Serializable exp = (Serializable) expressionCache.get(expression);
vars.put("MVEL", MVEL.class);
if (exp == null) {
try {
exp = MVEL.compileExpression(expression, getParserContext());
} catch (CompileException ce) {
LOG.warn("Compile exception processing phrase: " + expression,ce);
return Boolean.FALSE;
}
expressionCache.put(expression, exp);
}
try {
return (Boolean) MVEL.executeExpression(exp, vars);
} catch (Exception e) {
LOG.error(e);
}
return false;
}
/**
* List of class names to add to the MVEL ParserContext.
*
* @return
* @see {@link ParserContext}
*/
public Map<String, String> getContextClassNames() {
return contextClassNames;
}
/**
* List of class names to add to the MVEL ParserContext.
*
* @return
* @see {@link ParserContext}
*/
public void setContextClassNames(Map<String, String> contextClassNames) {
this.contextClassNames = contextClassNames;
}
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_service_AbstractPageRuleProcessor.java |
3,308 | static class Empty extends DoubleArrayAtomicFieldData {
Empty(int numDocs) {
super(numDocs);
}
@Override
public LongValues getLongValues() {
return LongValues.EMPTY;
}
@Override
public DoubleValues getDoubleValues() {
return DoubleValues.EMPTY;
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public boolean isValuesOrdered() {
return false;
}
@Override
public long getNumberUniqueValues() {
return 0;
}
@Override
public long getMemorySizeInBytes() {
return 0;
}
@Override
public BytesValues getBytesValues(boolean needsHashes) {
return BytesValues.EMPTY;
}
@Override
public ScriptDocValues getScriptValues() {
return ScriptDocValues.EMPTY;
}
} | 1no label
| src_main_java_org_elasticsearch_index_fielddata_plain_DoubleArrayAtomicFieldData.java |
39 | (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
public sun.misc.Unsafe run() throws Exception {
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
for (java.lang.reflect.Field f : k.getDeclaredFields()) {
f.setAccessible(true);
Object x = f.get(null);
if (k.isInstance(x))
return k.cast(x);
}
throw new NoSuchFieldError("the Unsafe");
}}); | 0true
| src_main_java_jsr166e_ConcurrentHashMapV8.java |
477 | makeDbCall(databaseDocumentTxTwo, new ODocumentHelper.ODbRelatedCall<java.lang.Object>() {
public Object call() {
convertSchemaDoc(doc2);
return null;
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java |
190 | new ThreadLocal<ThreadLocalRandom>() {
protected ThreadLocalRandom initialValue() {
return new ThreadLocalRandom();
}
}; | 0true
| src_main_java_jsr166y_ThreadLocalRandom.java |
1,214 | CONCURRENT {
@Override
<T> Recycler<T> build(Recycler.C<T> c, int limit, int availableProcessors) {
return concurrent(dequeFactory(c, limit), availableProcessors);
}
}, | 0true
| src_main_java_org_elasticsearch_cache_recycler_CacheRecycler.java |
1,059 | public class OCommandExecutorSQLTruncateCluster extends OCommandExecutorSQLAbstract implements OCommandDistributedReplicateRequest {
public static final String KEYWORD_TRUNCATE = "TRUNCATE";
public static final String KEYWORD_CLUSTER = "CLUSTER";
private String clusterName;
@SuppressWarnings("unchecked")
public OCommandExecutorSQLTruncateCluster parse(final OCommandRequest iRequest) {
init((OCommandRequestText) iRequest);
StringBuilder word = new StringBuilder();
int oldPos = 0;
int pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
if (pos == -1 || !word.toString().equals(KEYWORD_TRUNCATE))
throw new OCommandSQLParsingException("Keyword " + KEYWORD_TRUNCATE + " not found. Use " + getSyntax(), parserText, oldPos);
oldPos = pos;
pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
if (pos == -1 || !word.toString().equals(KEYWORD_CLUSTER))
throw new OCommandSQLParsingException("Keyword " + KEYWORD_CLUSTER + " not found. Use " + getSyntax(), parserText, oldPos);
oldPos = pos;
pos = nextWord(parserText, parserText, oldPos, word, true);
if (pos == -1)
throw new OCommandSQLParsingException("Expected cluster name. Use " + getSyntax(), parserText, oldPos);
clusterName = word.toString();
final ODatabaseRecord database = getDatabase();
if (database.getClusterIdByName(clusterName) == -1)
throw new OCommandSQLParsingException("Cluster '" + clusterName + "' not found", parserText, oldPos);
return this;
}
/**
* Execute the command.
*/
public Object execute(final Map<Object, Object> iArgs) {
if (clusterName == null)
throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
final OCluster cluster = ((OStorageEmbedded) getDatabase().getStorage()).getClusterByName(clusterName);
final long recs = cluster.getEntries();
try {
cluster.truncate();
} catch (IOException e) {
throw new OCommandExecutionException("Error on executing command", e);
}
return recs;
}
@Override
public String getSyntax() {
return "TRUNCATE CLUSTER <cluster-name>";
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLTruncateCluster.java |
7 | fBrowser.addOpenWindowListener(new OpenWindowListener() {
@Override
public void open(WindowEvent event) {
event.required= true; // Cancel opening of new windows
}
}); | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_browser_BrowserInformationControl.java |
241 | service.submit(runnable, new ExecutionCallback() {
public void onResponse(Object response) {
responseLatch.countDown();
}
public void onFailure(Throwable t) {
}
}); | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceSubmitTest.java |
101 | serializationConfig.addPortableFactory(5, new PortableFactory() {
public Portable create(int classId) {
return new SamplePortable();
}
}); | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_ClientIssueTest.java |
1,160 | @Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_BANK_ACCOUNT_PAYMENT")
public class BankAccountPaymentInfoImpl implements BankAccountPaymentInfo {
private static final long serialVersionUID = 1L;
protected BankAccountPaymentInfoImpl() {
//do not allow direct instantiation -- must at least be package private for bytecode instrumentation
//this complies with JPA specification requirements for entity construction
}
@Transient
protected EncryptionModule encryptionModule;
@Id
@GeneratedValue(generator = "BankPaymentId")
@GenericGenerator(
name="BankPaymentId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="BankAccountPaymentInfoImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.payment.domain.BankAccountPaymentInfoImpl")
}
)
@Column(name = "PAYMENT_ID")
protected Long id;
@Column(name = "REFERENCE_NUMBER", nullable=false)
@Index(name="BANKACCOUNT_INDEX", columnNames={"REFERENCE_NUMBER"})
protected String referenceNumber;
@Column(name = "ACCOUNT_NUMBER", nullable=false)
protected String accountNumber;
@Column(name = "ROUTING_NUMBER", nullable=false)
protected String routingNumber;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getReferenceNumber() {
return referenceNumber;
}
@Override
public void setReferenceNumber(String referenceNumber) {
this.referenceNumber = referenceNumber;
}
@Override
public String getAccountNumber() {
return encryptionModule.decrypt(accountNumber);
}
@Override
public void setAccountNumber(String accountNumber) {
this.accountNumber = encryptionModule.encrypt(accountNumber);
}
@Override
public String getRoutingNumber() {
return encryptionModule.decrypt(routingNumber);
}
@Override
public void setRoutingNumber(String routingNumber) {
this.routingNumber = encryptionModule.encrypt(routingNumber);
}
@Override
public EncryptionModule getEncryptionModule() {
return encryptionModule;
}
@Override
public void setEncryptionModule(EncryptionModule encryptionModule) {
this.encryptionModule = encryptionModule;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((accountNumber == null) ? 0 : accountNumber.hashCode());
result = prime * result + ((referenceNumber == null) ? 0 : referenceNumber.hashCode());
result = prime * result + ((routingNumber == null) ? 0 : routingNumber.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;
BankAccountPaymentInfoImpl other = (BankAccountPaymentInfoImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (accountNumber == null) {
if (other.accountNumber != null)
return false;
} else if (!accountNumber.equals(other.accountNumber))
return false;
if (referenceNumber == null) {
if (other.referenceNumber != null)
return false;
} else if (!referenceNumber.equals(other.referenceNumber))
return false;
if (routingNumber == null) {
if (other.routingNumber != null)
return false;
} else if (!routingNumber.equals(other.routingNumber))
return false;
return true;
}
} | 1no label
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_domain_BankAccountPaymentInfoImpl.java |
435 | public class RuleType implements Serializable {
private static final long serialVersionUID = 1L;
private static final Map<String, RuleType> TYPES = new HashMap<String, RuleType>();
public static final RuleType CUSTOMER = new RuleType("1", "Customer");
public static final RuleType REQUEST = new RuleType("2", "Request");
public static final RuleType TIME = new RuleType("3", "Time");
public static final RuleType PRODUCT = new RuleType("4", "Product");
public static final RuleType ORDER_ITEM = new RuleType("5", "OrderItem");
public static final RuleType LOCALE = new RuleType("6", "Locale");
public static final RuleType ORDER_ITEM_HISTORY = new RuleType("7", "OrderItemHistory");
public static RuleType getInstance(final String type) {
return TYPES.get(type);
}
private String type;
private String friendlyType;
public RuleType() {
//do nothing
}
public RuleType(final String type, final String friendlyType) {
this.friendlyType = friendlyType;
setType(type);
}
public String getType() {
return type;
}
public String getFriendlyType() {
return friendlyType;
}
private void setType(final String type) {
this.type = type;
if (!TYPES.containsKey(type)) {
TYPES.put(type, this);
} else {
throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName());
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RuleType other = (RuleType) 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_presentation_client_RuleType.java |
913 | public abstract class AdapterActionFuture<T, L> extends BaseFuture<T> implements ActionFuture<T>, ActionListener<L> {
private Throwable rootFailure;
@Override
public T actionGet() throws ElasticsearchException {
try {
return get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ElasticsearchIllegalStateException("Future got interrupted", e);
} catch (ExecutionException e) {
throw rethrowExecutionException(e);
}
}
@Override
public T actionGet(String timeout) throws ElasticsearchException {
return actionGet(TimeValue.parseTimeValue(timeout, null));
}
@Override
public T actionGet(long timeoutMillis) throws ElasticsearchException {
return actionGet(timeoutMillis, TimeUnit.MILLISECONDS);
}
@Override
public T actionGet(TimeValue timeout) throws ElasticsearchException {
return actionGet(timeout.millis(), TimeUnit.MILLISECONDS);
}
@Override
public T actionGet(long timeout, TimeUnit unit) throws ElasticsearchException {
try {
return get(timeout, unit);
} catch (TimeoutException e) {
throw new ElasticsearchTimeoutException(e.getMessage());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ElasticsearchIllegalStateException("Future got interrupted", e);
} catch (ExecutionException e) {
throw rethrowExecutionException(e);
}
}
static ElasticsearchException rethrowExecutionException(ExecutionException e) {
if (e.getCause() instanceof ElasticsearchException) {
ElasticsearchException esEx = (ElasticsearchException) e.getCause();
Throwable root = esEx.unwrapCause();
if (root instanceof ElasticsearchException) {
return (ElasticsearchException) root;
}
return new UncategorizedExecutionException("Failed execution", root);
} else {
return new UncategorizedExecutionException("Failed execution", e);
}
}
@Override
public void onResponse(L result) {
set(convert(result));
}
@Override
public void onFailure(Throwable e) {
setException(e);
}
protected abstract T convert(L listenerResponse);
@Override
public Throwable getRootFailure() {
return rootFailure;
}
} | 0true
| src_main_java_org_elasticsearch_action_support_AdapterActionFuture.java |
378 | @RunWith(HazelcastParallelClassRunner.class)
@Category(NightlyTest.class)
public class ClientMultiMapListenerStressTest {
static final int MAX_SECONDS = 60 * 10;
static final String MAP_NAME = randomString();
static final int NUMBER_OF_CLIENTS = 8;
static final int THREADS_PER_CLIENT = 8;
static HazelcastInstance server;
@BeforeClass
public static void init() {
server = Hazelcast.newHazelcastInstance();
}
@AfterClass
public static void destroy() {
HazelcastClient.shutdownAll();
Hazelcast.shutdownAll();
}
@Category(ProblematicTest.class)
@Test
public void listenerAddStressTest() throws InterruptedException {
final PutItemsThread[] putThreads = new PutItemsThread[NUMBER_OF_CLIENTS * THREADS_PER_CLIENT];
int idx=0;
for(int i=0; i<NUMBER_OF_CLIENTS; i++){
HazelcastInstance client = HazelcastClient.newHazelcastClient();
for(int j=0; j<THREADS_PER_CLIENT; j++){
PutItemsThread t = new PutItemsThread(client);
putThreads[idx++]=t;
}
}
for(int i=0; i<putThreads.length; i++){
putThreads[i].start();
}
MultiMap mm = server.getMultiMap(MAP_NAME);
assertJoinable(MAX_SECONDS, putThreads );
assertEquals(PutItemsThread.MAX_ITEMS * putThreads.length, mm.size());
assertTrueEventually(new AssertTask() {
public void run() throws Exception {
for(int i=0; i<putThreads.length; i++){
putThreads[i].assertResult(PutItemsThread.MAX_ITEMS * putThreads.length);
}
}
});
}
public class PutItemsThread extends Thread{
public static final int MAX_ITEMS = 1000;
public final MyEntryListener listener = new MyEntryListener();
public HazelcastInstance hzInstance;
public MultiMap mm;
public String id;
public PutItemsThread(HazelcastInstance hzInstance){
this.id = randomString();
this.hzInstance = hzInstance;
this.mm = hzInstance.getMultiMap(MAP_NAME);
mm.addEntryListener(listener, true);
}
public void run(){
for(int i=0; i< MAX_ITEMS; i++){
mm.put(id+i, id+i);
}
}
public void assertResult(int target){
System.out.println("listener "+id+" add events received "+listener.add.get());
assertEquals(target, listener.add.get());
}
}
static class MyEntryListener implements EntryListener {
public AtomicInteger add = new AtomicInteger(0);
public void entryAdded(EntryEvent event) {
add.incrementAndGet();
}
public void entryRemoved(EntryEvent event) {
}
public void entryUpdated(EntryEvent event) {
}
public void entryEvicted(EntryEvent event) {
}
};
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_multimap_ClientMultiMapListenerStressTest.java |
273 | @SuppressWarnings("serial")
public abstract class OCommandRequestAbstract implements OCommandRequestInternal {
protected OCommandResultListener resultListener;
protected OProgressListener progressListener;
protected int limit = -1;
protected long timeoutMs = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong();
protected TIMEOUT_STRATEGY timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION;
protected Map<Object, Object> parameters;
protected String fetchPlan = null;
protected boolean useCache = false;
protected OCommandContext context;
protected OCommandRequestAbstract() {
}
public OCommandResultListener getResultListener() {
return resultListener;
}
public void setResultListener(OCommandResultListener iListener) {
resultListener = iListener;
}
public Map<Object, Object> getParameters() {
return parameters;
}
protected void setParameters(final Object... iArgs) {
if (iArgs != null && iArgs.length > 0)
parameters = convertToParameters(iArgs);
}
@SuppressWarnings("unchecked")
protected Map<Object, Object> convertToParameters(final Object... iArgs) {
final Map<Object, Object> params;
if (iArgs.length == 1 && iArgs[0] instanceof Map) {
params = (Map<Object, Object>) iArgs[0];
} else {
params = new HashMap<Object, Object>(iArgs.length);
for (int i = 0; i < iArgs.length; ++i) {
Object par = iArgs[i];
if (par instanceof OIdentifiable && ((OIdentifiable) par).getIdentity().isValid())
// USE THE RID ONLY
par = ((OIdentifiable) par).getIdentity();
params.put(i, par);
}
}
return params;
}
public OProgressListener getProgressListener() {
return progressListener;
}
public OCommandRequestAbstract setProgressListener(OProgressListener progressListener) {
this.progressListener = progressListener;
return this;
}
public void reset() {
}
public int getLimit() {
return limit;
}
public OCommandRequestAbstract setLimit(final int limit) {
this.limit = limit;
return this;
}
public String getFetchPlan() {
return fetchPlan;
}
@SuppressWarnings("unchecked")
public <RET extends OCommandRequest> RET setFetchPlan(String fetchPlan) {
this.fetchPlan = fetchPlan;
return (RET) this;
}
public boolean isUseCache() {
return useCache;
}
public void setUseCache(boolean useCache) {
this.useCache = useCache;
}
@Override
public OCommandContext getContext() {
if (context == null)
context = new OBasicCommandContext();
return context;
}
public OCommandRequestAbstract setContext(final OCommandContext iContext) {
context = iContext;
return this;
}
public long getTimeoutTime() {
return timeoutMs;
}
public void setTimeout(final long timeout, TIMEOUT_STRATEGY strategy) {
this.timeoutMs = timeout;
this.timeoutStrategy = strategy;
}
public TIMEOUT_STRATEGY getTimeoutStrategy() {
return timeoutStrategy;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_command_OCommandRequestAbstract.java |
1,129 | public static class Factory implements NativeScriptFactory {
@Override
public ExecutableScript newScript(@Nullable Map<String, Object> params) {
return new NativeNaiveTFIDFScoreScript(params);
}
} | 0true
| src_test_java_org_elasticsearch_benchmark_scripts_score_script_NativeNaiveTFIDFScoreScript.java |
555 | public class ClientTxnSetProxy<E> extends AbstractClientTxnCollectionProxy<E> implements TransactionalSet<E> {
public ClientTxnSetProxy(String name, TransactionContextProxy proxy) {
super(name, proxy);
}
public boolean add(E e) {
throwExceptionIfNull(e);
final Data value = toData(e);
final TxnSetAddRequest request = new TxnSetAddRequest(getName(), value);
final Boolean result = invoke(request);
return result;
}
public boolean remove(E e) {
throwExceptionIfNull(e);
final Data value = toData(e);
final TxnSetRemoveRequest request = new TxnSetRemoveRequest(getName(), value);
final Boolean result = invoke(request);
return result;
}
public int size() {
final TxnSetSizeRequest request = new TxnSetSizeRequest(getName());
final Integer result = invoke(request);
return result;
}
public String getServiceName() {
return SetService.SERVICE_NAME;
}
} | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_txn_proxy_ClientTxnSetProxy.java |
62 | public class OModificationOperationProhibitedException extends OException {
private static final long serialVersionUID = 1L;
public OModificationOperationProhibitedException() {
}
public OModificationOperationProhibitedException(String message) {
super(message);
}
public OModificationOperationProhibitedException(Throwable cause) {
super(cause);
}
public OModificationOperationProhibitedException(String message, Throwable cause) {
super(message, cause);
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_concur_lock_OModificationOperationProhibitedException.java |
631 | public class IndexShardStatus implements Iterable<ShardStatus> {
private final ShardId shardId;
private final ShardStatus[] shards;
IndexShardStatus(ShardId shardId, ShardStatus[] shards) {
this.shardId = shardId;
this.shards = shards;
}
public ShardId getShardId() {
return this.shardId;
}
public ShardStatus[] getShards() {
return this.shards;
}
public ShardStatus getAt(int position) {
return shards[position];
}
/**
* Returns only the primary shards store size in bytes.
*/
public ByteSizeValue getPrimaryStoreSize() {
long bytes = -1;
for (ShardStatus shard : getShards()) {
if (!shard.getShardRouting().primary()) {
// only sum docs for the primaries
continue;
}
if (shard.getStoreSize() != null) {
if (bytes == -1) {
bytes = 0;
}
bytes += shard.getStoreSize().bytes();
}
}
if (bytes == -1) {
return null;
}
return new ByteSizeValue(bytes);
}
/**
* Returns the full store size in bytes, of both primaries and replicas.
*/
public ByteSizeValue getStoreSize() {
long bytes = -1;
for (ShardStatus shard : getShards()) {
if (shard.getStoreSize() != null) {
if (bytes == -1) {
bytes = 0;
}
bytes += shard.getStoreSize().bytes();
}
}
if (bytes == -1) {
return null;
}
return new ByteSizeValue(bytes);
}
public long getTranslogOperations() {
long translogOperations = -1;
for (ShardStatus shard : getShards()) {
if (shard.getTranslogOperations() != -1) {
if (translogOperations == -1) {
translogOperations = 0;
}
translogOperations += shard.getTranslogOperations();
}
}
return translogOperations;
}
private transient DocsStatus docs;
public DocsStatus getDocs() {
if (docs != null) {
return docs;
}
DocsStatus docs = null;
for (ShardStatus shard : getShards()) {
if (!shard.getShardRouting().primary()) {
// only sum docs for the primaries
continue;
}
if (shard.getDocs() == null) {
continue;
}
if (docs == null) {
docs = new DocsStatus();
}
docs.numDocs += shard.getDocs().getNumDocs();
docs.maxDoc += shard.getDocs().getMaxDoc();
docs.deletedDocs += shard.getDocs().getDeletedDocs();
}
this.docs = docs;
return this.docs;
}
/**
* Total merges of this shard replication group.
*/
public MergeStats getMergeStats() {
MergeStats mergeStats = new MergeStats();
for (ShardStatus shard : shards) {
mergeStats.add(shard.getMergeStats());
}
return mergeStats;
}
public RefreshStats getRefreshStats() {
RefreshStats refreshStats = new RefreshStats();
for (ShardStatus shard : shards) {
refreshStats.add(shard.getRefreshStats());
}
return refreshStats;
}
public FlushStats getFlushStats() {
FlushStats flushStats = new FlushStats();
for (ShardStatus shard : shards) {
flushStats.add(shard.flushStats);
}
return flushStats;
}
@Override
public Iterator<ShardStatus> iterator() {
return Iterators.forArray(shards);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_status_IndexShardStatus.java |
3,358 | abstract class BasicInvocation implements ResponseHandler, Runnable {
private final static AtomicReferenceFieldUpdater RESPONSE_RECEIVED_FIELD_UPDATER =
AtomicReferenceFieldUpdater.newUpdater(BasicInvocation.class, Boolean.class, "responseReceived");
static final Object NULL_RESPONSE = new InternalResponse("Invocation::NULL_RESPONSE");
static final Object RETRY_RESPONSE = new InternalResponse("Invocation::RETRY_RESPONSE");
static final Object WAIT_RESPONSE = new InternalResponse("Invocation::WAIT_RESPONSE");
static final Object TIMEOUT_RESPONSE = new InternalResponse("Invocation::TIMEOUT_RESPONSE");
static final Object INTERRUPTED_RESPONSE = new InternalResponse("Invocation::INTERRUPTED_RESPONSE");
static class InternalResponse {
private String toString;
private InternalResponse(String toString) {
this.toString = toString;
}
@Override
public String toString() {
return toString;
}
}
private static final long MIN_TIMEOUT = 10000;
protected final long callTimeout;
protected final NodeEngineImpl nodeEngine;
protected final String serviceName;
protected final Operation op;
protected final int partitionId;
protected final int replicaIndex;
protected final int tryCount;
protected final long tryPauseMillis;
protected final ILogger logger;
private final BasicInvocationFuture invocationFuture;
//needs to be a Boolean because it is updated through the RESPONSE_RECEIVED_FIELD_UPDATER
private volatile Boolean responseReceived = Boolean.FALSE;
private volatile int invokeCount = 0;
boolean remote = false;
private final String executorName;
final boolean resultDeserialized;
private Address invTarget;
private MemberImpl invTargetMember;
volatile int backupsCompleted;
volatile NormalResponse potentialResponse;
volatile int backupsExpected;
BasicInvocation(NodeEngineImpl nodeEngine, String serviceName, Operation op, int partitionId,
int replicaIndex, int tryCount, long tryPauseMillis, long callTimeout, Callback<Object> callback,
String executorName, boolean resultDeserialized) {
this.logger = nodeEngine.getLogger(BasicInvocation.class);
this.nodeEngine = nodeEngine;
this.serviceName = serviceName;
this.op = op;
this.partitionId = partitionId;
this.replicaIndex = replicaIndex;
this.tryCount = tryCount;
this.tryPauseMillis = tryPauseMillis;
this.callTimeout = getCallTimeout(callTimeout);
this.invocationFuture = new BasicInvocationFuture(this, callback);
this.executorName = executorName;
this.resultDeserialized = resultDeserialized;
}
abstract ExceptionAction onException(Throwable t);
public String getServiceName() {
return serviceName;
}
InternalPartition getPartition() {
return nodeEngine.getPartitionService().getPartition(partitionId);
}
public int getReplicaIndex() {
return replicaIndex;
}
public int getPartitionId() {
return partitionId;
}
ExecutorService getAsyncExecutor() {
return nodeEngine.getExecutionService().getExecutor(ExecutionService.ASYNC_EXECUTOR);
}
private long getCallTimeout(long callTimeout) {
if (callTimeout > 0) {
return callTimeout;
}
BasicOperationService operationService = (BasicOperationService) nodeEngine.operationService;
final long defaultCallTimeout = operationService.getDefaultCallTimeout();
if (op instanceof WaitSupport) {
final long waitTimeoutMillis = op.getWaitTimeout();
if (waitTimeoutMillis > 0 && waitTimeoutMillis < Long.MAX_VALUE) {
/*
* final long minTimeout = Math.min(defaultCallTimeout, MIN_TIMEOUT);
* long callTimeout = Math.min(waitTimeoutMillis, defaultCallTimeout);
* callTimeout = Math.max(a, minTimeout);
* return callTimeout;
*
* Below two lines are shortened version of above*
* using min(max(x,y),z)=max(min(x,z),min(y,z))
*/
final long max = Math.max(waitTimeoutMillis, MIN_TIMEOUT);
return Math.min(max, defaultCallTimeout);
}
}
return defaultCallTimeout;
}
public final BasicInvocationFuture invoke() {
if (invokeCount > 0) { // no need to be pessimistic.
throw new IllegalStateException("An invocation can not be invoked more than once!");
}
if (op.getCallId() != 0) {
throw new IllegalStateException("An operation[" + op + "] can not be used for multiple invocations!");
}
try {
setCallTimeout(op, callTimeout);
setCallerAddress(op, nodeEngine.getThisAddress());
op.setNodeEngine(nodeEngine)
.setServiceName(serviceName)
.setPartitionId(partitionId)
.setReplicaIndex(replicaIndex)
.setExecutorName(executorName);
if (op.getCallerUuid() == null) {
op.setCallerUuid(nodeEngine.getLocalMember().getUuid());
}
BasicOperationService operationService = (BasicOperationService) nodeEngine.operationService;
if (!operationService.scheduler.isInvocationAllowedFromCurrentThread(op) && !isMigrationOperation(op)) {
throw new IllegalThreadStateException(Thread.currentThread() + " cannot make remote call: " + op);
}
doInvoke();
} catch (Exception e) {
if (e instanceof RetryableException) {
notify(e);
} else {
throw ExceptionUtil.rethrow(e);
}
}
return invocationFuture;
}
private void resetAndReInvoke() {
invokeCount = 0;
potentialResponse = null;
backupsExpected = -1;
doInvoke();
}
private void doInvoke() {
if (!nodeEngine.isActive()) {
remote = false;
notify(new HazelcastInstanceNotActiveException());
return;
}
invTarget = getTarget();
invokeCount++;
final Address thisAddress = nodeEngine.getThisAddress();
if (invTarget == null) {
remote = false;
if (nodeEngine.isActive()) {
notify(new WrongTargetException(thisAddress, null, partitionId, replicaIndex, op.getClass().getName(), serviceName));
} else {
notify(new HazelcastInstanceNotActiveException());
}
return;
}
invTargetMember = nodeEngine.getClusterService().getMember(invTarget);
if (!isJoinOperation(op) && invTargetMember == null) {
notify(new TargetNotMemberException(invTarget, partitionId, op.getClass().getName(), serviceName));
return;
}
if (op.getPartitionId() != partitionId) {
notify(new IllegalStateException("Partition id of operation: " + op.getPartitionId() +
" is not equal to the partition id of invocation: " + partitionId));
return;
}
if (op.getReplicaIndex() != replicaIndex) {
notify(new IllegalStateException("Replica index of operation: " + op.getReplicaIndex() +
" is not equal to the replica index of invocation: " + replicaIndex));
return;
}
final BasicOperationService operationService = (BasicOperationService) nodeEngine.operationService;
setInvocationTime(op, nodeEngine.getClusterTime());
remote = !thisAddress.equals(invTarget);
if (remote) {
final long callId = operationService.registerInvocation(this);
boolean sent = operationService.send(op, invTarget);
if (!sent) {
operationService.deregisterInvocation(callId);
notify(new RetryableIOException("Packet not send to -> " + invTarget));
}
} else {
if (op instanceof BackupAwareOperation) {
operationService.registerInvocation(this);
}
responseReceived = Boolean.FALSE;
op.setResponseHandler(this);
//todo: should move to the operationService.
if (operationService.scheduler.isAllowedToRunInCurrentThread(op)) {
operationService.runOperationOnCallingThread(op);
} else {
operationService.executeOperation(op);
}
}
}
private static Throwable getError(Object obj) {
if (obj == null) {
return null;
}
if (obj instanceof Throwable) {
return (Throwable) obj;
}
if (!(obj instanceof NormalResponse)) {
return null;
}
NormalResponse response = (NormalResponse) obj;
if (!(response.getValue() instanceof Throwable)) {
return null;
}
return (Throwable) response.getValue();
}
@Override
public void sendResponse(Object obj) {
if (!RESPONSE_RECEIVED_FIELD_UPDATER.compareAndSet(this, Boolean.FALSE, Boolean.TRUE)) {
throw new ResponseAlreadySentException("NormalResponse already responseReceived for callback: " + this
+ ", current-response: : " + obj);
}
notify(obj);
}
@Override
public boolean isLocal() {
return true;
}
public boolean isCallTarget(MemberImpl leftMember) {
if (invTargetMember == null) {
return leftMember.getAddress().equals(invTarget);
} else {
return leftMember.getUuid().equals(invTargetMember.getUuid());
}
}
//this method is called by the operation service to signal the invocation that something has happened, e.g.
//a response is returned.
//@Override
public void notify(Object obj) {
Object response = resolveResponse(obj);
if (response == RETRY_RESPONSE) {
handleRetryResponse();
return;
}
if (response == WAIT_RESPONSE) {
handleWaitResponse();
return;
}
//if a regular response came and there are backups, we need to wait for the backs.
//when the backups complete, the response will be send by the last backup.
if (response instanceof NormalResponse && op instanceof BackupAwareOperation) {
final NormalResponse resp = (NormalResponse) response;
if (resp.getBackupCount() > 0) {
waitForBackups(resp.getBackupCount(), 5, TimeUnit.SECONDS, resp);
return;
}
}
//we don't need to wait for a backup, so we can set the response immediately.
invocationFuture.set(response);
}
private void handleWaitResponse() {
invocationFuture.set(WAIT_RESPONSE);
}
private void handleRetryResponse() {
if (invocationFuture.interrupted) {
invocationFuture.set(INTERRUPTED_RESPONSE);
} else {
invocationFuture.set(WAIT_RESPONSE);
final ExecutionService ex = nodeEngine.getExecutionService();
// fast retry for the first few invocations
if (invokeCount < 5) {
getAsyncExecutor().execute(this);
} else {
ex.schedule(ExecutionService.ASYNC_EXECUTOR, this, tryPauseMillis, TimeUnit.MILLISECONDS);
}
}
}
private Object resolveResponse(Object obj) {
if (obj == null) {
return NULL_RESPONSE;
}
Throwable error = getError(obj);
if (error == null) {
return obj;
}
if (error instanceof CallTimeoutException) {
if (logger.isFinestEnabled()) {
logger.finest("Call timed-out during wait-notify phase, retrying call: " + toString());
}
if (op instanceof WaitSupport) {
// decrement wait-timeout by call-timeout
long waitTimeout = op.getWaitTimeout();
waitTimeout -= callTimeout;
op.setWaitTimeout(waitTimeout);
}
invokeCount--;
return RETRY_RESPONSE;
}
final ExceptionAction action = onException(error);
final int localInvokeCount = invokeCount;
if (action == ExceptionAction.RETRY_INVOCATION && localInvokeCount < tryCount) {
if (localInvokeCount > 99 && localInvokeCount % 10 == 0) {
logger.warning("Retrying invocation: " + toString() + ", Reason: " + error);
}
return RETRY_RESPONSE;
}
if (action == ExceptionAction.CONTINUE_WAIT) {
return WAIT_RESPONSE;
}
return error;
}
protected abstract Address getTarget();
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("BasicInvocation");
sb.append("{ serviceName='").append(serviceName).append('\'');
sb.append(", op=").append(op);
sb.append(", partitionId=").append(partitionId);
sb.append(", replicaIndex=").append(replicaIndex);
sb.append(", tryCount=").append(tryCount);
sb.append(", tryPauseMillis=").append(tryPauseMillis);
sb.append(", invokeCount=").append(invokeCount);
sb.append(", callTimeout=").append(callTimeout);
sb.append(", target=").append(invTarget);
sb.append('}');
return sb.toString();
}
//backupsCompleted is incremented while a lock is hold.
@edu.umd.cs.findbugs.annotations.SuppressWarnings("VO_VOLATILE_INCREMENT")
public void signalOneBackupComplete() {
synchronized (this) {
backupsCompleted++;
if (backupsExpected == -1) {
return;
}
if (backupsExpected != backupsCompleted) {
return;
}
if (potentialResponse != null) {
invocationFuture.set(potentialResponse);
}
}
}
private void waitForBackups(int backupCount, long timeout, TimeUnit unit, NormalResponse response) {
synchronized (this) {
this.backupsExpected = backupCount;
if (backupsCompleted == backupsExpected) {
invocationFuture.set(response);
return;
}
this.potentialResponse = response;
}
nodeEngine.getExecutionService().schedule(ExecutionService.ASYNC_EXECUTOR, new Runnable() {
@Override
public void run() {
synchronized (BasicInvocation.this) {
if (backupsExpected == backupsCompleted) {
return;
}
}
if (nodeEngine.getClusterService().getMember(invTarget) != null) {
synchronized (BasicInvocation.this) {
if (BasicInvocation.this.potentialResponse != null) {
invocationFuture.set(BasicInvocation.this.potentialResponse);
BasicInvocation.this.potentialResponse = null;
}
}
return;
}
resetAndReInvoke();
}
}, timeout, unit);
}
@Override
public void run() {
doInvoke();
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_spi_impl_BasicInvocation.java |
105 | static class MapInterceptorImpl implements MapInterceptor {
MapInterceptorImpl() {
}
public Object interceptGet(Object value) {
if ("value1".equals(value)) {
return "getIntercepted";
}
return null;
}
public void afterGet(Object value) {
}
public Object interceptPut(Object oldValue, Object newValue) {
if ("oldValue".equals(oldValue) && "newValue".equals(newValue)) {
return "putIntercepted";
}
return null;
}
public void afterPut(Object value) {
}
public Object interceptRemove(Object removedValue) {
if ("value2".equals(removedValue)) {
return "removeIntercepted";
}
return null;
}
public void afterRemove(Object value) {
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_ClientIssueTest.java |
429 | public enum AddMethodType {
PERSIST,
LOOKUP
} | 0true
| common_src_main_java_org_broadleafcommerce_common_presentation_client_AddMethodType.java |
655 | constructors[COLLECTION_CONTAINS] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new CollectionContainsOperation();
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java |
1,533 | public class ThrottlingAllocationTests extends ElasticsearchAllocationTestCase {
private final ESLogger logger = Loggers.getLogger(ThrottlingAllocationTests.class);
@Test
public void testPrimaryRecoveryThrottling() {
AllocationService strategy = createAllocationService(settingsBuilder()
.put("cluster.routing.allocation.node_concurrent_recoveries", 3)
.put("cluster.routing.allocation.node_initial_primaries_recoveries", 3)
.build());
logger.info("Building initial routing table");
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test").numberOfShards(10).numberOfReplicas(1))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test"))
.build();
ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build();
logger.info("start one node, do reroute, only 3 should initialize");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1"))).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(routingTable.shardsWithState(STARTED).size(), equalTo(0));
assertThat(routingTable.shardsWithState(INITIALIZING).size(), equalTo(3));
assertThat(routingTable.shardsWithState(UNASSIGNED).size(), equalTo(17));
logger.info("start initializing, another 3 should initialize");
routingTable = strategy.applyStartedShards(clusterState, routingTable.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(routingTable.shardsWithState(STARTED).size(), equalTo(3));
assertThat(routingTable.shardsWithState(INITIALIZING).size(), equalTo(3));
assertThat(routingTable.shardsWithState(UNASSIGNED).size(), equalTo(14));
logger.info("start initializing, another 3 should initialize");
routingTable = strategy.applyStartedShards(clusterState, routingTable.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(routingTable.shardsWithState(STARTED).size(), equalTo(6));
assertThat(routingTable.shardsWithState(INITIALIZING).size(), equalTo(3));
assertThat(routingTable.shardsWithState(UNASSIGNED).size(), equalTo(11));
logger.info("start initializing, another 1 should initialize");
routingTable = strategy.applyStartedShards(clusterState, routingTable.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(routingTable.shardsWithState(STARTED).size(), equalTo(9));
assertThat(routingTable.shardsWithState(INITIALIZING).size(), equalTo(1));
assertThat(routingTable.shardsWithState(UNASSIGNED).size(), equalTo(10));
logger.info("start initializing, all primaries should be started");
routingTable = strategy.applyStartedShards(clusterState, routingTable.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(routingTable.shardsWithState(STARTED).size(), equalTo(10));
assertThat(routingTable.shardsWithState(INITIALIZING).size(), equalTo(0));
assertThat(routingTable.shardsWithState(UNASSIGNED).size(), equalTo(10));
}
@Test
public void testReplicaAndPrimaryRecoveryThrottling() {
AllocationService strategy = createAllocationService(settingsBuilder()
.put("cluster.routing.allocation.concurrent_recoveries", 3)
.put("cluster.routing.allocation.node_initial_primaries_recoveries", 3)
.build());
logger.info("Building initial routing table");
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test").numberOfShards(5).numberOfReplicas(1))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test"))
.build();
ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build();
logger.info("start one node, do reroute, only 3 should initialize");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1"))).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(routingTable.shardsWithState(STARTED).size(), equalTo(0));
assertThat(routingTable.shardsWithState(INITIALIZING).size(), equalTo(3));
assertThat(routingTable.shardsWithState(UNASSIGNED).size(), equalTo(7));
logger.info("start initializing, another 2 should initialize");
routingTable = strategy.applyStartedShards(clusterState, routingTable.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(routingTable.shardsWithState(STARTED).size(), equalTo(3));
assertThat(routingTable.shardsWithState(INITIALIZING).size(), equalTo(2));
assertThat(routingTable.shardsWithState(UNASSIGNED).size(), equalTo(5));
logger.info("start initializing, all primaries should be started");
routingTable = strategy.applyStartedShards(clusterState, routingTable.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(routingTable.shardsWithState(STARTED).size(), equalTo(5));
assertThat(routingTable.shardsWithState(INITIALIZING).size(), equalTo(0));
assertThat(routingTable.shardsWithState(UNASSIGNED).size(), equalTo(5));
logger.info("start another node, replicas should start being allocated");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node2"))).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(routingTable.shardsWithState(STARTED).size(), equalTo(5));
assertThat(routingTable.shardsWithState(INITIALIZING).size(), equalTo(3));
assertThat(routingTable.shardsWithState(UNASSIGNED).size(), equalTo(2));
logger.info("start initializing replicas");
routingTable = strategy.applyStartedShards(clusterState, routingTable.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(routingTable.shardsWithState(STARTED).size(), equalTo(8));
assertThat(routingTable.shardsWithState(INITIALIZING).size(), equalTo(2));
assertThat(routingTable.shardsWithState(UNASSIGNED).size(), equalTo(0));
logger.info("start initializing replicas, all should be started");
routingTable = strategy.applyStartedShards(clusterState, routingTable.shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
assertThat(routingTable.shardsWithState(STARTED).size(), equalTo(10));
assertThat(routingTable.shardsWithState(INITIALIZING).size(), equalTo(0));
assertThat(routingTable.shardsWithState(UNASSIGNED).size(), equalTo(0));
}
} | 0true
| src_test_java_org_elasticsearch_cluster_routing_allocation_ThrottlingAllocationTests.java |
3,761 | public class LogByteSizeMergePolicyProvider extends AbstractMergePolicyProvider<LogByteSizeMergePolicy> {
private final IndexSettingsService indexSettingsService;
private volatile ByteSizeValue minMergeSize;
private volatile ByteSizeValue maxMergeSize;
private volatile int mergeFactor;
private volatile int maxMergeDocs;
private final boolean calibrateSizeByDeletes;
private boolean asyncMerge;
private final Set<CustomLogByteSizeMergePolicy> policies = new CopyOnWriteArraySet<CustomLogByteSizeMergePolicy>();
private final ApplySettings applySettings = new ApplySettings();
@Inject
public LogByteSizeMergePolicyProvider(Store store, IndexSettingsService indexSettingsService) {
super(store);
Preconditions.checkNotNull(store, "Store must be provided to merge policy");
this.indexSettingsService = indexSettingsService;
this.minMergeSize = componentSettings.getAsBytesSize("min_merge_size", new ByteSizeValue((long) (LogByteSizeMergePolicy.DEFAULT_MIN_MERGE_MB * 1024 * 1024), ByteSizeUnit.BYTES));
this.maxMergeSize = componentSettings.getAsBytesSize("max_merge_size", new ByteSizeValue((long) LogByteSizeMergePolicy.DEFAULT_MAX_MERGE_MB, ByteSizeUnit.MB));
this.mergeFactor = componentSettings.getAsInt("merge_factor", LogByteSizeMergePolicy.DEFAULT_MERGE_FACTOR);
this.maxMergeDocs = componentSettings.getAsInt("max_merge_docs", LogByteSizeMergePolicy.DEFAULT_MAX_MERGE_DOCS);
this.calibrateSizeByDeletes = componentSettings.getAsBoolean("calibrate_size_by_deletes", true);
this.asyncMerge = indexSettings.getAsBoolean("index.merge.async", true);
logger.debug("using [log_bytes_size] merge policy with merge_factor[{}], min_merge_size[{}], max_merge_size[{}], max_merge_docs[{}], calibrate_size_by_deletes[{}], async_merge[{}]",
mergeFactor, minMergeSize, maxMergeSize, maxMergeDocs, calibrateSizeByDeletes, asyncMerge);
indexSettingsService.addListener(applySettings);
}
@Override
public LogByteSizeMergePolicy newMergePolicy() {
CustomLogByteSizeMergePolicy mergePolicy;
if (asyncMerge) {
mergePolicy = new EnableMergeLogByteSizeMergePolicy(this);
} else {
mergePolicy = new CustomLogByteSizeMergePolicy(this);
}
mergePolicy.setMinMergeMB(minMergeSize.mbFrac());
mergePolicy.setMaxMergeMB(maxMergeSize.mbFrac());
mergePolicy.setMergeFactor(mergeFactor);
mergePolicy.setMaxMergeDocs(maxMergeDocs);
mergePolicy.setCalibrateSizeByDeletes(calibrateSizeByDeletes);
mergePolicy.setNoCFSRatio(noCFSRatio);
policies.add(mergePolicy);
return mergePolicy;
}
@Override
public void close() throws ElasticsearchException {
indexSettingsService.removeListener(applySettings);
}
public static final String INDEX_MERGE_POLICY_MIN_MERGE_SIZE = "index.merge.policy.min_merge_size";
public static final String INDEX_MERGE_POLICY_MAX_MERGE_SIZE = "index.merge.policy.max_merge_size";
public static final String INDEX_MERGE_POLICY_MAX_MERGE_DOCS = "index.merge.policy.max_merge_docs";
public static final String INDEX_MERGE_POLICY_MERGE_FACTOR = "index.merge.policy.merge_factor";
class ApplySettings implements IndexSettingsService.Listener {
@Override
public void onRefreshSettings(Settings settings) {
ByteSizeValue minMergeSize = settings.getAsBytesSize(INDEX_MERGE_POLICY_MIN_MERGE_SIZE, LogByteSizeMergePolicyProvider.this.minMergeSize);
if (!minMergeSize.equals(LogByteSizeMergePolicyProvider.this.minMergeSize)) {
logger.info("updating min_merge_size from [{}] to [{}]", LogByteSizeMergePolicyProvider.this.minMergeSize, minMergeSize);
LogByteSizeMergePolicyProvider.this.minMergeSize = minMergeSize;
for (CustomLogByteSizeMergePolicy policy : policies) {
policy.setMinMergeMB(minMergeSize.mbFrac());
}
}
ByteSizeValue maxMergeSize = settings.getAsBytesSize(INDEX_MERGE_POLICY_MAX_MERGE_SIZE, LogByteSizeMergePolicyProvider.this.maxMergeSize);
if (!maxMergeSize.equals(LogByteSizeMergePolicyProvider.this.maxMergeSize)) {
logger.info("updating max_merge_size from [{}] to [{}]", LogByteSizeMergePolicyProvider.this.maxMergeSize, maxMergeSize);
LogByteSizeMergePolicyProvider.this.maxMergeSize = maxMergeSize;
for (CustomLogByteSizeMergePolicy policy : policies) {
policy.setMaxMergeMB(maxMergeSize.mbFrac());
}
}
int maxMergeDocs = settings.getAsInt(INDEX_MERGE_POLICY_MAX_MERGE_DOCS, LogByteSizeMergePolicyProvider.this.maxMergeDocs);
if (maxMergeDocs != LogByteSizeMergePolicyProvider.this.maxMergeDocs) {
logger.info("updating max_merge_docs from [{}] to [{}]", LogByteSizeMergePolicyProvider.this.maxMergeDocs, maxMergeDocs);
LogByteSizeMergePolicyProvider.this.maxMergeDocs = maxMergeDocs;
for (CustomLogByteSizeMergePolicy policy : policies) {
policy.setMaxMergeDocs(maxMergeDocs);
}
}
int mergeFactor = settings.getAsInt(INDEX_MERGE_POLICY_MERGE_FACTOR, LogByteSizeMergePolicyProvider.this.mergeFactor);
if (mergeFactor != LogByteSizeMergePolicyProvider.this.mergeFactor) {
logger.info("updating merge_factor from [{}] to [{}]", LogByteSizeMergePolicyProvider.this.mergeFactor, mergeFactor);
LogByteSizeMergePolicyProvider.this.mergeFactor = mergeFactor;
for (CustomLogByteSizeMergePolicy policy : policies) {
policy.setMergeFactor(mergeFactor);
}
}
final double noCFSRatio = parseNoCFSRatio(settings.get(INDEX_COMPOUND_FORMAT, Double.toString(LogByteSizeMergePolicyProvider.this.noCFSRatio)));
if (noCFSRatio != LogByteSizeMergePolicyProvider.this.noCFSRatio) {
logger.info("updating index.compound_format from [{}] to [{}]", formatNoCFSRatio(LogByteSizeMergePolicyProvider.this.noCFSRatio), formatNoCFSRatio(noCFSRatio));
LogByteSizeMergePolicyProvider.this.noCFSRatio = noCFSRatio;
for (CustomLogByteSizeMergePolicy policy : policies) {
policy.setNoCFSRatio(noCFSRatio);
}
}
}
}
public static class CustomLogByteSizeMergePolicy extends LogByteSizeMergePolicy {
private final LogByteSizeMergePolicyProvider provider;
public CustomLogByteSizeMergePolicy(LogByteSizeMergePolicyProvider provider) {
super();
this.provider = provider;
}
@Override
public void close() {
super.close();
provider.policies.remove(this);
}
@Override
public MergePolicy clone() {
// Lucene IW makes a clone internally but since we hold on to this instance
// the clone will just be the identity.
return this;
}
}
public static class EnableMergeLogByteSizeMergePolicy extends CustomLogByteSizeMergePolicy {
public EnableMergeLogByteSizeMergePolicy(LogByteSizeMergePolicyProvider provider) {
super(provider);
}
@Override
public MergeSpecification findMerges(MergeTrigger trigger, SegmentInfos infos) throws IOException {
// we don't enable merges while indexing documents, we do them in the background
if (trigger == MergeTrigger.SEGMENT_FLUSH) {
return null;
}
return super.findMerges(trigger, infos);
}
}
} | 1no label
| src_main_java_org_elasticsearch_index_merge_policy_LogByteSizeMergePolicyProvider.java |
4,417 | public class IndicesFilterCache extends AbstractComponent implements RemovalListener<WeightedFilterCache.FilterCacheKey, DocIdSet> {
private final ThreadPool threadPool;
private final CacheRecycler cacheRecycler;
private Cache<WeightedFilterCache.FilterCacheKey, DocIdSet> cache;
private volatile String size;
private volatile long sizeInBytes;
private volatile TimeValue expire;
private final TimeValue cleanInterval;
private final Set<Object> readersKeysToClean = ConcurrentCollections.newConcurrentSet();
private volatile boolean closed;
public static final String INDICES_CACHE_FILTER_SIZE = "indices.cache.filter.size";
public static final String INDICES_CACHE_FILTER_EXPIRE = "indices.cache.filter.expire";
class ApplySettings implements NodeSettingsService.Listener {
@Override
public void onRefreshSettings(Settings settings) {
boolean replace = false;
String size = settings.get(INDICES_CACHE_FILTER_SIZE, IndicesFilterCache.this.size);
if (!size.equals(IndicesFilterCache.this.size)) {
logger.info("updating [indices.cache.filter.size] from [{}] to [{}]", IndicesFilterCache.this.size, size);
IndicesFilterCache.this.size = size;
replace = true;
}
TimeValue expire = settings.getAsTime(INDICES_CACHE_FILTER_EXPIRE, IndicesFilterCache.this.expire);
if (!Objects.equal(expire, IndicesFilterCache.this.expire)) {
logger.info("updating [indices.cache.filter.expire] from [{}] to [{}]", IndicesFilterCache.this.expire, expire);
IndicesFilterCache.this.expire = expire;
replace = true;
}
if (replace) {
Cache<WeightedFilterCache.FilterCacheKey, DocIdSet> oldCache = IndicesFilterCache.this.cache;
computeSizeInBytes();
buildCache();
oldCache.invalidateAll();
}
}
}
@Inject
public IndicesFilterCache(Settings settings, ThreadPool threadPool, CacheRecycler cacheRecycler, NodeSettingsService nodeSettingsService) {
super(settings);
this.threadPool = threadPool;
this.cacheRecycler = cacheRecycler;
this.size = componentSettings.get("size", "20%");
this.expire = componentSettings.getAsTime("expire", null);
this.cleanInterval = componentSettings.getAsTime("clean_interval", TimeValue.timeValueSeconds(60));
computeSizeInBytes();
buildCache();
logger.debug("using [node] weighted filter cache with size [{}], actual_size [{}], expire [{}], clean_interval [{}]",
size, new ByteSizeValue(sizeInBytes), expire, cleanInterval);
nodeSettingsService.addListener(new ApplySettings());
threadPool.schedule(cleanInterval, ThreadPool.Names.SAME, new ReaderCleaner());
}
private void buildCache() {
CacheBuilder<WeightedFilterCache.FilterCacheKey, DocIdSet> cacheBuilder = CacheBuilder.newBuilder()
.removalListener(this)
.maximumWeight(sizeInBytes).weigher(new WeightedFilterCache.FilterCacheValueWeigher());
// defaults to 4, but this is a busy map for all indices, increase it a bit
cacheBuilder.concurrencyLevel(16);
if (expire != null) {
cacheBuilder.expireAfterAccess(expire.millis(), TimeUnit.MILLISECONDS);
}
cache = cacheBuilder.build();
}
private void computeSizeInBytes() {
this.sizeInBytes = MemorySizeValue.parseBytesSizeValueOrHeapRatio(size).bytes();
}
public void addReaderKeyToClean(Object readerKey) {
readersKeysToClean.add(readerKey);
}
public void close() {
closed = true;
cache.invalidateAll();
}
public Cache<WeightedFilterCache.FilterCacheKey, DocIdSet> cache() {
return this.cache;
}
@Override
public void onRemoval(RemovalNotification<WeightedFilterCache.FilterCacheKey, DocIdSet> removalNotification) {
WeightedFilterCache.FilterCacheKey key = removalNotification.getKey();
if (key == null) {
return;
}
if (key.removalListener != null) {
key.removalListener.onRemoval(removalNotification);
}
}
/**
* The reason we need this class is because we need to clean all the filters that are associated
* with a reader. We don't want to do it every time a reader closes, since iterating over all the map
* is expensive. There doesn't seem to be a nicer way to do it (and maintaining a list per reader
* of the filters will cost more).
*/
class ReaderCleaner implements Runnable {
@Override
public void run() {
if (closed) {
return;
}
if (readersKeysToClean.isEmpty()) {
schedule();
return;
}
try {
threadPool.executor(ThreadPool.Names.GENERIC).execute(new Runnable() {
@Override
public void run() {
Recycler.V<ObjectOpenHashSet<Object>> keys = cacheRecycler.hashSet(-1);
try {
for (Iterator<Object> it = readersKeysToClean.iterator(); it.hasNext(); ) {
keys.v().add(it.next());
it.remove();
}
cache.cleanUp();
if (!keys.v().isEmpty()) {
for (Iterator<WeightedFilterCache.FilterCacheKey> it = cache.asMap().keySet().iterator(); it.hasNext(); ) {
WeightedFilterCache.FilterCacheKey filterCacheKey = it.next();
if (keys.v().contains(filterCacheKey.readerKey())) {
// same as invalidate
it.remove();
}
}
}
schedule();
} finally {
keys.release();
}
}
});
} catch (EsRejectedExecutionException ex) {
logger.debug("Can not run ReaderCleaner - execution rejected", ex);
}
}
private void schedule() {
try {
threadPool.schedule(cleanInterval, ThreadPool.Names.SAME, this);
} catch (EsRejectedExecutionException ex) {
logger.debug("Can not schedule ReaderCleaner - execution rejected", ex);
}
}
}
} | 1no label
| src_main_java_org_elasticsearch_indices_cache_filter_IndicesFilterCache.java |
594 | public class IndicesSegmentsAction extends IndicesAction<IndicesSegmentsRequest, IndicesSegmentResponse, IndicesSegmentsRequestBuilder> {
public static final IndicesSegmentsAction INSTANCE = new IndicesSegmentsAction();
public static final String NAME = "indices/segments";
private IndicesSegmentsAction() {
super(NAME);
}
@Override
public IndicesSegmentResponse newResponse() {
return new IndicesSegmentResponse();
}
@Override
public IndicesSegmentsRequestBuilder newRequestBuilder(IndicesAdminClient client) {
return new IndicesSegmentsRequestBuilder(client);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_segments_IndicesSegmentsAction.java |
1,120 | public class OSQLFunctionDate extends OSQLFunctionAbstract {
public static final String NAME = "date";
private Date date;
private SimpleDateFormat format;
/**
* Get the date at construction to have the same date for all the iteration.
*/
public OSQLFunctionDate() {
super(NAME, 0, 3);
date = new Date();
}
public Object execute(final OIdentifiable iCurrentRecord, final Object iCurrentResult, final Object[] iParameters,
OCommandContext iContext) {
if (iParameters.length == 0)
return date;
if (iParameters[0] instanceof Number)
return new Date(((Number) iParameters[0]).longValue());
if (format == null) {
if (iParameters.length > 1) {
format = new SimpleDateFormat((String) iParameters[1]);
format.setTimeZone(ODateHelper.getDatabaseTimeZone());
} else
format = ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getConfiguration().getDateTimeFormatInstance();
if (iParameters.length == 3)
format.setTimeZone(TimeZone.getTimeZone(iParameters[2].toString()));
}
try {
return format.parse((String) iParameters[0]);
} catch (ParseException e) {
throw new OQueryParsingException("Error on formatting date '" + iParameters[0] + "' using the format: " + format, e);
}
}
public boolean aggregateResults(final Object[] configuredParameters) {
return false;
}
public String getSyntax() {
return "Syntax error: date([<date-as-string>] [,<format>] [,<timezone>])";
}
@Override
public Object getResult() {
format = null;
return null;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_sql_functions_misc_OSQLFunctionDate.java |
1,476 | public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> {
private boolean isVertex;
private HashSet set = new HashSet();
@Override
public void setup(final Mapper.Context context) throws IOException, InterruptedException {
this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class);
}
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException {
long pathsFiltered = 0l;
if (this.isVertex) {
if (value.hasPaths()) {
final Iterator<List<FaunusPathElement.MicroElement>> itty = value.getPaths().iterator();
while (itty.hasNext()) {
final List<FaunusPathElement.MicroElement> path = itty.next();
this.set.clear();
this.set.addAll(path);
if (path.size() != this.set.size()) {
itty.remove();
pathsFiltered++;
}
}
}
} else {
for (final Edge e : value.getEdges(Direction.BOTH)) {
final StandardFaunusEdge edge = (StandardFaunusEdge) e;
if (edge.hasPaths()) {
final Iterator<List<FaunusPathElement.MicroElement>> itty = edge.getPaths().iterator();
while (itty.hasNext()) {
final List<FaunusPathElement.MicroElement> path = itty.next();
this.set.clear();
this.set.addAll(path);
if (path.size() != this.set.size()) {
itty.remove();
pathsFiltered++;
}
}
}
}
}
DEFAULT_COMPAT.incrementContextCounter(context, Counters.PATHS_FILTERED, pathsFiltered);
context.write(NullWritable.get(), value);
}
} | 1no label
| titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_filter_CyclicPathFilterMap.java |
517 | @Target(value={ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AutoPopulate {
boolean autoUpdateValue() default false;
} | 0true
| common_src_main_java_org_broadleafcommerce_common_time_domain_AutoPopulate.java |
781 | public class CollectionTxnRemoveOperation extends CollectionBackupAwareOperation {
private long itemId;
private transient CollectionItem item;
public CollectionTxnRemoveOperation() {
}
public CollectionTxnRemoveOperation(String name, long itemId) {
super(name);
this.itemId = itemId;
}
@Override
public boolean shouldBackup() {
return true;
}
@Override
public Operation getBackupOperation() {
return new CollectionTxnRemoveBackupOperation(name, itemId);
}
@Override
public int getId() {
return CollectionDataSerializerHook.COLLECTION_TXN_REMOVE;
}
@Override
public void beforeRun() throws Exception {
}
@Override
public void run() throws Exception {
item = getOrCreateContainer().commitRemove(itemId);
}
@Override
public void afterRun() throws Exception {
if (item != null) {
publishEvent(ItemEventType.REMOVED, (Data) item.getValue());
}
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeLong(itemId);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
itemId = in.readLong();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_txn_CollectionTxnRemoveOperation.java |
148 | public class Backend implements LockerProvider {
private static final Logger log = LoggerFactory.getLogger(Backend.class);
/**
* These are the names for the edge store and property index databases, respectively.
* The edge store contains all edges and properties. The property index contains an
* inverted index from attribute value to vertex.
* <p/>
* These names are fixed and should NEVER be changed. Changing these strings can
* disrupt storage adapters that rely on these names for specific configurations.
*/
public static final String EDGESTORE_NAME = "edgestore";
public static final String INDEXSTORE_NAME = "graphindex";
public static final String ID_STORE_NAME = "titan_ids";
public static final String METRICS_MERGED_STORE = "stores";
public static final String METRICS_MERGED_CACHE = "caches";
public static final String METRICS_CACHE_SUFFIX = ".cache";
public static final String LOCK_STORE_SUFFIX = "_lock_";
public static final String SYSTEM_TX_LOG_NAME = "txlog";
public static final String SYSTEM_MGMT_LOG_NAME = "systemlog";
public static final double EDGESTORE_CACHE_PERCENT = 0.8;
public static final double INDEXSTORE_CACHE_PERCENT = 0.2;
private static final long ETERNAL_CACHE_EXPIRATION = 1000l*3600*24*365*200; //200 years
public static final int THREAD_POOL_SIZE_SCALE_FACTOR = 2;
public static final Map<String, Integer> STATIC_KEY_LENGTHS = new HashMap<String, Integer>() {{
put(EDGESTORE_NAME, 8);
put(EDGESTORE_NAME + LOCK_STORE_SUFFIX, 8);
put(ID_STORE_NAME, 8);
}};
private final KeyColumnValueStoreManager storeManager;
private final KeyColumnValueStoreManager storeManagerLocking;
private final StoreFeatures storeFeatures;
private KCVSCache edgeStore;
private KCVSCache indexStore;
private KCVSCache txLogStore;
private IDAuthority idAuthority;
private KCVSConfiguration systemConfig;
private boolean hasAttemptedClose;
private final KCVSLogManager mgmtLogManager;
private final KCVSLogManager txLogManager;
private final LogManager userLogManager;
private final Map<String, IndexProvider> indexes;
private final int bufferSize;
private final Duration maxWriteTime;
private final Duration maxReadTime;
private final boolean cacheEnabled;
private final ExecutorService threadPool;
private final Function<String, Locker> lockerCreator;
private final ConcurrentHashMap<String, Locker> lockers =
new ConcurrentHashMap<String, Locker>();
private final Configuration configuration;
public Backend(Configuration configuration) {
this.configuration = configuration;
storeManager = getStorageManager(configuration);
indexes = getIndexes(configuration);
storeFeatures = storeManager.getFeatures();
mgmtLogManager = getKCVSLogManager(MANAGEMENT_LOG);
txLogManager = getKCVSLogManager(TRANSACTION_LOG);
userLogManager = getLogManager(USER_LOG);
cacheEnabled = !configuration.get(STORAGE_BATCH) && configuration.get(DB_CACHE);
int bufferSizeTmp = configuration.get(BUFFER_SIZE);
Preconditions.checkArgument(bufferSizeTmp > 0, "Buffer size must be positive");
if (!storeFeatures.hasBatchMutation()) {
bufferSize = Integer.MAX_VALUE;
} else bufferSize = bufferSizeTmp;
maxWriteTime = configuration.get(STORAGE_WRITE_WAITTIME);
maxReadTime = configuration.get(STORAGE_READ_WAITTIME);
if (!storeFeatures.hasLocking()) {
Preconditions.checkArgument(storeFeatures.isKeyConsistent(),"Store needs to support some form of locking");
storeManagerLocking = new ExpectedValueCheckingStoreManager(storeManager,LOCK_STORE_SUFFIX,this,maxReadTime);
} else {
storeManagerLocking = storeManager;
}
if (configuration.get(PARALLEL_BACKEND_OPS)) {
int poolsize = Runtime.getRuntime().availableProcessors() * THREAD_POOL_SIZE_SCALE_FACTOR;
threadPool = Executors.newFixedThreadPool(poolsize);
log.info("Initiated backend operations thread pool of size {}", poolsize);
} else {
threadPool = null;
}
final String lockBackendName = configuration.get(LOCK_BACKEND);
if (REGISTERED_LOCKERS.containsKey(lockBackendName)) {
lockerCreator = REGISTERED_LOCKERS.get(lockBackendName);
} else {
throw new TitanConfigurationException("Unknown lock backend \"" +
lockBackendName + "\". Known lock backends: " +
Joiner.on(", ").join(REGISTERED_LOCKERS.keySet()) + ".");
}
// Never used for backends that have innate transaction support, but we
// want to maintain the non-null invariant regardless; it will default
// to connsistentkey impl if none is specified
Preconditions.checkNotNull(lockerCreator);
}
@Override
public Locker getLocker(String lockerName) {
Preconditions.checkNotNull(lockerName);
Locker l = lockers.get(lockerName);
if (null == l) {
l = lockerCreator.apply(lockerName);
final Locker x = lockers.putIfAbsent(lockerName, l);
if (null != x) {
l = x;
}
}
return l;
}
/**
* Initializes this backend with the given configuration. Must be called before this Backend can be used
*
* @param config
*/
public void initialize(Configuration config) {
try {
boolean reportMetrics = configuration.get(BASIC_METRICS);
//EdgeStore & VertexIndexStore
KeyColumnValueStore idStore = storeManager.openDatabase(ID_STORE_NAME);
if (reportMetrics) {
idStore = new MetricInstrumentedStore(idStore, getMetricsStoreName(ID_STORE_NAME));
}
idAuthority = null;
if (storeFeatures.isKeyConsistent()) {
idAuthority = new ConsistentKeyIDAuthority(idStore, storeManager, config);
} else {
throw new IllegalStateException("Store needs to support consistent key or transactional operations for ID manager to guarantee proper id allocations");
}
KeyColumnValueStore edgeStoreRaw = storeManagerLocking.openDatabase(EDGESTORE_NAME);
KeyColumnValueStore indexStoreRaw = storeManagerLocking.openDatabase(INDEXSTORE_NAME);
if (reportMetrics) {
edgeStoreRaw = new MetricInstrumentedStore(edgeStoreRaw, getMetricsStoreName(EDGESTORE_NAME));
indexStoreRaw = new MetricInstrumentedStore(indexStoreRaw, getMetricsStoreName(INDEXSTORE_NAME));
}
//Configure caches
if (cacheEnabled) {
long expirationTime = configuration.get(DB_CACHE_TIME);
Preconditions.checkArgument(expirationTime>=0,"Invalid cache expiration time: %s",expirationTime);
if (expirationTime==0) expirationTime=ETERNAL_CACHE_EXPIRATION;
long cacheSizeBytes;
double cachesize = configuration.get(DB_CACHE_SIZE);
Preconditions.checkArgument(cachesize>0.0,"Invalid cache size specified: %s",cachesize);
if (cachesize<1.0) {
//Its a percentage
Runtime runtime = Runtime.getRuntime();
cacheSizeBytes = (long)((runtime.maxMemory()-(runtime.totalMemory()-runtime.freeMemory())) * cachesize);
} else {
Preconditions.checkArgument(cachesize>1000,"Cache size is too small: %s",cachesize);
cacheSizeBytes = (long)cachesize;
}
log.info("Configuring total store cache size: {}",cacheSizeBytes);
long cleanWaitTime = configuration.get(DB_CACHE_CLEAN_WAIT);
Preconditions.checkArgument(EDGESTORE_CACHE_PERCENT + INDEXSTORE_CACHE_PERCENT == 1.0,"Cache percentages don't add up!");
long edgeStoreCacheSize = Math.round(cacheSizeBytes * EDGESTORE_CACHE_PERCENT);
long indexStoreCacheSize = Math.round(cacheSizeBytes * INDEXSTORE_CACHE_PERCENT);
edgeStore = new ExpirationKCVSCache(edgeStoreRaw,getMetricsCacheName("edgeStore",reportMetrics),expirationTime,cleanWaitTime,edgeStoreCacheSize);
indexStore = new ExpirationKCVSCache(indexStoreRaw,getMetricsCacheName("indexStore",reportMetrics),expirationTime,cleanWaitTime,indexStoreCacheSize);
} else {
edgeStore = new NoKCVSCache(edgeStoreRaw);
indexStore = new NoKCVSCache(indexStoreRaw);
}
//Just open them so that they are cached
txLogManager.openLog(SYSTEM_TX_LOG_NAME);
mgmtLogManager.openLog(SYSTEM_MGMT_LOG_NAME);
txLogStore = new NoKCVSCache(storeManager.openDatabase(SYSTEM_TX_LOG_NAME));
//Open global configuration
KeyColumnValueStore systemConfigStore = storeManagerLocking.openDatabase(SYSTEM_PROPERTIES_STORE_NAME);
systemConfig = getGlobalConfiguration(new BackendOperation.TransactionalProvider() {
@Override
public StoreTransaction openTx() throws BackendException {
return storeManagerLocking.beginTransaction(StandardBaseTransactionConfig.of(
configuration.get(TIMESTAMP_PROVIDER),
storeFeatures.getKeyConsistentTxConfig()));
}
@Override
public void close() throws BackendException {
//Do nothing, storeManager is closed explicitly by Backend
}
},systemConfigStore,configuration);
} catch (BackendException e) {
throw new TitanException("Could not initialize backend", e);
}
}
/**
* Get information about all registered {@link IndexProvider}s.
*
* @return
*/
public Map<String, IndexInformation> getIndexInformation() {
ImmutableMap.Builder<String, IndexInformation> copy = ImmutableMap.builder();
copy.putAll(indexes);
return copy.build();
}
//
// public IndexProvider getIndexProvider(String name) {
// return indexes.get(name);
// }
public KCVSLog getSystemTxLog() {
try {
return txLogManager.openLog(SYSTEM_TX_LOG_NAME);
} catch (BackendException e) {
throw new TitanException("Could not re-open transaction log", e);
}
}
public Log getSystemMgmtLog() {
try {
return mgmtLogManager.openLog(SYSTEM_MGMT_LOG_NAME);
} catch (BackendException e) {
throw new TitanException("Could not re-open management log", e);
}
}
public Log getUserLog(String identifier) throws BackendException {
return userLogManager.openLog(getUserLogName(identifier));
}
public static final String getUserLogName(String identifier) {
Preconditions.checkArgument(StringUtils.isNotBlank(identifier));
return USER_LOG_PREFIX +identifier;
}
public KCVSConfiguration getGlobalSystemConfig() {
return systemConfig;
}
private String getMetricsStoreName(String storeName) {
return configuration.get(METRICS_MERGE_STORES) ? METRICS_MERGED_STORE : storeName;
}
private String getMetricsCacheName(String storeName, boolean reportMetrics) {
if (!reportMetrics) return null;
return configuration.get(METRICS_MERGE_STORES) ? METRICS_MERGED_CACHE : storeName + METRICS_CACHE_SUFFIX;
}
public KCVSLogManager getKCVSLogManager(String logName) {
Preconditions.checkArgument(configuration.restrictTo(logName).get(LOG_BACKEND).equalsIgnoreCase(LOG_BACKEND.getDefaultValue()));
return (KCVSLogManager)getLogManager(logName);
}
public LogManager getLogManager(String logName) {
return getLogManager(configuration, logName, storeManager);
}
private static LogManager getLogManager(Configuration config, String logName, KeyColumnValueStoreManager sm) {
Configuration logConfig = config.restrictTo(logName);
String backend = logConfig.get(LOG_BACKEND);
if (backend.equalsIgnoreCase(LOG_BACKEND.getDefaultValue())) {
return new KCVSLogManager(sm,logConfig);
} else {
Preconditions.checkArgument(config!=null);
LogManager lm = getImplementationClass(logConfig,logConfig.get(LOG_BACKEND),REGISTERED_LOG_MANAGERS);
Preconditions.checkNotNull(lm);
return lm;
}
}
public static KeyColumnValueStoreManager getStorageManager(Configuration storageConfig) {
StoreManager manager = getImplementationClass(storageConfig, storageConfig.get(STORAGE_BACKEND),
REGISTERED_STORAGE_MANAGERS);
if (manager instanceof OrderedKeyValueStoreManager) {
manager = new OrderedKeyValueStoreManagerAdapter((OrderedKeyValueStoreManager) manager, STATIC_KEY_LENGTHS);
}
Preconditions.checkArgument(manager instanceof KeyColumnValueStoreManager,"Invalid storage manager: %s",manager.getClass());
return (KeyColumnValueStoreManager) manager;
}
private static KCVSConfiguration getGlobalConfiguration(final BackendOperation.TransactionalProvider txProvider,
final KeyColumnValueStore store,
final Configuration config) {
try {
KCVSConfiguration kcvsConfig = new KCVSConfiguration(txProvider,config.get(TIMESTAMP_PROVIDER),store,SYSTEM_CONFIGURATION_IDENTIFIER);
kcvsConfig.setMaxOperationWaitTime(config.get(SETUP_WAITTIME));
return kcvsConfig;
} catch (BackendException e) {
throw new TitanException("Could not open global configuration",e);
}
}
public static KCVSConfiguration getStandaloneGlobalConfiguration(final KeyColumnValueStoreManager manager,
final Configuration config) {
try {
final StoreFeatures features = manager.getFeatures();
return getGlobalConfiguration(new BackendOperation.TransactionalProvider() {
@Override
public StoreTransaction openTx() throws BackendException {
return manager.beginTransaction(StandardBaseTransactionConfig.of(config.get(TIMESTAMP_PROVIDER),features.getKeyConsistentTxConfig()));
}
@Override
public void close() throws BackendException {
manager.close();
}
},manager.openDatabase(SYSTEM_PROPERTIES_STORE_NAME),config);
} catch (BackendException e) {
throw new TitanException("Could not open global configuration",e);
}
}
private final static Map<String, IndexProvider> getIndexes(Configuration config) {
ImmutableMap.Builder<String, IndexProvider> builder = ImmutableMap.builder();
for (String index : config.getContainedNamespaces(INDEX_NS)) {
Preconditions.checkArgument(StringUtils.isNotBlank(index), "Invalid index name [%s]", index);
log.info("Configuring index [{}]", index);
IndexProvider provider = getImplementationClass(config.restrictTo(index), config.get(INDEX_BACKEND,index),
REGISTERED_INDEX_PROVIDERS);
Preconditions.checkNotNull(provider);
builder.put(index, provider);
}
return builder.build();
}
public final static <T> T getImplementationClass(Configuration config, String clazzname, Map<String, String> registeredImpls) {
if (registeredImpls.containsKey(clazzname.toLowerCase())) {
clazzname = registeredImpls.get(clazzname.toLowerCase());
}
return ConfigurationUtil.instantiate(clazzname, new Object[]{config}, new Class[]{Configuration.class});
}
/**
* Returns the configured {@link IDAuthority}.
*
* @return
*/
public IDAuthority getIDAuthority() {
Preconditions.checkNotNull(idAuthority, "Backend has not yet been initialized");
return idAuthority;
}
/**
* Returns the {@link StoreFeatures} of the configured backend storage engine.
*
* @return
*/
public StoreFeatures getStoreFeatures() {
return storeFeatures;
}
/**
* Returns the {@link IndexFeatures} of all configured index backends
*/
public Map<String,IndexFeatures> getIndexFeatures() {
return Maps.transformValues(indexes,new Function<IndexProvider, IndexFeatures>() {
@Nullable
@Override
public IndexFeatures apply(@Nullable IndexProvider indexProvider) {
return indexProvider.getFeatures();
}
});
}
/**
* Opens a new transaction against all registered backend system wrapped in one {@link BackendTransaction}.
*
* @return
* @throws BackendException
*/
public BackendTransaction beginTransaction(TransactionConfiguration configuration, KeyInformation.Retriever indexKeyRetriever) throws BackendException {
StoreTransaction tx = storeManagerLocking.beginTransaction(configuration);
// Cache
CacheTransaction cacheTx = new CacheTransaction(tx, storeManagerLocking, bufferSize, maxWriteTime, configuration.hasEnabledBatchLoading());
// Index transactions
Map<String, IndexTransaction> indexTx = new HashMap<String, IndexTransaction>(indexes.size());
for (Map.Entry<String, IndexProvider> entry : indexes.entrySet()) {
indexTx.put(entry.getKey(), new IndexTransaction(entry.getValue(), indexKeyRetriever.get(entry.getKey()), configuration, maxWriteTime));
}
return new BackendTransaction(cacheTx, configuration, storeFeatures,
edgeStore, indexStore, txLogStore,
maxReadTime, indexTx, threadPool);
}
public synchronized void close() throws BackendException {
if (!hasAttemptedClose) {
hasAttemptedClose = true;
mgmtLogManager.close();
txLogManager.close();
userLogManager.close();
edgeStore.close();
indexStore.close();
idAuthority.close();
systemConfig.close();
storeManager.close();
if(threadPool != null) {
threadPool.shutdown();
}
//Indexes
for (IndexProvider index : indexes.values()) index.close();
} else {
log.debug("Backend {} has already been closed or cleared", this);
}
}
/**
* Clears the storage of all registered backend data providers. This includes backend storage engines and index providers.
* <p/>
* IMPORTANT: Clearing storage means that ALL data will be lost and cannot be recovered.
*
* @throws BackendException
*/
public synchronized void clearStorage() throws BackendException {
if (!hasAttemptedClose) {
hasAttemptedClose = true;
mgmtLogManager.close();
txLogManager.close();
userLogManager.close();
edgeStore.close();
indexStore.close();
idAuthority.close();
systemConfig.close();
storeManager.clearStorage();
storeManager.close();
//Indexes
for (IndexProvider index : indexes.values()) {
index.clearStorage();
index.close();
}
} else {
log.debug("Backend {} has already been closed or cleared", this);
}
}
//############ Registered Storage Managers ##############
private static final ImmutableMap<String, String> REGISTERED_STORAGE_MANAGERS;
static {
ImmutableMap.Builder<String, String> b = ImmutableMap.builder();
b.put("berkeleyje", "com.thinkaurelius.titan.diskstorage.berkeleyje.BerkeleyJEStoreManager");
b.put("infinispan", "com.thinkaurelius.titan.diskstorage.infinispan.InfinispanCacheStoreManager");
b.put("cassandrathrift", "com.thinkaurelius.titan.diskstorage.cassandra.thrift.CassandraThriftStoreManager");
b.put("cassandra", "com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager");
b.put("astyanax", "com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager");
b.put("hbase", "com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager");
b.put("embeddedcassandra", "com.thinkaurelius.titan.diskstorage.cassandra.embedded.CassandraEmbeddedStoreManager");
b.put("inmemory", "com.thinkaurelius.titan.diskstorage.keycolumnvalue.inmemory.InMemoryStoreManager");
REGISTERED_STORAGE_MANAGERS = b.build();
}
public static final Map<String, String> getRegisteredStoreManagers() {
return REGISTERED_STORAGE_MANAGERS;
}
public static final Map<String, ConfigOption> REGISTERED_STORAGE_MANAGERS_SHORTHAND = new HashMap<String, ConfigOption>() {{
put("berkeleyje", STORAGE_DIRECTORY);
put("hazelcast", STORAGE_DIRECTORY);
put("hazelcastcache", STORAGE_DIRECTORY);
put("infinispan", STORAGE_DIRECTORY);
put("cassandra", STORAGE_HOSTS);
put("cassandrathrift", STORAGE_HOSTS);
put("astyanax", STORAGE_HOSTS);
put("hbase", STORAGE_HOSTS);
put("embeddedcassandra", STORAGE_CONF_FILE);
put("inmemory", null);
}};
public static final Map<String, String> REGISTERED_INDEX_PROVIDERS = new HashMap<String, String>() {{
put("lucene", "com.thinkaurelius.titan.diskstorage.lucene.LuceneIndex");
put("elasticsearch", "com.thinkaurelius.titan.diskstorage.es.ElasticSearchIndex");
put("es", "com.thinkaurelius.titan.diskstorage.es.ElasticSearchIndex");
put("solr", "com.thinkaurelius.titan.diskstorage.solr.SolrIndex");
}};
public static final Map<String,String> REGISTERED_LOG_MANAGERS = new HashMap<String, String>() {{
put("default","com.thinkaurelius.titan.diskstorage.log.kcvs.KCVSLogManager");
}};
private final Function<String, Locker> CONSISTENT_KEY_LOCKER_CREATOR = new Function<String, Locker>() {
@Override
public Locker apply(String lockerName) {
KeyColumnValueStore lockerStore;
try {
lockerStore = storeManager.openDatabase(lockerName);
} catch (BackendException e) {
throw new TitanConfigurationException("Could not retrieve store named " + lockerName + " for locker configuration", e);
}
return new ConsistentKeyLocker.Builder(lockerStore, storeManager).fromConfig(configuration).build();
}
};
private final Function<String, Locker> ASTYANAX_RECIPE_LOCKER_CREATOR = new Function<String, Locker>() {
@Override
public Locker apply(String lockerName) {
String expectedManagerName = "com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager";
String actualManagerName = storeManager.getClass().getCanonicalName();
// Require AstyanaxStoreManager
Preconditions.checkArgument(expectedManagerName.equals(actualManagerName),
"Astyanax Recipe locker is only supported with the Astyanax storage backend (configured:"
+ actualManagerName + " != required:" + expectedManagerName + ")");
try {
Class<?> c = storeManager.getClass();
Method method = c.getMethod("openLocker", String.class);
Object o = method.invoke(storeManager, lockerName);
return (Locker) o;
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Could not find method when configuring locking with Astyanax Recipes");
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Could not access method when configuring locking with Astyanax Recipes", e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException("Could not invoke method when configuring locking with Astyanax Recipes", e);
}
}
};
private final Function<String, Locker> TEST_LOCKER_CREATOR = new Function<String, Locker>() {
@Override
public Locker apply(String lockerName) {
return openManagedLocker("com.thinkaurelius.titan.diskstorage.util.TestLockerManager",lockerName);
}
};
private final Map<String, Function<String, Locker>> REGISTERED_LOCKERS = ImmutableMap.of(
"consistentkey", CONSISTENT_KEY_LOCKER_CREATOR,
"astyanaxrecipe", ASTYANAX_RECIPE_LOCKER_CREATOR,
"test", TEST_LOCKER_CREATOR
);
private static Locker openManagedLocker(String classname, String lockerName) {
try {
Class c = Class.forName(classname);
Constructor constructor = c.getConstructor();
Object instance = constructor.newInstance();
Method method = c.getMethod("openLocker", String.class);
Object o = method.invoke(instance, lockerName);
return (Locker) o;
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Could not find implementation class: " + classname);
} catch (InstantiationException e) {
throw new IllegalArgumentException("Could not instantiate implementation: " + classname, e);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("Could not find method when configuring locking for: " + classname,e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Could not access method when configuring locking for: " + classname,e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException("Could not invoke method when configuring locking for: " + classname,e);
} catch (ClassCastException e) {
throw new IllegalArgumentException("Could not instantiate implementation: " + classname, e);
}
}
static {
Properties props;
try {
props = new Properties();
InputStream in = TitanFactory.class.getClassLoader().getResourceAsStream(TitanConstants.TITAN_PROPERTIES_FILE);
if (in != null && in.available() > 0) {
props.load(in);
}
} catch (IOException e) {
throw new AssertionError(e);
}
registerShorthands(props, "storage.", REGISTERED_STORAGE_MANAGERS);
registerShorthands(props, "index.", REGISTERED_INDEX_PROVIDERS);
}
public static final void registerShorthands(Properties props, String prefix, Map<String, String> shorthands) {
for (String key : props.stringPropertyNames()) {
if (key.toLowerCase().startsWith(prefix)) {
String shorthand = key.substring(prefix.length()).toLowerCase();
String clazz = props.getProperty(key);
shorthands.put(shorthand, clazz);
log.debug("Registering shorthand [{}] for [{}]", shorthand, clazz);
}
}
}
//
// public synchronized static final void registerStorageManager(String name, Class<? extends StoreManager> clazz) {
// Preconditions.checkNotNull(name);
// Preconditions.checkNotNull(clazz);
// Preconditions.checkArgument(!StringUtils.isEmpty(name));
// Preconditions.checkNotNull(!REGISTERED_STORAGE_MANAGERS.containsKey(name),"A storage manager has already been registered for name: " + name);
// REGISTERED_STORAGE_MANAGERS.put(name,clazz);
// }
//
// public synchronized static final void removeStorageManager(String name) {
// Preconditions.checkNotNull(name);
// REGISTERED_STORAGE_MANAGERS.remove(name);
// }
} | 1no label
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_Backend.java |
622 | public class ShardStats extends BroadcastShardOperationResponse implements ToXContent {
private ShardRouting shardRouting;
CommonStats stats;
ShardStats() {
}
public ShardStats(IndexShard indexShard, CommonStatsFlags flags) {
super(indexShard.routingEntry().index(), indexShard.routingEntry().id());
this.shardRouting = indexShard.routingEntry();
this.stats = new CommonStats(indexShard, flags);
}
/**
* The shard routing information (cluster wide shard state).
*/
public ShardRouting getShardRouting() {
return this.shardRouting;
}
public CommonStats getStats() {
return this.stats;
}
public static ShardStats readShardStats(StreamInput in) throws IOException {
ShardStats stats = new ShardStats();
stats.readFrom(in);
return stats;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
shardRouting = readShardRoutingEntry(in);
stats = CommonStats.readCommonStats(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
shardRouting.writeTo(out);
stats.writeTo(out);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(Fields.ROUTING)
.field(Fields.STATE, shardRouting.state())
.field(Fields.PRIMARY, shardRouting.primary())
.field(Fields.NODE, shardRouting.currentNodeId())
.field(Fields.RELOCATING_NODE, shardRouting.relocatingNodeId())
.endObject();
stats.toXContent(builder, params);
return builder;
}
static final class Fields {
static final XContentBuilderString ROUTING = new XContentBuilderString("routing");
static final XContentBuilderString STATE = new XContentBuilderString("state");
static final XContentBuilderString PRIMARY = new XContentBuilderString("primary");
static final XContentBuilderString NODE = new XContentBuilderString("node");
static final XContentBuilderString RELOCATING_NODE = new XContentBuilderString("relocating_node");
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_stats_ShardStats.java |
40 | public class SimpleCommandProcessor extends MemcacheCommandProcessor<SimpleCommand> {
private final ILogger logger;
public SimpleCommandProcessor(TextCommandService textCommandService) {
super(textCommandService);
logger = textCommandService.getNode().getLogger(this.getClass().getName());
}
public void handle(SimpleCommand command) {
if (command.getType() == QUIT) {
try {
command.getSocketTextReader().closeConnection();
} catch (Exception e) {
logger.warning(e);
}
} else if (command.getType() == UNKNOWN) {
command.setResponse(ERROR);
textCommandService.sendResponse(command);
}
}
public void handleRejection(SimpleCommand command) {
handle(command);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_ascii_memcache_SimpleCommandProcessor.java |
576 | public interface CacheRequest {
public List<CacheItemRequest> getCacheItemRequests();
} | 0true
| common_src_main_java_org_broadleafcommerce_common_vendor_service_cache_CacheRequest.java |
188 | public interface BroadleafEnumerationType {
public String getType();
public String getFriendlyType();
} | 0true
| common_src_main_java_org_broadleafcommerce_common_BroadleafEnumerationType.java |
977 | public class ReplicationShardOperationFailedException extends IndexShardException implements ElasticsearchWrapperException {
public ReplicationShardOperationFailedException(ShardId shardId, String msg) {
super(shardId, msg, null);
}
public ReplicationShardOperationFailedException(ShardId shardId, Throwable cause) {
super(shardId, "", cause);
}
public ReplicationShardOperationFailedException(ShardId shardId, String msg, Throwable cause) {
super(shardId, msg, cause);
}
} | 0true
| src_main_java_org_elasticsearch_action_support_replication_ReplicationShardOperationFailedException.java |
186 | static final class QNode implements ForkJoinPool.ManagedBlocker {
final Phaser phaser;
final int phase;
final boolean interruptible;
final boolean timed;
boolean wasInterrupted;
long nanos;
long lastTime;
volatile Thread thread; // nulled to cancel wait
QNode next;
QNode(Phaser phaser, int phase, boolean interruptible,
boolean timed, long nanos) {
this.phaser = phaser;
this.phase = phase;
this.interruptible = interruptible;
this.nanos = nanos;
this.timed = timed;
this.lastTime = timed ? System.nanoTime() : 0L;
thread = Thread.currentThread();
}
public boolean isReleasable() {
if (thread == null)
return true;
if (phaser.getPhase() != phase) {
thread = null;
return true;
}
if (Thread.interrupted())
wasInterrupted = true;
if (wasInterrupted && interruptible) {
thread = null;
return true;
}
if (timed) {
if (nanos > 0L) {
long now = System.nanoTime();
nanos -= now - lastTime;
lastTime = now;
}
if (nanos <= 0L) {
thread = null;
return true;
}
}
return false;
}
public boolean block() {
if (isReleasable())
return true;
else if (!timed)
LockSupport.park(this);
else if (nanos > 0)
LockSupport.parkNanos(this, nanos);
return isReleasable();
}
} | 0true
| src_main_java_jsr166y_Phaser.java |
11 | .withPredicateProvider(new PredicateProvider() {
@Override
public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder,
From root, String ceilingEntity,
String fullPropertyName, Path explicitPath, List directValues) {
return explicitPath.as(Long.class).in(directValues);
}
}) | 0true
| admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_server_service_handler_SkuCustomPersistenceHandler.java |
348 | static class TestComparator implements Comparator<Map.Entry>, Serializable {
int ascending = 1;
IterationType iterationType = IterationType.ENTRY;
TestComparator() {
}
TestComparator(boolean ascending, IterationType iterationType) {
this.ascending = ascending ? 1 : -1;
this.iterationType = iterationType;
}
public int compare(Map.Entry e1, Map.Entry e2) {
Map.Entry<Integer, Integer> o1 = e1;
Map.Entry<Integer, Integer> o2 = e2;
switch (iterationType) {
case KEY:
return (o1.getKey() - o2.getKey()) * ascending;
case VALUE:
return (o1.getValue() - o2.getValue()) * ascending;
default:
int result = (o1.getValue() - o2.getValue()) * ascending;
if (result != 0) {
return result;
}
return (o1.getKey() - o2.getKey()) * ascending;
}
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_map_ClientSortLimitTest.java |
550 | public interface TypedTransformer<K> extends Transformer {
public K transform(Object input);
} | 0true
| common_src_main_java_org_broadleafcommerce_common_util_TypedTransformer.java |
66 | public class AddThrowsAnnotationProposal extends CorrectionProposal {
public static void addThrowsAnnotationProposal(Collection<ICompletionProposal> proposals,
Tree.Statement statement, Tree.CompilationUnit cu, IFile file, IDocument doc) {
ProducedType exceptionType = determineExceptionType(statement);
if (exceptionType == null) {
return;
}
Tree.Declaration throwContainer = determineThrowContainer(statement, cu);
if( !(throwContainer instanceof Tree.MethodDefinition) &&
!(throwContainer instanceof Tree.AttributeGetterDefinition) &&
!(throwContainer instanceof Tree.AttributeSetterDefinition) &&
!(throwContainer instanceof Tree.ClassOrInterface) ) {
return;
}
if (isAlreadyPresent(throwContainer, exceptionType)) {
return;
}
String throwsAnnotation = "throws (`class " + exceptionType.getProducedTypeName() + "`, \"\")";
InsertEdit throwsAnnotationInsertEdit = createInsertAnnotationEdit(throwsAnnotation, throwContainer, doc);
TextFileChange throwsAnnotationChange = new TextFileChange("Add Throws Annotation", file);
throwsAnnotationChange.setEdit(throwsAnnotationInsertEdit);
int cursorOffset = throwsAnnotationInsertEdit.getOffset() + throwsAnnotationInsertEdit.getText().indexOf(")") - 1;
AddThrowsAnnotationProposal proposal =
new AddThrowsAnnotationProposal(throwsAnnotationChange, exceptionType, cursorOffset,
throwContainer.getIdentifier() != null ? throwContainer.getIdentifier().getText() : "");
if (!proposals.contains(proposal)) {
proposals.add(proposal);
}
}
private static ProducedType determineExceptionType(Tree.Statement statement) {
ProducedType exceptionType = null;
if (statement instanceof Tree.Throw) {
ProducedType ceylonLangExceptionType = statement.getUnit().getExceptionDeclaration().getType();
Tree.Expression throwExpression = ((Tree.Throw) statement).getExpression();
if (throwExpression == null) {
exceptionType = ceylonLangExceptionType;
} else {
ProducedType throwExpressionType = throwExpression.getTypeModel();
if ( throwExpressionType != null &&
throwExpressionType.isSubtypeOf(ceylonLangExceptionType) ) {
exceptionType = throwExpressionType;
}
}
}
return exceptionType;
}
private static Tree.Declaration determineThrowContainer(Tree.Statement statement,
Tree.CompilationUnit cu) {
FindContainerVisitor fcv = new FindContainerVisitor(statement);
fcv.visit(cu);
return fcv.getDeclaration();
}
private static boolean isAlreadyPresent(Tree.Declaration throwContainer, ProducedType exceptionType) {
Tree.AnnotationList annotationList = throwContainer.getAnnotationList();
if (annotationList != null) {
for (Tree.Annotation annotation : annotationList.getAnnotations()) {
String annotationIdentifier = getAnnotationIdentifier(annotation);
if ("throws".equals(annotationIdentifier)) {
Tree.PositionalArgumentList positionalArgumentList = annotation.getPositionalArgumentList();
if (positionalArgumentList != null &&
positionalArgumentList.getPositionalArguments() != null &&
positionalArgumentList.getPositionalArguments().size() > 0) {
Tree.PositionalArgument throwsArg = positionalArgumentList.getPositionalArguments().get(0);
if (throwsArg instanceof Tree.ListedArgument) {
Tree.Expression throwsArgExp = ((Tree.ListedArgument) throwsArg).getExpression();
if (throwsArgExp != null) {
Tree.Term term = throwsArgExp.getTerm();
if (term instanceof Tree.MemberOrTypeExpression) {
Declaration declaration = ((Tree.MemberOrTypeExpression) term).getDeclaration();
if (declaration instanceof TypeDeclaration) {
ProducedType type = ((TypeDeclaration) declaration).getType();
if (exceptionType.isExactly(type)) {
return true;
}
}
}
}
}
}
}
}
}
return false;
}
private AddThrowsAnnotationProposal(Change change, ProducedType exceptionType, int offset, String declName) {
super("Add throws annotation to '" + declName + "'", change, new Region(offset, 0));
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_AddThrowsAnnotationProposal.java |
808 | @Entity
@Table(name = "BLC_OFFER_AUDIT")
@Inheritance(strategy=InheritanceType.JOINED)
public class OfferAuditImpl implements OfferAudit {
public static final long serialVersionUID = 1L;
protected static final Log LOG = LogFactory.getLog(OfferAuditImpl.class);
@Id
@GeneratedValue(generator = "OfferAuditId")
@GenericGenerator(
name="OfferAuditId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="OfferAuditImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.offer.domain.OfferAuditImpl")
}
)
@Column(name = "OFFER_AUDIT_ID")
protected Long id;
@Column(name = "OFFER_ID")
@Index(name="OFFERAUDIT_OFFER_INDEX", columnNames={"OFFER_ID"})
protected Long offerId;
@Column(name = "CUSTOMER_ID")
@Index(name="OFFERAUDIT_CUSTOMER_INDEX", columnNames={"CUSTOMER_ID"})
protected Long customerId;
@Column(name = "ORDER_ID")
@Index(name="OFFERAUDIT_ORDER_INDEX", columnNames={"ORDER_ID"})
protected Long orderId;
@Column(name = "REDEEMED_DATE")
protected Date redeemedDate;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public Long getOfferId() {
return offerId;
}
@Override
public void setOfferId(Long offerId) {
this.offerId = offerId;
}
@Override
public Long getOfferCodeId() {
throw new UnsupportedOperationException();
}
@Override
public void setOfferCodeId(Long offerCodeId) {
throw new UnsupportedOperationException();
}
@Override
public Long getCustomerId() {
return customerId;
}
@Override
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
@Override
public Long getOrderId() {
return orderId;
}
@Override
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
@Override
public Date getRedeemedDate() {
return redeemedDate;
}
@Override
public void setRedeemedDate(Date redeemedDate) {
this.redeemedDate = redeemedDate;
}
@Override
public int hashCode() {
try {
return new HashCodeBuilder()
.append(customerId)
.append(offerId)
.append(getOfferCodeId())
.append(redeemedDate)
.append(orderId)
.build();
} catch (UnsupportedOperationException e) {
return new HashCodeBuilder()
.append(customerId)
.append(offerId)
.append(redeemedDate)
.append(orderId)
.build();
}
}
@Override
public boolean equals(Object o) {
if (o instanceof OfferAuditImpl) {
OfferAuditImpl that = (OfferAuditImpl) o;
try {
return new EqualsBuilder()
.append(this.id, that.id)
.append(this.customerId, that.customerId)
.append(this.offerId, that.offerId)
.append(this.getOfferCodeId(), that.getOfferCodeId())
.append(this.redeemedDate, that.redeemedDate)
.append(this.orderId, that.orderId)
.build();
} catch (UnsupportedOperationException e) {
return new EqualsBuilder()
.append(this.id, that.id)
.append(this.customerId, that.customerId)
.append(this.offerId, that.offerId)
.append(this.redeemedDate, that.redeemedDate)
.append(this.orderId, that.orderId)
.build();
}
}
return false;
}
} | 1no label
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_OfferAuditImpl.java |
3,311 | public abstract class Operation implements DataSerializable {
// serialized
private String serviceName;
private int partitionId = -1;
private int replicaIndex;
private long callId;
private boolean validateTarget = true;
private long invocationTime = -1;
private long callTimeout = Long.MAX_VALUE;
private long waitTimeout = -1;
private String callerUuid;
private String executorName;
// injected
private transient NodeEngine nodeEngine;
private transient Object service;
private transient Address callerAddress;
private transient Connection connection;
private transient ResponseHandler responseHandler;
private transient long startTime;
public boolean isUrgent() {
return this instanceof UrgentSystemOperation;
}
// runs before wait-support
public abstract void beforeRun() throws Exception;
// runs after wait-support, supposed to do actual operation
public abstract void run() throws Exception;
// runs after backups, before wait-notify
public abstract void afterRun() throws Exception;
public abstract boolean returnsResponse();
public abstract Object getResponse();
public String getServiceName() {
return serviceName;
}
public final Operation setServiceName(String serviceName) {
this.serviceName = serviceName;
return this;
}
public final int getPartitionId() {
return partitionId;
}
public final Operation setPartitionId(int partitionId) {
this.partitionId = partitionId;
return this;
}
public final int getReplicaIndex() {
return replicaIndex;
}
public final Operation setReplicaIndex(int replicaIndex) {
if (replicaIndex < 0 || replicaIndex >= InternalPartition.MAX_REPLICA_COUNT) {
throw new IllegalArgumentException("Replica index is out of range [0-"
+ (InternalPartition.MAX_REPLICA_COUNT - 1) + "]");
}
this.replicaIndex = replicaIndex;
return this;
}
public String getExecutorName() {
return executorName;
}
public void setExecutorName(String executorName) {
this.executorName = executorName;
}
public final long getCallId() {
return callId;
}
// Accessed using OperationAccessor
final Operation setCallId(long callId) {
this.callId = callId;
return this;
}
public boolean validatesTarget() {
return validateTarget;
}
public final Operation setValidateTarget(boolean validateTarget) {
this.validateTarget = validateTarget;
return this;
}
public final NodeEngine getNodeEngine() {
return nodeEngine;
}
public final Operation setNodeEngine(NodeEngine nodeEngine) {
this.nodeEngine = nodeEngine;
return this;
}
public final <T> T getService() {
if (service == null) {
// one might have overridden getServiceName() method...
final String name = serviceName != null ? serviceName : getServiceName();
service = ((NodeEngineImpl) nodeEngine).getService(name);
if (service == null) {
if (nodeEngine.isActive()) {
throw new HazelcastException("Service with name '" + name + "' not found!");
} else {
throw new RetryableHazelcastException("HazelcastInstance[" + nodeEngine.getThisAddress()
+ "] is not active!");
}
}
}
return (T) service;
}
public final Operation setService(Object service) {
this.service = service;
return this;
}
public final Address getCallerAddress() {
return callerAddress;
}
// Accessed using OperationAccessor
final Operation setCallerAddress(Address callerAddress) {
this.callerAddress = callerAddress;
return this;
}
public final Connection getConnection() {
return connection;
}
// Accessed using OperationAccessor
final Operation setConnection(Connection connection) {
this.connection = connection;
return this;
}
public final Operation setResponseHandler(ResponseHandler responseHandler) {
this.responseHandler = responseHandler;
return this;
}
public final ResponseHandler getResponseHandler() {
return responseHandler;
}
public final long getStartTime() {
return startTime;
}
// Accessed using OperationAccessor
final Operation setStartTime(long startTime) {
this.startTime = startTime;
return this;
}
public final long getInvocationTime() {
return invocationTime;
}
// Accessed using OperationAccessor
final Operation setInvocationTime(long invocationTime) {
this.invocationTime = invocationTime;
return this;
}
public final long getCallTimeout() {
return callTimeout;
}
// Accessed using OperationAccessor
final Operation setCallTimeout(long callTimeout) {
this.callTimeout = callTimeout;
return this;
}
public final long getWaitTimeout() {
return waitTimeout;
}
public final void setWaitTimeout(long timeout) {
this.waitTimeout = timeout;
}
public ExceptionAction onException(Throwable throwable) {
return (throwable instanceof RetryableException)
? ExceptionAction.RETRY_INVOCATION : ExceptionAction.THROW_EXCEPTION;
}
public String getCallerUuid() {
return callerUuid;
}
public Operation setCallerUuid(String callerUuid) {
this.callerUuid = callerUuid;
return this;
}
protected final ILogger getLogger() {
final NodeEngine ne = nodeEngine;
return ne != null ? ne.getLogger(getClass()) : Logger.getLogger(getClass());
}
public void logError(Throwable e) {
final ILogger logger = getLogger();
if (e instanceof RetryableException) {
final Level level = returnsResponse() ? Level.FINEST : Level.WARNING;
if (logger.isLoggable(level)) {
logger.log(level, e.getClass().getName() + ": " + e.getMessage());
}
} else if (e instanceof OutOfMemoryError) {
try {
logger.log(Level.SEVERE, e.getMessage(), e);
} catch (Throwable ignored) {
}
} else {
final Level level = nodeEngine != null && nodeEngine.isActive() ? Level.SEVERE : Level.FINEST;
if (logger.isLoggable(level)) {
logger.log(level, e.getMessage(), e);
}
}
}
@Override
public final void writeData(ObjectDataOutput out) throws IOException {
out.writeUTF(serviceName);
out.writeInt(partitionId);
out.writeInt(replicaIndex);
out.writeLong(callId);
out.writeBoolean(validateTarget);
out.writeLong(invocationTime);
out.writeLong(callTimeout);
out.writeLong(waitTimeout);
out.writeUTF(callerUuid);
out.writeUTF(executorName);
writeInternal(out);
}
@Override
public final void readData(ObjectDataInput in) throws IOException {
serviceName = in.readUTF();
partitionId = in.readInt();
replicaIndex = in.readInt();
callId = in.readLong();
validateTarget = in.readBoolean();
invocationTime = in.readLong();
callTimeout = in.readLong();
waitTimeout = in.readLong();
callerUuid = in.readUTF();
executorName = in.readUTF();
readInternal(in);
}
protected abstract void writeInternal(ObjectDataOutput out) throws IOException;
protected abstract void readInternal(ObjectDataInput in) throws IOException;
} | 1no label
| hazelcast_src_main_java_com_hazelcast_spi_Operation.java |
361 | public class FilterParameter {
protected String name;
protected String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_filter_FilterParameter.java |
701 | public class BulkShardResponse extends ActionResponse {
private ShardId shardId;
private BulkItemResponse[] responses;
BulkShardResponse() {
}
BulkShardResponse(ShardId shardId, BulkItemResponse[] responses) {
this.shardId = shardId;
this.responses = responses;
}
public ShardId getShardId() {
return shardId;
}
public BulkItemResponse[] getResponses() {
return responses;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
shardId = ShardId.readShardId(in);
responses = new BulkItemResponse[in.readVInt()];
for (int i = 0; i < responses.length; i++) {
responses[i] = BulkItemResponse.readBulkItem(in);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
shardId.writeTo(out);
out.writeVInt(responses.length);
for (BulkItemResponse response : responses) {
response.writeTo(out);
}
}
} | 0true
| src_main_java_org_elasticsearch_action_bulk_BulkShardResponse.java |
425 | public enum OptionFilterParamType {
BOOLEAN,STRING,INTEGER,LONG,DOUBLE,FLOAT,BIGDECIMAL
} | 0true
| common_src_main_java_org_broadleafcommerce_common_presentation_OptionFilterParamType.java |
793 | ex.execute(new Runnable() {
public void run() {
instances[id] = nodeFactory.newHazelcastInstance();
instances[id].getAtomicLong(name).incrementAndGet();
countDownLatch.countDown();
}
}); | 0true
| hazelcast_src_test_java_com_hazelcast_concurrent_atomiclong_AtomicLongTest.java |
554 | public class BatchRetrieveDao {
//Default batch read size
private int inClauseBatchSize = 300;
@SuppressWarnings("unchecked")
public <T> List<T> batchExecuteReadQuery(Query query, List<?> params, String parameterName) {
List<T> response = new ArrayList<T>();
int start = 0;
while (start < params.size()) {
List<?> batchParams = params.subList(start, params.size() < inClauseBatchSize ? params.size() : inClauseBatchSize);
query.setParameter(parameterName, batchParams);
response.addAll(query.getResultList());
start += inClauseBatchSize;
}
return response;
}
public int getInClauseBatchSize() {
return inClauseBatchSize;
}
public void setInClauseBatchSize(int inClauseBatchSize) {
this.inClauseBatchSize = inClauseBatchSize;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_util_dao_BatchRetrieveDao.java |
197 | @RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class XmlClientConfigBuilderTest {
@Test
public void readClientExecutorPoolSize() {
String xml =
"<hazelcast-client>\n" +
"<executor-pool-size>18</executor-pool-size>" +
"</hazelcast-client>";
final ClientConfig clientConfig = buildConfig(xml);
assertEquals(18, clientConfig.getExecutorPoolSize());
}
@Test
public void readProperties() {
String xml =
"<hazelcast-client>\n" +
"<properties>" +
"<property name=\"hazelcast.client.connection.timeout\">6000</property>" +
"<property name=\"hazelcast.client.retry.count\">8</property>" +
"</properties>" +
"</hazelcast-client>";
final ClientConfig clientConfig = buildConfig(xml);
assertEquals("6000", clientConfig.getProperty("hazelcast.client.connection.timeout"));
assertEquals("8", clientConfig.getProperty("hazelcast.client.retry.count"));
}
private ClientConfig buildConfig(String xml) {
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
XmlClientConfigBuilder configBuilder = new XmlClientConfigBuilder(bis);
return configBuilder.build();
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_config_XmlClientConfigBuilderTest.java |
656 | constructors[COLLECTION_ADD_ALL] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new CollectionAddAllOperation();
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java |
492 | class ShardClearIndicesCacheResponse extends BroadcastShardOperationResponse {
ShardClearIndicesCacheResponse() {
}
public ShardClearIndicesCacheResponse(String index, int shardId) {
super(index, shardId);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_cache_clear_ShardClearIndicesCacheResponse.java |
49 | {
@Override
public int defaultPort()
{
return 5001;
}
@Override
public int port()
{
return config.get( ClusterSettings.cluster_server ).getPort();
}
}, receiver, logging); | 1no label
| enterprise_cluster_src_main_java_org_neo4j_cluster_NetworkedServerFactory.java |
1,549 | public static class Map extends Mapper<NullWritable, FaunusVertex, LongWritable, Text> {
private boolean isVertex;
private SafeMapperOutputs outputs;
@Override
public void setup(final Mapper.Context context) throws IOException, InterruptedException {
this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class);
this.outputs = new SafeMapperOutputs(context);
}
private LongWritable longWritable = new LongWritable();
private Text text = new Text();
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, LongWritable, Text>.Context context) throws IOException, InterruptedException {
if (this.isVertex) {
if (value.hasPaths()) {
this.longWritable.set(value.getLongId());
this.text.set(ElementPicker.getPropertyAsString(value, Tokens._PROPERTIES));
for (int i = 0; i < value.pathCount(); i++) {
this.outputs.write(Tokens.SIDEEFFECT, this.longWritable, this.text);
}
DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_PROCESSED, 1L);
}
} else {
long edgesProcessed = 0;
for (final Edge e : value.getEdges(Direction.OUT)) {
final StandardFaunusEdge edge = (StandardFaunusEdge) e;
if (edge.hasPaths()) {
this.longWritable.set(edge.getLongId());
this.text.set(ElementPicker.getPropertyAsString(edge, Tokens._PROPERTIES));
for (int i = 0; i < edge.pathCount(); i++) {
this.outputs.write(Tokens.SIDEEFFECT, this.longWritable, this.text);
}
edgesProcessed++;
}
}
DEFAULT_COMPAT.incrementContextCounter(context, Counters.OUT_EDGES_PROCESSED, edgesProcessed);
}
this.outputs.write(Tokens.GRAPH, NullWritable.get(), value);
}
@Override
public void cleanup(final Mapper<NullWritable, FaunusVertex, LongWritable, Text>.Context context) throws IOException, InterruptedException {
this.outputs.close();
}
} | 1no label
| titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_transform_PropertyMapMap.java |
573 | return new Iterator<ODocument>() {
public boolean hasNext() {
return iterator.hasNext();
}
public ODocument next() {
return iterator.next().document;
}
public void remove() {
iterator.remove();
}
}; | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_ODocumentFieldsHashSet.java |
759 | public class ListProxyImpl<E> extends AbstractCollectionProxyImpl<ListService, E> implements IList<E> {
protected ListProxyImpl(String name, NodeEngine nodeEngine, ListService service) {
super(name, nodeEngine, service);
}
@Override
protected CollectionConfig getConfig(NodeEngine nodeEngine) {
return nodeEngine.getConfig().findListConfig(name);
}
@Override
public void add(int index, E e) {
throwExceptionIfNull(e);
final Data value = getNodeEngine().toData(e);
final ListAddOperation operation = new ListAddOperation(name, index, value);
invoke(operation);
}
@Override
public E get(int index) {
final ListGetOperation operation = new ListGetOperation(name, index);
return invoke(operation);
}
@Override
public E set(int index, E element) {
throwExceptionIfNull(element);
final Data value = getNodeEngine().toData(element);
final ListSetOperation operation = new ListSetOperation(name, index, value);
return invoke(operation);
}
@Override
public E remove(int index) {
final ListRemoveOperation operation = new ListRemoveOperation(name, index);
return invoke(operation);
}
@Override
public int indexOf(Object o) {
return indexOfInternal(false, o);
}
@Override
public int lastIndexOf(Object o) {
return indexOfInternal(true, o);
}
private int indexOfInternal(boolean last, Object o) {
throwExceptionIfNull(o);
final Data value = getNodeEngine().toData(o);
final ListIndexOfOperation operation = new ListIndexOfOperation(name, last, value);
final Integer result = invoke(operation);
return result;
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
throwExceptionIfNull(c);
List<Data> valueList = new ArrayList<Data>(c.size());
final NodeEngine nodeEngine = getNodeEngine();
for (E e : c) {
throwExceptionIfNull(e);
valueList.add(nodeEngine.toData(e));
}
final ListAddAllOperation operation = new ListAddAllOperation(name, index, valueList);
final Boolean result = invoke(operation);
return result;
}
@Override
public ListIterator<E> listIterator() {
return listIterator(0);
}
@Override
public ListIterator<E> listIterator(int index) {
final List<E> list = subList(-1, -1);
return list.listIterator(index);
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
final ListSubOperation operation = new ListSubOperation(name, fromIndex, toIndex);
final SerializableCollection result = invoke(operation);
final Collection<Data> collection = result.getCollection();
final List<E> list = new ArrayList<E>(collection.size());
final NodeEngine nodeEngine = getNodeEngine();
for (Data data : collection) {
list.add(nodeEngine.<E>toObject(data));
}
return list;
}
@Override
public Iterator<E> iterator() {
return listIterator(0);
}
@Override
public Object[] toArray() {
return subList(-1, -1).toArray();
}
@Override
public <T> T[] toArray(T[] a) {
throwExceptionIfNull(a);
return subList(-1, -1).toArray(a);
}
@Override
public String getServiceName() {
return ListService.SERVICE_NAME;
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_list_ListProxyImpl.java |
1,083 | public class FieldChain {
private FieldChain() {
}
public String getItemName(int fieldIndex) {
if (fieldIndex == 0) {
return name;
} else {
return operationsChain.get(fieldIndex - 1).getValue()[0].toString();
}
}
public int getItemCount() {
if (operationsChain == null) {
return 1;
} else {
return operationsChain.size() + 1;
}
}
/**
* Field chain is considered as long chain if it contains more than one item.
*
* @return true if this chain is long and false in another case.
*/
public boolean isLong() {
return operationsChain != null && operationsChain.size() > 0;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_sql_filter_OSQLFilterItemField.java |
243 | @Repository("blCurrencyDao")
public class BroadleafCurrencyDaoImpl implements BroadleafCurrencyDao {
@PersistenceContext(unitName = "blPU")
protected EntityManager em;
@Resource(name="blEntityConfiguration")
protected EntityConfiguration entityConfiguration;
@Override
public BroadleafCurrency findDefaultBroadleafCurrency() {
Query query = em.createNamedQuery("BC_READ_DEFAULT_CURRENCY");
query.setHint(org.hibernate.ejb.QueryHints.HINT_CACHEABLE, true);
List<BroadleafCurrency> currencyList = (List<BroadleafCurrency>) query.getResultList();
if (currencyList.size() >= 1) {
return currencyList.get(0);
}
return null;
}
/**
* @return The locale for the passed in code
*/
@Override
public BroadleafCurrency findCurrencyByCode(String currencyCode) {
Query query = em.createNamedQuery("BC_READ_CURRENCY_BY_CODE");
query.setParameter("currencyCode", currencyCode);
query.setHint(org.hibernate.ejb.QueryHints.HINT_CACHEABLE, true);
List<BroadleafCurrency> currencyList = (List<BroadleafCurrency>) query.getResultList();
if (currencyList.size() >= 1) {
return currencyList.get(0);
}
return null;
}
@Override
public List<BroadleafCurrency> getAllCurrencies() {
Query query = em.createNamedQuery("BC_READ_ALL_CURRENCIES");
query.setHint(org.hibernate.ejb.QueryHints.HINT_CACHEABLE, true);
return (List<BroadleafCurrency>) query.getResultList();
}
@Override
public BroadleafCurrency save(BroadleafCurrency currency) {
return em.merge(currency);
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_currency_dao_BroadleafCurrencyDaoImpl.java |
282 | static class ActionEntry<Request extends ActionRequest, Response extends ActionResponse> {
public final GenericAction<Request, Response> action;
public final Class<? extends TransportAction<Request, Response>> transportAction;
public final Class[] supportTransportActions;
ActionEntry(GenericAction<Request, Response> action, Class<? extends TransportAction<Request, Response>> transportAction, Class... supportTransportActions) {
this.action = action;
this.transportAction = transportAction;
this.supportTransportActions = supportTransportActions;
}
} | 0true
| src_main_java_org_elasticsearch_action_ActionModule.java |
467 | static class TrySemaphoreThread extends SemaphoreTestThread{
public TrySemaphoreThread(ISemaphore semaphore, AtomicInteger upTotal, AtomicInteger downTotal){
super(semaphore, upTotal, downTotal);
}
public void iterativelyRun() throws Exception{
if(semaphore.tryAcquire()){
work();
semaphore.release();
}
}
} | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_semaphore_ClientSemaphoreThreadedTest.java |
1,689 | public class URLBlobStore extends AbstractComponent implements BlobStore {
private final Executor executor;
private final URL path;
private final int bufferSizeInBytes;
/**
* Constructs new read-only URL-based blob store
* <p/>
* The following settings are supported
* <dl>
* <dt>buffer_size</dt>
* <dd>- size of the read buffer, defaults to 100KB</dd>
* </dl>
*
* @param settings settings
* @param executor executor for read operations
* @param path base URL
*/
public URLBlobStore(Settings settings, Executor executor, URL path) {
super(settings);
this.path = path;
this.bufferSizeInBytes = (int) settings.getAsBytesSize("buffer_size", new ByteSizeValue(100, ByteSizeUnit.KB)).bytes();
this.executor = executor;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return path.toString();
}
/**
* Returns base URL
*
* @return base URL
*/
public URL path() {
return path;
}
/**
* Returns read buffer size
*
* @return read buffer size
*/
public int bufferSizeInBytes() {
return this.bufferSizeInBytes;
}
/**
* Returns executor used for read operations
*
* @return executor
*/
public Executor executor() {
return executor;
}
/**
* {@inheritDoc}
*/
@Override
public ImmutableBlobContainer immutableBlobContainer(BlobPath path) {
try {
return new URLImmutableBlobContainer(this, path, buildPath(path));
} catch (MalformedURLException ex) {
throw new BlobStoreException("malformed URL " + path, ex);
}
}
/**
* This operation is not supported by URL Blob Store
*
* @param path
*/
@Override
public void delete(BlobPath path) {
throw new UnsupportedOperationException("URL repository is read only");
}
/**
* {@inheritDoc}
*/
@Override
public void close() {
// nothing to do here...
}
/**
* Builds URL using base URL and specified path
*
* @param path relative path
* @return Base URL + path
* @throws MalformedURLException
*/
private URL buildPath(BlobPath path) throws MalformedURLException {
String[] paths = path.toArray();
if (paths.length == 0) {
return path();
}
URL blobPath = new URL(this.path, paths[0] + "/");
if (paths.length > 1) {
for (int i = 1; i < paths.length; i++) {
blobPath = new URL(blobPath, paths[i] + "/");
}
}
return blobPath;
}
} | 1no label
| src_main_java_org_elasticsearch_common_blobstore_url_URLBlobStore.java |
1,406 | public static class Request {
final String index;
TimeValue timeout = TimeValue.timeValueSeconds(10);
TimeValue masterTimeout = MasterNodeOperationRequest.DEFAULT_MASTER_NODE_TIMEOUT;
public Request(String index) {
this.index = index;
}
public Request timeout(TimeValue timeout) {
this.timeout = timeout;
return this;
}
public Request masterTimeout(TimeValue masterTimeout) {
this.masterTimeout = masterTimeout;
return this;
}
} | 0true
| src_main_java_org_elasticsearch_cluster_metadata_MetaDataDeleteIndexService.java |
98 | @Repository("blPageDao")
public class PageDaoImpl implements PageDao {
private static SandBox DUMMY_SANDBOX = new SandBoxImpl();
{
DUMMY_SANDBOX.setId(-1l);
}
@PersistenceContext(unitName = "blPU")
protected EntityManager em;
@Resource(name="blEntityConfiguration")
protected EntityConfiguration entityConfiguration;
@Override
public Page readPageById(Long id) {
return em.find(PageImpl.class, id);
}
@Override
public PageTemplate readPageTemplateById(Long id) {
return em.find(PageTemplateImpl.class, id);
}
@Override
public PageTemplate savePageTemplate(PageTemplate template) {
return em.merge(template);
}
@Override
public Map<String, PageField> readPageFieldsByPage(Page page) {
Query query = em.createNamedQuery("BC_READ_PAGE_FIELDS_BY_PAGE_ID");
query.setParameter("page", page);
query.setHint(QueryHints.HINT_CACHEABLE, true);
List<PageField> pageFields = query.getResultList();
Map<String, PageField> pageFieldMap = new HashMap<String, PageField>();
for (PageField pageField : pageFields) {
pageFieldMap.put(pageField.getFieldKey(), pageField);
}
return pageFieldMap;
}
@Override
public Page updatePage(Page page) {
return em.merge(page);
}
@Override
public void delete(Page page) {
if (!em.contains(page)) {
page = readPageById(page.getId());
}
em.remove(page);
}
@Override
public Page addPage(Page clonedPage) {
return em.merge(clonedPage);
}
@Override
public List<Page> findPageByURI(SandBox sandBox, Locale fullLocale, Locale languageOnlyLocale, String uri) {
Query query;
if (languageOnlyLocale == null) {
languageOnlyLocale = fullLocale;
}
// locale
if (sandBox == null) {
query = em.createNamedQuery("BC_READ_PAGE_BY_URI");
} else if (SandBoxType.PRODUCTION.equals(sandBox.getSandBoxType())) {
query = em.createNamedQuery("BC_READ_PAGE_BY_URI_AND_PRODUCTION_SANDBOX");
query.setParameter("sandbox", sandBox);
} else {
query = em.createNamedQuery("BC_READ_PAGE_BY_URI_AND_USER_SANDBOX");
query.setParameter("sandboxId", sandBox.getId());
}
query.setParameter("fullLocale", fullLocale);
query.setParameter("languageOnlyLocale", languageOnlyLocale);
query.setParameter("uri", uri);
return query.getResultList();
}
@Override
public List<Page> readAllPages() {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Page> criteria = builder.createQuery(Page.class);
Root<PageImpl> page = criteria.from(PageImpl.class);
criteria.select(page);
try {
return em.createQuery(criteria).getResultList();
} catch (NoResultException e) {
return new ArrayList<Page>();
}
}
@Override
public List<PageTemplate> readAllPageTemplates() {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<PageTemplate> criteria = builder.createQuery(PageTemplate.class);
Root<PageTemplateImpl> template = criteria.from(PageTemplateImpl.class);
criteria.select(template);
try {
return em.createQuery(criteria).getResultList();
} catch (NoResultException e) {
return new ArrayList<PageTemplate>();
}
}
@Override
public List<Page> findPageByURI(SandBox sandBox, Locale locale, String uri) {
return findPageByURI(sandBox, locale, null, uri);
}
@Override
public void detachPage(Page page) {
em.detach(page);
}
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_dao_PageDaoImpl.java |
2,067 | public class MapReplicationOperation extends AbstractOperation {
private Map<String, Set<RecordReplicationInfo>> data;
private Map<String, Boolean> mapInitialLoadInfo;
private Map<String, List<DelayedEntry>> delayedEntries;
public MapReplicationOperation() {
}
public MapReplicationOperation(MapService mapService, PartitionContainer container, int partitionId, int replicaIndex) {
this.setPartitionId(partitionId).setReplicaIndex(replicaIndex);
data = new HashMap<String, Set<RecordReplicationInfo>>(container.getMaps().size());
mapInitialLoadInfo = new HashMap<String, Boolean>(container.getMaps().size());
for (Entry<String, RecordStore> entry : container.getMaps().entrySet()) {
RecordStore recordStore = entry.getValue();
MapContainer mapContainer = recordStore.getMapContainer();
final MapConfig mapConfig = mapContainer.getMapConfig();
if (mapConfig.getTotalBackupCount() < replicaIndex) {
continue;
}
String name = entry.getKey();
// adding if initial data is loaded for the only maps that has mapstore behind
if (mapContainer.getStore() != null) {
mapInitialLoadInfo.put(name, replicaIndex > 0 || recordStore.isLoaded());
}
// now prepare data to migrate records
Set<RecordReplicationInfo> recordSet = new HashSet<RecordReplicationInfo>();
for (Entry<Data, Record> recordEntry : recordStore.getReadonlyRecordMap().entrySet()) {
Record record = recordEntry.getValue();
RecordReplicationInfo recordReplicationInfo;
recordReplicationInfo = mapService.createRecordReplicationInfo(record);
recordSet.add(recordReplicationInfo);
}
data.put(name, recordSet);
}
readDelayedEntries(container);
}
private void readDelayedEntries(PartitionContainer container) {
delayedEntries = new HashMap<String, List<DelayedEntry>>(container.getMaps().size());
for (Entry<String, RecordStore> entry : container.getMaps().entrySet()) {
RecordStore recordStore = entry.getValue();
final List<DelayedEntry> delayedEntries = recordStore.getWriteBehindQueue().getSnapShot().asList();
if (delayedEntries != null && delayedEntries.size() == 0) {
continue;
}
this.delayedEntries.put(entry.getKey(), delayedEntries);
}
}
public void run() {
MapService mapService = getService();
if (data != null) {
for (Entry<String, Set<RecordReplicationInfo>> dataEntry : data.entrySet()) {
Set<RecordReplicationInfo> recordReplicationInfos = dataEntry.getValue();
final String mapName = dataEntry.getKey();
RecordStore recordStore = mapService.getRecordStore(getPartitionId(), mapName);
for (RecordReplicationInfo recordReplicationInfo : recordReplicationInfos) {
Data key = recordReplicationInfo.getKey();
Record newRecord = mapService.createRecord(mapName, key, recordReplicationInfo.getValue(), -1);
mapService.applyRecordInfo(newRecord, recordReplicationInfo);
recordStore.putForReplication(key, newRecord);
}
}
}
if (mapInitialLoadInfo != null) {
for (Entry<String, Boolean> entry : mapInitialLoadInfo.entrySet()) {
final String mapName = entry.getKey();
RecordStore recordStore = mapService.getRecordStore(getPartitionId(), mapName);
recordStore.setLoaded(entry.getValue());
}
}
for (Entry<String, List<DelayedEntry>> entry : delayedEntries.entrySet()) {
final RecordStore recordStore = mapService.getRecordStore(getPartitionId(), entry.getKey());
final List<DelayedEntry> replicatedEntries = entry.getValue();
final WriteBehindQueue<DelayedEntry> writeBehindQueue = recordStore.getWriteBehindQueue();
writeBehindQueue.addEnd(replicatedEntries);
}
}
public String getServiceName() {
return MapService.SERVICE_NAME;
}
protected void readInternal(final ObjectDataInput in) throws IOException {
int size = in.readInt();
data = new HashMap<String, Set<RecordReplicationInfo>>(size);
for (int i = 0; i < size; i++) {
String name = in.readUTF();
int mapSize = in.readInt();
Set<RecordReplicationInfo> recordReplicationInfos = new HashSet<RecordReplicationInfo>(mapSize);
for (int j = 0; j < mapSize; j++) {
RecordReplicationInfo recordReplicationInfo = in.readObject();
recordReplicationInfos.add(recordReplicationInfo);
}
data.put(name, recordReplicationInfos);
}
size = in.readInt();
mapInitialLoadInfo = new HashMap<String, Boolean>(size);
for (int i = 0; i < size; i++) {
String name = in.readUTF();
boolean loaded = in.readBoolean();
mapInitialLoadInfo.put(name, loaded);
}
size = in.readInt();
delayedEntries = new HashMap<String, List<DelayedEntry>>(size);
for (int i = 0; i < size; i++) {
final String mapName = in.readUTF();
final int listSize = in.readInt();
final List<DelayedEntry> delayedEntriesList = new ArrayList<DelayedEntry>(listSize);
for (int j = 0; j < listSize; j++) {
final Data key = IOUtil.readNullableData(in);
final Data value = IOUtil.readNullableData(in);
final long storeTime = in.readLong();
final int partitionId = in.readInt();
final DelayedEntry<Data, Data> entry
= DelayedEntry.create(key, value, storeTime, partitionId);
delayedEntriesList.add(entry);
}
delayedEntries.put(mapName, delayedEntriesList);
}
}
protected void writeInternal(final ObjectDataOutput out) throws IOException {
out.writeInt(data.size());
for (Entry<String, Set<RecordReplicationInfo>> mapEntry : data.entrySet()) {
out.writeUTF(mapEntry.getKey());
Set<RecordReplicationInfo> recordReplicationInfos = mapEntry.getValue();
out.writeInt(recordReplicationInfos.size());
for (RecordReplicationInfo recordReplicationInfo : recordReplicationInfos) {
out.writeObject(recordReplicationInfo);
}
}
out.writeInt(mapInitialLoadInfo.size());
for (Entry<String, Boolean> entry : mapInitialLoadInfo.entrySet()) {
out.writeUTF(entry.getKey());
out.writeBoolean(entry.getValue());
}
final MapService mapService = getService();
out.writeInt(delayedEntries.size());
for (Entry<String, List<DelayedEntry>> entry : delayedEntries.entrySet()) {
out.writeUTF(entry.getKey());
final List<DelayedEntry> delayedEntryList = entry.getValue();
out.writeInt(delayedEntryList.size());
for (DelayedEntry e : delayedEntryList) {
final Data key = mapService.toData(e.getKey());
final Data value = mapService.toData(e.getValue());
IOUtil.writeNullableData(out, key);
IOUtil.writeNullableData(out, value);
out.writeLong(e.getStoreTime());
out.writeInt(e.getPartitionId());
}
}
}
public boolean isEmpty() {
return data == null || data.isEmpty();
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_map_operation_MapReplicationOperation.java |
1,053 | return new Terms() {
@Override
public TermsEnum iterator(TermsEnum reuse) throws IOException {
// convert bytes ref for the terms to actual data
return new TermsEnum() {
int currentTerm = 0;
int freq = 0;
int docFreq = -1;
long totalTermFrequency = -1;
int[] positions = new int[1];
int[] startOffsets = new int[1];
int[] endOffsets = new int[1];
BytesRef[] payloads = new BytesRef[1];
final BytesRef spare = new BytesRef();
@Override
public BytesRef next() throws IOException {
if (currentTerm++ < numTerms) {
// term string. first the size...
int termVectorSize = perFieldTermVectorInput.readVInt();
spare.grow(termVectorSize);
// ...then the value.
perFieldTermVectorInput.readBytes(spare.bytes, 0, termVectorSize);
spare.length = termVectorSize;
if (hasTermStatistic) {
docFreq = readPotentiallyNegativeVInt(perFieldTermVectorInput);
totalTermFrequency = readPotentiallyNegativeVLong(perFieldTermVectorInput);
}
freq = readPotentiallyNegativeVInt(perFieldTermVectorInput);
// grow the arrays to read the values. this is just
// for performance reasons. Re-use memory instead of
// realloc.
growBuffers();
// finally, read the values into the arrays
// curentPosition etc. so that we can just iterate
// later
writeInfos(perFieldTermVectorInput);
return spare;
} else {
return null;
}
}
private void writeInfos(final BytesStreamInput input) throws IOException {
for (int i = 0; i < freq; i++) {
if (hasPositions) {
positions[i] = input.readVInt();
}
if (hasOffsets) {
startOffsets[i] = input.readVInt();
endOffsets[i] = input.readVInt();
}
if (hasPayloads) {
int payloadLength = input.readVInt();
if (payloads[i] == null) {
payloads[i] = new BytesRef(payloadLength);
} else {
payloads[i].grow(payloadLength);
}
input.readBytes(payloads[i].bytes, 0, payloadLength);
payloads[i].length = payloadLength;
payloads[i].offset = 0;
}
}
}
private void growBuffers() {
if (hasPositions) {
positions = grow(positions, freq);
}
if (hasOffsets) {
startOffsets = grow(startOffsets, freq);
endOffsets = grow(endOffsets, freq);
}
if (hasPayloads) {
if (payloads.length < freq) {
final BytesRef[] newArray = new BytesRef[ArrayUtil.oversize(freq, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
System.arraycopy(payloads, 0, newArray, 0, payloads.length);
payloads = newArray;
}
}
}
@Override
public Comparator<BytesRef> getComparator() {
return BytesRef.getUTF8SortedAsUnicodeComparator();
}
@Override
public SeekStatus seekCeil(BytesRef text) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void seekExact(long ord) throws IOException {
throw new UnsupportedOperationException("Seek is not supported");
}
@Override
public BytesRef term() throws IOException {
return spare;
}
@Override
public long ord() throws IOException {
throw new UnsupportedOperationException("ordinals are not supported");
}
@Override
public int docFreq() throws IOException {
return docFreq;
}
@Override
public long totalTermFreq() throws IOException {
return totalTermFrequency;
}
@Override
public DocsEnum docs(Bits liveDocs, DocsEnum reuse, int flags) throws IOException {
return docsAndPositions(liveDocs, reuse instanceof DocsAndPositionsEnum ? (DocsAndPositionsEnum) reuse : null, 0);
}
@Override
public DocsAndPositionsEnum docsAndPositions(Bits liveDocs, DocsAndPositionsEnum reuse, int flags) throws IOException {
final TermVectorsDocsAndPosEnum retVal = (reuse instanceof TermVectorsDocsAndPosEnum ? (TermVectorsDocsAndPosEnum) reuse
: new TermVectorsDocsAndPosEnum());
return retVal.reset(hasPositions ? positions : null, hasOffsets ? startOffsets : null, hasOffsets ? endOffsets
: null, hasPayloads ? payloads : null, freq);
}
};
}
@Override
public Comparator<BytesRef> getComparator() {
return BytesRef.getUTF8SortedAsUnicodeComparator();
}
@Override
public long size() throws IOException {
return numTerms;
}
@Override
public long getSumTotalTermFreq() throws IOException {
return sumTotalTermFreq;
}
@Override
public long getSumDocFreq() throws IOException {
return sumDocFreq;
}
@Override
public int getDocCount() throws IOException {
return docCount;
}
@Override
public boolean hasFreqs() {
return true;
}
@Override
public boolean hasOffsets() {
return hasOffsets;
}
@Override
public boolean hasPositions() {
return hasPositions;
}
@Override
public boolean hasPayloads() {
return hasPayloads;
}
}; | 0true
| src_main_java_org_elasticsearch_action_termvector_TermVectorFields.java |
1,254 | public class TransportClientNodesService extends AbstractComponent {
private final TimeValue nodesSamplerInterval;
private final long pingTimeout;
private final ClusterName clusterName;
private final TransportService transportService;
private final ThreadPool threadPool;
private final Version version;
// nodes that are added to be discovered
private volatile ImmutableList<DiscoveryNode> listedNodes = ImmutableList.of();
private final Object mutex = new Object();
private volatile ImmutableList<DiscoveryNode> nodes = ImmutableList.of();
private volatile ImmutableList<DiscoveryNode> filteredNodes = ImmutableList.of();
private final AtomicInteger tempNodeIdGenerator = new AtomicInteger();
private final NodeSampler nodesSampler;
private volatile ScheduledFuture nodesSamplerFuture;
private final AtomicInteger randomNodeGenerator = new AtomicInteger();
private final boolean ignoreClusterName;
private volatile boolean closed;
@Inject
public TransportClientNodesService(Settings settings, ClusterName clusterName, TransportService transportService, ThreadPool threadPool, Version version) {
super(settings);
this.clusterName = clusterName;
this.transportService = transportService;
this.threadPool = threadPool;
this.version = version;
this.nodesSamplerInterval = componentSettings.getAsTime("nodes_sampler_interval", timeValueSeconds(5));
this.pingTimeout = componentSettings.getAsTime("ping_timeout", timeValueSeconds(5)).millis();
this.ignoreClusterName = componentSettings.getAsBoolean("ignore_cluster_name", false);
if (logger.isDebugEnabled()) {
logger.debug("node_sampler_interval[" + nodesSamplerInterval + "]");
}
if (componentSettings.getAsBoolean("sniff", false)) {
this.nodesSampler = new SniffNodesSampler();
} else {
this.nodesSampler = new SimpleNodeSampler();
}
this.nodesSamplerFuture = threadPool.schedule(nodesSamplerInterval, ThreadPool.Names.GENERIC, new ScheduledNodeSampler());
// we want the transport service to throw connect exceptions, so we can retry
transportService.throwConnectException(true);
}
public ImmutableList<TransportAddress> transportAddresses() {
ImmutableList.Builder<TransportAddress> lstBuilder = ImmutableList.builder();
for (DiscoveryNode listedNode : listedNodes) {
lstBuilder.add(listedNode.address());
}
return lstBuilder.build();
}
public ImmutableList<DiscoveryNode> connectedNodes() {
return this.nodes;
}
public ImmutableList<DiscoveryNode> filteredNodes() {
return this.filteredNodes;
}
public ImmutableList<DiscoveryNode> listedNodes() {
return this.listedNodes;
}
public TransportClientNodesService addTransportAddresses(TransportAddress... transportAddresses) {
synchronized (mutex) {
if (closed) {
throw new ElasticsearchIllegalStateException("transport client is closed, can't add an address");
}
List<TransportAddress> filtered = Lists.newArrayListWithExpectedSize(transportAddresses.length);
for (TransportAddress transportAddress : transportAddresses) {
boolean found = false;
for (DiscoveryNode otherNode : listedNodes) {
if (otherNode.address().equals(transportAddress)) {
found = true;
logger.debug("address [{}] already exists with [{}], ignoring...", transportAddress, otherNode);
break;
}
}
if (!found) {
filtered.add(transportAddress);
}
}
if (filtered.isEmpty()) {
return this;
}
ImmutableList.Builder<DiscoveryNode> builder = ImmutableList.builder();
builder.addAll(listedNodes());
for (TransportAddress transportAddress : filtered) {
DiscoveryNode node = new DiscoveryNode("#transport#-" + tempNodeIdGenerator.incrementAndGet(), transportAddress, version);
logger.debug("adding address [{}]", node);
builder.add(node);
}
listedNodes = builder.build();
nodesSampler.sample();
}
return this;
}
public TransportClientNodesService removeTransportAddress(TransportAddress transportAddress) {
synchronized (mutex) {
if (closed) {
throw new ElasticsearchIllegalStateException("transport client is closed, can't remove an address");
}
ImmutableList.Builder<DiscoveryNode> builder = ImmutableList.builder();
for (DiscoveryNode otherNode : listedNodes) {
if (!otherNode.address().equals(transportAddress)) {
builder.add(otherNode);
} else {
logger.debug("removing address [{}]", otherNode);
}
}
listedNodes = builder.build();
nodesSampler.sample();
}
return this;
}
public <T> T execute(NodeCallback<T> callback) throws ElasticsearchException {
ImmutableList<DiscoveryNode> nodes = this.nodes;
if (nodes.isEmpty()) {
throw new NoNodeAvailableException();
}
int index = randomNodeGenerator.incrementAndGet();
if (index < 0) {
index = 0;
randomNodeGenerator.set(0);
}
for (int i = 0; i < nodes.size(); i++) {
DiscoveryNode node = nodes.get((index + i) % nodes.size());
try {
return callback.doWithNode(node);
} catch (ElasticsearchException e) {
if (!(e.unwrapCause() instanceof ConnectTransportException)) {
throw e;
}
}
}
throw new NoNodeAvailableException();
}
public <Response> void execute(NodeListenerCallback<Response> callback, ActionListener<Response> listener) throws ElasticsearchException {
ImmutableList<DiscoveryNode> nodes = this.nodes;
if (nodes.isEmpty()) {
throw new NoNodeAvailableException();
}
int index = randomNodeGenerator.incrementAndGet();
if (index < 0) {
index = 0;
randomNodeGenerator.set(0);
}
RetryListener<Response> retryListener = new RetryListener<Response>(callback, listener, nodes, index);
try {
callback.doWithNode(nodes.get((index) % nodes.size()), retryListener);
} catch (ElasticsearchException e) {
if (e.unwrapCause() instanceof ConnectTransportException) {
retryListener.onFailure(e);
} else {
throw e;
}
}
}
public static class RetryListener<Response> implements ActionListener<Response> {
private final NodeListenerCallback<Response> callback;
private final ActionListener<Response> listener;
private final ImmutableList<DiscoveryNode> nodes;
private final int index;
private volatile int i;
public RetryListener(NodeListenerCallback<Response> callback, ActionListener<Response> listener, ImmutableList<DiscoveryNode> nodes, int index) {
this.callback = callback;
this.listener = listener;
this.nodes = nodes;
this.index = index;
}
@Override
public void onResponse(Response response) {
listener.onResponse(response);
}
@Override
public void onFailure(Throwable e) {
if (ExceptionsHelper.unwrapCause(e) instanceof ConnectTransportException) {
int i = ++this.i;
if (i >= nodes.size()) {
listener.onFailure(new NoNodeAvailableException());
} else {
try {
callback.doWithNode(nodes.get((index + i) % nodes.size()), this);
} catch (Throwable e1) {
// retry the next one...
onFailure(e);
}
}
} else {
listener.onFailure(e);
}
}
}
public void close() {
synchronized (mutex) {
if (closed) {
return;
}
closed = true;
nodesSamplerFuture.cancel(true);
for (DiscoveryNode node : nodes) {
transportService.disconnectFromNode(node);
}
for (DiscoveryNode listedNode : listedNodes) {
transportService.disconnectFromNode(listedNode);
}
nodes = ImmutableList.of();
}
}
abstract class NodeSampler {
public void sample() {
synchronized (mutex) {
if (closed) {
return;
}
doSample();
}
}
protected abstract void doSample();
/**
* validates a set of potentially newly discovered nodes and returns an immutable
* list of the nodes that has passed.
*/
protected ImmutableList<DiscoveryNode> validateNewNodes(Set<DiscoveryNode> nodes) {
for (Iterator<DiscoveryNode> it = nodes.iterator(); it.hasNext(); ) {
DiscoveryNode node = it.next();
if (!transportService.nodeConnected(node)) {
try {
logger.trace("connecting to node [{}]", node);
transportService.connectToNode(node);
} catch (Throwable e) {
it.remove();
logger.debug("failed to connect to discovered node [" + node + "]", e);
}
}
}
return new ImmutableList.Builder<DiscoveryNode>().addAll(nodes).build();
}
}
class ScheduledNodeSampler implements Runnable {
@Override
public void run() {
try {
nodesSampler.sample();
if (!closed) {
nodesSamplerFuture = threadPool.schedule(nodesSamplerInterval, ThreadPool.Names.GENERIC, this);
}
} catch (Exception e) {
logger.warn("failed to sample", e);
}
}
}
class SimpleNodeSampler extends NodeSampler {
@Override
protected void doSample() {
HashSet<DiscoveryNode> newNodes = new HashSet<DiscoveryNode>();
HashSet<DiscoveryNode> newFilteredNodes = new HashSet<DiscoveryNode>();
for (DiscoveryNode listedNode : listedNodes) {
if (!transportService.nodeConnected(listedNode)) {
try {
// its a listed node, light connect to it...
logger.trace("connecting to listed node (light) [{}]", listedNode);
transportService.connectToNodeLight(listedNode);
} catch (Throwable e) {
logger.debug("failed to connect to node [{}], removed from nodes list", e, listedNode);
continue;
}
}
try {
NodesInfoResponse nodeInfo = transportService.submitRequest(listedNode, NodesInfoAction.NAME,
Requests.nodesInfoRequest("_local"),
TransportRequestOptions.options().withType(TransportRequestOptions.Type.STATE).withTimeout(pingTimeout),
new FutureTransportResponseHandler<NodesInfoResponse>() {
@Override
public NodesInfoResponse newInstance() {
return new NodesInfoResponse();
}
}).txGet();
if (!ignoreClusterName && !clusterName.equals(nodeInfo.getClusterName())) {
logger.warn("node {} not part of the cluster {}, ignoring...", listedNode, clusterName);
newFilteredNodes.add(listedNode);
} else if (nodeInfo.getNodes().length != 0) {
// use discovered information but do keep the original transport address, so people can control which address is exactly used.
DiscoveryNode nodeWithInfo = nodeInfo.getNodes()[0].getNode();
newNodes.add(new DiscoveryNode(nodeWithInfo.name(), nodeWithInfo.id(), nodeWithInfo.getHostName(), nodeWithInfo.getHostAddress(), listedNode.address(), nodeWithInfo.attributes(), nodeWithInfo.version()));
} else {
// although we asked for one node, our target may not have completed initialization yet and doesn't have cluster nodes
logger.debug("node {} didn't return any discovery info, temporarily using transport discovery node", listedNode);
newNodes.add(listedNode);
}
} catch (Throwable e) {
logger.info("failed to get node info for {}, disconnecting...", e, listedNode);
transportService.disconnectFromNode(listedNode);
}
}
nodes = validateNewNodes(newNodes);
filteredNodes = ImmutableList.copyOf(newFilteredNodes);
}
}
class SniffNodesSampler extends NodeSampler {
@Override
protected void doSample() {
// the nodes we are going to ping include the core listed nodes that were added
// and the last round of discovered nodes
Set<DiscoveryNode> nodesToPing = Sets.newHashSet();
for (DiscoveryNode node : listedNodes) {
nodesToPing.add(node);
}
for (DiscoveryNode node : nodes) {
nodesToPing.add(node);
}
final CountDownLatch latch = new CountDownLatch(nodesToPing.size());
final ConcurrentMap<DiscoveryNode, ClusterStateResponse> clusterStateResponses = ConcurrentCollections.newConcurrentMap();
for (final DiscoveryNode listedNode : nodesToPing) {
threadPool.executor(ThreadPool.Names.MANAGEMENT).execute(new Runnable() {
@Override
public void run() {
try {
if (!transportService.nodeConnected(listedNode)) {
try {
// if its one of hte actual nodes we will talk to, not to listed nodes, fully connect
if (nodes.contains(listedNode)) {
logger.trace("connecting to cluster node [{}]", listedNode);
transportService.connectToNode(listedNode);
} else {
// its a listed node, light connect to it...
logger.trace("connecting to listed node (light) [{}]", listedNode);
transportService.connectToNodeLight(listedNode);
}
} catch (Exception e) {
logger.debug("failed to connect to node [{}], ignoring...", e, listedNode);
latch.countDown();
return;
}
}
transportService.sendRequest(listedNode, ClusterStateAction.NAME,
Requests.clusterStateRequest()
.clear().nodes(true).local(true),
TransportRequestOptions.options().withType(TransportRequestOptions.Type.STATE).withTimeout(pingTimeout),
new BaseTransportResponseHandler<ClusterStateResponse>() {
@Override
public ClusterStateResponse newInstance() {
return new ClusterStateResponse();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void handleResponse(ClusterStateResponse response) {
clusterStateResponses.put(listedNode, response);
latch.countDown();
}
@Override
public void handleException(TransportException e) {
logger.info("failed to get local cluster state for {}, disconnecting...", e, listedNode);
transportService.disconnectFromNode(listedNode);
latch.countDown();
}
});
} catch (Throwable e) {
logger.info("failed to get local cluster state info for {}, disconnecting...", e, listedNode);
transportService.disconnectFromNode(listedNode);
latch.countDown();
}
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
return;
}
HashSet<DiscoveryNode> newNodes = new HashSet<DiscoveryNode>(listedNodes);
HashSet<DiscoveryNode> newFilteredNodes = new HashSet<DiscoveryNode>();
for (Map.Entry<DiscoveryNode, ClusterStateResponse> entry : clusterStateResponses.entrySet()) {
if (!ignoreClusterName && !clusterName.equals(entry.getValue().getClusterName())) {
logger.warn("node {} not part of the cluster {}, ignoring...", entry.getValue().getState().nodes().localNode(), clusterName);
newFilteredNodes.add(entry.getKey());
continue;
}
for (ObjectCursor<DiscoveryNode> cursor : entry.getValue().getState().nodes().dataNodes().values()) {
newNodes.add(cursor.value);
}
}
nodes = validateNewNodes(newNodes);
filteredNodes = ImmutableList.copyOf(newFilteredNodes);
}
}
public static interface NodeCallback<T> {
T doWithNode(DiscoveryNode node) throws ElasticsearchException;
}
public static interface NodeListenerCallback<Response> {
void doWithNode(DiscoveryNode node, ActionListener<Response> listener) throws ElasticsearchException;
}
} | 1no label
| src_main_java_org_elasticsearch_client_transport_TransportClientNodesService.java |
589 | protected static final class RemovedValue {
public static final RemovedValue INSTANCE = new RemovedValue();
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_OIndexAbstract.java |
524 | Runnable incrementor = new Runnable() {
public void run() {
try {
getKeyForUpdateLatch.await(30, TimeUnit.SECONDS);
boolean result = map.tryPut(key, value, 0, TimeUnit.SECONDS);
tryPutResult.set(result);
afterTryPutResult.countDown();
} catch (Exception e) {
}
}
}; | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_txn_ClientTxnMapTest.java |
711 | @Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_PRODUCT_OPTION")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blStandardElements")
@AdminPresentationClass(friendlyName = "ProductOptionImpl_baseProductOption", populateToOneFields=PopulateToOneFieldsEnum.TRUE)
public class ProductOptionImpl implements ProductOption, AdminMainEntity {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator= "ProductOptionId")
@GenericGenerator(
name="ProductOptionId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="ProductOptionImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.core.catalog.domain.ProductOptionImpl")
}
)
@Column(name = "PRODUCT_OPTION_ID")
protected Long id;
@Column(name = "OPTION_TYPE")
@AdminPresentation(friendlyName = "productOption_Type", fieldType = SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration = "org.broadleafcommerce.core.catalog.service.type.ProductOptionType")
protected String type;
@Column(name = "ATTRIBUTE_NAME")
@AdminPresentation(friendlyName = "productOption_name", helpText = "productOption_nameHelp")
protected String attributeName;
@Column(name = "LABEL")
@AdminPresentation(friendlyName = "productOption_Label", helpText = "productOption_labelHelp",
prominent = true,
translatable = true)
protected String label;
@Column(name = "REQUIRED")
@AdminPresentation(friendlyName = "productOption_Required")
protected Boolean required;
@Column(name = "USE_IN_SKU_GENERATION")
@AdminPresentation(friendlyName = "productOption_UseInSKUGeneration")
private Boolean useInSkuGeneration;
@Column(name = "DISPLAY_ORDER")
@AdminPresentation(friendlyName = "productOption_displayOrder")
protected Integer displayOrder;
@Column(name = "VALIDATION_TYPE")
@AdminPresentation(friendlyName = "productOption_validationType", group = "productOption_validation", fieldType = SupportedFieldType.BROADLEAF_ENUMERATION, broadleafEnumeration = "org.broadleafcommerce.core.catalog.service.type.ProductOptionValidationType")
private String productOptionValidationType;
@Column(name = "VALIDATION_STRING")
@AdminPresentation(friendlyName = "productOption_validationSring", group = "productOption_validation")
protected String validationString;
@Column(name = "ERROR_CODE")
@AdminPresentation(friendlyName = "productOption_errorCode", group = "productOption_validation")
protected String errorCode;
@Column(name = "ERROR_MESSAGE")
@AdminPresentation(friendlyName = "productOption_errorMessage", group = "productOption_validation")
protected String errorMessage;
@OneToMany(mappedBy = "productOption", targetEntity = ProductOptionValueImpl.class, cascade = {CascadeType.ALL})
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@OrderBy(value = "displayOrder")
@AdminPresentationCollection(addType = AddMethodType.PERSIST, friendlyName = "ProductOptionImpl_Allowed_Values")
protected List<ProductOptionValue> allowedValues = new ArrayList<ProductOptionValue>();
@ManyToMany(fetch = FetchType.LAZY, targetEntity = ProductImpl.class)
@JoinTable(name = "BLC_PRODUCT_OPTION_XREF", joinColumns = @JoinColumn(name = "PRODUCT_OPTION_ID", referencedColumnName = "PRODUCT_OPTION_ID"), inverseJoinColumns = @JoinColumn(name = "PRODUCT_ID", referencedColumnName = "PRODUCT_ID"))
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements")
@BatchSize(size = 50)
protected List<Product> products = new ArrayList<Product>();
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public ProductOptionType getType() {
return ProductOptionType.getInstance(type);
}
@Override
public void setType(ProductOptionType type) {
this.type = type == null ? null : type.getType();
}
@Override
public String getAttributeName() {
return attributeName;
}
@Override
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
@Override
public String getLabel() {
return DynamicTranslationProvider.getValue(this, "label", label);
}
@Override
public void setLabel(String label) {
this.label = label;
}
@Override
public Boolean getRequired() {
return required;
}
@Override
public void setRequired(Boolean required) {
this.required = required;
}
@Override
public Integer getDisplayOrder() {
return displayOrder;
}
@Override
public void setDisplayOrder(Integer displayOrder) {
this.displayOrder = displayOrder;
}
@Override
public List<Product> getProducts() {
return products;
}
@Override
public void setProducts(List<Product> products){
this.products = products;
}
@Override
public List<ProductOptionValue> getAllowedValues() {
return allowedValues;
}
@Override
public void setAllowedValues(List<ProductOptionValue> allowedValues) {
this.allowedValues = allowedValues;
}
@Override
public Boolean getUseInSkuGeneration() {
return (useInSkuGeneration == null) ? true : useInSkuGeneration;
}
@Override
public void setUseInSkuGeneration(Boolean useInSkuGeneration) {
this.useInSkuGeneration = useInSkuGeneration;
}
@Override
public ProductOptionValidationType getProductOptionValidationType() {
return ProductOptionValidationType.getInstance(productOptionValidationType);
}
@Override
public void setProductOptionValidationType(ProductOptionValidationType productOptionValidationType) {
this.productOptionValidationType = productOptionValidationType == null ? null : productOptionValidationType.getType();
}
@Override
public String getValidationString() {
return validationString;
}
@Override
public void setValidationString(String validationString) {
this.validationString = validationString;
}
@Override
public String getErrorCode() {
return errorCode;
}
@Override
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
@Override
public String getErrorMessage() {
return errorMessage;
}
@Override
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
@Override
public String getMainEntityName() {
return getLabel();
}
} | 1no label
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_ProductOptionImpl.java |
1,291 | clusterService1.submitStateUpdateTask("test2", new TimeoutClusterStateUpdateTask() {
@Override
public TimeValue timeout() {
return TimeValue.timeValueMillis(2);
}
@Override
public void onFailure(String source, Throwable t) {
timedOut.countDown();
}
@Override
public ClusterState execute(ClusterState currentState) {
executeCalled.set(true);
return currentState;
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
}
}); | 0true
| src_test_java_org_elasticsearch_cluster_ClusterServiceTests.java |
31 | public class IncrementCommandProcessor extends MemcacheCommandProcessor<IncrementCommand> {
private final ILogger logger;
public IncrementCommandProcessor(TextCommandServiceImpl textCommandService) {
super(textCommandService);
logger = textCommandService.getNode().getLogger(this.getClass().getName());
}
public void handle(IncrementCommand incrementCommand) {
String key = null;
try {
key = URLDecoder.decode(incrementCommand.getKey(), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new HazelcastException(e);
}
String mapName = DEFAULT_MAP_NAME;
int index = key.indexOf(':');
if (index != -1) {
mapName = MAP_NAME_PRECEDER + key.substring(0, index);
key = key.substring(index + 1);
}
try {
textCommandService.lock(mapName, key);
} catch (Exception e) {
incrementCommand.setResponse(NOT_FOUND);
if (incrementCommand.shouldReply()) {
textCommandService.sendResponse(incrementCommand);
}
return;
}
Object value = textCommandService.get(mapName, key);
MemcacheEntry entry = null;
if (value != null) {
if (value instanceof MemcacheEntry) {
entry = (MemcacheEntry) value;
} else if (value instanceof byte[]) {
entry = new MemcacheEntry(incrementCommand.getKey(), (byte[]) value, 0);
} else if (value instanceof String) {
entry = new MemcacheEntry(incrementCommand.getKey(), stringToBytes((String) value), 0);
} else {
try {
entry = new MemcacheEntry(incrementCommand.getKey(), textCommandService.toByteArray(value), 0);
} catch (Exception e) {
throw ExceptionUtil.rethrow(e);
}
}
final byte[] value1 = entry.getValue();
final long current = (value1 == null || value1.length == 0) ? 0 : byteArrayToLong(value1);
long result = -1;
if (incrementCommand.getType() == TextCommandType.INCREMENT) {
result = current + incrementCommand.getValue();
result = 0 > result ? Long.MAX_VALUE : result;
textCommandService.incrementIncHitCount();
} else if (incrementCommand.getType() == TextCommandType.DECREMENT) {
result = current - incrementCommand.getValue();
result = 0 > result ? 0 : result;
textCommandService.incrementDecrHitCount();
}
incrementCommand.setResponse(ByteUtil.concatenate(stringToBytes(String.valueOf(result)), RETURN));
MemcacheEntry newValue = new MemcacheEntry(key, longToByteArray(result), entry.getFlag());
textCommandService.put(mapName, key, newValue);
} else {
if (incrementCommand.getType() == TextCommandType.INCREMENT) {
textCommandService.incrementIncMissCount();
} else {
textCommandService.incrementDecrMissCount();
}
incrementCommand.setResponse(NOT_FOUND);
}
textCommandService.unlock(mapName, key);
if (incrementCommand.shouldReply()) {
textCommandService.sendResponse(incrementCommand);
}
}
public void handleRejection(IncrementCommand incrementCommand) {
incrementCommand.setResponse(NOT_FOUND);
if (incrementCommand.shouldReply()) {
textCommandService.sendResponse(incrementCommand);
}
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_ascii_memcache_IncrementCommandProcessor.java |
399 | class CacheRecord<K> {
final K key;
final Object value;
volatile long lastAccessTime;
final long creationTime;
final AtomicInteger hit;
CacheRecord(K key, Object value) {
this.key = key;
this.value = value;
long time = Clock.currentTimeMillis();
this.lastAccessTime = time;
this.creationTime = time;
this.hit = new AtomicInteger(0);
}
void access() {
hit.incrementAndGet();
clientNearCacheStats.incrementHits();
lastAccessTime = Clock.currentTimeMillis();
}
public long getCost() {
// todo find object size if not a Data instance.
if (!(value instanceof Data)) {
return 0;
}
if (!(key instanceof Data)) {
return 0;
}
// value is Data
return ((Data) key).getHeapCost()
+ ((Data) value).getHeapCost()
+ 2 * (Long.SIZE / Byte.SIZE)
// sizeof atomic integer
+ (Integer.SIZE / Byte.SIZE)
// object references (key, value, hit)
+ 3 * (Integer.SIZE / Byte.SIZE);
}
boolean expired() {
long time = Clock.currentTimeMillis();
return (maxIdleMillis > 0 && time > lastAccessTime + maxIdleMillis)
|| (timeToLiveMillis > 0 && time > creationTime + timeToLiveMillis);
}
} | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_nearcache_ClientNearCache.java |
1,525 | public class RoutingNodesUtils {
public static int numberOfShardsOfType(RoutingNodes nodes, ShardRoutingState state) {
int count = 0;
for (RoutingNode routingNode : nodes) {
count += routingNode.numberOfShardsWithState(state);
}
return count;
}
} | 0true
| src_test_java_org_elasticsearch_cluster_routing_allocation_RoutingNodesUtils.java |
411 | public class CleanImportsHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event)
throws ExecutionException {
CeylonEditor editor = (CeylonEditor) getCurrentEditor();
IDocument doc = editor.getCeylonSourceViewer().getDocument();
cleanImports(editor.getParseController(), doc);
return null;
}
public static void cleanImports(CeylonParseController cpc, IDocument doc) {
if (!isEnabled(cpc)) return;
Tree.CompilationUnit rootNode = cpc.getRootNode();
if (rootNode!=null) {
String imports = imports(rootNode, doc);
if (imports!=null &&
!(imports.trim().isEmpty() &&
rootNode.getImportList().getImports().isEmpty())) {
Tree.ImportList il = rootNode.getImportList();
int start;
int length;
String extra;
if (il==null || il.getImports().isEmpty()) {
start=0;
length=0;
extra=getDefaultLineDelimiter(doc);
}
else {
start = il.getStartIndex();
length = il.getStopIndex()-il.getStartIndex()+1;
extra="";
}
try {
if (!doc.get(start, length).equals(imports+extra)) {
DocumentChange change =
new DocumentChange("Organize Imports", doc);
change.setEdit(new ReplaceEdit(start, length, imports+extra));
try {
change.perform(new NullProgressMonitor());
}
catch (CoreException e) {
e.printStackTrace();
}
}
}
catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
public static String imports(Node node, Tree.ImportList til,
IDocument doc) {
List<Declaration> unused = new ArrayList<Declaration>();
DetectUnusedImportsVisitor duiv =
new DetectUnusedImportsVisitor(unused);
til.visit(duiv);
node.visit(duiv);
return reorganizeImports(til, unused,
Collections.<Declaration>emptyList(), doc);
}
private static String imports(final Tree.CompilationUnit cu,
IDocument doc) {
List<Declaration> proposals = new ArrayList<Declaration>();
List<Declaration> unused = new ArrayList<Declaration>();
new ImportProposalsVisitor(cu, proposals).visit(cu);
new DetectUnusedImportsVisitor(unused).visit(cu);
return reorganizeImports(cu.getImportList(), unused, proposals, doc);
}
public static String imports(List<Declaration> proposed,
IDocument doc) {
return reorganizeImports(null,
Collections.<Declaration>emptyList(),
proposed, doc);
}
public static String reorganizeImports(Tree.ImportList til,
List<Declaration> unused, List<Declaration> proposed,
IDocument doc) {
Map<String,List<Tree.Import>> packages =
new TreeMap<String,List<Tree.Import>>();
if (til!=null) {
for (Tree.Import i: til.getImports()) {
String pn = packageName(i);
if (pn!=null) {
List<Tree.Import> is = packages.get(pn);
if (is==null) {
is = new ArrayList<Tree.Import>();
packages.put(pn, is);
}
is.add(i);
}
}
}
for (Declaration d: proposed) {
String pn = d.getUnit().getPackage().getNameAsString();
if (!packages.containsKey(pn)) {
packages.put(pn, Collections.<Tree.Import>emptyList());
}
}
StringBuilder builder = new StringBuilder();
String lastToplevel=null;
String delim = getDefaultLineDelimiter(doc);
for (Map.Entry<String, List<Tree.Import>> pack:
packages.entrySet()) {
String packageName = pack.getKey();
List<Tree.Import> imports = pack.getValue();
boolean hasWildcard = hasWildcard(imports);
List<Tree.ImportMemberOrType> list =
getUsedImportElements(imports, unused,
hasWildcard, packages);
if (hasWildcard || !list.isEmpty() ||
imports.isEmpty()) { //in this last case there is no existing import, but imports are proposed
lastToplevel = appendBreakIfNecessary(lastToplevel,
packageName, builder, doc);
Referenceable packageModel = imports.isEmpty() ?
null : //TODO: what to do in this case? look up the Package where?
imports.get(0).getImportPath().getModel();
String escapedPackageName = packageModel instanceof Package ?
escapePackageName((Package) packageModel) :
packageName;
if (builder.length()!=0) {
builder.append(delim);
}
builder.append("import ")
.append(escapedPackageName)
.append(" {");
appendImportElements(packageName, list, unused,
proposed, hasWildcard, builder, doc);
builder.append(delim).append("}");
}
}
return builder.toString();
}
private static boolean hasWildcard(List<Tree.Import> imports) {
boolean hasWildcard = false;
for (Tree.Import i: imports) {
hasWildcard = hasWildcard ||
i!=null && i.getImportMemberOrTypeList()
.getImportWildcard()!=null;
}
return hasWildcard;
}
private static String appendBreakIfNecessary(String lastToplevel,
String currentPackage, StringBuilder builder, IDocument doc) {
int di = currentPackage.indexOf('.');
String topLevel = di<0 ?
currentPackage:currentPackage.substring(0, di);
if (lastToplevel!=null && !topLevel.equals(lastToplevel)) {
builder.append(getDefaultLineDelimiter(doc));
}
return topLevel;
}
private static void appendImportElements(String packageName,
List<Tree.ImportMemberOrType> elements, List<Declaration> unused,
List<Declaration> proposed, boolean hasWildcard,
StringBuilder builder, IDocument doc) {
String indent = getDefaultIndent();
for (Tree.ImportMemberOrType i: elements) {
if (i.getDeclarationModel()!=null &&
i.getIdentifier().getErrors().isEmpty() &&
i.getErrors().isEmpty()) {
builder.append(getDefaultLineDelimiter(doc))
.append(indent);
if (!i.getImportModel().getAlias()
.equals(i.getDeclarationModel().getName())) {
String escapedAlias = escapeAliasedName(i.getDeclarationModel(),
i.getImportModel().getAlias());
builder.append(escapedAlias).append("=");
}
builder.append(escapeName(i.getDeclarationModel()));
appendNestedImportElements(i, unused, builder, doc);
builder.append(",");
}
}
for (Declaration d: proposed) {
if (d.getUnit().getPackage().getNameAsString()
.equals(packageName)) {
builder.append(getDefaultLineDelimiter(doc))
.append(indent);
builder.append(escapeName(d)).append(",");
}
}
if (hasWildcard) {
builder.append(getDefaultLineDelimiter(doc))
.append(indent)
.append("...");
}
else {
// remove trailing ,
builder.setLength(builder.length()-1);
}
}
private static void appendNestedImportElements(Tree.ImportMemberOrType imt,
List<Declaration> unused, StringBuilder builder, IDocument doc) {
String indent = getDefaultIndent();
if (imt.getImportMemberOrTypeList()!=null) {
builder.append(" {");
boolean found=false;
for (Tree.ImportMemberOrType nimt:
imt.getImportMemberOrTypeList()
.getImportMemberOrTypes()) {
if (nimt.getDeclarationModel()!=null &&
nimt.getIdentifier().getErrors().isEmpty() &&
nimt.getErrors().isEmpty()) {
if (!unused.contains(nimt.getDeclarationModel())) {
found=true;
builder.append(getDefaultLineDelimiter(doc))
.append(indent).append(indent);
if (!nimt.getImportModel().getAlias()
.equals(nimt.getDeclarationModel().getName())) {
builder.append(nimt.getImportModel().getAlias())
.append("=");
}
builder.append(nimt.getDeclarationModel().getName())
.append(",");
}
}
}
if (imt.getImportMemberOrTypeList()
.getImportWildcard()!=null) {
found=true;
builder.append(getDefaultLineDelimiter(doc))
.append(indent).append(indent)
.append("...,");
}
if (found) {
// remove trailing ","
builder.setLength(builder.length()-1);
builder.append(getDefaultLineDelimiter(doc))
.append(indent)
.append('}');
} else {
// remove the " {"
builder.setLength(builder.length()-2);
}
}
}
private static boolean hasRealErrors(Node node) {
for (Message m: node.getErrors()) {
if (m instanceof AnalysisError) {
return true;
}
}
return false;
}
private static List<Tree.ImportMemberOrType> getUsedImportElements(
List<Tree.Import> imports, List<Declaration> unused,
boolean hasWildcard, Map<String, List<Tree.Import>> packages) {
List<Tree.ImportMemberOrType> list =
new ArrayList<Tree.ImportMemberOrType>();
for (Tree.Import ti: imports) {
for (Tree.ImportMemberOrType imt:
ti.getImportMemberOrTypeList()
.getImportMemberOrTypes()) {
Declaration dm = imt.getDeclarationModel();
if (dm!=null &&
!hasRealErrors(imt.getIdentifier()) &&
!hasRealErrors(imt)) {
Tree.ImportMemberOrTypeList nimtl = imt.getImportMemberOrTypeList();
if (unused.contains(dm)) {
if (nimtl!=null) {
for (Tree.ImportMemberOrType nimt:
nimtl.getImportMemberOrTypes()) {
Declaration ndm = nimt.getDeclarationModel();
if (ndm!=null &&
!hasRealErrors(nimt.getIdentifier()) &&
!hasRealErrors(nimt)) {
if (!unused.contains(ndm)) {
list.add(imt);
break;
}
}
}
if (nimtl.getImportWildcard()!=null) {
list.add(imt);
}
}
}
else {
if (!hasWildcard ||
imt.getAlias()!=null ||
nimtl!=null ||
preventAmbiguityDueWildcards(dm, packages)) {
list.add(imt);
}
}
}
}
}
return list;
}
private static boolean preventAmbiguityDueWildcards(Declaration d,
Map<String, List<Tree.Import>> importsMap) {
Module module = d.getUnit().getPackage().getModule();
String containerName = d.getContainer().getQualifiedNameString();
for (Map.Entry<String, List<Tree.Import>> importEntry:
importsMap.entrySet()) {
String packageName = importEntry.getKey();
List<Tree.Import> importList = importEntry.getValue();
if (!packageName.equals(containerName) &&
hasWildcard(importList)) {
Package p2 = module.getPackage(packageName);
if (p2 != null) {
Declaration d2 = p2.getMember(d.getName(), null, false);
if (d2!=null &&
d2.isToplevel() &&
d2.isShared() &&
!d2.isAnonymous() &&
!isImportedWithAlias(d2, importList)) {
return true;
}
}
}
}
return false;
}
private static boolean isImportedWithAlias(Declaration d,
List<Tree.Import> importList) {
for (Tree.Import i: importList) {
for (Tree.ImportMemberOrType imt:
i.getImportMemberOrTypeList()
.getImportMemberOrTypes()) {
if (d.getName().equals(imt.getIdentifier().getText()) &&
imt.getAlias() != null) {
return true;
}
}
}
return false;
}
private static String packageName(Tree.Import i) {
if (i.getImportPath()!=null) {
return formatPath(i.getImportPath().getIdentifiers());
}
else {
return null;
}
}
@Override
public boolean isEnabled() {
IEditorPart editor = getCurrentEditor();
if (super.isEnabled() &&
editor instanceof CeylonEditor &&
editor.getEditorInput() instanceof IFileEditorInput) {
CeylonParseController cpc =
((CeylonEditor) editor).getParseController();
return isEnabled(cpc);
}
else {
return false;
}
}
public static boolean isEnabled(CeylonParseController cpc) {
return cpc!=null &&
cpc.getStage().ordinal()>=Stage.TYPE_ANALYSIS.ordinal() &&
cpc.getRootNode()!=null;
}
public static Declaration select(List<Declaration> proposals) {
CeylonEditor editor = (CeylonEditor) getCurrentEditor();
ImportSelectionDialog fid =
new ImportSelectionDialog(editor.getSite().getShell(),
proposals);
if (fid.open() == Window.OK) {
return (Declaration) fid.getFirstResult();
}
else {
return null;
}
}
} | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_imports_CleanImportsHandler.java |
385 | public static enum OChangeType {
ADD, UPDATE, REMOVE
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_record_OMultiValueChangeEvent.java |
1,195 | class Handler extends SimpleChannelUpstreamHandler {
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
logger.trace("received message size [{}]", buffer.readableBytes());
try {
bulkProcessor.add(new ChannelBufferBytesReference(buffer), false, null, null);
} catch (Exception e1) {
logger.warn("failed to execute bulk request", e1);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
if (e.getCause() instanceof BindException) {
// ignore, this happens when we retry binding to several ports, its fine if we fail...
return;
}
logger.warn("failure caught", e.getCause());
}
} | 0true
| src_main_java_org_elasticsearch_bulk_udp_BulkUdpService.java |
225 | XPostingsHighlighter highlighter = new XPostingsHighlighter() {
@Override
protected BreakIterator getBreakIterator(String field) {
return new WholeBreakIterator();
}
@Override
protected char getMultiValuedSeparator(String field) {
//U+2029 PARAGRAPH SEPARATOR (PS): each value holds a discrete passage for highlighting
return 8233;
}
}; | 0true
| src_test_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighterTests.java |
1,368 | public class ClusterBlockException extends ElasticsearchException {
private final ImmutableSet<ClusterBlock> blocks;
public ClusterBlockException(ImmutableSet<ClusterBlock> blocks) {
super(buildMessage(blocks));
this.blocks = blocks;
}
public boolean retryable() {
for (ClusterBlock block : blocks) {
if (!block.retryable()) {
return false;
}
}
return true;
}
public ImmutableSet<ClusterBlock> blocks() {
return blocks;
}
private static String buildMessage(ImmutableSet<ClusterBlock> blocks) {
StringBuilder sb = new StringBuilder("blocked by: ");
for (ClusterBlock block : blocks) {
sb.append("[").append(block.status()).append("/").append(block.id()).append("/").append(block.description()).append("];");
}
return sb.toString();
}
@Override
public RestStatus status() {
RestStatus status = null;
for (ClusterBlock block : blocks) {
if (status == null) {
status = block.status();
} else if (status.getStatus() < block.status().getStatus()) {
status = block.status();
}
}
return status;
}
} | 0true
| src_main_java_org_elasticsearch_cluster_block_ClusterBlockException.java |
392 | static class UnLockThread extends Thread{
public Exception exception=null;
public MultiMap mm=null;
public Object key=null;
public UnLockThread(MultiMap mm, Object key){
this.mm = mm;
this.key = key;
}
public void run() {
try{
mm.unlock(key);
}catch (Exception e){
exception = e;
}
}
}; | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_multimap_ClientMultiMapLockTest.java |
1,818 | @Component("blHTMLFieldPersistenceProvider")
@Scope("prototype")
public class HTMLFieldPersistenceProvider extends FieldPersistenceProviderAdapter {
@Value("${asset.server.url.prefix.internal}")
protected String staticAssetUrlPrefix;
protected boolean canHandlePersistence(PopulateValueRequest populateValueRequest, Serializable instance) {
return populateValueRequest.getMetadata().getFieldType() == SupportedFieldType.HTML ||
populateValueRequest.getMetadata().getFieldType() == SupportedFieldType.HTML_BASIC;
}
protected boolean canHandleExtraction(ExtractValueRequest extractValueRequest, Property property) {
return extractValueRequest.getMetadata().getFieldType() == SupportedFieldType.HTML ||
extractValueRequest.getMetadata().getFieldType() == SupportedFieldType.HTML_BASIC;
}
@Override
public FieldProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) throws PersistenceException {
if (!canHandlePersistence(populateValueRequest, instance)) {
return FieldProviderResponse.NOT_HANDLED;
}
try {
String requestedValue = populateValueRequest.getRequestedValue();
String fixedValue = fixAssetPathsForStorage(requestedValue);
populateValueRequest.getFieldManager().setFieldValue(instance,
populateValueRequest.getProperty().getName(), fixedValue);
} catch (Exception e) {
throw new PersistenceException(e);
}
return FieldProviderResponse.HANDLED;
}
@Override
public FieldProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException {
if (!canHandleExtraction(extractValueRequest, property)) {
return FieldProviderResponse.NOT_HANDLED;
}
if (extractValueRequest.getRequestedValue() != null) {
String val = extractValueRequest.getRequestedValue().toString();
if (val != null) {
if (val.contains(staticAssetUrlPrefix)) {
val = fixAssetPathsForDisplay(val);
}
}
property.setValue(val);
property.setDisplayValue(extractValueRequest.getDisplayVal());
}
return FieldProviderResponse.HANDLED;
}
/**
* Stores the image paths at the root (e.g. no Servlet Context).
* @param val
* @return
*/
public String fixAssetPathsForStorage(String val) {
if (staticAssetUrlPrefix != null) {
String tmpPrefix = staticAssetUrlPrefix;
if (tmpPrefix.startsWith("/")) {
tmpPrefix = tmpPrefix.substring(1);
}
return val.replaceAll("(?<=src=\").*?(?=" + tmpPrefix + ")", "/");
}
return val;
}
/**
*
* @param val
* @return
*/
public String fixAssetPathsForDisplay(String val) {
String contextPath = "/";
BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext();
if (brc != null) {
HttpServletRequest request = brc.getRequest();
if (request != null) {
contextPath = request.getContextPath();
}
}
if (!contextPath.endsWith("/")) {
contextPath = contextPath + "/";
}
if (staticAssetUrlPrefix != null) {
String tmpPrefix = staticAssetUrlPrefix;
if (tmpPrefix.startsWith("/")) {
tmpPrefix = tmpPrefix.substring(1);
}
return val.replaceAll("(?<=src=\").*?(?=" + tmpPrefix + ")", contextPath);
}
return val;
}
} | 1no label
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_provider_HTMLFieldPersistenceProvider.java |
907 | public final class SuggestRequest extends BroadcastOperationRequest<SuggestRequest> {
static final XContentType contentType = Requests.CONTENT_TYPE;
@Nullable
private String routing;
@Nullable
private String preference;
private BytesReference suggestSource;
private boolean suggestSourceUnsafe;
SuggestRequest() {
}
/**
* Constructs a new suggest request against the provided indices. No indices provided means it will
* run against all indices.
*/
public SuggestRequest(String... indices) {
super(indices);
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = super.validate();
return validationException;
}
@Override
protected void beforeStart() {
if (suggestSourceUnsafe) {
suggest(suggestSource.copyBytesArray(), false);
}
}
/**
* The Phrase to get correction suggestions for
*/
BytesReference suggest() {
return suggestSource;
}
/**
* set a new source for the suggest query
*/
public SuggestRequest suggest(BytesReference suggestSource) {
return suggest(suggestSource, false);
}
/**
* A comma separated list of routing values to control the shards the search will be executed on.
*/
public String routing() {
return this.routing;
}
/**
* A comma separated list of routing values to control the shards the search will be executed on.
*/
public SuggestRequest routing(String routing) {
this.routing = routing;
return this;
}
/**
* The routing values to control the shards that the search will be executed on.
*/
public SuggestRequest routing(String... routings) {
this.routing = Strings.arrayToCommaDelimitedString(routings);
return this;
}
public SuggestRequest preference(String preference) {
this.preference = preference;
return this;
}
public String preference() {
return this.preference;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
routing = in.readOptionalString();
preference = in.readOptionalString();
suggest(in.readBytesReference());
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeOptionalString(routing);
out.writeOptionalString(preference);
out.writeBytesReference(suggestSource);
}
@Override
public String toString() {
String sSource = "_na_";
try {
sSource = XContentHelper.convertToJson(suggestSource, false);
} catch (Exception e) {
// ignore
}
return "[" + Arrays.toString(indices) + "]" + ", suggestSource[" + sSource + "]";
}
public SuggestRequest suggest(BytesReference suggestSource, boolean contentUnsafe) {
this.suggestSource = suggestSource;
this.suggestSourceUnsafe = contentUnsafe;
return this;
}
public SuggestRequest suggest(String source) {
return suggest(new BytesArray(source));
}
} | 0true
| src_main_java_org_elasticsearch_action_suggest_SuggestRequest.java |
423 | trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
Assert.assertEquals(event.getChangeType(), OMultiValueChangeEvent.OChangeType.ADD);
Assert.assertNull(event.getOldValue());
Assert.assertEquals(event.getKey().intValue(), 1);
Assert.assertEquals(event.getValue(), "value3");
changed.value = true;
}
}); | 0true
| core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedListTest.java |
33 | @edu.umd.cs.findbugs.annotations.SuppressWarnings("EI_EXPOSE_REP")
public class MemcacheEntry implements DataSerializable, TextCommandConstants {
private byte[] bytes;
private byte[] value;
private int flag;
public MemcacheEntry(String key, byte[] value, int flag) {
byte[] flagBytes = stringToBytes(" " + flag + " ");
byte[] valueLen = stringToBytes(String.valueOf(value.length));
byte[] keyBytes = stringToBytes(key);
this.value = value.clone();
int size = VALUE_SPACE.length
+ keyBytes.length
+ flagBytes.length
+ valueLen.length
+ RETURN.length
+ value.length
+ RETURN.length;
ByteBuffer entryBuffer = ByteBuffer.allocate(size);
entryBuffer.put(VALUE_SPACE);
entryBuffer.put(keyBytes);
entryBuffer.put(flagBytes);
entryBuffer.put(valueLen);
entryBuffer.put(RETURN);
entryBuffer.put(value);
entryBuffer.put(RETURN);
this.bytes = entryBuffer.array();
this.flag = flag;
}
public MemcacheEntry() {
}
public void readData(ObjectDataInput in) throws IOException {
int size = in.readInt();
bytes = new byte[size];
in.readFully(bytes);
size = in.readInt();
value = new byte[size];
in.readFully(value);
flag = in.readInt();
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(bytes.length);
out.write(bytes);
out.writeInt(value.length);
out.write(value);
out.writeInt(flag);
}
public ByteBuffer toNewBuffer() {
return ByteBuffer.wrap(bytes);
}
public int getFlag() {
return flag;
}
public byte[] getBytes() {
return bytes;
}
public byte[] getValue() {
return value;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MemcacheEntry that = (MemcacheEntry) o;
if (flag != that.flag) {
return false;
}
if (!Arrays.equals(bytes, that.bytes)) {
return false;
}
if (!Arrays.equals(value, that.value)) {
return false;
}
return true;
}
public int hashCode() {
int result = bytes != null ? Arrays.hashCode(bytes) : 0;
result = 31 * result + (value != null ? Arrays.hashCode(value) : 0);
result = 31 * result + flag;
return result;
}
public String toString() {
return "MemcacheEntry{"
+ "bytes="
+ bytesToString(bytes)
+ ", flag="
+ flag
+ '}';
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_ascii_memcache_MemcacheEntry.java |
67 | public class TransactionAlreadyActiveException extends IllegalStateException
{
public TransactionAlreadyActiveException( Thread thread, Transaction tx )
{
super( "Thread '" + thread.getName() + "' tried to resume " + tx + ", but that transaction is already active" );
}
} | 0true
| community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TransactionAlreadyActiveException.java |
1,504 | public class GroupCountMapReduce {
public static final String KEY_CLOSURE = Tokens.makeNamespace(GroupCountMapReduce.class) + ".keyClosure";
public static final String VALUE_CLOSURE = Tokens.makeNamespace(GroupCountMapReduce.class) + ".valueClosure";
public static final String CLASS = Tokens.makeNamespace(GroupCountMapReduce.class) + ".class";
private static final ScriptEngine engine = new GremlinGroovyScriptEngine();
public enum Counters {
VERTICES_PROCESSED,
OUT_EDGES_PROCESSED
}
public static Configuration createConfiguration(final Class<? extends Element> klass, final String keyClosure, final String valueClosure) {
final Configuration configuration = new EmptyConfiguration();
configuration.setClass(CLASS, klass, Element.class);
if (null != keyClosure)
configuration.set(KEY_CLOSURE, keyClosure);
if (null != valueClosure)
configuration.set(VALUE_CLOSURE, valueClosure);
return configuration;
}
public static class Map extends Mapper<NullWritable, FaunusVertex, Text, LongWritable> {
private Closure keyClosure;
private Closure valueClosure;
private boolean isVertex;
private CounterMap<Object> map;
private int mapSpillOver;
private SafeMapperOutputs outputs;
@Override
public void setup(final Mapper.Context context) throws IOException, InterruptedException {
Configuration hc = DEFAULT_COMPAT.getContextConfiguration(context);
ModifiableHadoopConfiguration titanConf = ModifiableHadoopConfiguration.of(hc);
try {
this.mapSpillOver = titanConf.get(PIPELINE_MAP_SPILL_OVER);
final String keyClosureString = context.getConfiguration().get(KEY_CLOSURE, null);
if (null == keyClosureString)
this.keyClosure = null;
else
this.keyClosure = (Closure) engine.eval(keyClosureString);
final String valueClosureString = context.getConfiguration().get(VALUE_CLOSURE, null);
if (null == valueClosureString)
this.valueClosure = null;
else
this.valueClosure = (Closure) engine.eval(valueClosureString);
} catch (final ScriptException e) {
throw new IOException(e.getMessage(), e);
}
this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class);
this.map = new CounterMap<Object>();
this.outputs = new SafeMapperOutputs(context);
}
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, Text, LongWritable>.Context context) throws IOException, InterruptedException {
if (this.isVertex) {
if (value.hasPaths()) {
final Object object = (null == this.keyClosure) ? new FaunusVertex.MicroVertex(value.getLongId()) : this.keyClosure.call(value);
final Number number = (null == this.valueClosure) ? 1 : (Number) this.valueClosure.call(value);
this.map.incr(object, number.longValue() * value.pathCount());
DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_PROCESSED, 1L);
}
} else {
long edgesProcessed = 0;
for (final Edge e : value.getEdges(Direction.OUT)) {
final StandardFaunusEdge edge = (StandardFaunusEdge) e;
if (edge.hasPaths()) {
final Object object = (null == this.keyClosure) ? new StandardFaunusEdge.MicroEdge(edge.getLongId()) : this.keyClosure.call(edge);
final Number number = (null == this.valueClosure) ? 1 : (Number) this.valueClosure.call(edge);
this.map.incr(object, number.longValue() * edge.pathCount());
edgesProcessed++;
}
}
DEFAULT_COMPAT.incrementContextCounter(context, Counters.OUT_EDGES_PROCESSED, edgesProcessed);
}
// protected against memory explosion
if (this.map.size() > this.mapSpillOver) {
this.dischargeMap(context);
}
this.outputs.write(Tokens.GRAPH, NullWritable.get(), value);
}
private final Text textWritable = new Text();
private final LongWritable longWritable = new LongWritable();
public void dischargeMap(final Mapper<NullWritable, FaunusVertex, Text, LongWritable>.Context context) throws IOException, InterruptedException {
for (final java.util.Map.Entry<Object, Long> entry : this.map.entrySet()) {
this.textWritable.set(null == entry.getKey() ? Tokens.NULL : entry.getKey().toString());
this.longWritable.set(entry.getValue());
context.write(this.textWritable, this.longWritable);
}
this.map.clear();
}
@Override
public void cleanup(final Mapper<NullWritable, FaunusVertex, Text, LongWritable>.Context context) throws IOException, InterruptedException {
this.dischargeMap(context);
this.outputs.close();
}
}
public static class Combiner extends Reducer<Text, LongWritable, Text, LongWritable> {
private final LongWritable longWritable = new LongWritable();
@Override
public void reduce(final Text key, final Iterable<LongWritable> values, final Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
long totalCount = 0;
for (final LongWritable token : values) {
totalCount = totalCount + token.get();
}
this.longWritable.set(totalCount);
context.write(key, this.longWritable);
}
}
public static class Reduce extends Reducer<Text, LongWritable, Text, LongWritable> {
private SafeReducerOutputs outputs;
@Override
public void setup(final Reducer.Context context) throws IOException, InterruptedException {
this.outputs = new SafeReducerOutputs(context);
}
private final LongWritable longWritable = new LongWritable();
@Override
public void reduce(final Text key, final Iterable<LongWritable> values, final Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
long totalCount = 0;
for (final LongWritable token : values) {
totalCount = totalCount + token.get();
}
this.longWritable.set(totalCount);
this.outputs.write(Tokens.SIDEEFFECT, key, this.longWritable);
}
@Override
public void cleanup(final Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
this.outputs.close();
}
}
} | 1no label
| titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_sideeffect_GroupCountMapReduce.java |
1,240 | public final class CeylonClasspathUtil {
private CeylonClasspathUtil() {
// utility class
}
/**
* Get the Ivy classpath container from the selection in the Java package view
*
* @param selection
* the selection
* @return
* @throws JavaModelException
*/
public static CeylonProjectModulesContainer getCeylonClasspathContainer(IStructuredSelection selection) {
if (selection == null) {
return null;
}
for (@SuppressWarnings("rawtypes") Iterator it = selection.iterator();
it.hasNext();) {
Object element = it.next();
CeylonProjectModulesContainer cp = (CeylonProjectModulesContainer) CeylonPlugin.adapt(element,
CeylonProjectModulesContainer.class);
if (cp != null) {
return cp;
}
if (element instanceof ClassPathContainer) {
// FIXME: we shouldn't check against internal JDT API but there are not adaptable to
// useful class
return jdt2CeylonCPC((ClassPathContainer) element);
}
}
return null;
}
/**
* Work around the non adaptability of ClassPathContainer
*
* @param cpc
* the container to transform into an CeylonApplicationModulesContainer
* @return the CeylonApplicationModulesContainer is such, null, if not
*/
public static CeylonProjectModulesContainer jdt2CeylonCPC(ClassPathContainer cpc) {
IClasspathEntry entry = cpc.getClasspathEntry();
try {
IClasspathContainer icp = JavaCore.getClasspathContainer(entry.getPath(), cpc
.getJavaProject());
if (icp instanceof CeylonProjectModulesContainer) {
return (CeylonProjectModulesContainer) icp;
}
}
catch (JavaModelException e) {
// unless there are issues with the JDT, this should never happen
e.printStackTrace();
}
return null;
}
public static boolean isCeylonClasspathContainer(IPath containerPath) {
return isLanguageModuleClasspathContainer(containerPath) ||
isProjectModulesClasspathContainer(containerPath);
}
public static boolean isLanguageModuleClasspathContainer(IPath containerPath) {
int size = containerPath.segmentCount();
if (size > 0) {
return (containerPath.segment(0).equals(CeylonLanguageModuleContainer.CONTAINER_ID));
}
return false;
}
public static boolean isProjectModulesClasspathContainer(IPath containerPath) {
int size = containerPath.segmentCount();
if (size > 0) {
return (containerPath.segment(0).equals(CeylonProjectModulesContainer.CONTAINER_ID));
}
return false;
}
/**
* Search the Ceylon classpath containers within the specified Java project
*
* @param javaProject
* the project to search into
* @return the Ceylon classpath container if found
*/
public static List <IClasspathContainer> getCeylonClasspathContainers(
IJavaProject javaProject) {
List<IClasspathContainer> containers = new ArrayList<IClasspathContainer>();
if (FakeProjectManager.isFake(javaProject) || !javaProject.exists()) {
return containers;
}
try {
IClasspathEntry[] entries = javaProject.getRawClasspath();
for (int i = 0; i < entries.length; i++) {
IClasspathEntry entry = entries[i];
if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
IPath path = entry.getPath();
if (isCeylonClasspathContainer(path)) {
IClasspathContainer cp = JavaCore.getClasspathContainer(path, javaProject);
if (cp instanceof CeylonProjectModulesContainer ||
cp instanceof CeylonLanguageModuleContainer) {
containers.add(cp);
}
}
}
}
}
catch (JavaModelException e) {
// unless there are issues with the JDT, this should never happen
e.printStackTrace();
}
return containers;
}
public static CeylonProjectModulesContainer getCeylonProjectModulesClasspathContainer(
IJavaProject javaProject) {
try {
IClasspathEntry[] entries = javaProject.getRawClasspath();
for (int i = 0; i < entries.length; i++) {
IClasspathEntry entry = entries[i];
if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
IPath path = entry.getPath();
if (isProjectModulesClasspathContainer(path)) {
IClasspathContainer cp = JavaCore.getClasspathContainer(path, javaProject);
if (cp instanceof CeylonProjectModulesContainer) {
return (CeylonProjectModulesContainer) cp;
}
}
}
}
}
catch (JavaModelException e) {
// unless there are issues with the JDT, this should never happen
e.printStackTrace();
}
return null;
}
public static List<String> split(String str) {
String[] terms = str.split(",");
List<String> ret = new ArrayList<String>();
for (int i = 0; i < terms.length; i++) {
String t = terms[i].trim();
if (t.length() > 0) {
ret.add(t);
}
}
return ret;
}
public static String concat(Collection<String> list) {
if (list == null) {
return "";
}
StringBuffer b = new StringBuffer();
Iterator<String> it = list.iterator();
while (it.hasNext()) {
b.append(it.next());
if (it.hasNext()) {
b.append(",");
}
}
return b.toString();
}
/**
* Just a verbatim copy of the internal Eclipse function:
* org.eclipse.jdt.internal.corext.javadoc
* .JavaDocLocations#getLibraryJavadocLocation(IClasspathEntry)
*
* @param entry
* @return
*/
public static URL getLibraryJavadocLocation(IClasspathEntry entry) {
if (entry == null) {
throw new IllegalArgumentException("Entry must not be null"); //$NON-NLS-1$
}
int kind = entry.getEntryKind();
if (kind != IClasspathEntry.CPE_LIBRARY && kind != IClasspathEntry.CPE_VARIABLE) {
throw new IllegalArgumentException(
"Entry must be of kind CPE_LIBRARY or " + "CPE_VARIABLE"); //$NON-NLS-1$
}
IClasspathAttribute[] extraAttributes = entry.getExtraAttributes();
for (int i = 0; i < extraAttributes.length; i++) {
IClasspathAttribute attrib = extraAttributes[i];
if (IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME.equals(attrib.getName())) {
try {
return new URL(attrib.getValue());
} catch (MalformedURLException e) {
return null;
}
}
}
return null;
}
/**
* Search the Ivy classpath entry within the specified Java project with the specific path
*
* @param containerPath
* the path of the container
* @param javaProject
* the project to search into
* @return the Ivy classpath container if found, otherwise return <code>null</code>
*/
public static IClasspathEntry getCeylonClasspathEntry(IPath containerPath,
IJavaProject javaProject) {
if (FakeProjectManager.isFake(javaProject) || !javaProject.exists()) {
return null;
}
try {
IClasspathEntry[] entries = javaProject.getRawClasspath();
for (int i = 0; i < entries.length; i++) {
IClasspathEntry entry = entries[i];
if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
if (containerPath.equals(entry.getPath())) {
return entry;
}
}
}
}
catch (JavaModelException e) {
// unless there are issues with the JDT, this should never happen
e.printStackTrace();
}
return null;
}
} | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_classpath_CeylonClasspathUtil.java |
942 | public abstract class AcknowledgedRequestBuilder<Request extends AcknowledgedRequest<Request>, Response extends AcknowledgedResponse, RequestBuilder extends AcknowledgedRequestBuilder<Request, Response, RequestBuilder>>
extends MasterNodeOperationRequestBuilder<Request, Response, RequestBuilder> {
protected AcknowledgedRequestBuilder(InternalGenericClient client, Request request) {
super(client, request);
}
/**
* Sets the maximum wait for acknowledgement from other nodes
*/
@SuppressWarnings("unchecked")
public RequestBuilder setTimeout(TimeValue timeout) {
request.timeout(timeout);
return (RequestBuilder)this;
}
/**
* Timeout to wait for the operation to be acknowledged by current cluster nodes. Defaults
* to <tt>10s</tt>.
*/
@SuppressWarnings("unchecked")
public RequestBuilder setTimeout(String timeout) {
request.timeout(timeout);
return (RequestBuilder)this;
}
} | 0true
| src_main_java_org_elasticsearch_action_support_master_AcknowledgedRequestBuilder.java |
945 | public abstract class MasterNodeOperationRequestBuilder<Request extends MasterNodeOperationRequest<Request>, Response extends ActionResponse, RequestBuilder extends MasterNodeOperationRequestBuilder<Request, Response, RequestBuilder>>
extends ActionRequestBuilder<Request, Response, RequestBuilder> {
protected MasterNodeOperationRequestBuilder(InternalGenericClient client, Request request) {
super(client, request);
}
/**
* Sets the master node timeout in case the master has not yet been discovered.
*/
@SuppressWarnings("unchecked")
public final RequestBuilder setMasterNodeTimeout(TimeValue timeout) {
request.masterNodeTimeout(timeout);
return (RequestBuilder) this;
}
/**
* Sets the master node timeout in case the master has not yet been discovered.
*/
@SuppressWarnings("unchecked")
public final RequestBuilder setMasterNodeTimeout(String timeout) {
request.masterNodeTimeout(timeout);
return (RequestBuilder) this;
}
} | 0true
| src_main_java_org_elasticsearch_action_support_master_MasterNodeOperationRequestBuilder.java |
663 | constructors[COLLECTION_EVENT_FILTER] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() {
public IdentifiedDataSerializable createNew(Integer arg) {
return new CollectionEventFilter();
}
}; | 0true
| hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java |
211 | public class OStorageRemoteSession {
public boolean commandExecuting = false;
public Integer sessionId = -1;
public String serverURL = null;
} | 0true
| client_src_main_java_com_orientechnologies_orient_client_remote_OStorageRemoteThreadLocal.java |
388 | public abstract class OProxedResource<T> {
protected T delegate;
protected ODatabaseRecord database;
public OProxedResource(final T iDelegate, final ODatabaseRecord iDatabase) {
this.delegate = iDelegate;
this.database = iDatabase;
}
protected void setCurrentDatabaseInThreadLocal() {
ODatabaseRecordThreadLocal.INSTANCE.set(database);
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_record_OProxedResource.java |
1,689 | public class ONetworkProtocolBinary extends OBinaryNetworkProtocolAbstract {
protected OClientConnection connection;
protected OUser account;
private String dbType;
public ONetworkProtocolBinary() {
super("OrientDB <- BinaryClient/?");
}
public ONetworkProtocolBinary(final String iThreadName) {
super(iThreadName);
}
@Override
public void config(final OServer iServer, final Socket iSocket, final OContextConfiguration iConfig,
final List<?> iStatelessCommands, List<?> iStatefulCommands) throws IOException {
// CREATE THE CLIENT CONNECTION
connection = OClientConnectionManager.instance().connect(this);
super.config(iServer, iSocket, iConfig, iStatelessCommands, iStatefulCommands);
// SEND PROTOCOL VERSION
channel.writeShort((short) OChannelBinaryProtocol.CURRENT_PROTOCOL_VERSION);
channel.flush();
start();
setName("OrientDB <- BinaryClient (" + iSocket.getRemoteSocketAddress() + ")");
}
@Override
public int getVersion() {
return OChannelBinaryProtocol.CURRENT_PROTOCOL_VERSION;
}
@Override
protected void onBeforeRequest() throws IOException {
waitNodeIsOnline();
connection = OClientConnectionManager.instance().getConnection(clientTxId);
if (clientTxId < 0) {
short protocolId = 0;
if (connection != null)
protocolId = connection.data.protocolVersion;
connection = OClientConnectionManager.instance().connect(this);
if (connection != null)
connection.data.protocolVersion = protocolId;
}
if (connection != null) {
ODatabaseRecordThreadLocal.INSTANCE.set(connection.database);
if (connection.database != null) {
connection.data.lastDatabase = connection.database.getName();
connection.data.lastUser = connection.database.getUser() != null ? connection.database.getUser().getName() : null;
} else {
connection.data.lastDatabase = null;
connection.data.lastUser = null;
}
++connection.data.totalRequests;
setDataCommandInfo("Listening");
connection.data.commandDetail = "-";
connection.data.lastCommandReceived = System.currentTimeMillis();
} else {
if (requestType != OChannelBinaryProtocol.REQUEST_DB_CLOSE && requestType != OChannelBinaryProtocol.REQUEST_SHUTDOWN) {
OLogManager.instance().debug(this, "Found unknown session %d, shutdown current connection", clientTxId);
shutdown();
throw new OIOException("Found unknown session " + clientTxId);
}
}
OServerPluginHelper.invokeHandlerCallbackOnBeforeClientRequest(server, connection, (byte) requestType);
}
@Override
protected void onAfterRequest() throws IOException {
OServerPluginHelper.invokeHandlerCallbackOnAfterClientRequest(server, connection, (byte) requestType);
if (connection != null) {
if (connection.database != null)
if (!connection.database.isClosed())
connection.database.getLevel1Cache().clear();
connection.data.lastCommandExecutionTime = System.currentTimeMillis() - connection.data.lastCommandReceived;
connection.data.totalCommandExecutionTime += connection.data.lastCommandExecutionTime;
connection.data.lastCommandInfo = connection.data.commandInfo;
connection.data.lastCommandDetail = connection.data.commandDetail;
setDataCommandInfo("Listening");
connection.data.commandDetail = "-";
}
}
protected boolean executeRequest() throws IOException {
switch (requestType) {
case OChannelBinaryProtocol.REQUEST_SHUTDOWN:
shutdownConnection();
break;
case OChannelBinaryProtocol.REQUEST_CONNECT:
connect();
break;
case OChannelBinaryProtocol.REQUEST_DB_LIST:
listDatabases();
break;
case OChannelBinaryProtocol.REQUEST_DB_OPEN:
openDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_RELOAD:
reloadDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_CREATE:
createDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_CLOSE:
closeDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_EXIST:
existsDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_DROP:
dropDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_SIZE:
sizeDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_COUNTRECORDS:
countDatabaseRecords();
break;
case OChannelBinaryProtocol.REQUEST_DB_COPY:
copyDatabase();
break;
case OChannelBinaryProtocol.REQUEST_REPLICATION:
replicationDatabase();
break;
case OChannelBinaryProtocol.REQUEST_CLUSTER:
distributedCluster();
break;
case OChannelBinaryProtocol.REQUEST_DATASEGMENT_ADD:
addDataSegment();
break;
case OChannelBinaryProtocol.REQUEST_DATASEGMENT_DROP:
dropDataSegment();
break;
case OChannelBinaryProtocol.REQUEST_DATACLUSTER_COUNT:
countClusters();
break;
case OChannelBinaryProtocol.REQUEST_DATACLUSTER_DATARANGE:
rangeCluster();
break;
case OChannelBinaryProtocol.REQUEST_DATACLUSTER_ADD:
addCluster();
break;
case OChannelBinaryProtocol.REQUEST_DATACLUSTER_DROP:
removeCluster();
break;
case OChannelBinaryProtocol.REQUEST_RECORD_METADATA:
readRecordMetadata();
break;
case OChannelBinaryProtocol.REQUEST_RECORD_LOAD:
readRecord();
break;
case OChannelBinaryProtocol.REQUEST_RECORD_CREATE:
createRecord();
break;
case OChannelBinaryProtocol.REQUEST_RECORD_UPDATE:
updateRecord();
break;
case OChannelBinaryProtocol.REQUEST_RECORD_DELETE:
deleteRecord();
break;
case OChannelBinaryProtocol.REQUEST_POSITIONS_HIGHER:
higherPositions();
break;
case OChannelBinaryProtocol.REQUEST_POSITIONS_CEILING:
ceilingPositions();
break;
case OChannelBinaryProtocol.REQUEST_POSITIONS_LOWER:
lowerPositions();
break;
case OChannelBinaryProtocol.REQUEST_POSITIONS_FLOOR:
floorPositions();
break;
case OChannelBinaryProtocol.REQUEST_COUNT:
throw new UnsupportedOperationException("Operation OChannelBinaryProtocol.REQUEST_COUNT has been deprecated");
case OChannelBinaryProtocol.REQUEST_COMMAND:
command();
break;
case OChannelBinaryProtocol.REQUEST_TX_COMMIT:
commit();
break;
case OChannelBinaryProtocol.REQUEST_CONFIG_GET:
configGet();
break;
case OChannelBinaryProtocol.REQUEST_CONFIG_SET:
configSet();
break;
case OChannelBinaryProtocol.REQUEST_CONFIG_LIST:
configList();
break;
case OChannelBinaryProtocol.REQUEST_DB_FREEZE:
freezeDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DB_RELEASE:
releaseDatabase();
break;
case OChannelBinaryProtocol.REQUEST_DATACLUSTER_FREEZE:
freezeCluster();
break;
case OChannelBinaryProtocol.REQUEST_DATACLUSTER_RELEASE:
releaseCluster();
break;
case OChannelBinaryProtocol.REQUEST_RECORD_CLEAN_OUT:
cleanOutRecord();
break;
default:
setDataCommandInfo("Command not supported");
return false;
}
return true;
}
private void lowerPositions() throws IOException {
setDataCommandInfo("Retrieve lower positions");
final int clusterId = channel.readInt();
final OClusterPosition clusterPosition = channel.readClusterPosition();
beginResponse();
try {
sendOk(clientTxId);
final OPhysicalPosition[] previousPositions = connection.database.getStorage().lowerPhysicalPositions(clusterId,
new OPhysicalPosition(clusterPosition));
if (previousPositions != null) {
channel.writeInt(previousPositions.length);
for (final OPhysicalPosition physicalPosition : previousPositions) {
channel.writeClusterPosition(physicalPosition.clusterPosition);
channel.writeInt(physicalPosition.dataSegmentId);
channel.writeLong(physicalPosition.dataSegmentPos);
channel.writeInt(physicalPosition.recordSize);
channel.writeVersion(physicalPosition.recordVersion);
}
} else {
channel.writeInt(0); // NO MORE RECORDS
}
} finally {
endResponse();
}
}
private void floorPositions() throws IOException {
setDataCommandInfo("Retrieve floor positions");
final int clusterId = channel.readInt();
final OClusterPosition clusterPosition = channel.readClusterPosition();
beginResponse();
try {
sendOk(clientTxId);
final OPhysicalPosition[] previousPositions = connection.database.getStorage().floorPhysicalPositions(clusterId,
new OPhysicalPosition(clusterPosition));
if (previousPositions != null) {
channel.writeInt(previousPositions.length);
for (final OPhysicalPosition physicalPosition : previousPositions) {
channel.writeClusterPosition(physicalPosition.clusterPosition);
channel.writeInt(physicalPosition.dataSegmentId);
channel.writeLong(physicalPosition.dataSegmentPos);
channel.writeInt(physicalPosition.recordSize);
channel.writeVersion(physicalPosition.recordVersion);
}
} else {
channel.writeInt(0); // NO MORE RECORDS
}
} finally {
endResponse();
}
}
private void higherPositions() throws IOException {
setDataCommandInfo("Retrieve higher positions");
final int clusterId = channel.readInt();
final OClusterPosition clusterPosition = channel.readClusterPosition();
beginResponse();
try {
sendOk(clientTxId);
OPhysicalPosition[] nextPositions = connection.database.getStorage().higherPhysicalPositions(clusterId,
new OPhysicalPosition(clusterPosition));
if (nextPositions != null) {
channel.writeInt(nextPositions.length);
for (final OPhysicalPosition physicalPosition : nextPositions) {
channel.writeClusterPosition(physicalPosition.clusterPosition);
channel.writeInt(physicalPosition.dataSegmentId);
channel.writeLong(physicalPosition.dataSegmentPos);
channel.writeInt(physicalPosition.recordSize);
channel.writeVersion(physicalPosition.recordVersion);
}
} else {
channel.writeInt(0); // NO MORE RECORDS
}
} finally {
endResponse();
}
}
private void ceilingPositions() throws IOException {
setDataCommandInfo("Retrieve ceiling positions");
final int clusterId = channel.readInt();
final OClusterPosition clusterPosition = channel.readClusterPosition();
beginResponse();
try {
sendOk(clientTxId);
final OPhysicalPosition[] previousPositions = connection.database.getStorage().ceilingPhysicalPositions(clusterId,
new OPhysicalPosition(clusterPosition));
if (previousPositions != null) {
channel.writeInt(previousPositions.length);
for (final OPhysicalPosition physicalPosition : previousPositions) {
channel.writeClusterPosition(physicalPosition.clusterPosition);
channel.writeInt(physicalPosition.dataSegmentId);
channel.writeLong(physicalPosition.dataSegmentPos);
channel.writeInt(physicalPosition.recordSize);
channel.writeVersion(physicalPosition.recordVersion);
}
} else {
channel.writeInt(0); // NO MORE RECORDS
}
} finally {
endResponse();
}
}
protected void checkServerAccess(final String iResource) {
if (connection.serverUser == null)
throw new OSecurityAccessException("Server user not authenticated.");
if (!server.authenticate(connection.serverUser.name, null, iResource))
throw new OSecurityAccessException("User '" + connection.serverUser.name + "' cannot access to the resource [" + iResource
+ "]. Use another server user or change permission in the file config/orientdb-server-config.xml");
}
protected ODatabaseComplex<?> openDatabase(final ODatabaseComplex<?> database, final String iUser, final String iPassword) {
if (database.isClosed())
if (database.getStorage() instanceof OStorageMemory && !database.exists())
database.create();
else {
try {
database.open(iUser, iPassword);
} catch (OSecurityException e) {
// TRY WITH SERVER'S USER
try {
connection.serverUser = server.serverLogin(iUser, iPassword, "database.passthrough");
} catch (OSecurityException ex) {
throw e;
}
// SERVER AUTHENTICATED, BYPASS SECURITY
database.setProperty(ODatabase.OPTIONS.SECURITY.toString(), Boolean.FALSE);
database.open(iUser, iPassword);
}
}
return database;
}
protected void addDataSegment() throws IOException {
setDataCommandInfo("Add data segment");
if (!isConnectionAlive())
return;
final String name = channel.readString();
final String location = channel.readString();
final int num = connection.database.addDataSegment(name, location);
beginResponse();
try {
sendOk(clientTxId);
channel.writeInt(num);
} finally {
endResponse();
}
}
protected void dropDataSegment() throws IOException {
setDataCommandInfo("Drop data segment");
if (!isConnectionAlive())
return;
final String name = channel.readString();
boolean result = connection.database.dropDataSegment(name);
beginResponse();
try {
sendOk(clientTxId);
channel.writeByte((byte) (result ? 1 : 0));
} finally {
endResponse();
}
}
protected void removeCluster() throws IOException {
setDataCommandInfo("Remove cluster");
if (!isConnectionAlive())
return;
final int id = channel.readShort();
final String clusterName = connection.database.getClusterNameById(id);
if (clusterName == null)
throw new IllegalArgumentException("Cluster " + id
+ " doesn't exist anymore. Refresh the db structure or just reconnect to the database");
boolean result = connection.database.dropCluster(clusterName, true);
beginResponse();
try {
sendOk(clientTxId);
channel.writeByte((byte) (result ? 1 : 0));
} finally {
endResponse();
}
}
protected void addCluster() throws IOException {
setDataCommandInfo("Add cluster");
if (!isConnectionAlive())
return;
final String type = channel.readString();
final String name = channel.readString();
int clusterId = -1;
final String location;
if (connection.data.protocolVersion >= 10 || type.equalsIgnoreCase("PHYSICAL"))
location = channel.readString();
else
location = null;
final String dataSegmentName;
if (connection.data.protocolVersion >= 10)
dataSegmentName = channel.readString();
else {
channel.readInt(); // OLD INIT SIZE, NOT MORE USED
dataSegmentName = null;
}
if (connection.data.protocolVersion >= 18)
clusterId = channel.readShort();
Object[] params = null;
final int num;
if (clusterId < 0)
num = connection.database.addCluster(type, name, location, dataSegmentName, params);
else
num = connection.database.addCluster(type, name, clusterId, location, dataSegmentName, params);
beginResponse();
try {
sendOk(clientTxId);
channel.writeShort((short) num);
} finally {
endResponse();
}
}
protected void rangeCluster() throws IOException {
setDataCommandInfo("Get the begin/end range of data in cluster");
if (!isConnectionAlive())
return;
OClusterPosition[] pos = connection.database.getStorage().getClusterDataRange(channel.readShort());
beginResponse();
try {
sendOk(clientTxId);
channel.writeClusterPosition(pos[0]);
channel.writeClusterPosition(pos[1]);
} finally {
endResponse();
}
}
protected void countClusters() throws IOException {
setDataCommandInfo("Count cluster elements");
if (!isConnectionAlive())
return;
int[] clusterIds = new int[channel.readShort()];
for (int i = 0; i < clusterIds.length; ++i)
clusterIds[i] = channel.readShort();
boolean countTombstones = false;
if (connection.data.protocolVersion >= 13)
countTombstones = channel.readByte() > 0;
final long count = connection.database.countClusterElements(clusterIds, countTombstones);
beginResponse();
try {
sendOk(clientTxId);
channel.writeLong(count);
} finally {
endResponse();
}
}
protected void reloadDatabase() throws IOException {
setDataCommandInfo("Reload database information");
if (!isConnectionAlive())
return;
beginResponse();
try {
sendOk(clientTxId);
sendDatabaseInformation();
} finally {
endResponse();
}
}
protected void openDatabase() throws IOException {
setDataCommandInfo("Open database");
readConnectionData();
final String dbURL = channel.readString();
dbType = ODatabaseDocument.TYPE;
if (connection.data.protocolVersion >= 8)
// READ DB-TYPE FROM THE CLIENT
dbType = channel.readString();
final String user = channel.readString();
final String passwd = channel.readString();
connection.database = (ODatabaseDocumentTx) server.openDatabase(dbType, dbURL, user, passwd);
connection.rawDatabase = ((ODatabaseRaw) ((ODatabaseComplex<?>) connection.database.getUnderlying()).getUnderlying());
if (connection.database.getStorage() instanceof OStorageProxy && !loadUserFromSchema(user, passwd)) {
sendError(clientTxId, new OSecurityAccessException(connection.database.getName(),
"User or password not valid for database: '" + connection.database.getName() + "'"));
} else {
beginResponse();
try {
sendOk(clientTxId);
channel.writeInt(connection.id);
sendDatabaseInformation();
final OServerPlugin plugin = server.getPlugin("cluster");
ODocument distributedCfg = null;
if (plugin != null && plugin instanceof ODistributedServerManager)
distributedCfg = ((ODistributedServerManager) plugin).getClusterConfiguration();
channel.writeBytes(distributedCfg != null ? distributedCfg.toStream() : null);
if (connection.data.protocolVersion >= 14)
channel.writeString(OConstants.getVersion());
} finally {
endResponse();
}
}
}
protected void connect() throws IOException {
setDataCommandInfo("Connect");
readConnectionData();
connection.serverUser = server.serverLogin(channel.readString(), channel.readString(), "connect");
beginResponse();
try {
sendOk(clientTxId);
channel.writeInt(connection.id);
} finally {
endResponse();
}
}
protected void shutdownConnection() throws IOException {
setDataCommandInfo("Shutdowning");
OLogManager.instance().info(this, "Received shutdown command from the remote client %s:%d", channel.socket.getInetAddress(),
channel.socket.getPort());
final String user = channel.readString();
final String passwd = channel.readString();
if (server.authenticate(user, passwd, "shutdown")) {
OLogManager.instance().info(this, "Remote client %s:%d authenticated. Starting shutdown of server...",
channel.socket.getInetAddress(), channel.socket.getPort());
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
channel.close();
server.shutdown();
System.exit(0);
}
OLogManager.instance().error(this, "Authentication error of remote client %s:%d: shutdown is aborted.",
channel.socket.getInetAddress(), channel.socket.getPort());
sendError(clientTxId, new OSecurityAccessException("Invalid user/password to shutdown the server"));
}
protected void copyDatabase() throws IOException {
setDataCommandInfo("Copy the database to a remote server");
final String dbUrl = channel.readString();
final String dbUser = channel.readString();
final String dbPassword = channel.readString();
final String remoteServerName = channel.readString();
final String remoteServerEngine = channel.readString();
checkServerAccess("database.copy");
final ODatabaseDocumentTx db = (ODatabaseDocumentTx) server.openDatabase(ODatabaseDocument.TYPE, dbUrl, dbUser, dbPassword);
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
protected void replicationDatabase() throws IOException {
setDataCommandInfo("Replication command");
final ODocument request = new ODocument(channel.readBytes());
final ODistributedServerManager dManager = server.getDistributedManager();
if (dManager == null)
throw new OConfigurationException("No distributed manager configured");
final String operation = request.field("operation");
ODocument response = null;
if (operation.equals("start")) {
checkServerAccess("server.replication.start");
} else if (operation.equals("stop")) {
checkServerAccess("server.replication.stop");
} else if (operation.equals("config")) {
checkServerAccess("server.replication.config");
response = new ODocument().fromJSON(dManager.getDatabaseConfiguration((String) request.field("db")).serialize()
.toJSON("prettyPrint"));
}
sendResponse(response);
}
protected void distributedCluster() throws IOException {
setDataCommandInfo("Cluster status");
final ODocument req = new ODocument(channel.readBytes());
ODocument response = null;
final String operation = req.field("operation");
if (operation == null)
throw new IllegalArgumentException("Cluster operation is null");
if (operation.equals("status")) {
final OServerPlugin plugin = server.getPlugin("cluster");
if (plugin != null && plugin instanceof ODistributedServerManager)
response = ((ODistributedServerManager) plugin).getClusterConfiguration();
} else
throw new IllegalArgumentException("Cluster operation '" + operation + "' is not supported");
sendResponse(response);
}
protected void countDatabaseRecords() throws IOException {
setDataCommandInfo("Database count records");
if (!isConnectionAlive())
return;
beginResponse();
try {
sendOk(clientTxId);
channel.writeLong(connection.database.getStorage().countRecords());
} finally {
endResponse();
}
}
protected void sizeDatabase() throws IOException {
setDataCommandInfo("Database size");
if (!isConnectionAlive())
return;
beginResponse();
try {
sendOk(clientTxId);
channel.writeLong(connection.database.getStorage().getSize());
} finally {
endResponse();
}
}
protected void dropDatabase() throws IOException {
setDataCommandInfo("Drop database");
String dbName = channel.readString();
String storageType;
if (connection.data.protocolVersion >= 16)
storageType = channel.readString();
else
storageType = "local";
checkServerAccess("database.delete");
connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType);
if (connection.database.exists()) {
OLogManager.instance().info(this, "Dropped database '%s'", connection.database.getName());
if (connection.database.isClosed())
openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password);
connection.database.drop();
connection.close();
} else {
throw new OStorageException("Database with name '" + dbName + "' doesn't exits.");
}
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
protected void existsDatabase() throws IOException {
setDataCommandInfo("Exists database");
final String dbName = channel.readString();
final String storageType;
if (connection.data.protocolVersion >= 16)
storageType = channel.readString();
else
storageType = "local";
checkServerAccess("database.exists");
connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType);
beginResponse();
try {
sendOk(clientTxId);
channel.writeByte((byte) (connection.database.exists() ? 1 : 0));
} finally {
endResponse();
}
}
protected void createDatabase() throws IOException {
setDataCommandInfo("Create database");
String dbName = channel.readString();
String dbType = ODatabaseDocument.TYPE;
if (connection.data.protocolVersion >= 8)
// READ DB-TYPE FROM THE CLIENT
dbType = channel.readString();
String storageType = channel.readString();
checkServerAccess("database.create");
checkStorageExistence(dbName);
connection.database = getDatabaseInstance(dbName, dbType, storageType);
createDatabase(connection.database, null, null);
connection.rawDatabase = (((ODatabaseComplex<?>) connection.database.getUnderlying()).getUnderlying());
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
protected void closeDatabase() throws IOException {
setDataCommandInfo("Close Database");
if (connection != null) {
if (connection.data.protocolVersion > 0 && connection.data.protocolVersion < 9)
// OLD CLIENTS WAIT FOR A OK
sendOk(clientTxId);
if (OClientConnectionManager.instance().disconnect(connection.id))
sendShutdown();
}
}
protected void configList() throws IOException {
setDataCommandInfo("List config");
checkServerAccess("server.config.get");
beginResponse();
try {
sendOk(clientTxId);
channel.writeShort((short) OGlobalConfiguration.values().length);
for (OGlobalConfiguration cfg : OGlobalConfiguration.values()) {
String key;
try {
key = cfg.getKey();
} catch (Exception e) {
key = "?";
}
String value;
try {
value = cfg.getValueAsString() != null ? cfg.getValueAsString() : "";
} catch (Exception e) {
value = "";
}
channel.writeString(key);
channel.writeString(value);
}
} finally {
endResponse();
}
}
protected void configSet() throws IOException {
setDataCommandInfo("Get config");
checkServerAccess("server.config.set");
final String key = channel.readString();
final String value = channel.readString();
final OGlobalConfiguration cfg = OGlobalConfiguration.findByKey(key);
if (cfg != null)
cfg.setValue(value);
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
protected void configGet() throws IOException {
setDataCommandInfo("Get config");
checkServerAccess("server.config.get");
final String key = channel.readString();
final OGlobalConfiguration cfg = OGlobalConfiguration.findByKey(key);
String cfgValue = cfg != null ? cfg.getValueAsString() : "";
beginResponse();
try {
sendOk(clientTxId);
channel.writeString(cfgValue);
} finally {
endResponse();
}
}
protected void commit() throws IOException {
setDataCommandInfo("Transaction commit");
if (!isConnectionAlive())
return;
final OTransactionOptimisticProxy tx = new OTransactionOptimisticProxy((ODatabaseRecordTx) connection.database.getUnderlying(),
channel);
try {
connection.database.begin(tx);
try {
connection.database.commit();
beginResponse();
try {
sendOk(clientTxId);
// SEND BACK ALL THE RECORD IDS FOR THE CREATED RECORDS
channel.writeInt(tx.getCreatedRecords().size());
for (Entry<ORecordId, ORecordInternal<?>> entry : tx.getCreatedRecords().entrySet()) {
channel.writeRID(entry.getKey());
channel.writeRID(entry.getValue().getIdentity());
// IF THE NEW OBJECT HAS VERSION > 0 MEANS THAT HAS BEEN UPDATED IN THE SAME TX. THIS HAPPENS FOR GRAPHS
if (entry.getValue().getRecordVersion().getCounter() > 0)
tx.getUpdatedRecords().put((ORecordId) entry.getValue().getIdentity(), entry.getValue());
}
// SEND BACK ALL THE NEW VERSIONS FOR THE UPDATED RECORDS
channel.writeInt(tx.getUpdatedRecords().size());
for (Entry<ORecordId, ORecordInternal<?>> entry : tx.getUpdatedRecords().entrySet()) {
channel.writeRID(entry.getKey());
channel.writeVersion(entry.getValue().getRecordVersion());
}
} finally {
endResponse();
}
} catch (Exception e) {
connection.database.rollback();
sendError(clientTxId, e);
}
} catch (OTransactionAbortedException e) {
// TX ABORTED BY THE CLIENT
} catch (Exception e) {
// Error during TX initialization, possibly index constraints violation.
tx.rollback();
tx.close();
sendError(clientTxId, e);
}
}
protected void command() throws IOException {
setDataCommandInfo("Execute remote command");
final boolean asynch = channel.readByte() == 'a';
final OCommandRequestText command = (OCommandRequestText) OStreamSerializerAnyStreamable.INSTANCE.fromStream(channel
.readBytes());
connection.data.commandDetail = command.getText();
// ENABLES THE CACHE TO IMPROVE PERFORMANCE OF COMPLEX COMMANDS LIKE TRAVERSE
// connection.database.getLevel1Cache().setEnable(true);
beginResponse();
try {
final OAbstractCommandResultListener listener;
if (asynch) {
listener = new OAsyncCommandResultListener(this, clientTxId);
command.setResultListener(listener);
} else
listener = new OSyncCommandResultListener();
final long serverTimeout = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong();
if (serverTimeout > 0 && command.getTimeoutTime() > serverTimeout)
// FORCE THE SERVER'S TIMEOUT
command.setTimeout(serverTimeout, command.getTimeoutStrategy());
if (!isConnectionAlive())
return;
// ASSIGNED THE PARSED FETCHPLAN
listener.setFetchPlan(((OCommandRequestInternal) connection.database.command(command)).getFetchPlan());
final Object result = ((OCommandRequestInternal) connection.database.command(command)).execute();
if (asynch) {
// ASYNCHRONOUS
if (listener.isEmpty())
try {
sendOk(clientTxId);
} catch (IOException e1) {
}
} else {
// SYNCHRONOUS
sendOk(clientTxId);
if (result == null) {
// NULL VALUE
channel.writeByte((byte) 'n');
} else if (result instanceof OIdentifiable) {
// RECORD
channel.writeByte((byte) 'r');
listener.result(result);
writeIdentifiable((OIdentifiable) result);
} else if (OMultiValue.isMultiValue(result)) {
channel.writeByte((byte) 'l');
channel.writeInt(OMultiValue.getSize(result));
for (Object o : OMultiValue.getMultiValueIterable(result)) {
listener.result(o);
writeIdentifiable((OIdentifiable) o);
}
} else {
// ANY OTHER (INCLUDING LITERALS)
channel.writeByte((byte) 'a');
final StringBuilder value = new StringBuilder();
listener.result(result);
ORecordSerializerStringAbstract.fieldTypeToString(value, OType.getTypeByClass(result.getClass()), result);
channel.writeString(value.toString());
}
}
if (asynch || connection.data.protocolVersion >= 17) {
// SEND FETCHED RECORDS TO LOAD IN CLIENT CACHE
for (ODocument doc : listener.getFetchedRecordsToSend()) {
channel.writeByte((byte) 2); // CLIENT CACHE RECORD. IT
// ISN'T PART OF THE
// RESULT SET
writeIdentifiable(doc);
}
channel.writeByte((byte) 0); // NO MORE RECORDS
}
} finally {
endResponse();
}
}
private boolean isConnectionAlive() {
if (connection == null || connection.database == null) {
// CONNECTION/DATABASE CLOSED, KILL IT
OClientConnectionManager.instance().kill(connection);
return false;
}
return true;
}
protected void deleteRecord() throws IOException {
setDataCommandInfo("Delete record");
if (!isConnectionAlive())
return;
final ORID rid = channel.readRID();
final ORecordVersion version = channel.readVersion();
final byte mode = channel.readByte();
final int result = deleteRecord(connection.database, rid, version);
if (mode < 2) {
beginResponse();
try {
sendOk(clientTxId);
channel.writeByte((byte) result);
} finally {
endResponse();
}
}
}
protected void cleanOutRecord() throws IOException {
setDataCommandInfo("Clean out record");
if (!isConnectionAlive())
return;
final ORID rid = channel.readRID();
final ORecordVersion version = channel.readVersion();
final byte mode = channel.readByte();
final int result = cleanOutRecord(connection.database, rid, version);
if (mode < 2) {
beginResponse();
try {
sendOk(clientTxId);
channel.writeByte((byte) result);
} finally {
endResponse();
}
}
}
/**
* VERSION MANAGEMENT:<br/>
* -1 : DOCUMENT UPDATE, NO VERSION CONTROL<br/>
* -2 : DOCUMENT UPDATE, NO VERSION CONTROL, NO VERSION INCREMENT<br/>
* -3 : DOCUMENT ROLLBACK, DECREMENT VERSION<br/>
* >-1 : MVCC CONTROL, RECORD UPDATE AND VERSION INCREMENT<br/>
* <-3 : WRONG VERSION VALUE
*
* @throws IOException
*/
protected void updateRecord() throws IOException {
setDataCommandInfo("Update record");
if (!isConnectionAlive())
return;
if (!isConnectionAlive())
return;
final ORecordId rid = channel.readRID();
final byte[] buffer = channel.readBytes();
final ORecordVersion version = channel.readVersion();
final byte recordType = channel.readByte();
final byte mode = channel.readByte();
final ORecordVersion newVersion = updateRecord(connection.database, rid, buffer, version, recordType);
if (mode < 2) {
beginResponse();
try {
sendOk(clientTxId);
channel.writeVersion(newVersion);
} finally {
endResponse();
}
}
}
protected void createRecord() throws IOException {
setDataCommandInfo("Create record");
if (!isConnectionAlive())
return;
final int dataSegmentId = connection.data.protocolVersion >= 10 ? channel.readInt() : 0;
final ORecordId rid = new ORecordId(channel.readShort(), ORID.CLUSTER_POS_INVALID);
final byte[] buffer = channel.readBytes();
final byte recordType = channel.readByte();
final byte mode = channel.readByte();
final ORecord<?> record = createRecord(connection.database, rid, buffer, recordType, dataSegmentId);
if (mode < 2) {
beginResponse();
try {
sendOk(clientTxId);
channel.writeClusterPosition(record.getIdentity().getClusterPosition());
if (connection.data.protocolVersion >= 11)
channel.writeVersion(record.getRecordVersion());
} finally {
endResponse();
}
}
}
protected void readRecordMetadata() throws IOException {
setDataCommandInfo("Record metadata");
final ORID rid = channel.readRID();
beginResponse();
try {
final ORecordMetadata metadata = connection.database.getRecordMetadata(rid);
sendOk(clientTxId);
channel.writeRID(metadata.getRecordId());
channel.writeVersion(metadata.getRecordVersion());
} finally {
endResponse();
}
}
protected void readRecord() throws IOException {
setDataCommandInfo("Load record");
if (!isConnectionAlive())
return;
final ORecordId rid = channel.readRID();
final String fetchPlanString = channel.readString();
boolean ignoreCache = false;
if (connection.data.protocolVersion >= 9)
ignoreCache = channel.readByte() == 1;
boolean loadTombstones = false;
if (connection.data.protocolVersion >= 13)
loadTombstones = channel.readByte() > 0;
if (rid.clusterId == 0 && rid.clusterPosition.longValue() == 0) {
// @COMPATIBILITY 0.9.25
// SEND THE DB CONFIGURATION INSTEAD SINCE IT WAS ON RECORD 0:0
OFetchHelper.checkFetchPlanValid(fetchPlanString);
beginResponse();
try {
sendOk(clientTxId);
channel.writeByte((byte) 1);
channel.writeBytes(connection.database.getStorage().getConfiguration().toStream());
channel.writeVersion(OVersionFactory.instance().createVersion());
channel.writeByte(ORecordBytes.RECORD_TYPE);
channel.writeByte((byte) 0); // NO MORE RECORDS
} finally {
endResponse();
}
} else {
final ORecordInternal<?> record = connection.database.load(rid, fetchPlanString, ignoreCache, loadTombstones);
beginResponse();
try {
sendOk(clientTxId);
if (record != null) {
channel.writeByte((byte) 1); // HAS RECORD
channel.writeBytes(record.toStream());
channel.writeVersion(record.getRecordVersion());
channel.writeByte(record.getRecordType());
if (fetchPlanString.length() > 0) {
// BUILD THE SERVER SIDE RECORD TO ACCES TO THE FETCH
// PLAN
if (record instanceof ODocument) {
final Map<String, Integer> fetchPlan = OFetchHelper.buildFetchPlan(fetchPlanString);
final Set<ODocument> recordsToSend = new HashSet<ODocument>();
final ODocument doc = (ODocument) record;
final OFetchListener listener = new ORemoteFetchListener(recordsToSend);
final OFetchContext context = new ORemoteFetchContext();
OFetchHelper.fetch(doc, doc, fetchPlan, listener, context, "");
// SEND RECORDS TO LOAD IN CLIENT CACHE
for (ODocument d : recordsToSend) {
if (d.getIdentity().isValid()) {
channel.writeByte((byte) 2); // CLIENT CACHE
// RECORD. IT ISN'T PART OF THE RESULT SET
writeIdentifiable(d);
}
}
}
}
}
channel.writeByte((byte) 0); // NO MORE RECORDS
} finally {
endResponse();
}
}
}
protected void beginResponse() {
channel.acquireWriteLock();
}
protected void endResponse() throws IOException {
channel.flush();
channel.releaseWriteLock();
}
protected void setDataCommandInfo(final String iCommandInfo) {
if (connection != null)
connection.data.commandInfo = iCommandInfo;
}
protected void readConnectionData() throws IOException {
connection.data.driverName = channel.readString();
connection.data.driverVersion = channel.readString();
connection.data.protocolVersion = channel.readShort();
connection.data.clientId = channel.readString();
}
private void sendDatabaseInformation() throws IOException {
final Collection<? extends OCluster> clusters = connection.database.getStorage().getClusterInstances();
int clusterCount = 0;
for (OCluster c : clusters) {
if (c != null) {
++clusterCount;
}
}
if (connection.data.protocolVersion >= 7)
channel.writeShort((short) clusterCount);
else
channel.writeInt(clusterCount);
for (OCluster c : clusters) {
if (c != null) {
channel.writeString(c.getName());
channel.writeShort((short) c.getId());
channel.writeString(c.getType());
if (connection.data.protocolVersion >= 12)
channel.writeShort((short) c.getDataSegmentId());
}
}
}
@Override
public void startup() {
super.startup();
OServerPluginHelper.invokeHandlerCallbackOnClientConnection(server, connection);
}
@Override
public void shutdown() {
sendShutdown();
super.shutdown();
if (connection == null)
return;
OServerPluginHelper.invokeHandlerCallbackOnClientDisconnection(server, connection);
OClientConnectionManager.instance().disconnect(connection);
}
protected void sendOk(final int iClientTxId) throws IOException {
channel.writeByte(OChannelBinaryProtocol.RESPONSE_STATUS_OK);
channel.writeInt(iClientTxId);
}
private void listDatabases() throws IOException {
checkServerAccess("server.dblist");
final ODocument result = new ODocument();
result.field("databases", server.getAvailableStorageNames());
setDataCommandInfo("List databases");
beginResponse();
try {
sendOk(clientTxId);
channel.writeBytes(result.toStream());
} finally {
endResponse();
}
}
protected void sendError(final int iClientTxId, final Throwable t) throws IOException {
channel.acquireWriteLock();
try {
channel.writeByte(OChannelBinaryProtocol.RESPONSE_STATUS_ERROR);
channel.writeInt(iClientTxId);
Throwable current;
if (t instanceof OLockException && t.getCause() instanceof ODatabaseException)
// BYPASS THE DB POOL EXCEPTION TO PROPAGATE THE RIGHT SECURITY ONE
current = t.getCause();
else
current = t;
final Throwable original = current;
while (current != null) {
// MORE DETAILS ARE COMING AS EXCEPTION
channel.writeByte((byte) 1);
channel.writeString(current.getClass().getName());
channel.writeString(current != null ? current.getMessage() : null);
current = current.getCause();
}
channel.writeByte((byte) 0);
if (connection != null && connection.data.protocolVersion >= 19) {
final OMemoryStream memoryStream = new OMemoryStream();
final ObjectOutputStream objectOutputStream = new ObjectOutputStream(memoryStream);
objectOutputStream.writeObject(original);
objectOutputStream.flush();
final byte[] result = memoryStream.toByteArray();
objectOutputStream.close();
channel.writeBytes(result);
}
channel.flush();
if (OLogManager.instance().isLevelEnabled(logClientExceptions)) {
if (logClientFullStackTrace)
OLogManager.instance().log(this, logClientExceptions, "Sent run-time exception to the client %s: %s", t,
channel.socket.getRemoteSocketAddress(), t.toString());
else
OLogManager.instance().log(this, logClientExceptions, "Sent run-time exception to the client %s: %s", null,
channel.socket.getRemoteSocketAddress(), t.toString());
}
} catch (Exception e) {
if (e instanceof SocketException)
shutdown();
} finally {
channel.releaseWriteLock();
}
}
private boolean loadUserFromSchema(final String iUserName, final String iUserPassword) {
account = connection.database.getMetadata().getSecurity().authenticate(iUserName, iUserPassword);
return true;
}
@Override
protected void handleConnectionError(final OChannelBinaryServer iChannel, final Throwable e) {
super.handleConnectionError(channel, e);
OServerPluginHelper.invokeHandlerCallbackOnClientError(server, connection, e);
}
public String getType() {
return "binary";
}
protected void sendResponse(final ODocument iResponse) throws IOException {
beginResponse();
try {
sendOk(clientTxId);
channel.writeBytes(iResponse != null ? iResponse.toStream() : null);
} finally {
endResponse();
}
}
protected void freezeDatabase() throws IOException {
setDataCommandInfo("Freeze database");
String dbName = channel.readString();
checkServerAccess("database.freeze");
final String storageType;
if (connection.data.protocolVersion >= 16)
storageType = channel.readString();
else
storageType = "local";
connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType);
if (connection.database.exists()) {
OLogManager.instance().info(this, "Freezing database '%s'", connection.database.getURL());
if (connection.database.isClosed())
openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password);
connection.database.freeze(true);
} else {
throw new OStorageException("Database with name '" + dbName + "' doesn't exits.");
}
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
protected void releaseDatabase() throws IOException {
setDataCommandInfo("Release database");
String dbName = channel.readString();
checkServerAccess("database.release");
final String storageType;
if (connection.data.protocolVersion >= 16)
storageType = channel.readString();
else
storageType = "local";
connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType);
if (connection.database.exists()) {
OLogManager.instance().info(this, "Realising database '%s'", connection.database.getURL());
if (connection.database.isClosed())
openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password);
connection.database.release();
} else {
throw new OStorageException("Database with name '" + dbName + "' doesn't exits.");
}
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
protected void freezeCluster() throws IOException {
setDataCommandInfo("Freeze cluster");
final String dbName = channel.readString();
final int clusterId = channel.readShort();
checkServerAccess("database.freeze");
final String storageType;
if (connection.data.protocolVersion >= 16)
storageType = channel.readString();
else
storageType = "local";
connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType);
if (connection.database.exists()) {
OLogManager.instance().info(this, "Freezing database '%s' cluster %d", connection.database.getURL(), clusterId);
if (connection.database.isClosed()) {
openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password);
}
connection.database.freezeCluster(clusterId);
} else {
throw new OStorageException("Database with name '" + dbName + "' doesn't exits.");
}
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
protected void releaseCluster() throws IOException {
setDataCommandInfo("Release database");
final String dbName = channel.readString();
final int clusterId = channel.readShort();
checkServerAccess("database.release");
final String storageType;
if (connection.data.protocolVersion >= 16)
storageType = channel.readString();
else
storageType = "local";
connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType);
if (connection.database.exists()) {
OLogManager.instance().info(this, "Realising database '%s' cluster %d", connection.database.getURL(), clusterId);
if (connection.database.isClosed()) {
openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password);
}
connection.database.releaseCluster(clusterId);
} else {
throw new OStorageException("Database with name '" + dbName + "' doesn't exits.");
}
beginResponse();
try {
sendOk(clientTxId);
} finally {
endResponse();
}
}
} | 1no label
| server_src_main_java_com_orientechnologies_orient_server_network_protocol_binary_ONetworkProtocolBinary.java |
1,820 | @Component("blMediaFieldPersistenceProvider")
@Scope("prototype")
public class MediaFieldPersistenceProvider extends FieldPersistenceProviderAdapter {
@Resource(name="blEntityConfiguration")
protected EntityConfiguration entityConfiguration;
protected boolean canHandlePersistence(PopulateValueRequest populateValueRequest, Serializable instance) {
return populateValueRequest.getMetadata().getFieldType() == SupportedFieldType.MEDIA;
}
protected boolean canHandleExtraction(ExtractValueRequest extractValueRequest, Property property) {
return extractValueRequest.getMetadata().getFieldType() == SupportedFieldType.MEDIA;
}
@Override
public FieldProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) throws PersistenceException {
if (!canHandlePersistence(populateValueRequest, instance)) {
return FieldProviderResponse.NOT_HANDLED;
}
try {
Class<?> valueType = null;
if (!populateValueRequest.getProperty().getName().contains(FieldManager.MAPFIELDSEPARATOR)) {
valueType = populateValueRequest.getReturnType();
} else {
String valueClassName = populateValueRequest.getMetadata().getMapFieldValueClass();
if (valueClassName != null) {
valueType = Class.forName(valueClassName);
}
if (valueType == null) {
valueType = populateValueRequest.getReturnType();
}
}
if (valueType == null) {
throw new IllegalAccessException("Unable to determine the valueType for the rule field (" + populateValueRequest.getProperty().getName() + ")");
}
if (Media.class.isAssignableFrom(valueType)) {
Media newMedia = convertJsonToMedia(populateValueRequest.getProperty().getUnHtmlEncodedValue());
Media media;
try {
media = (Media) populateValueRequest.getFieldManager().getFieldValue(instance,
populateValueRequest.getProperty().getName());
} catch (FieldNotAvailableException e) {
throw new IllegalArgumentException(e);
}
if (media == null) {
media = (Media) valueType.newInstance();
}
updateMediaFields(media, newMedia);
populateValueRequest.getPersistenceManager().getDynamicEntityDao().persist(media);
populateValueRequest.getFieldManager().setFieldValue(instance,
populateValueRequest.getProperty().getName(), media);
} else {
throw new UnsupportedOperationException("MediaFields only work with Media types.");
}
} catch (Exception e) {
throw new PersistenceException(e);
}
return FieldProviderResponse.HANDLED;
}
@Override
public FieldProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException {
if (!canHandleExtraction(extractValueRequest, property)) {
return FieldProviderResponse.NOT_HANDLED;
}
if (extractValueRequest.getRequestedValue() != null) {
if (extractValueRequest.getRequestedValue() instanceof Media) {
Media media = (Media) extractValueRequest.getRequestedValue();
String jsonString = convertMediaToJson(media);
property.setValue(jsonString);
property.setUnHtmlEncodedValue(jsonString);
property.setDisplayValue(extractValueRequest.getDisplayVal());
} else {
throw new UnsupportedOperationException("MEDIA type is currently only supported on fields of type Media");
}
}
return FieldProviderResponse.HANDLED;
}
@Override
public FieldProviderResponse filterProperties(AddFilterPropertiesRequest addFilterPropertiesRequest, Map<String, FieldMetadata> properties) {
// BP: Basically copied this from RuleFieldPersistenceProvider
List<Property> propertyList = new ArrayList<Property>();
propertyList.addAll(Arrays.asList(addFilterPropertiesRequest.getEntity().getProperties()));
Iterator<Property> itr = propertyList.iterator();
List<Property> additionalProperties = new ArrayList<Property>();
while(itr.hasNext()) {
Property prop = itr.next();
if (prop.getName().endsWith("Json")) {
for (Map.Entry<String, FieldMetadata> entry : properties.entrySet()) {
if (prop.getName().startsWith(entry.getKey())) {
BasicFieldMetadata originalFM = (BasicFieldMetadata) entry.getValue();
if (originalFM.getFieldType() == SupportedFieldType.MEDIA) {
Property originalProp = addFilterPropertiesRequest.getEntity().findProperty(originalFM
.getName());
if (originalProp == null) {
originalProp = new Property();
originalProp.setName(originalFM.getName());
additionalProperties.add(originalProp);
}
originalProp.setValue(prop.getValue());
originalProp.setRawValue(prop.getRawValue());
originalProp.setUnHtmlEncodedValue(prop.getUnHtmlEncodedValue());
itr.remove();
break;
}
}
}
}
}
propertyList.addAll(additionalProperties);
addFilterPropertiesRequest.getEntity().setProperties(propertyList.toArray(new Property[propertyList.size()]));
return FieldProviderResponse.HANDLED;
}
@Override
public int getOrder() {
return FieldPersistenceProvider.MEDIA;
}
protected String convertMediaToJson(Media media) {
String json;
try {
ObjectMapper om = new ObjectMapper();
return om.writeValueAsString(media);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected Media convertJsonToMedia(String jsonProp) {
try {
ObjectMapper om = new ObjectMapper();
return om.readValue(jsonProp, entityConfiguration.lookupEntityClass(Media.class.getName(), Media.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void updateMediaFields(Media oldMedia, Media newMedia) {
oldMedia.setAltText(newMedia.getAltText());
oldMedia.setTags(newMedia.getTags());
oldMedia.setTitle(newMedia.getTitle());
oldMedia.setUrl(newMedia.getUrl());
}
} | 1no label
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_provider_MediaFieldPersistenceProvider.java |
4,679 | final static class MatchAndScore extends QueryCollector {
final PercolateContext context;
final HighlightPhase highlightPhase;
final List<BytesRef> matches = new ArrayList<BytesRef>();
final List<Map<String, HighlightField>> hls = new ArrayList<Map<String, HighlightField>>();
// TODO: Use thread local in order to cache the scores lists?
final FloatArrayList scores = new FloatArrayList();
final boolean limit;
final int size;
long counter = 0;
private Scorer scorer;
MatchAndScore(ESLogger logger, PercolateContext context, HighlightPhase highlightPhase) {
super(logger, context);
this.limit = context.limit;
this.size = context.size;
this.context = context;
this.highlightPhase = highlightPhase;
}
@Override
public void collect(int doc) throws IOException {
final Query query = getQuery(doc);
if (query == null) {
// log???
return;
}
// run the query
try {
collector.reset();
if (context.highlight() != null) {
context.parsedQuery(new ParsedQuery(query, ImmutableMap.<String, Filter>of()));
context.hitContext().cache().clear();
}
searcher.search(query, collector);
if (collector.exists()) {
if (!limit || counter < size) {
matches.add(values.copyShared());
scores.add(scorer.score());
if (context.highlight() != null) {
highlightPhase.hitExecute(context, context.hitContext());
hls.add(context.hitContext().hit().getHighlightFields());
}
}
counter++;
if (facetAndAggregatorCollector != null) {
facetAndAggregatorCollector.collect(doc);
}
}
} catch (IOException e) {
logger.warn("[" + spare.bytes.utf8ToString() + "] failed to execute query", e);
}
}
@Override
public void setScorer(Scorer scorer) throws IOException {
this.scorer = scorer;
}
long counter() {
return counter;
}
List<BytesRef> matches() {
return matches;
}
FloatArrayList scores() {
return scores;
}
List<Map<String, HighlightField>> hls() {
return hls;
}
} | 1no label
| src_main_java_org_elasticsearch_percolator_QueryCollector.java |
330 | public interface ODataSegmentStrategy {
/**
* Tells to the database in what data segment put the new record. Default strategy always use data segment 0 (default).
*
* @param iDatabase
* Database instance
* @param iRecord
* Record istance
* @return The data segment id
*/
public int assignDataSegmentId(ODatabase iDatabase, ORecord<?> iRecord);
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_db_ODataSegmentStrategy.java |
584 | public class TaxException extends Exception {
private static final long serialVersionUID = 1L;
protected TaxResponse taxResponse;
public TaxException() {
super();
}
public TaxException(String message, Throwable cause) {
super(message, cause);
}
public TaxException(String message) {
super(message);
}
public TaxException(Throwable cause) {
super(cause);
}
public TaxResponse getTaxResponse() {
return taxResponse;
}
public void setTaxResponse(TaxResponse taxResponse) {
this.taxResponse = taxResponse;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_vendor_service_exception_TaxException.java |
186 | @Component("blContentProcessor")
public class ContentProcessor extends AbstractModelVariableModifierProcessor {
protected final Log LOG = LogFactory.getLog(getClass());
public static final String REQUEST_DTO = "blRequestDTO";
public static final String BLC_RULE_MAP_PARAM = "blRuleMap";
@Resource(name = "blStructuredContentService")
protected StructuredContentService structuredContentService;
@Resource(name = "blStaticAssetService")
protected StaticAssetService staticAssetService;
/**
* Sets the name of this processor to be used in Thymeleaf template
*/
public ContentProcessor() {
super("content");
}
public ContentProcessor(String elementName) {
super(elementName);
}
@Override
public int getPrecedence() {
return 10000;
}
/**
* Returns a default name
* @param element
* @param valueName
* @return
*/
protected String getAttributeValue(Element element, String valueName, String defaultValue) {
String returnValue = element.getAttributeValue(valueName);
if (returnValue == null) {
return defaultValue;
} else {
return returnValue;
}
}
@Override
protected void modifyModelAttributes(Arguments arguments, Element element) {
String contentType = element.getAttributeValue("contentType");
String contentName = element.getAttributeValue("contentName");
String maxResultsStr = element.getAttributeValue("maxResults");
Integer maxResults = null;
if (maxResultsStr != null) {
maxResults = Ints.tryParse(maxResultsStr);
}
if (maxResults == null) {
maxResults = Integer.MAX_VALUE;
}
String contentListVar = getAttributeValue(element, "contentListVar", "contentList");
String contentItemVar = getAttributeValue(element, "contentItemVar", "contentItem");
String numResultsVar = getAttributeValue(element, "numResultsVar", "numResults");
String fieldFilters = element.getAttributeValue("fieldFilters");
String sortField = element.getAttributeValue("sortField");
IWebContext context = (IWebContext) arguments.getContext();
HttpServletRequest request = context.getHttpServletRequest();
BroadleafRequestContext blcContext = BroadleafRequestContext.getBroadleafRequestContext();
Map<String, Object> mvelParameters = buildMvelParameters(request, arguments, element);
SandBox currentSandbox = blcContext.getSandbox();
List<StructuredContentDTO> contentItems;
StructuredContentType structuredContentType = structuredContentService.findStructuredContentTypeByName(contentType);
Locale locale = blcContext.getLocale();
contentItems = getContentItems(contentName, maxResults, request, mvelParameters, currentSandbox, structuredContentType, locale, arguments, element);
if (contentItems.size() > 0) {
List<Map<String,String>> contentItemFields = new ArrayList<Map<String, String>>();
for (StructuredContentDTO item : contentItems) {
if (StringUtils.isNotEmpty(fieldFilters)) {
AssignationSequence assignments = StandardExpressionProcessor.parseAssignationSequence(arguments, fieldFilters, false);
boolean valid = true;
for (Assignation assignment : assignments) {
if (ObjectUtils.notEqual(StandardExpressionProcessor.executeExpression(arguments, assignment.getRight()),
item.getValues().get(assignment.getLeft().getValue()))) {
valid = false;
break;
}
}
if (valid) {
contentItemFields.add(item.getValues());
}
} else {
contentItemFields.add(item.getValues());
}
}
addToModel(arguments, contentItemVar, contentItemFields.get(0));
addToModel(arguments, contentListVar, contentItemFields);
addToModel(arguments, numResultsVar, contentItems.size());
} else {
if (LOG.isInfoEnabled()) {
LOG.info("**************************The contentItems is null*************************");
}
addToModel(arguments, contentItemVar, null);
addToModel(arguments, contentListVar, null);
addToModel(arguments, numResultsVar, 0);
}
}
/**
* @param contentName name of the content to be looked up (can be null)
* @param maxResults maximum results to return
* @param request servlet request
* @param mvelParameters values that should be considered when filtering the content list by rules
* @param currentSandbox current sandbox being used
* @param structuredContentType the type of content that should be returned
* @param locale current locale
* @param arguments Thymeleaf Arguments passed into the tag
* @param element element context that this Thymeleaf processor is being executed in
* @return
*/
protected List<StructuredContentDTO> getContentItems(String contentName, Integer maxResults, HttpServletRequest request,
Map<String, Object> mvelParameters,
SandBox currentSandbox,
StructuredContentType structuredContentType,
Locale locale,
Arguments arguments,
Element element) {
List<StructuredContentDTO> contentItems;
if (structuredContentType == null) {
contentItems = structuredContentService.lookupStructuredContentItemsByName(currentSandbox, contentName, locale, maxResults, mvelParameters, isSecure(request));
} else {
if (contentName == null || "".equals(contentName)) {
contentItems = structuredContentService.lookupStructuredContentItemsByType(currentSandbox, structuredContentType, locale, maxResults, mvelParameters, isSecure(request));
} else {
contentItems = structuredContentService.lookupStructuredContentItemsByName(currentSandbox, structuredContentType, contentName, locale, maxResults, mvelParameters, isSecure(request));
}
}
return contentItems;
}
/**
* MVEL is used to process the content targeting rules.
*
* @param request
* @return
*/
protected Map<String, Object> buildMvelParameters(HttpServletRequest request, Arguments arguments, Element element) {
TimeZone timeZone = BroadleafRequestContext.getBroadleafRequestContext().getTimeZone();
final TimeDTO timeDto;
if (timeZone != null) {
timeDto = new TimeDTO(SystemTime.asCalendar(timeZone));
} else {
timeDto = new TimeDTO();
}
RequestDTO requestDto = (RequestDTO) request.getAttribute(REQUEST_DTO);
Map<String, Object> mvelParameters = new HashMap<String, Object>();
mvelParameters.put("time", timeDto);
mvelParameters.put("request", requestDto);
String productString = element.getAttributeValue("product");
if (productString != null) {
Object product = StandardExpressionProcessor.processExpression(arguments, productString);
if (product != null) {
mvelParameters.put("product", product);
}
}
String categoryString = element.getAttributeValue("category");
if (categoryString != null) {
Object category = StandardExpressionProcessor.processExpression(arguments, categoryString);
if (category != null) {
mvelParameters.put("category", category);
}
}
@SuppressWarnings("unchecked")
Map<String,Object> blcRuleMap = (Map<String,Object>) request.getAttribute(BLC_RULE_MAP_PARAM);
if (blcRuleMap != null) {
for (String mapKey : blcRuleMap.keySet()) {
mvelParameters.put(mapKey, blcRuleMap.get(mapKey));
}
}
return mvelParameters;
}
public boolean isSecure(HttpServletRequest request) {
boolean secure = false;
if (request != null) {
secure = ("HTTPS".equalsIgnoreCase(request.getScheme()) || request.isSecure());
}
return secure;
}
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_web_processor_ContentProcessor.java |
87 | {
@Override
public void run()
{
dbr.getGraphDatabaseService().getNodeById( node.getId() );
dbr.getGraphDatabaseService().getRelationshipById( relationship.getId() );
}
}; | 0true
| community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_ReadTransactionLogWritingTest.java |
3,582 | public class AddMessageListenerRequest extends CallableClientRequest implements RetryableRequest {
private String name;
public AddMessageListenerRequest() {
}
public AddMessageListenerRequest(String name) {
this.name = name;
}
@Override
public String call() throws Exception {
TopicService service = getService();
ClientEngine clientEngine = getClientEngine();
ClientEndpoint endpoint = getEndpoint();
MessageListener listener = new MessageListenerImpl(endpoint, clientEngine, getCallId());
String registrationId = service.addMessageListener(name, listener);
endpoint.setListenerRegistration(TopicService.SERVICE_NAME, name, registrationId);
return registrationId;
}
@Override
public String getServiceName() {
return TopicService.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return TopicPortableHook.F_ID;
}
@Override
public int getClassId() {
return TopicPortableHook.ADD_LISTENER;
}
@Override
public void write(PortableWriter writer) throws IOException {
writer.writeUTF("n", name);
}
@Override
public void read(PortableReader reader) throws IOException {
name = reader.readUTF("n");
}
@Override
public Permission getRequiredPermission() {
return new TopicPermission(name, ActionConstants.ACTION_LISTEN);
}
private static class MessageListenerImpl implements MessageListener {
private final ClientEndpoint endpoint;
private final ClientEngine clientEngine;
private final int callId;
public MessageListenerImpl(ClientEndpoint endpoint, ClientEngine clientEngine, int callId) {
this.endpoint = endpoint;
this.clientEngine = clientEngine;
this.callId = callId;
}
@Override
public void onMessage(Message message) {
if (!endpoint.live()) {
return;
}
Data messageData = clientEngine.toData(message.getMessageObject());
String publisherUuid = message.getPublishingMember().getUuid();
PortableMessage portableMessage = new PortableMessage(messageData, message.getPublishTime(), publisherUuid);
endpoint.sendEvent(portableMessage, callId);
}
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_topic_client_AddMessageListenerRequest.java |
77 | public class CeylonMarkerResolutionProposal implements ICompletionProposal {
private IMarkerResolution fResolution;
private IMarker fMarker;
public CeylonMarkerResolutionProposal(IMarkerResolution resolution, IMarker marker) {
fResolution = resolution;
fMarker = marker;
}
public void apply(IDocument document) {
fResolution.run(fMarker);
}
public String getAdditionalProposalInfo() {
if (fResolution instanceof IMarkerResolution2) {
return ((IMarkerResolution2) fResolution).getDescription();
}
if (fResolution instanceof ICompletionProposal) {
return ((ICompletionProposal) fResolution)
.getAdditionalProposalInfo();
}
try {
return "Problem description: " + fMarker.getAttribute(IMarker.MESSAGE);
} catch (CoreException e) {
// JavaPlugin.log(e);
}
return null;
}
public IContextInformation getContextInformation() {
return null;
}
public String getDisplayString() {
return fResolution.getLabel();
}
public Image getImage() {
if (fResolution instanceof IMarkerResolution2) {
return ((IMarkerResolution2) fResolution).getImage();
}
if (fResolution instanceof ICompletionProposal) {
return ((ICompletionProposal) fResolution).getImage();
}
return MINOR_CHANGE;
}
public Point getSelection(IDocument document) {
if (fResolution instanceof ICompletionProposal) {
return ((ICompletionProposal) fResolution).getSelection(document);
}
return null;
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_CeylonMarkerResolutionProposal.java |