Unnamed: 0
int64
0
6.45k
func
stringlengths
37
161k
target
class label
2 classes
project
stringlengths
33
167
548
public class XAResourceProxy implements XAResource { private final TransactionContextProxy transactionContext; private final ClientTransactionManager transactionManager; private final ILogger logger; private final String uuid = UUID.randomUUID().toString(); //To overcome race condition in Atomikos private int transactionTimeoutSeconds; public XAResourceProxy(TransactionContextProxy transactionContext) { this.transactionContext = transactionContext; this.transactionManager = transactionContext.getTransactionManager(); logger = Logger.getLogger(XAResourceProxy.class); } @Override public synchronized void start(Xid xid, int flags) throws XAException { nullCheck(xid); switch (flags) { case TMNOFLAGS: if (getTransaction(xid) != null) { final XAException xaException = new XAException(XAException.XAER_DUPID); logger.severe("Duplicate xid: " + xid, xaException); throw xaException; } try { final TransactionProxy transaction = getTransaction(); transactionManager.addManagedTransaction(xid, transaction); transaction.begin(); } catch (IllegalStateException e) { throw new XAException(XAException.XAER_INVAL); } break; case TMRESUME: case TMJOIN: break; default: throw new XAException(XAException.XAER_INVAL); } } @Override public synchronized void end(Xid xid, int flags) throws XAException { nullCheck(xid); final TransactionProxy transaction = getTransaction(); final SerializableXID sXid = transaction.getXid(); if (sXid == null || !sXid.equals(xid)) { logger.severe("started xid: " + sXid + " and given xid : " + xid + " not equal!!!"); } validateTx(transaction, ACTIVE); switch (flags) { case XAResource.TMSUCCESS: //successfully end. break; case XAResource.TMFAIL: try { transaction.rollback(); transactionManager.removeManagedTransaction(xid); } catch (IllegalStateException e) { throw new XAException(XAException.XAER_RMERR); } break; case XAResource.TMSUSPEND: break; default: throw new XAException(XAException.XAER_INVAL); } } @Override public synchronized int prepare(Xid xid) throws XAException { nullCheck(xid); final TransactionProxy transaction = getTransaction(); final SerializableXID sXid = transaction.getXid(); if (sXid == null || !sXid.equals(xid)) { logger.severe("started xid: " + sXid + " and given xid : " + xid + " not equal!!!"); } validateTx(transaction, ACTIVE); try { transaction.prepare(); } catch (TransactionException e) { throw new XAException(XAException.XAER_RMERR); } return XAResource.XA_OK; } @Override public synchronized void commit(Xid xid, boolean onePhase) throws XAException { nullCheck(xid); final TransactionProxy transaction = getTransaction(xid); if (transaction == null) { if (transactionManager.recover(xid, true)) { return; } final XAException xaException = new XAException(XAException.XAER_NOTA); logger.severe("Transaction is not available!!!", xaException); throw xaException; } validateTx(transaction, onePhase ? ACTIVE : PREPARED); try { transaction.commit(onePhase); transactionManager.removeManagedTransaction(xid); } catch (TransactionException e) { throw new XAException(XAException.XAER_RMERR); } } @Override public synchronized void rollback(Xid xid) throws XAException { nullCheck(xid); final TransactionProxy transaction = getTransaction(xid); if (transaction == null) { if (transactionManager.recover(xid, false)) { return; } final XAException xaException = new XAException(XAException.XAER_NOTA); logger.severe("Transaction is not available!!!", xaException); throw xaException; } validateTx(transaction, Transaction.State.NO_TXN); //NO_TXN means do not validate state try { transaction.rollback(); transactionManager.removeManagedTransaction(xid); } catch (TransactionException e) { throw new XAException(XAException.XAER_RMERR); } } @Override public synchronized void forget(Xid xid) throws XAException { throw new XAException(XAException.XAER_PROTO); } @Override public synchronized boolean isSameRM(XAResource xaResource) throws XAException { if (this == xaResource) { return true; } if (xaResource instanceof XAResourceProxy) { XAResourceProxy other = (XAResourceProxy) xaResource; return transactionManager.equals(other.transactionManager); } return false; } @Override public synchronized Xid[] recover(int flag) throws XAException { return transactionManager.recover(); } @Override public synchronized int getTransactionTimeout() throws XAException { return transactionTimeoutSeconds; } @Override public synchronized boolean setTransactionTimeout(int seconds) throws XAException { this.transactionTimeoutSeconds = seconds; return false; } private void nullCheck(Xid xid) throws XAException { if (xid == null) { final XAException xaException = new XAException(XAException.XAER_INVAL); logger.severe("Xid cannot be null!!!", xaException); throw xaException; } } private TransactionProxy getTransaction() { return transactionContext.transaction; } private TransactionProxy getTransaction(Xid xid) { return transactionManager.getManagedTransaction(xid); } private void validateTx(TransactionProxy tx, Transaction.State state) throws XAException { if (tx == null) { final XAException xaException = new XAException(XAException.XAER_NOTA); logger.severe("Transaction is not available!!!", xaException); throw xaException; } final Transaction.State txState = tx.getState(); switch (state) { case ACTIVE: if (txState != ACTIVE) { final XAException xaException = new XAException(XAException.XAER_NOTA); logger.severe("Transaction is not active!!! state: " + txState, xaException); throw xaException; } break; case PREPARED: if (txState != Transaction.State.PREPARED) { final XAException xaException = new XAException(XAException.XAER_INVAL); logger.severe("Transaction is not prepared!!! state: " + txState, xaException); throw xaException; } break; default: break; } } @Override public String toString() { final String txnId = transactionContext.getTxnId(); final StringBuilder sb = new StringBuilder("XAResourceImpl{"); sb.append("uuid=").append(uuid); sb.append("txdId=").append(txnId); sb.append(", transactionTimeoutSeconds=").append(transactionTimeoutSeconds); sb.append('}'); return sb.toString(); } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_txn_XAResourceProxy.java
46
public class OCaseInsentiveComparator implements Comparator<String> { public int compare(final String stringOne, final String stringTwo) { return stringOne.compareToIgnoreCase(stringTwo); } }
0true
commons_src_main_java_com_orientechnologies_common_comparator_OCaseInsentiveComparator.java
3,687
return new Comparator<Map.Entry>() { public int compare(Map.Entry entry1, Map.Entry entry2) { return SortingUtil.compare(pagingPredicate.getComparator(), pagingPredicate.getIterationType(), entry1, entry2); } };
1no label
hazelcast_src_main_java_com_hazelcast_util_SortingUtil.java
106
public static class MyCredentials extends UsernamePasswordCredentials { public MyCredentials() { super("foo", "bar"); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_ClientIssueTest.java
1,637
public class OHazelcastDistributedMessageService implements ODistributedMessageService { protected final OHazelcastPlugin manager; protected Map<String, OHazelcastDistributedDatabase> databases = new ConcurrentHashMap<String, OHazelcastDistributedDatabase>(); protected final static Map<String, IQueue<?>> queues = new HashMap<String, IQueue<?>>(); protected final IQueue<ODistributedResponse> nodeResponseQueue; protected final ConcurrentHashMap<Long, ODistributedResponseManager> responsesByRequestIds; protected final TimerTask asynchMessageManager; public static final String NODE_QUEUE_PREFIX = "orientdb.node."; public static final String NODE_QUEUE_REQUEST_POSTFIX = ".request"; public static final String NODE_QUEUE_RESPONSE_POSTFIX = ".response"; public static final String NODE_QUEUE_UNDO_POSTFIX = ".undo"; public OHazelcastDistributedMessageService(final OHazelcastPlugin manager) { this.manager = manager; this.responsesByRequestIds = new ConcurrentHashMap<Long, ODistributedResponseManager>(); // CREAT THE QUEUE final String queueName = getResponseQueueName(manager.getLocalNodeName()); nodeResponseQueue = getQueue(queueName); if (ODistributedServerLog.isDebugEnabled()) ODistributedServerLog.debug(this, getLocalNodeNameAndThread(), null, DIRECTION.NONE, "listening for incoming responses on queue: %s", queueName); checkForPendingMessages(nodeResponseQueue, queueName, false); // CREATE TASK THAT CHECK ASYNCHRONOUS MESSAGE RECEIVED asynchMessageManager = new TimerTask() { @Override public void run() { purgePendingMessages(); } }; // CREATE THREAD LISTENER AGAINST orientdb.node.<node>.response, ONE PER NODE, THEN DISPATCH THE MESSAGE INTERNALLY USING THE // THREAD ID new Thread(new Runnable() { @Override public void run() { while (!Thread.interrupted()) { String senderNode = null; ODistributedResponse message = null; try { message = nodeResponseQueue.take(); if (message != null) { senderNode = message.getSenderNodeName(); dispatchResponseToThread(message); } } catch (InterruptedException e) { // EXIT CURRENT THREAD Thread.interrupted(); break; } catch (Throwable e) { ODistributedServerLog.error(this, manager.getLocalNodeName(), senderNode, DIRECTION.IN, "error on reading distributed response", e, message != null ? message.getPayload() : "-"); } } } }).start(); } public OHazelcastDistributedDatabase getDatabase(final String iDatabaseName) { return databases.get(iDatabaseName); } @Override public ODistributedRequest createRequest() { return new OHazelcastDistributedRequest(); } protected void dispatchResponseToThread(final ODistributedResponse response) { try { final long reqId = response.getRequestId(); // GET ASYNCHRONOUS MSG MANAGER IF ANY final ODistributedResponseManager asynchMgr = responsesByRequestIds.get(reqId); if (asynchMgr == null) { if (ODistributedServerLog.isDebugEnabled()) ODistributedServerLog.debug(this, manager.getLocalNodeName(), response.getExecutorNodeName(), DIRECTION.IN, "received response for message %d after the timeout (%dms)", reqId, OGlobalConfiguration.DISTRIBUTED_ASYNCH_RESPONSES_TIMEOUT.getValueAsLong()); } else if (asynchMgr.addResponse(response)) // ALL RESPONSE RECEIVED, REMOVE THE RESPONSE MANAGER responsesByRequestIds.remove(reqId); } finally { Orient.instance().getProfiler() .updateCounter("distributed.replication.msgReceived", "Number of replication messages received in current node", +1); Orient .instance() .getProfiler() .updateCounter("distributed.replication." + response.getExecutorNodeName() + ".msgReceived", "Number of replication messages received in current node from a node", +1, "distributed.replication.*.msgReceived"); } } public void shutdown() { for (Entry<String, OHazelcastDistributedDatabase> m : databases.entrySet()) m.getValue().shutdown(); asynchMessageManager.cancel(); responsesByRequestIds.clear(); if (nodeResponseQueue != null) { nodeResponseQueue.clear(); nodeResponseQueue.destroy(); } } /** * Composes the request queue name based on node name and database. */ protected static String getRequestQueueName(final String iNodeName, final String iDatabaseName) { final StringBuilder buffer = new StringBuilder(); buffer.append(NODE_QUEUE_PREFIX); buffer.append(iNodeName); if (iDatabaseName != null) { buffer.append('.'); buffer.append(iDatabaseName); } buffer.append(NODE_QUEUE_REQUEST_POSTFIX); return buffer.toString(); } /** * Composes the response queue name based on node name. */ protected static String getResponseQueueName(final String iNodeName) { final StringBuilder buffer = new StringBuilder(); buffer.append(NODE_QUEUE_PREFIX); buffer.append(iNodeName); buffer.append(NODE_QUEUE_RESPONSE_POSTFIX); return buffer.toString(); } protected String getLocalNodeNameAndThread() { return manager.getLocalNodeName() + ":" + Thread.currentThread().getId(); } protected void purgePendingMessages() { final long now = System.currentTimeMillis(); final long timeout = OGlobalConfiguration.DISTRIBUTED_ASYNCH_RESPONSES_TIMEOUT.getValueAsLong(); for (Iterator<Entry<Long, ODistributedResponseManager>> it = responsesByRequestIds.entrySet().iterator(); it.hasNext();) { final Entry<Long, ODistributedResponseManager> item = it.next(); final ODistributedResponseManager resp = item.getValue(); final long timeElapsed = now - resp.getSentOn(); if (timeElapsed > timeout) { // EXPIRED, FREE IT! final List<String> missingNodes = resp.getMissingNodes(); ODistributedServerLog.warn(this, manager.getLocalNodeName(), missingNodes.toString(), DIRECTION.IN, "%d missed response(s) for message %d by nodes %s after %dms when timeout is %dms", missingNodes.size(), resp.getMessageId(), missingNodes, timeElapsed, timeout); Orient .instance() .getProfiler() .updateCounter("distributed.replication." + resp.getDatabaseName() + ".timeouts", "Number of timeouts on replication messages responses", +1, "distributed.replication.*.timeouts"); resp.timeout(); it.remove(); } } } protected void checkForPendingMessages(final IQueue<?> iQueue, final String iQueueName, final boolean iUnqueuePendingMessages) { final int queueSize = iQueue.size(); if (queueSize > 0) { if (!iUnqueuePendingMessages) { ODistributedServerLog.warn(this, manager.getLocalNodeName(), null, DIRECTION.NONE, "found %d previous messages in queue %s, clearing them...", queueSize, iQueueName); iQueue.clear(); } else ODistributedServerLog.warn(this, manager.getLocalNodeName(), null, DIRECTION.NONE, "found %d previous messages in queue %s, aligning the database...", queueSize, iQueueName); } } /** * Return the queue. If not exists create and register it. */ @SuppressWarnings("unchecked") protected <T> IQueue<T> getQueue(final String iQueueName) { synchronized (queues) { IQueue<T> queue = (IQueue<T>) queues.get(iQueueName); if (queue == null) { queue = manager.getHazelcastInstance().getQueue(iQueueName); queues.put(iQueueName, queue); } return manager.getHazelcastInstance().getQueue(iQueueName); } } /** * Remove the queue. */ protected void removeQueue(final String iQueueName) { synchronized (queues) { queues.remove(iQueueName); IQueue<?> queue = manager.getHazelcastInstance().getQueue(iQueueName); queue.clear(); } } public void registerRequest(final long id, final ODistributedResponseManager currentResponseMgr) { responsesByRequestIds.put(id, currentResponseMgr); } public OHazelcastDistributedDatabase registerDatabase(final String iDatabaseName) { final OHazelcastDistributedDatabase db = new OHazelcastDistributedDatabase(manager, this, iDatabaseName); databases.put(iDatabaseName, db); return db; } public Set<String> getDatabases() { return databases.keySet(); } }
1no label
distributed_src_main_java_com_orientechnologies_orient_server_hazelcast_OHazelcastDistributedMessageService.java
481
public class AnalyzeRequest extends SingleCustomOperationRequest<AnalyzeRequest> { private String index; private String text; private String analyzer; private String tokenizer; private String[] tokenFilters; private String field; AnalyzeRequest() { } /** * Constructs a new analyzer request for the provided text. * * @param text The text to analyze */ public AnalyzeRequest(String text) { this.text = text; } /** * Constructs a new analyzer request for the provided index and text. * * @param index The index name * @param text The text to analyze */ public AnalyzeRequest(@Nullable String index, String text) { this.index = index; this.text = text; } public String text() { return this.text; } public AnalyzeRequest index(String index) { this.index = index; return this; } public String index() { return this.index; } public AnalyzeRequest analyzer(String analyzer) { this.analyzer = analyzer; return this; } public String analyzer() { return this.analyzer; } public AnalyzeRequest tokenizer(String tokenizer) { this.tokenizer = tokenizer; return this; } public String tokenizer() { return this.tokenizer; } public AnalyzeRequest tokenFilters(String... tokenFilters) { this.tokenFilters = tokenFilters; return this; } public String[] tokenFilters() { return this.tokenFilters; } public AnalyzeRequest field(String field) { this.field = field; return this; } public String field() { return this.field; } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = super.validate(); if (text == null) { validationException = addValidationError("text is missing", validationException); } return validationException; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); index = in.readOptionalString(); text = in.readString(); analyzer = in.readOptionalString(); tokenizer = in.readOptionalString(); int size = in.readVInt(); if (size > 0) { tokenFilters = new String[size]; for (int i = 0; i < size; i++) { tokenFilters[i] = in.readString(); } } field = in.readOptionalString(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeOptionalString(index); out.writeString(text); out.writeOptionalString(analyzer); out.writeOptionalString(tokenizer); if (tokenFilters == null) { out.writeVInt(0); } else { out.writeVInt(tokenFilters.length); for (String tokenFilter : tokenFilters) { out.writeString(tokenFilter); } } out.writeOptionalString(field); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_analyze_AnalyzeRequest.java
396
public class ORecordLazySet implements Set<OIdentifiable>, ORecordLazyMultiValue, ORecordElement, ORecordLazyListener { public static final ORecordLazySet EMPTY_SET = new ORecordLazySet(); private static final Object NEWMAP_VALUE = new Object(); protected final ORecordLazyList delegate; protected IdentityHashMap<ORecord<?>, Object> newItems; protected boolean sorted = true; public ORecordLazySet() { delegate = new ORecordLazyList().setListener(this); } public ORecordLazySet(final ODocument iSourceRecord) { delegate = new ORecordLazyList(iSourceRecord).setListener(this); } public ORecordLazySet(final ODocument iSourceRecord, final ORecordLazySet iSource) { delegate = iSource.delegate.copy(iSourceRecord).setListener(this); sorted = iSource.sorted; if (iSource.newItems != null) newItems = new IdentityHashMap<ORecord<?>, Object>(iSource.newItems); } public ORecordLazySet(final ODocument iSourceRecord, final Collection<OIdentifiable> iValues) { this(iSourceRecord); addAll(iValues); } public void onBeforeIdentityChanged(final ORID iRID) { delegate.onBeforeIdentityChanged(iRID); } public void onAfterIdentityChanged(final ORecord<?> iRecord) { delegate.onAfterIdentityChanged(iRecord); } @SuppressWarnings("unchecked") public <RET> RET setDirty() { delegate.setDirty(); return (RET) this; } public Iterator<OIdentifiable> iterator() { if (hasNewItems()) { lazyLoad(false); return new OLazyRecordMultiIterator(delegate.sourceRecord, new Object[] { delegate.iterator(), newItems.keySet().iterator() }, delegate.autoConvertToRecord); } return delegate.iterator(); } public Iterator<OIdentifiable> rawIterator() { if (hasNewItems()) { lazyLoad(false); return new OLazyRecordMultiIterator(delegate.sourceRecord, new Object[] { delegate.rawIterator(), newItems.keySet().iterator() }, false); } return delegate.rawIterator(); } public Iterator<OIdentifiable> newItemsIterator() { if (hasNewItems()) return new OLazyRecordIterator(delegate.sourceRecord, newItems.keySet().iterator(), false); return null; } public boolean convertRecords2Links() { savedAllNewItems(); return delegate.convertRecords2Links(); } public boolean isAutoConvertToRecord() { return delegate.isAutoConvertToRecord(); } public void setAutoConvertToRecord(final boolean convertToRecord) { delegate.setAutoConvertToRecord(convertToRecord); } public int size() { int tot = delegate.size(); if (newItems != null) tot += newItems.size(); return tot; } public boolean isEmpty() { boolean empty = delegate.isEmpty(); if (empty && newItems != null) empty = newItems.isEmpty(); return empty; } public boolean contains(final Object o) { boolean found; final OIdentifiable obj = (OIdentifiable) o; if (OGlobalConfiguration.LAZYSET_WORK_ON_STREAM.getValueAsBoolean() && getStreamedContent() != null) { found = getStreamedContent().indexOf(obj.getIdentity().toString()) > -1; } else { lazyLoad(false); found = indexOf((OIdentifiable) o) > -1; } if (!found && hasNewItems()) // SEARCH INSIDE NEW ITEMS MAP found = newItems.containsKey(o); return found; } public Object[] toArray() { Object[] result = delegate.toArray(); if (newItems != null && !newItems.isEmpty()) { int start = result.length; result = Arrays.copyOf(result, start + newItems.size()); for (ORecord<?> r : newItems.keySet()) { result[start++] = r; } } return result; } @SuppressWarnings("unchecked") public <T> T[] toArray(final T[] a) { T[] result = delegate.toArray(a); if (newItems != null && !newItems.isEmpty()) { int start = result.length; result = Arrays.copyOf(result, start + newItems.size()); for (ORecord<?> r : newItems.keySet()) { result[start++] = (T) r; } } return result; } /** * Adds the item in the underlying List preserving the order of the collection. */ public boolean add(final OIdentifiable e) { if (e.getIdentity().isNew()) { final ORecord<?> record = e.getRecord(); // ADD IN TEMP LIST if (newItems == null) newItems = new IdentityHashMap<ORecord<?>, Object>(); else if (newItems.containsKey(record)) return false; newItems.put(record, NEWMAP_VALUE); setDirty(); return true; } else if (OGlobalConfiguration.LAZYSET_WORK_ON_STREAM.getValueAsBoolean() && getStreamedContent() != null) { // FAST INSERT final String ridString = e.getIdentity().toString(); final StringBuilder buffer = getStreamedContent(); if (buffer.indexOf(ridString) < 0) { if (buffer.length() > 0) buffer.append(','); e.getIdentity().toString(buffer); setDirty(); return true; } return false; } else { final int pos = indexOf(e); if (pos < 0) { // FOUND delegate.add(pos * -1 - 1, e); return true; } return false; } } /** * Returns the position of the element in the set. Execute a binary search since the elements are always ordered. * * @param iElement * element to find * @return The position of the element if found, otherwise false */ public int indexOf(final OIdentifiable iElement) { if (delegate.isEmpty()) return -1; final boolean prevConvert = delegate.isAutoConvertToRecord(); if (prevConvert) delegate.setAutoConvertToRecord(false); final int pos = Collections.binarySearch(delegate, iElement); if (prevConvert) // RESET PREVIOUS SETTINGS delegate.setAutoConvertToRecord(true); return pos; } public boolean remove(final Object o) { if (OGlobalConfiguration.LAZYSET_WORK_ON_STREAM.getValueAsBoolean() && getStreamedContent() != null) { // WORK ON STREAM if (delegate.remove(o)) return true; } else { lazyLoad(true); final int pos = indexOf((OIdentifiable) o); if (pos > -1) { delegate.remove(pos); return true; } } if (hasNewItems()) { // SEARCH INSIDE NEW ITEMS MAP final boolean removed = newItems.remove(o) != null; if (newItems.size() == 0) // EARLY REMOVE THE MAP TO SAVE MEMORY newItems = null; if (removed) setDirty(); return removed; } return false; } public boolean containsAll(final Collection<?> c) { lazyLoad(false); return delegate.containsAll(c); } @SuppressWarnings("unchecked") public boolean addAll(Collection<? extends OIdentifiable> c) { final Iterator<OIdentifiable> it = (Iterator<OIdentifiable>) (c instanceof ORecordLazyMultiValue ? ((ORecordLazyMultiValue) c) .rawIterator() : c.iterator()); while (it.hasNext()) add(it.next()); return true; } public boolean retainAll(final Collection<?> c) { if (hasNewItems()) { final Collection<Object> v = newItems.values(); v.retainAll(c); if (newItems.size() == 0) newItems = null; } return delegate.retainAll(c); } public boolean removeAll(final Collection<?> c) { if (hasNewItems()) { final Collection<Object> v = newItems.values(); v.removeAll(c); if (newItems.size() == 0) newItems = null; } return delegate.removeAll(c); } public void clear() { delegate.clear(); if (newItems != null) { newItems.clear(); newItems = null; } } public byte getRecordType() { return delegate.getRecordType(); } @Override public String toString() { final StringBuilder buffer = new StringBuilder(delegate.toString()); if (hasNewItems()) { for (ORecord<?> item : newItems.keySet()) { if (buffer.length() > 2) buffer.insert(buffer.length() - 1, ", "); buffer.insert(buffer.length() - 1, item.toString()); } return buffer.toString(); } return buffer.toString(); } public void sort() { if (!sorted && !delegate.isEmpty()) { final boolean prevConvert = delegate.isAutoConvertToRecord(); if (prevConvert) delegate.setAutoConvertToRecord(false); delegate.marshalling = true; Collections.sort(delegate); delegate.marshalling = false; if (prevConvert) // RESET PREVIOUS SETTINGS delegate.setAutoConvertToRecord(true); sorted = true; } } public ORecordLazySet setStreamedContent(final StringBuilder iStream) { delegate.setStreamedContent(iStream); return this; } public StringBuilder getStreamedContent() { return delegate.getStreamedContent(); } public boolean lazyLoad(final boolean iNotIdempotent) { if (delegate.lazyLoad(iNotIdempotent)) { sort(); return true; } return false; } public void convertLinks2Records() { delegate.convertLinks2Records(); } private boolean hasNewItems() { return newItems != null && !newItems.isEmpty(); } public void savedAllNewItems() { if (hasNewItems()) { for (ORecord<?> record : newItems.keySet()) { if (record.getIdentity().isNew() || getStreamedContent() == null || getStreamedContent().indexOf(record.getIdentity().toString()) == -1) // NEW ITEM OR NOT CONTENT IN STREAMED BUFFER add(record.getIdentity()); } newItems.clear(); newItems = null; } } public ORecordLazySet copy(final ODocument iSourceRecord) { return new ORecordLazySet(iSourceRecord, this); } public void onLazyLoad() { sorted = false; sort(); } public STATUS getInternalStatus() { return delegate.getInternalStatus(); } public void setInternalStatus(final STATUS iStatus) { delegate.setInternalStatus(iStatus); } public boolean isRidOnly() { return delegate.isRidOnly(); } public ORecordLazySet setRidOnly(final boolean ridOnly) { delegate.setRidOnly(ridOnly); return this; } public boolean detach() { return convertRecords2Links(); } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_record_ORecordLazySet.java
79
public class ClientDestroyRequest extends CallableClientRequest implements Portable, RetryableRequest, SecureRequest { private String name; private String serviceName; public ClientDestroyRequest() { } public ClientDestroyRequest(String name, String serviceName) { this.name = name; this.serviceName = serviceName; } @Override public Object call() throws Exception { ProxyService proxyService = getClientEngine().getProxyService(); proxyService.destroyDistributedObject(getServiceName(), name); return null; } @Override public String getServiceName() { return serviceName; } @Override public int getFactoryId() { return ClientPortableHook.ID; } @Override public int getClassId() { return ClientPortableHook.DESTROY_PROXY; } @Override public void write(PortableWriter writer) throws IOException { writer.writeUTF("n", name); writer.writeUTF("s", serviceName); } @Override public void read(PortableReader reader) throws IOException { name = reader.readUTF("n"); serviceName = reader.readUTF("s"); } @Override public Permission getRequiredPermission() { return getPermission(name, serviceName, ActionConstants.ACTION_DESTROY); } }
0true
hazelcast_src_main_java_com_hazelcast_client_ClientDestroyRequest.java
1,282
public class ClusterInfo { private final ImmutableMap<String, DiskUsage> usages; private final ImmutableMap<String, Long> shardSizes; public ClusterInfo(ImmutableMap<String, DiskUsage> usages, ImmutableMap<String, Long> shardSizes) { this.usages = usages; this.shardSizes = shardSizes; } public Map<String, DiskUsage> getNodeDiskUsages() { return this.usages; } public Map<String, Long> getShardSizes() { return this.shardSizes; } }
0true
src_main_java_org_elasticsearch_cluster_ClusterInfo.java
81
public static class Tab { public static class Name { public static final String File_Details = "StaticAssetImpl_FileDetails_Tab"; public static final String Advanced = "StaticAssetImpl_Advanced_Tab"; } public static class Order { public static final int File_Details = 2000; public static final int Advanced = 3000; } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_domain_StaticAssetImpl.java
170
public abstract class SpeedTestThread extends Thread implements SpeedTest { protected SpeedTestData data; protected SpeedTestMultiThreads owner; protected SpeedTestThread() { data = new SpeedTestData(); } protected SpeedTestThread(long iCycles) { data = new SpeedTestData(iCycles); } public void setCycles(long iCycles) { data.cycles = iCycles; } public void setOwner(SpeedTestMultiThreads iOwner) { owner = iOwner; } @Override public void run() { data.printResults = false; data.go(this); } public void init() throws Exception { } public void deinit() throws Exception { } public void afterCycle() throws Exception { } public void beforeCycle() throws Exception { } }
0true
commons_src_test_java_com_orientechnologies_common_test_SpeedTestThread.java
3,252
public class CountDownLatchPermission extends InstancePermission { private static final int READ = 0x4; private static final int MODIFY = 0x8; private static final int ALL = CREATE | DESTROY | READ | MODIFY; public CountDownLatchPermission(String name, String... actions) { super(name, actions); } @Override protected int initMask(String[] actions) { int mask = NONE; for (String action : actions) { if (ActionConstants.ACTION_ALL.equals(action)) { return ALL; } if (ActionConstants.ACTION_CREATE.equals(action)) { mask |= CREATE; } else if (ActionConstants.ACTION_DESTROY.equals(action)) { mask |= DESTROY; } else if (ActionConstants.ACTION_READ.equals(action)) { mask |= READ; } else if (ActionConstants.ACTION_MODIFY.equals(action)) { mask |= MODIFY; } } return mask; } }
1no label
hazelcast_src_main_java_com_hazelcast_security_permission_CountDownLatchPermission.java
518
MessageListener listener = new MessageListener() { public void onMessage(Message message) { } };
0true
hazelcast-client_src_test_java_com_hazelcast_client_topic_ClientTopicTest.java
839
private static class NullFunction implements IFunction<String, String> { @Override public String apply(String input) { return null; } }
0true
hazelcast_src_test_java_com_hazelcast_concurrent_atomicreference_AtomicReferenceTest.java
590
public class FinalizeJoinOperation extends MemberInfoUpdateOperation implements JoinOperation { private PostJoinOperation postJoinOp; public FinalizeJoinOperation() { } public FinalizeJoinOperation(Collection<MemberInfo> members, PostJoinOperation postJoinOp, long masterTime) { super(members, masterTime, true); this.postJoinOp = postJoinOp; } @Override public void run() throws Exception { if (isValid()) { processMemberUpdate(); // Post join operations must be lock free; means no locks at all; // no partition locks, no key-based locks, no service level locks! final ClusterServiceImpl clusterService = getService(); final NodeEngineImpl nodeEngine = clusterService.getNodeEngine(); final Operation[] postJoinOperations = nodeEngine.getPostJoinOperations(); Collection<Future> calls = null; if (postJoinOperations != null && postJoinOperations.length > 0) { final Collection<MemberImpl> members = clusterService.getMemberList(); calls = new ArrayList<Future>(members.size()); for (MemberImpl member : members) { if (!member.localMember()) { Future f = nodeEngine.getOperationService().createInvocationBuilder(ClusterServiceImpl.SERVICE_NAME, new PostJoinOperation(postJoinOperations), member.getAddress()) .setTryCount(10).setTryPauseMillis(100).invoke(); calls.add(f); } } } if (postJoinOp != null) { postJoinOp.setNodeEngine(nodeEngine); OperationAccessor.setCallerAddress(postJoinOp, getCallerAddress()); OperationAccessor.setConnection(postJoinOp, getConnection()); postJoinOp.setResponseHandler(ResponseHandlerFactory.createEmptyResponseHandler()); nodeEngine.getOperationService().runOperationOnCallingThread(postJoinOp); } if (calls != null) { for (Future f : calls) { try { f.get(1, TimeUnit.SECONDS); } catch (InterruptedException ignored) { } catch (TimeoutException ignored) { } catch (ExecutionException e) { final ILogger logger = nodeEngine.getLogger(FinalizeJoinOperation.class); if (logger.isFinestEnabled()) { logger.finest("Error while executing post-join operations -> " + e.getClass().getSimpleName() + "[" + e.getMessage() + "]"); } } } } } } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); boolean hasPJOp = postJoinOp != null; out.writeBoolean(hasPJOp); if (hasPJOp) { postJoinOp.writeData(out); } } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); boolean hasPJOp = in.readBoolean(); if (hasPJOp) { postJoinOp = new PostJoinOperation(); postJoinOp.readData(in); } } }
1no label
hazelcast_src_main_java_com_hazelcast_cluster_FinalizeJoinOperation.java
303
public interface OConfigurationChangeCallback { public void change(final Object iCurrentValue, final Object iNewValue); }
0true
core_src_main_java_com_orientechnologies_orient_core_config_OConfigurationChangeCallback.java
340
public abstract class ODatabasePoolAbstract<DB extends ODatabase> extends OAdaptiveLock implements OResourcePoolListener<String, DB>, OOrientListener { private final HashMap<String, OResourcePool<String, DB>> pools = new HashMap<String, OResourcePool<String, DB>>(); private int maxSize; private int timeout; protected Object owner; private Timer evictionTask; private Evictor evictor; public ODatabasePoolAbstract(final Object iOwner, final int iMinSize, final int iMaxSize) { this(iOwner, iMinSize, iMaxSize, OGlobalConfiguration.CLIENT_CONNECT_POOL_WAIT_TIMEOUT.getValueAsInteger(), OGlobalConfiguration.DB_POOL_IDLE_TIMEOUT.getValueAsLong(), OGlobalConfiguration.DB_POOL_IDLE_CHECK_DELAY.getValueAsLong()); } public ODatabasePoolAbstract(final Object iOwner, final int iMinSize, final int iMaxSize, final long idleTimeout, final long timeBetweenEvictionRunsMillis) { this(iOwner, iMinSize, iMaxSize, OGlobalConfiguration.CLIENT_CONNECT_POOL_WAIT_TIMEOUT.getValueAsInteger(), idleTimeout, timeBetweenEvictionRunsMillis); } public ODatabasePoolAbstract(final Object iOwner, final int iMinSize, final int iMaxSize, final int iTimeout, final long idleTimeoutMillis, final long timeBetweenEvictionRunsMillis) { super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean(), OGlobalConfiguration.STORAGE_LOCK_TIMEOUT .getValueAsInteger(), true); maxSize = iMaxSize; timeout = iTimeout; owner = iOwner; Orient.instance().registerListener(this); if (idleTimeoutMillis > 0 && timeBetweenEvictionRunsMillis > 0) { this.evictionTask = new Timer(); this.evictor = new Evictor(idleTimeoutMillis); this.evictionTask.schedule(evictor, timeBetweenEvictionRunsMillis, timeBetweenEvictionRunsMillis); } } public DB acquire(final String iURL, final String iUserName, final String iUserPassword) throws OLockException { return acquire(iURL, iUserName, iUserPassword, null); } public DB acquire(final String iURL, final String iUserName, final String iUserPassword, final Map<String, Object> iOptionalParams) throws OLockException { final String dbPooledName = OIOUtils.getUnixFileName(iUserName + "@" + iURL); lock(); try { OResourcePool<String, DB> pool = pools.get(dbPooledName); if (pool == null) // CREATE A NEW ONE pool = new OResourcePool<String, DB>(maxSize, this); final DB db = pool.getResource(iURL, timeout, iUserName, iUserPassword, iOptionalParams); // PUT IN THE POOL MAP ONLY IF AUTHENTICATION SUCCEED pools.put(dbPooledName, pool); return db; } finally { unlock(); } } public void release(final DB iDatabase) { final String dbPooledName = iDatabase instanceof ODatabaseComplex ? ((ODatabaseComplex<?>) iDatabase).getUser().getName() + "@" + iDatabase.getURL() : iDatabase.getURL(); lock(); try { final OResourcePool<String, DB> pool = pools.get(dbPooledName); if (pool == null) throw new OLockException("Cannot release a database URL not acquired before. URL: " + iDatabase.getName()); pool.returnResource(iDatabase); this.notifyEvictor(dbPooledName, iDatabase); } finally { unlock(); } } public DB reuseResource(final String iKey, final DB iValue) { return iValue; } public Map<String, OResourcePool<String, DB>> getPools() { lock(); try { return Collections.unmodifiableMap(pools); } finally { unlock(); } } /** * Closes all the databases. */ public void close() { lock(); try { if (this.evictionTask != null) { this.evictionTask.cancel(); } for (Entry<String, OResourcePool<String, DB>> pool : pools.entrySet()) { for (DB db : pool.getValue().getResources()) { pool.getValue().close(); try { OLogManager.instance().debug(this, "Closing pooled database '%s'...", db.getName()); ((ODatabasePooled) db).forceClose(); OLogManager.instance().debug(this, "OK", db.getName()); } catch (Exception e) { OLogManager.instance().debug(this, "Error: %d", e.toString()); } } } } finally { unlock(); } } public void remove(final String iName, final String iUser) { remove(iUser + "@" + iName); } public void remove(final String iPoolName) { lock(); try { final OResourcePool<String, DB> pool = pools.get(iPoolName); if (pool != null) { for (DB db : pool.getResources()) { if (db.getStorage().getStatus() == OStorage.STATUS.OPEN) try { OLogManager.instance().debug(this, "Closing pooled database '%s'...", db.getName()); ((ODatabasePooled) db).forceClose(); OLogManager.instance().debug(this, "OK", db.getName()); } catch (Exception e) { OLogManager.instance().debug(this, "Error: %d", e.toString()); } } pool.close(); pools.remove(iPoolName); } } finally { unlock(); } } public int getMaxSize() { return maxSize; } public void onStorageRegistered(final OStorage iStorage) { } /** * Removes from memory the pool associated to the closed storage. This avoids pool open against closed storages. */ public void onStorageUnregistered(final OStorage iStorage) { final String storageURL = iStorage.getURL(); lock(); try { Set<String> poolToClose = null; for (Entry<String, OResourcePool<String, DB>> e : pools.entrySet()) { final int pos = e.getKey().indexOf("@"); final String dbName = e.getKey().substring(pos + 1); if (storageURL.equals(dbName)) { if (poolToClose == null) poolToClose = new HashSet<String>(); poolToClose.add(e.getKey()); } } if (poolToClose != null) for (String pool : poolToClose) remove(pool); } finally { unlock(); } } private void notifyEvictor(final String poolName, final DB iDatabase) { if (this.evictor != null) { this.evictor.updateIdleTime(poolName, iDatabase); } } /** * The idle object evictor {@link TimerTask}. */ class Evictor extends TimerTask { private HashMap<String, Map<DB, Long>> evictionMap = new HashMap<String, Map<DB, Long>>(); private long minIdleTime; public Evictor(long minIdleTime) { this.minIdleTime = minIdleTime; } /** * Run pool maintenance. Evict objects qualifying for eviction */ @Override public void run() { OLogManager.instance().debug(this, "Running Connection Pool Evictor Service..."); lock(); try { for (Entry<String, Map<DB, Long>> pool : this.evictionMap.entrySet()) { Map<DB, Long> poolDbs = pool.getValue(); Iterator<Entry<DB, Long>> iterator = poolDbs.entrySet().iterator(); while (iterator.hasNext()) { Entry<DB, Long> db = iterator.next(); if (System.currentTimeMillis() - db.getValue() >= this.minIdleTime) { OResourcePool<String, DB> oResourcePool = pools.get(pool.getKey()); if (oResourcePool != null) { OLogManager.instance().debug(this, "Closing idle pooled database '%s'...", db.getKey().getName()); ((ODatabasePooled) db.getKey()).forceClose(); oResourcePool.remove(db.getKey()); iterator.remove(); } } } } } finally { unlock(); } } public void updateIdleTime(final String poolName, final DB iDatabase) { Map<DB, Long> pool = this.evictionMap.get(poolName); if (pool == null) { pool = new HashMap<DB, Long>(); this.evictionMap.put(poolName, pool); } pool.put(iDatabase, System.currentTimeMillis()); } } }
1no label
core_src_main_java_com_orientechnologies_orient_core_db_ODatabasePoolAbstract.java
521
@RunWith(HazelcastParallelClassRunner.class) @Category(QuickTest.class) public class ClientTxnListTest { static HazelcastInstance client; static HazelcastInstance server; @BeforeClass public static void init(){ server = Hazelcast.newHazelcastInstance(); client = HazelcastClient.newHazelcastClient(null); } @AfterClass public static void destroy() { HazelcastClient.shutdownAll(); Hazelcast.shutdownAll(); } @Test public void testAddRemove() throws Exception { String listName = randomString(); final IList l = client.getList(listName); l.add("item1"); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalList<Object> list = context.getList(listName); assertTrue(list.add("item2")); assertEquals(2, list.size()); assertEquals(1, l.size()); assertFalse(list.remove("item3")); assertTrue(list.remove("item1")); context.commitTransaction(); assertEquals(1, l.size()); } @Test public void testAddAndRoleBack() throws Exception { final String listName = randomString(); final IList l = client.getList(listName); l.add("item1"); final TransactionContext context = client.newTransactionContext(); context.beginTransaction(); final TransactionalList<Object> list = context.getList(listName); list.add("item2"); context.rollbackTransaction(); assertEquals(1, l.size()); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_txn_ClientTxnListTest.java
520
public class BLCArrayUtils { /** * Given an array and a typed predicate, determines if the array has an object that matches the condition of the * predicate. The predicate should evaluate to true when a match occurs. * * @param array * @param predicate * @return whether or not the array contains an element that matches the predicate */ public static <T> boolean contains(T[] array, TypedPredicate<T> predicate) { for (T o : array) { if (predicate.evaluate(o)) { return true; } } return false; } /** * Given an input array, will return an ArrayList representation of the array. * * @param array * @return the ArrayList corresponding to the input array */ public static <T> ArrayList<T> asList(T[] array) { if (array == null || array.length == 0) { return null; } ArrayList<T> list = new ArrayList<T>(array.length); for (T e : array) { list.add(e); } return list; } /** * Similar to the CollectionUtils collect except that it works on an array instead of a Java Collection * * @param array * @param transformer * @return the transformed collection */ public static <T, O> ArrayList<T> collect(Object[] array, TypedTransformer<T> transformer) { ArrayList<T> list = new ArrayList<T>(array.length); for (Object o : array) { list.add(transformer.transform(o)); } return list; } /** * The same as {@link #collect(Object[], TypedTransformer)} but returns a set. * * @param array * @param transformer * @return the transformed set */ public static <T, O> HashSet<T> collectSet(Object[] array, TypedTransformer<T> transformer) { HashSet<T> set = new HashSet<T>(array.length); for (Object o : array) { set.add(transformer.transform(o)); } return set; } }
0true
common_src_main_java_org_broadleafcommerce_common_util_BLCArrayUtils.java
562
public class OCompositeIndexDefinition extends OAbstractIndexDefinition { private final List<OIndexDefinition> indexDefinitions; private String className; private int multiValueDefinitionIndex = -1; public OCompositeIndexDefinition() { indexDefinitions = new ArrayList<OIndexDefinition>(5); } /** * Constructor for new index creation. * * @param iClassName * - name of class which is owner of this index */ public OCompositeIndexDefinition(final String iClassName) { indexDefinitions = new ArrayList<OIndexDefinition>(5); className = iClassName; } /** * Constructor for new index creation. * * @param iClassName * - name of class which is owner of this index * @param iIndexes * List of indexDefinitions to add in given index. */ public OCompositeIndexDefinition(final String iClassName, final List<? extends OIndexDefinition> iIndexes) { indexDefinitions = new ArrayList<OIndexDefinition>(5); for (OIndexDefinition indexDefinition : iIndexes) { indexDefinitions.add(indexDefinition); if (indexDefinition instanceof OIndexDefinitionMultiValue) if (multiValueDefinitionIndex == -1) multiValueDefinitionIndex = indexDefinitions.size() - 1; else throw new OIndexException("Composite key can not contain more than one collection item"); } className = iClassName; } /** * {@inheritDoc} */ public String getClassName() { return className; } /** * Add new indexDefinition in current composite. * * @param indexDefinition * Index to add. */ public void addIndex(final OIndexDefinition indexDefinition) { indexDefinitions.add(indexDefinition); if (indexDefinition instanceof OIndexDefinitionMultiValue) { if (multiValueDefinitionIndex == -1) multiValueDefinitionIndex = indexDefinitions.size() - 1; else throw new OIndexException("Composite key can not contain more than one collection item"); } } /** * {@inheritDoc} */ public List<String> getFields() { final List<String> fields = new LinkedList<String>(); for (final OIndexDefinition indexDefinition : indexDefinitions) { fields.addAll(indexDefinition.getFields()); } return Collections.unmodifiableList(fields); } /** * {@inheritDoc} */ public List<String> getFieldsToIndex() { final List<String> fields = new LinkedList<String>(); for (final OIndexDefinition indexDefinition : indexDefinitions) { fields.addAll(indexDefinition.getFieldsToIndex()); } return Collections.unmodifiableList(fields); } /** * {@inheritDoc} */ public Object getDocumentValueToIndex(final ODocument iDocument) { final List<OCompositeKey> compositeKeys = new ArrayList<OCompositeKey>(10); final OCompositeKey firstKey = new OCompositeKey(); boolean containsCollection = false; compositeKeys.add(firstKey); for (final OIndexDefinition indexDefinition : indexDefinitions) { final Object result = indexDefinition.getDocumentValueToIndex(iDocument); if (result == null) return null; containsCollection = addKey(firstKey, compositeKeys, containsCollection, result); } if (!containsCollection) return firstKey; return compositeKeys; } public int getMultiValueDefinitionIndex() { return multiValueDefinitionIndex; } public String getMultiValueField() { if (multiValueDefinitionIndex >= 0) return indexDefinitions.get(multiValueDefinitionIndex).getFields().get(0); return null; } /** * {@inheritDoc} */ public Object createValue(final List<?> params) { int currentParamIndex = 0; final OCompositeKey firstKey = new OCompositeKey(); final List<OCompositeKey> compositeKeys = new ArrayList<OCompositeKey>(10); compositeKeys.add(firstKey); boolean containsCollection = false; for (final OIndexDefinition indexDefinition : indexDefinitions) { if (currentParamIndex + 1 > params.size()) break; final int endIndex; if (currentParamIndex + indexDefinition.getParamCount() > params.size()) endIndex = params.size(); else endIndex = currentParamIndex + indexDefinition.getParamCount(); final List<?> indexParams = params.subList(currentParamIndex, endIndex); currentParamIndex += indexDefinition.getParamCount(); final Object keyValue = indexDefinition.createValue(indexParams); if (keyValue == null) return null; containsCollection = addKey(firstKey, compositeKeys, containsCollection, keyValue); } if (!containsCollection) return firstKey; return compositeKeys; } public OIndexDefinitionMultiValue getMultiValueDefinition() { if (multiValueDefinitionIndex > -1) return (OIndexDefinitionMultiValue) indexDefinitions.get(multiValueDefinitionIndex); return null; } public OCompositeKey createSingleValue(final List<?> params) { final OCompositeKey compositeKey = new OCompositeKey(); int currentParamIndex = 0; for (final OIndexDefinition indexDefinition : indexDefinitions) { if (currentParamIndex + 1 > params.size()) break; final int endIndex; if (currentParamIndex + indexDefinition.getParamCount() > params.size()) endIndex = params.size(); else endIndex = currentParamIndex + indexDefinition.getParamCount(); final List<?> indexParams = params.subList(currentParamIndex, endIndex); currentParamIndex += indexDefinition.getParamCount(); final Object keyValue; if (indexDefinition instanceof OIndexDefinitionMultiValue) keyValue = ((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(indexParams.toArray()); else keyValue = indexDefinition.createValue(indexParams); if (keyValue == null) return null; compositeKey.addKey(keyValue); } return compositeKey; } private static boolean addKey(OCompositeKey firstKey, List<OCompositeKey> compositeKeys, boolean containsCollection, Object keyValue) { if (keyValue instanceof Collection) { final Collection<?> collectionKey = (Collection<?>) keyValue; if (!containsCollection) for (int i = 1; i < collectionKey.size(); i++) { final OCompositeKey compositeKey = new OCompositeKey(firstKey.getKeys()); compositeKeys.add(compositeKey); } else throw new OIndexException("Composite key can not contain more than one collection item"); int compositeIndex = 0; for (final Object keyItem : collectionKey) { final OCompositeKey compositeKey = compositeKeys.get(compositeIndex); compositeKey.addKey(keyItem); compositeIndex++; } containsCollection = true; } else if (containsCollection) for (final OCompositeKey compositeKey : compositeKeys) compositeKey.addKey(keyValue); else firstKey.addKey(keyValue); return containsCollection; } /** * {@inheritDoc} */ public Object createValue(final Object... params) { return createValue(Arrays.asList(params)); } public void processChangeEvent(OMultiValueChangeEvent<?, ?> changeEvent, Map<OCompositeKey, Integer> keysToAdd, Map<OCompositeKey, Integer> keysToRemove, Object... params) { final OIndexDefinitionMultiValue indexDefinitionMultiValue = (OIndexDefinitionMultiValue) indexDefinitions .get(multiValueDefinitionIndex); final CompositeWrapperMap compositeWrapperKeysToAdd = new CompositeWrapperMap(keysToAdd, indexDefinitions, params, multiValueDefinitionIndex); final CompositeWrapperMap compositeWrapperKeysToRemove = new CompositeWrapperMap(keysToRemove, indexDefinitions, params, multiValueDefinitionIndex); indexDefinitionMultiValue.processChangeEvent(changeEvent, compositeWrapperKeysToAdd, compositeWrapperKeysToRemove); } /** * {@inheritDoc} */ public int getParamCount() { int total = 0; for (final OIndexDefinition indexDefinition : indexDefinitions) total += indexDefinition.getParamCount(); return total; } /** * {@inheritDoc} */ public OType[] getTypes() { final List<OType> types = new LinkedList<OType>(); for (final OIndexDefinition indexDefinition : indexDefinitions) Collections.addAll(types, indexDefinition.getTypes()); return types.toArray(new OType[types.size()]); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final OCompositeIndexDefinition that = (OCompositeIndexDefinition) o; if (!className.equals(that.className)) return false; if (!indexDefinitions.equals(that.indexDefinitions)) return false; return true; } @Override public int hashCode() { int result = indexDefinitions.hashCode(); result = 31 * result + className.hashCode(); return result; } @Override public String toString() { return "OCompositeIndexDefinition{" + "indexDefinitions=" + indexDefinitions + ", className='" + className + '\'' + '}'; } /** * {@inheritDoc} */ @Override public ODocument toStream() { document.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); final List<ODocument> inds = new ArrayList<ODocument>(indexDefinitions.size()); final List<String> indClasses = new ArrayList<String>(indexDefinitions.size()); try { document.field("className", className); for (final OIndexDefinition indexDefinition : indexDefinitions) { final ODocument indexDocument = indexDefinition.toStream(); inds.add(indexDocument); indClasses.add(indexDefinition.getClass().getName()); } document.field("indexDefinitions", inds, OType.EMBEDDEDLIST); document.field("indClasses", indClasses, OType.EMBEDDEDLIST); } finally { document.setInternalStatus(ORecordElement.STATUS.LOADED); } document.field("collate", collate.getName()); return document; } /** * {@inheritDoc} */ public String toCreateIndexDDL(final String indexName, final String indexType) { final StringBuilder ddl = new StringBuilder("create index "); ddl.append(indexName).append(" on ").append(className).append(" ( "); final Iterator<String> fieldIterator = getFieldsToIndex().iterator(); if (fieldIterator.hasNext()) { ddl.append(fieldIterator.next()); while (fieldIterator.hasNext()) { ddl.append(", ").append(fieldIterator.next()); } } ddl.append(" ) ").append(indexType).append(' '); if (multiValueDefinitionIndex == -1) { boolean first = true; for (OType oType : getTypes()) { if (first) first = false; else ddl.append(", "); ddl.append(oType.name()); } } return ddl.toString(); } /** * {@inheritDoc} */ @Override protected void fromStream() { try { className = document.field("className"); final List<ODocument> inds = document.field("indexDefinitions"); final List<String> indClasses = document.field("indClasses"); indexDefinitions.clear(); for (int i = 0; i < indClasses.size(); i++) { final Class<?> clazz = Class.forName(indClasses.get(i)); final ODocument indDoc = inds.get(i); final OIndexDefinition indexDefinition = (OIndexDefinition) clazz.getDeclaredConstructor().newInstance(); indexDefinition.fromStream(indDoc); indexDefinitions.add(indexDefinition); if (indexDefinition instanceof OIndexDefinitionMultiValue) multiValueDefinitionIndex = indexDefinitions.size() - 1; } setCollate((String) document.field("collate")); } catch (final ClassNotFoundException e) { throw new OIndexException("Error during composite index deserialization", e); } catch (final NoSuchMethodException e) { throw new OIndexException("Error during composite index deserialization", e); } catch (final InvocationTargetException e) { throw new OIndexException("Error during composite index deserialization", e); } catch (final InstantiationException e) { throw new OIndexException("Error during composite index deserialization", e); } catch (final IllegalAccessException e) { throw new OIndexException("Error during composite index deserialization", e); } } private static final class CompositeWrapperMap implements Map<Object, Integer> { private final Map<OCompositeKey, Integer> underlying; private final Object[] params; private final List<OIndexDefinition> indexDefinitions; private final int multiValueIndex; private CompositeWrapperMap(Map<OCompositeKey, Integer> underlying, List<OIndexDefinition> indexDefinitions, Object[] params, int multiValueIndex) { this.underlying = underlying; this.params = params; this.multiValueIndex = multiValueIndex; this.indexDefinitions = indexDefinitions; } public int size() { return underlying.size(); } public boolean isEmpty() { return underlying.isEmpty(); } public boolean containsKey(Object key) { final OCompositeKey compositeKey = convertToCompositeKey(key); return underlying.containsKey(compositeKey); } public boolean containsValue(Object value) { return underlying.containsValue(value); } public Integer get(Object key) { return underlying.get(convertToCompositeKey(key)); } public Integer put(Object key, Integer value) { final OCompositeKey compositeKey = convertToCompositeKey(key); return underlying.put(compositeKey, value); } public Integer remove(Object key) { return underlying.remove(convertToCompositeKey(key)); } public void putAll(Map<? extends Object, ? extends Integer> m) { throw new UnsupportedOperationException("Unsupported because of performance reasons"); } public void clear() { underlying.clear(); } public Set<Object> keySet() { throw new UnsupportedOperationException("Unsupported because of performance reasons"); } public Collection<Integer> values() { return underlying.values(); } public Set<Entry<Object, Integer>> entrySet() { throw new UnsupportedOperationException(); } private OCompositeKey convertToCompositeKey(Object key) { final OCompositeKey compositeKey = new OCompositeKey(); int paramsIndex = 0; for (int i = 0; i < indexDefinitions.size(); i++) { final OIndexDefinition indexDefinition = indexDefinitions.get(i); if (i != multiValueIndex) { compositeKey.addKey(indexDefinition.createValue(params[paramsIndex])); paramsIndex++; } else compositeKey.addKey(((OIndexDefinitionMultiValue) indexDefinition).createSingleValue(key)); } return compositeKey; } } @Override public boolean isAutomatic() { return indexDefinitions.get(0).isAutomatic(); } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_OCompositeIndexDefinition.java
1,169
clientTransportService.submitRequest(node, "benchmark", message, new BaseTransportResponseHandler<BenchmarkMessageResponse>() { @Override public BenchmarkMessageResponse newInstance() { return new BenchmarkMessageResponse(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void handleResponse(BenchmarkMessageResponse response) { } @Override public void handleException(TransportException exp) { exp.printStackTrace(); } }).txGet();
0true
src_test_java_org_elasticsearch_benchmark_transport_TransportBenchmark.java
733
private static final class PagePathItemUnit { private final long pageIndex; private final int itemIndex; private PagePathItemUnit(long pageIndex, int itemIndex) { this.pageIndex = pageIndex; this.itemIndex = itemIndex; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_index_sbtree_local_OSBTree.java
1,408
public class CeylonPlugin extends AbstractUIPlugin implements CeylonResources { public static final String PLUGIN_ID = "com.redhat.ceylon.eclipse.ui"; public static final String DIST_PLUGIN_ID = "com.redhat.ceylon.dist"; public static final String EMBEDDED_REPO_PLUGIN_ID = "com.redhat.ceylon.dist.repo"; public static final String LANGUAGE_ID = "ceylon"; public static final String EDITOR_ID = PLUGIN_ID + ".editor"; private static final String[] RUNTIME_LIBRARIES = new String[]{ "com.redhat.ceylon.compiler.java-"+Versions.CEYLON_VERSION_NUMBER+".jar", "com.redhat.ceylon.typechecker-"+Versions.CEYLON_VERSION_NUMBER+".jar", "com.redhat.ceylon.module-resolver-"+Versions.CEYLON_VERSION_NUMBER+".jar", "com.redhat.ceylon.common-"+Versions.CEYLON_VERSION_NUMBER+".jar", "org.jboss.modules-1.3.3.Final.jar", }; private static final String[] COMPILETIME_LIBRARIES = new String[]{ "com.redhat.ceylon.typechecker-"+Versions.CEYLON_VERSION_NUMBER+".jar", }; private FontRegistry fontRegistry; /** * The unique instance of this plugin class */ protected static CeylonPlugin pluginInstance; private File ceylonRepository = null; private BundleContext bundleContext; /** * - If the 'ceylon.repo' property exist, returns the corresponding file * <br> * - Else return the internal repo folder * * @return */ public File getCeylonRepository() { return ceylonRepository; } public static CeylonPlugin getInstance() { if (pluginInstance==null) new CeylonPlugin(); return pluginInstance; } public CeylonPlugin() { final String version = System.getProperty("java.version"); if (!version.startsWith("1.7") && !version.startsWith("1.8")) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { ErrorDialog.openError(getWorkbench().getActiveWorkbenchWindow().getShell(), "Ceylon IDE does not support this JVM", "Ceylon IDE requires Java 1.7 or 1.8.", new Status(IStatus.ERROR, PLUGIN_ID, "Eclipse is running on a Java " + version + " VM.", null)); }}); } pluginInstance = this; } @Override public void start(BundleContext context) throws Exception { String ceylonRepositoryProperty = System.getProperty("ceylon.repo", ""); ceylonRepository = getCeylonPluginRepository(ceylonRepositoryProperty); super.start(context); this.bundleContext = context; addResourceFilterPreference(); registerProjectOpenCloseListener(); CeylonEncodingSynchronizer.getInstance().install(); Job registerCeylonModules = new Job("Load the Ceylon Metamodel for plugin dependencies") { protected IStatus run(IProgressMonitor monitor) { Activator.loadBundleAsModule(bundleContext.getBundle()); return Status.OK_STATUS; }; }; registerCeylonModules.setRule(ResourcesPlugin.getWorkspace().getRoot()); registerCeylonModules.schedule(); } @Override public void stop(BundleContext context) throws Exception { super.stop(context); unregisterProjectOpenCloseListener(); CeylonEncodingSynchronizer.getInstance().uninstall(); } private void addResourceFilterPreference() throws BackingStoreException { new Job("Add Resource Filter for Ceylon projects") { @Override protected IStatus run(IProgressMonitor monitor) { IEclipsePreferences instancePreferences = InstanceScope.INSTANCE .getNode(JavaCore.PLUGIN_ID); /*IEclipsePreferences defaultPreferences = DefaultScope.INSTANCE .getNode(JavaCore.PLUGIN_ID);*/ String filter = instancePreferences.get(CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, ""); if (filter.isEmpty()) { filter = "*.launch, *.ceylon"; } else if (!filter.contains("*.ceylon")) { filter += ", *.ceylon"; } instancePreferences.put(CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, filter); try { instancePreferences.flush(); } catch (BackingStoreException e) { e.printStackTrace(); } return Status.OK_STATUS; } }.schedule(); } /** * - If the property is not empty, return the corresponding file * <br> * - Else return the internal repo folder * * @param ceylonRepositoryProperty * @return * */ public static File getCeylonPluginRepository(String ceylonRepositoryProperty) { File ceylonRepository=null; if (!"".equals(ceylonRepositoryProperty)) { File ceylonRepositoryPath = new File(ceylonRepositoryProperty); if (ceylonRepositoryPath.exists()) { ceylonRepository = ceylonRepositoryPath; } } if (ceylonRepository == null) { try { Bundle bundle = Platform.getBundle(EMBEDDED_REPO_PLUGIN_ID); IPath path = new Path("repo"); if (bundle == null) { bundle = Platform.getBundle(DIST_PLUGIN_ID); path = new Path("embeddedRepository").append(path); } URL eclipseUrl = FileLocator.find(bundle, path, null); URL fileURL = FileLocator.resolve(eclipseUrl); String urlPath = fileURL.getPath(); URI fileURI = new URI("file", null, urlPath, null); ceylonRepository = new File(fileURI); } catch (Exception e) { e.printStackTrace(); } } return ceylonRepository; } /** * Returns the list of jars in the bundled system repo that are required by the ceylon.language module at runtime */ public static List<String> getRuntimeRequiredJars(){ return getRequiredJars(RUNTIME_LIBRARIES); } /** * Returns the list of jars in the bundled system repo that are required by the ceylon.language module at compiletime */ public static List<String> getCompiletimeRequiredJars(){ return getRequiredJars(COMPILETIME_LIBRARIES); } /** * Returns the list of jars in the bundled lib folder required to launch a module */ public static List<String> getModuleLauncherJars(){ try { Bundle bundle = Platform.getBundle(DIST_PLUGIN_ID); Path path = new Path("lib"); URL eclipseUrl = FileLocator.find(bundle, path, null); URL fileURL = FileLocator.resolve(eclipseUrl); File libDir = new File(fileURL.getPath()); List<String> jars = new ArrayList<String>(); jars.add(new File(libDir, "ceylon-bootstrap.jar").getAbsolutePath()); return jars; } catch (IOException x) { x.printStackTrace(); return Collections.emptyList(); } } private static List<String> getRequiredJars(String[] libraries){ File repoDir = getCeylonPluginRepository(System.getProperty("ceylon.repo", "")); try{ List<String> jars = new ArrayList<String>(libraries.length); for(String jar : libraries){ File libDir = new File(repoDir, getRepoFolder(jar)); if( !libDir.exists() ) { System.out.println("WARNING directory doesn't exist: " + libDir); } jars.add(new File(libDir, jar).getAbsolutePath()); } return jars; } catch (Exception x) { x.printStackTrace(); return Collections.emptyList(); } } private static String getRepoFolder(String jarName) { int lastDot = jarName.lastIndexOf('.'); int lastDash = jarName.lastIndexOf('-'); return jarName.substring(0, lastDash).replace('.', '/') + "/" + jarName.substring(lastDash + 1, lastDot); } public String getID() { return PLUGIN_ID; } public String getLanguageID() { return LANGUAGE_ID; } private static IPath iconsPath = new Path("icons/"); public ImageDescriptor image(String file) { URL url = FileLocator.find(getBundle(), iconsPath.append(file), null); if (url!=null) { return ImageDescriptor.createFromURL(url); } else { return null; } } @Override protected void initializeImageRegistry(ImageRegistry reg) { reg.put(JAVA_FILE, image("jcu_obj.gif")); reg.put(GENERIC_FILE, image("file_obj.gif")); reg.put(CEYLON_PROJECT, image("prj_obj.gif")); reg.put(CEYLON_FILE, image("unit.gif")); reg.put(CEYLON_MODULE_DESC, image("m_desc.gif")); reg.put(CEYLON_PACKAGE_DESC, image("p_desc.gif")); reg.put(CEYLON_FOLDER, image("fldr_obj.gif")); reg.put(CEYLON_SOURCE_FOLDER, image("packagefolder_obj.gif")); reg.put(CEYLON_MODULE, image("jar_l_obj.gif")); reg.put(CEYLON_BINARY_ARCHIVE, image("jar_obj.gif")); reg.put(CEYLON_SOURCE_ARCHIVE, image("jar_src_obj.gif")); reg.put(CEYLON_PACKAGE, image("package_obj.gif")); reg.put(CEYLON_IMPORT_LIST, image("impc_obj.gif")); reg.put(CEYLON_IMPORT, image("imp_obj.gif")); reg.put(CEYLON_ALIAS, image("types.gif")); reg.put(CEYLON_CLASS, image("class_obj.gif")); reg.put(CEYLON_INTERFACE, image("int_obj.gif")); reg.put(CEYLON_LOCAL_CLASS, image("innerclass_private_obj.gif")); reg.put(CEYLON_LOCAL_INTERFACE, image("innerinterface_private_obj.gif")); reg.put(CEYLON_METHOD, image("public_co.gif")); reg.put(CEYLON_ATTRIBUTE, image("field_public_obj.gif")); reg.put(CEYLON_LOCAL_METHOD, image("private_co.gif")); reg.put(CEYLON_LOCAL_ATTRIBUTE, image("field_private_obj.gif")); reg.put(CEYLON_PARAMETER_METHOD, image("methpro_obj.gif")); reg.put(CEYLON_PARAMETER, image("field_protected_obj.gif")); reg.put(CEYLON_TYPE_PARAMETER, image("typevariable_obj.gif")); reg.put(CEYLON_ARGUMENT, image("arg_co.gif")); reg.put(CEYLON_DEFAULT_REFINEMENT, image("over_co.gif")); reg.put(CEYLON_FORMAL_REFINEMENT, image("implm_co.gif")); reg.put(CEYLON_OPEN_DECLARATION, image("opentype.gif")); reg.put(CEYLON_SEARCH_RESULTS, image("search_ref_obj.gif")); reg.put(CEYLON_CORRECTION, image("correction_change.gif")); reg.put(CEYLON_DELETE_IMPORT, image("correction_delete_import.gif")); reg.put(CEYLON_CHANGE, image("change.png")); reg.put(CEYLON_COMPOSITE_CHANGE, image("composite_change.png")); reg.put(CEYLON_RENAME, image("correction_rename.png")); reg.put(CEYLON_DELETE, image("delete_edit.gif")); reg.put(CEYLON_MOVE, image("file_change.png")); reg.put(CEYLON_ADD, image("add_obj.gif")); reg.put(CEYLON_REORDER, image("order_obj.gif")); reg.put(CEYLON_REVEAL, image("reveal.gif")); reg.put(CEYLON_ADD_CORRECTION, image("add_correction.gif")); reg.put(CEYLON_REMOVE_CORRECTION, image("remove_correction.gif")); reg.put(CEYLON_NEW_PROJECT, image("newprj_wiz.png")); reg.put(CEYLON_NEW_FILE, image("newfile_wiz.png")); reg.put(CEYLON_NEW_MODULE, image("addlibrary_wiz.png")); reg.put(CEYLON_NEW_PACKAGE, image("newpack_wiz.png")); reg.put(CEYLON_NEW_FOLDER, image("newfolder_wiz.gif")); reg.put(CEYLON_EXPORT_CAR, image("jar_pack_wiz.png")); reg.put(CEYLON_REFS, image("search_ref_obj.png")); reg.put(CEYLON_DECS, image("search_decl_obj.png")); reg.put(CEYLON_INHERITED, image("inher_co.gif")); reg.put(CEYLON_HIER, image("hierarchy_co.gif")); reg.put(CEYLON_SUP, image("super_co.gif")); reg.put(CEYLON_SUB, image("sub_co.gif")); reg.put(CEYLON_OUTLINE, image("outline_co.gif")); reg.put(CEYLON_HIERARCHY, image("class_hi.gif")); reg.put(CEYLON_SOURCE, image("source.gif")); reg.put(ELE32, image("ceylon_icon_32px.png")); reg.put(CEYLON_ERR, image("error_co.gif")); reg.put(CEYLON_WARN, image("warning_co.gif")); reg.put(GOTO, image("goto_obj.gif")); reg.put(HIERARCHY, image("class_hi_view.gif")); reg.put(SHIFT_LEFT, image("shift_l_edit.gif")); reg.put(SHIFT_RIGHT, image("shift_r_edit.gif")); reg.put(QUICK_ASSIST, image("quickassist_obj.gif")); reg.put(BUILDER, image("builder.gif")); reg.put(CONFIG_ANN, image("configure_annotations.gif")); reg.put(CONFIG_ANN_DIS, image("configure_annotations_disabled.gif")); reg.put(MODULE_VERSION, image("module_version.gif")); reg.put(HIDE_PRIVATE, image("hideprivate.gif")); reg.put(EXPAND_ALL, image("expandall.gif")); reg.put(PAGING, image("paging.gif")); reg.put(SHOW_DOC, image("show_doc.gif")); reg.put(REPOSITORIES, image("repositories.gif")); reg.put(RUNTIME_OBJ, image("runtime_obj.gif")); reg.put(CEYLON_LOCAL_NAME, image("localvariable_obj.gif")); reg.put(MULTIPLE_TYPES, image("types.gif")); reg.put(CEYLON_ERROR, image("error_obj.gif")); reg.put(CEYLON_WARNING, image("warning_obj.gif")); reg.put(CEYLON_FUN, image("public_fun.gif")); reg.put(CEYLON_LOCAL_FUN, image("private_fun.gif")); reg.put(WARNING_IMAGE, image(WARNING_IMAGE)); reg.put(ERROR_IMAGE, image(ERROR_IMAGE)); reg.put(REFINES_IMAGE, image(REFINES_IMAGE)); reg.put(IMPLEMENTS_IMAGE, image(IMPLEMENTS_IMAGE)); reg.put(FINAL_IMAGE, image(FINAL_IMAGE)); reg.put(ABSTRACT_IMAGE, image(ABSTRACT_IMAGE)); reg.put(VARIABLE_IMAGE, image(VARIABLE_IMAGE)); reg.put(ANNOTATION_IMAGE, image(ANNOTATION_IMAGE)); reg.put(ENUM_IMAGE, image(ENUM_IMAGE)); reg.put(ALIAS_IMAGE, image(ALIAS_IMAGE)); reg.put(DEPRECATED_IMAGE, image(DEPRECATED_IMAGE)); reg.put(PROJECT_MODE, image("prj_mode.gif")); reg.put(PACKAGE_MODE, image("package_mode.gif")); reg.put(MODULE_MODE, image("module_mode.gif")); reg.put(FOLDER_MODE, image("folder_mode.gif")); reg.put(UNIT_MODE, image("unit_mode.gif")); reg.put(TYPE_MODE, image("type_mode.gif")); reg.put(FLAT_MODE, image("flatLayout.gif")); reg.put(TREE_MODE, image("hierarchicalLayout.gif")); reg.put(TERMINATE_STATEMENT, image("correction_cast.gif")); reg.put(FORMAT_BLOCK, image("format_block.gif")); reg.put(REMOVE_COMMENT, image("remove_comment_edit.gif")); reg.put(ADD_COMMENT, image("comment_edit.gif")); reg.put(TOGGLE_COMMENT, image("url.gif")); reg.put(CORRECT_INDENT, image("correctindent.gif")); reg.put(LAST_EDIT, image("last_edit_pos.gif")); reg.put(NEXT_ANN, image("next_nav.gif")); reg.put(PREV_ANN, image("prev_nav.gif")); reg.put(SORT_ALPHA, image("alphab_sort_co.gif")); reg.put(CEYLON_LITERAL, image("correction_change.gif")); } private void registerProjectOpenCloseListener() { getWorkspace().addResourceChangeListener(projectOpenCloseListener, IResourceChangeEvent.POST_CHANGE); } private void unregisterProjectOpenCloseListener() { getWorkspace().removeResourceChangeListener(projectOpenCloseListener); } IResourceChangeListener projectOpenCloseListener = new ProjectChangeListener(); public BundleContext getBundleContext() { return this.bundleContext; } /** * Utility class that tries to adapt a non null object to the specified type * * @param object * the object to adapt * @param type * the class to adapt to * @return the adapted object */ public static Object adapt(Object object, Class<?> type) { if (type.isInstance(object)) { return object; } else if (object instanceof IAdaptable) { return ((IAdaptable) object).getAdapter(type); } return Platform.getAdapterManager().getAdapter(object, type); } public FontRegistry getFontRegistry() { // Hopefully this gets called late enough, i.e., after a Display has been // created on the current thread (see FontRegistry constructor). if (fontRegistry == null) { fontRegistry= new FontRegistry(); } return fontRegistry; } }
1no label
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_ui_CeylonPlugin.java
1,113
public class OSQLFunctionEval extends OSQLFunctionMathAbstract { public static final String NAME = "eval"; private OSQLPredicate predicate; public OSQLFunctionEval() { super(NAME, 1, 1); } public Object execute(final OIdentifiable iRecord, final Object iCurrentResult, final Object[] iParameters, OCommandContext iContext) { if (predicate == null) predicate = new OSQLPredicate((String) iParameters[0].toString()); try { return predicate.evaluate(iRecord != null ? iRecord.getRecord() : null, (ODocument) iCurrentResult, iContext); } catch (ArithmeticException e) { // DIVISION BY 0 return 0; } catch (Exception e) { return null; } } public boolean aggregateResults() { return false; } public String getSyntax() { return "Syntax error: eval(<expression>)"; } @Override public Object getResult() { return null; } @Override public Object mergeDistributedResult(List<Object> resultsToMerge) { return null; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_functions_math_OSQLFunctionEval.java
781
transportService.sendRequest(discoveryNode, MoreLikeThisAction.NAME, request, new TransportResponseHandler<SearchResponse>() { @Override public SearchResponse newInstance() { return new SearchResponse(); } @Override public void handleResponse(SearchResponse response) { listener.onResponse(response); } @Override public void handleException(TransportException exp) { listener.onFailure(exp); } @Override public String executor() { return ThreadPool.Names.SAME; } });
0true
src_main_java_org_elasticsearch_action_mlt_TransportMoreLikeThisAction.java
22
static abstract class NavigableSubMap<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, java.io.Serializable { /** * The backing map. */ final OMVRBTree<K, V> m; /** * Endpoints are represented as triples (fromStart, lo, loInclusive) and (toEnd, hi, hiInclusive). If fromStart is true, then * the low (absolute) bound is the start of the backing map, and the other values are ignored. Otherwise, if loInclusive is * true, lo is the inclusive bound, else lo is the exclusive bound. Similarly for the upper bound. */ final K lo, hi; final boolean fromStart, toEnd; final boolean loInclusive, hiInclusive; NavigableSubMap(final OMVRBTree<K, V> m, final boolean fromStart, K lo, final boolean loInclusive, final boolean toEnd, K hi, final boolean hiInclusive) { if (!fromStart && !toEnd) { if (m.compare(lo, hi) > 0) throw new IllegalArgumentException("fromKey > toKey"); } else { if (!fromStart) // type check m.compare(lo, lo); if (!toEnd) m.compare(hi, hi); } this.m = m; this.fromStart = fromStart; this.lo = lo; this.loInclusive = loInclusive; this.toEnd = toEnd; this.hi = hi; this.hiInclusive = hiInclusive; } // internal utilities final boolean tooLow(final Object key) { if (!fromStart) { int c = m.compare(key, lo); if (c < 0 || (c == 0 && !loInclusive)) return true; } return false; } final boolean tooHigh(final Object key) { if (!toEnd) { int c = m.compare(key, hi); if (c > 0 || (c == 0 && !hiInclusive)) return true; } return false; } final boolean inRange(final Object key) { return !tooLow(key) && !tooHigh(key); } final boolean inClosedRange(final Object key) { return (fromStart || m.compare(key, lo) >= 0) && (toEnd || m.compare(hi, key) >= 0); } final boolean inRange(final Object key, final boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } /* * Absolute versions of relation operations. Subclasses map to these using like-named "sub" versions that invert senses for * descending maps */ final OMVRBTreeEntryPosition<K, V> absLowest() { OMVRBTreeEntry<K, V> e = (fromStart ? m.getFirstEntry() : (loInclusive ? m.getCeilingEntry(lo, PartialSearchMode.LOWEST_BOUNDARY) : m.getHigherEntry(lo))); return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absHighest() { OMVRBTreeEntry<K, V> e = (toEnd ? m.getLastEntry() : (hiInclusive ? m.getFloorEntry(hi, PartialSearchMode.HIGHEST_BOUNDARY) : m.getLowerEntry(hi))); return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absCeiling(K key) { if (tooLow(key)) return absLowest(); OMVRBTreeEntry<K, V> e = m.getCeilingEntry(key, PartialSearchMode.NONE); return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absHigher(K key) { if (tooLow(key)) return absLowest(); OMVRBTreeEntry<K, V> e = m.getHigherEntry(key); return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absFloor(K key) { if (tooHigh(key)) return absHighest(); OMVRBTreeEntry<K, V> e = m.getFloorEntry(key, PartialSearchMode.NONE); return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absLower(K key) { if (tooHigh(key)) return absHighest(); OMVRBTreeEntry<K, V> e = m.getLowerEntry(key); return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } /** Returns the absolute high fence for ascending traversal */ final OMVRBTreeEntryPosition<K, V> absHighFence() { return (toEnd ? null : new OMVRBTreeEntryPosition<K, V>(hiInclusive ? m.getHigherEntry(hi) : m.getCeilingEntry(hi, PartialSearchMode.LOWEST_BOUNDARY))); } /** Return the absolute low fence for descending traversal */ final OMVRBTreeEntryPosition<K, V> absLowFence() { return (fromStart ? null : new OMVRBTreeEntryPosition<K, V>(loInclusive ? m.getLowerEntry(lo) : m.getFloorEntry(lo, PartialSearchMode.HIGHEST_BOUNDARY))); } // Abstract methods defined in ascending vs descending classes // These relay to the appropriate absolute versions abstract OMVRBTreeEntry<K, V> subLowest(); abstract OMVRBTreeEntry<K, V> subHighest(); abstract OMVRBTreeEntry<K, V> subCeiling(K key); abstract OMVRBTreeEntry<K, V> subHigher(K key); abstract OMVRBTreeEntry<K, V> subFloor(K key); abstract OMVRBTreeEntry<K, V> subLower(K key); /** Returns ascending iterator from the perspective of this submap */ abstract OLazyIterator<K> keyIterator(); /** Returns descending iterator from the perspective of this submap */ abstract OLazyIterator<K> descendingKeyIterator(); // public methods @Override public boolean isEmpty() { return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty(); } @Override public int size() { return (fromStart && toEnd) ? m.size() : entrySet().size(); } @Override public final boolean containsKey(Object key) { return inRange(key) && m.containsKey(key); } @Override public final V put(K key, V value) { if (!inRange(key)) throw new IllegalArgumentException("key out of range"); return m.put(key, value); } @Override public final V get(Object key) { return !inRange(key) ? null : m.get(key); } @Override public final V remove(Object key) { return !inRange(key) ? null : m.remove(key); } public final Map.Entry<K, V> ceilingEntry(K key) { return exportEntry(subCeiling(key)); } public final K ceilingKey(K key) { return keyOrNull(subCeiling(key)); } public final Map.Entry<K, V> higherEntry(K key) { return exportEntry(subHigher(key)); } public final K higherKey(K key) { return keyOrNull(subHigher(key)); } public final Map.Entry<K, V> floorEntry(K key) { return exportEntry(subFloor(key)); } public final K floorKey(K key) { return keyOrNull(subFloor(key)); } public final Map.Entry<K, V> lowerEntry(K key) { return exportEntry(subLower(key)); } public final K lowerKey(K key) { return keyOrNull(subLower(key)); } public final K firstKey() { return key(subLowest()); } public final K lastKey() { return key(subHighest()); } public final Map.Entry<K, V> firstEntry() { return exportEntry(subLowest()); } public final Map.Entry<K, V> lastEntry() { return exportEntry(subHighest()); } public final Map.Entry<K, V> pollFirstEntry() { OMVRBTreeEntry<K, V> e = subLowest(); Map.Entry<K, V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } public final Map.Entry<K, V> pollLastEntry() { OMVRBTreeEntry<K, V> e = subHighest(); Map.Entry<K, V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } // Views transient ONavigableMap<K, V> descendingMapView = null; transient EntrySetView entrySetView = null; transient KeySet<K> navigableKeySetView = null; @SuppressWarnings("rawtypes") public final ONavigableSet<K> navigableKeySet() { KeySet<K> nksv = navigableKeySetView; return (nksv != null) ? nksv : (navigableKeySetView = new OMVRBTree.KeySet(this)); } @Override public final Set<K> keySet() { return navigableKeySet(); } public ONavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } public final SortedMap<K, V> subMap(final K fromKey, final K toKey) { return subMap(fromKey, true, toKey, false); } public final SortedMap<K, V> headMap(final K toKey) { return headMap(toKey, false); } public final SortedMap<K, V> tailMap(final K fromKey) { return tailMap(fromKey, true); } // View classes abstract class EntrySetView extends AbstractSet<Map.Entry<K, V>> { private transient int size = -1, sizeModCount; @Override public int size() { if (fromStart && toEnd) return m.size(); if (size == -1 || sizeModCount != m.modCount) { sizeModCount = m.modCount; size = 0; Iterator<?> i = iterator(); while (i.hasNext()) { size++; i.next(); } } return size; } @Override public boolean isEmpty() { OMVRBTreeEntryPosition<K, V> n = absLowest(); return n == null || tooHigh(n.getKey()); } @Override public boolean contains(final Object o) { if (!(o instanceof OMVRBTreeEntry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final K key = entry.getKey(); if (!inRange(key)) return false; V nodeValue = m.get(key); return nodeValue != null && valEquals(nodeValue, entry.getValue()); } @Override public boolean remove(final Object o) { if (!(o instanceof OMVRBTreeEntry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final K key = entry.getKey(); if (!inRange(key)) return false; final OMVRBTreeEntry<K, V> node = m.getEntry(key, PartialSearchMode.NONE); if (node != null && valEquals(node.getValue(), entry.getValue())) { m.deleteEntry(node); return true; } return false; } } /** * Iterators for SubMaps */ abstract class SubMapIterator<T> implements OLazyIterator<T> { OMVRBTreeEntryPosition<K, V> lastReturned; OMVRBTreeEntryPosition<K, V> next; final K fenceKey; int expectedModCount; SubMapIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { expectedModCount = m.modCount; lastReturned = null; next = first; fenceKey = fence == null ? null : fence.getKey(); } public final boolean hasNext() { if (next != null) { final K k = next.getKey(); return k != fenceKey && !k.equals(fenceKey); } return false; } final OMVRBTreeEntryPosition<K, V> nextEntry() { final OMVRBTreeEntryPosition<K, V> e; if (next != null) e = new OMVRBTreeEntryPosition<K, V>(next); else e = null; if (e == null || e.entry == null) throw new NoSuchElementException(); final K k = e.getKey(); if (k == fenceKey || k.equals(fenceKey)) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next.assign(OMVRBTree.next(e)); lastReturned = e; return e; } final OMVRBTreeEntryPosition<K, V> prevEntry() { final OMVRBTreeEntryPosition<K, V> e; if (next != null) e = new OMVRBTreeEntryPosition<K, V>(next); else e = null; if (e == null || e.entry == null) throw new NoSuchElementException(); final K k = e.getKey(); if (k == fenceKey || k.equals(fenceKey)) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next.assign(OMVRBTree.previous(e)); lastReturned = e; return e; } final public T update(final T iValue) { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); return (T) lastReturned.entry.setValue((V) iValue); } final void removeAscending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); // deleted entries are replaced by their successors if (lastReturned.entry.getLeft() != null && lastReturned.entry.getRight() != null) next = lastReturned; m.deleteEntry(lastReturned.entry); lastReturned = null; expectedModCount = m.modCount; } final void removeDescending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); m.deleteEntry(lastReturned.entry); lastReturned = null; expectedModCount = m.modCount; } } final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> { SubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { super(first, fence); } public Map.Entry<K, V> next() { final Map.Entry<K, V> e = OMVRBTree.exportEntry(next); nextEntry(); return e; } public void remove() { removeAscending(); } } final class SubMapKeyIterator extends SubMapIterator<K> { SubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { super(first, fence); } public K next() { return nextEntry().getKey(); } public void remove() { removeAscending(); } } final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> { DescendingSubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) { super(last, fence); } public Map.Entry<K, V> next() { final Map.Entry<K, V> e = OMVRBTree.exportEntry(next); prevEntry(); return e; } public void remove() { removeDescending(); } } final class DescendingSubMapKeyIterator extends SubMapIterator<K> { DescendingSubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) { super(last, fence); } public K next() { return prevEntry().getKey(); } public void remove() { removeDescending(); } } }
0true
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
133
public static class ClientListenerLatch extends CountDownLatch implements ClientListener { public ClientListenerLatch(int count) { super(count); } @Override public void clientConnected(Client client) { countDown(); } @Override public void clientDisconnected(Client client) { } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_ClientServiceTest.java
5,290
public class IpRangeParser implements Aggregator.Parser { @Override public String type() { return InternalIPv4Range.TYPE.name(); } @Override public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException { ValuesSourceConfig<NumericValuesSource> config = new ValuesSourceConfig<NumericValuesSource>(NumericValuesSource.class); String field = null; List<RangeAggregator.Range> ranges = null; String script = null; String scriptLang = null; Map<String, Object> scriptParams = null; boolean keyed = false; boolean assumeSorted = false; XContentParser.Token token; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_STRING) { if ("field".equals(currentFieldName)) { field = parser.text(); } else if ("script".equals(currentFieldName)) { script = parser.text(); } else if ("lang".equals(currentFieldName)) { scriptLang = parser.text(); } else { throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "]."); } } else if (token == XContentParser.Token.START_ARRAY) { if ("ranges".equals(currentFieldName)) { ranges = new ArrayList<RangeAggregator.Range>(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { double from = Double.NEGATIVE_INFINITY; String fromAsStr = null; double to = Double.POSITIVE_INFINITY; String toAsStr = null; String key = null; String mask = null; String toOrFromOrMaskOrKey = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { toOrFromOrMaskOrKey = parser.currentName(); } else if (token == XContentParser.Token.VALUE_NUMBER) { if ("from".equals(toOrFromOrMaskOrKey)) { from = parser.doubleValue(); } else if ("to".equals(toOrFromOrMaskOrKey)) { to = parser.doubleValue(); } } else if (token == XContentParser.Token.VALUE_STRING) { if ("from".equals(toOrFromOrMaskOrKey)) { fromAsStr = parser.text(); } else if ("to".equals(toOrFromOrMaskOrKey)) { toAsStr = parser.text(); } else if ("key".equals(toOrFromOrMaskOrKey)) { key = parser.text(); } else if ("mask".equals(toOrFromOrMaskOrKey)) { mask = parser.text(); } } } RangeAggregator.Range range = new RangeAggregator.Range(key, from, fromAsStr, to, toAsStr); if (mask != null) { parseMaskRange(mask, range, aggregationName, context); } ranges.add(range); } } else { throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "]."); } } else if (token == XContentParser.Token.START_OBJECT) { if ("params".equals(currentFieldName)) { scriptParams = parser.map(); } else { throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "]."); } } else if (token == XContentParser.Token.VALUE_BOOLEAN) { if ("keyed".equals(currentFieldName)) { keyed = parser.booleanValue(); } else if ("script_values_sorted".equals(currentFieldName)) { assumeSorted = parser.booleanValue(); } else { throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "]."); } } else { throw new SearchParseException(context, "Unexpected token " + token + " in [" + aggregationName + "]."); } } if (ranges == null) { throw new SearchParseException(context, "Missing [ranges] in ranges aggregator [" + aggregationName + "]"); } if (script != null) { config.script(context.scriptService().search(context.lookup(), scriptLang, script, scriptParams)); } if (!assumeSorted) { // we need values to be sorted and unique for efficiency config.ensureSorted(true); } config.formatter(ValueFormatter.IPv4); config.parser(ValueParser.IPv4); if (field == null) { return new RangeAggregator.Factory(aggregationName, config, InternalIPv4Range.FACTORY, ranges, keyed); } FieldMapper<?> mapper = context.smartNameFieldMapper(field); if (mapper == null) { config.unmapped(true); return new RangeAggregator.Factory(aggregationName, config, InternalIPv4Range.FACTORY, ranges, keyed); } if (!(mapper instanceof IpFieldMapper)) { throw new AggregationExecutionException("ip_range aggregation can only be applied to ip fields which is not the case with field [" + field + "]"); } IndexFieldData<?> indexFieldData = context.fieldData().getForField(mapper); config.fieldContext(new FieldContext(field, indexFieldData)); return new RangeAggregator.Factory(aggregationName, config, InternalIPv4Range.FACTORY, ranges, keyed); } private static void parseMaskRange(String cidr, RangeAggregator.Range range, String aggregationName, SearchContext ctx) { long[] fromTo = IPv4RangeBuilder.cidrMaskToMinMax(cidr); if (fromTo == null) { throw new SearchParseException(ctx, "invalid CIDR mask [" + cidr + "] in aggregation [" + aggregationName + "]"); } range.from = fromTo[0] < 0 ? Double.NEGATIVE_INFINITY : fromTo[0]; range.to = fromTo[1] < 0 ? Double.POSITIVE_INFINITY : fromTo[1]; if (range.key == null) { range.key = cidr; } } }
1no label
src_main_java_org_elasticsearch_search_aggregations_bucket_range_ipv4_IpRangeParser.java
36
public class StandaloneClusterClientIT { @Test public void canJoinWithExplicitInitialHosts() throws Exception { startAndAssertJoined( 5003, // Config file stringMap(), // Arguments stringMap( initial_hosts.name(), ":5001", server_id.name(), "3" ) ); } @Test public void willFailJoinIfIncorrectInitialHostsSet() throws Exception { assumeFalse( "Cannot kill processes on windows.", osIsWindows() ); startAndAssertJoined( SHOULD_NOT_JOIN, // Config file stringMap(), // Arguments stringMap( initial_hosts.name(), ":5011", server_id.name(), "3" ) ); } @Test public void canJoinWithInitialHostsInConfigFile() throws Exception { startAndAssertJoined( 5003, // Config file stringMap( initial_hosts.name(), ":5001" ), // Arguments stringMap( server_id.name(), "3" ) ); } @Test public void willFailJoinIfIncorrectInitialHostsSetInConfigFile() throws Exception { assumeFalse( "Cannot kill processes on windows.", osIsWindows() ); startAndAssertJoined( SHOULD_NOT_JOIN, // Config file stringMap( initial_hosts.name(), ":5011" ), // Arguments stringMap( server_id.name(), "3" ) ); } @Test public void canOverrideInitialHostsConfigFromConfigFile() throws Exception { startAndAssertJoined( 5003, // Config file stringMap( initial_hosts.name(), ":5011" ), // Arguments stringMap( initial_hosts.name(), ":5001", server_id.name(), "3" ) ); } @Test public void canSetSpecificPort() throws Exception { startAndAssertJoined( 5010, // Config file stringMap(), // Arguments stringMap( initial_hosts.name(), ":5001", server_id.name(), "3", cluster_server.name(), ":5010" ) ); } @Test public void usesPortRangeFromConfigFile() throws Exception { startAndAssertJoined( 5012, // Config file stringMap( initial_hosts.name(), ":5001", cluster_server.name(), ":5012-5020" ), // Arguments stringMap( server_id.name(), "3" ) ); } // === Everything else === private static Integer SHOULD_NOT_JOIN = null; @Rule public TestRule dumpPorts = new DumpPortListenerOnNettyBindFailure(); private final File directory = TargetDirectory.forTest( getClass() ).cleanDirectory( "temp" ); private LifeSupport life; private ClusterClient[] clients; @Before public void before() throws Exception { life = new LifeSupport(); life.start(); // So that the clients get started as they are added clients = new ClusterClient[2]; for ( int i = 1; i <= clients.length; i++ ) { Map<String, String> config = stringMap(); config.put( cluster_server.name(), ":" + (5000 + i) ); config.put( server_id.name(), "" + i ); config.put( initial_hosts.name(), ":5001" ); Logging logging = new DevNullLoggingService(); ObjectStreamFactory objectStreamFactory = new ObjectStreamFactory(); final ClusterClient client = new ClusterClient( adapt( new Config( config ) ), logging, new ServerIdElectionCredentialsProvider(), objectStreamFactory, objectStreamFactory ); final CountDownLatch latch = new CountDownLatch( 1 ); client.addClusterListener( new ClusterListener.Adapter() { @Override public void enteredCluster( ClusterConfiguration configuration ) { latch.countDown(); client.removeClusterListener( this ); } } ); clients[i - 1] = life.add( client ); assertTrue( "Didn't join the cluster", latch.await( 2, SECONDS ) ); } } @After public void after() throws Exception { life.shutdown(); } private File configFile( Map<String, String> config ) throws IOException { File directory = TargetDirectory.forTest( getClass() ).cleanDirectory( "temp" ); File dbConfigFile = new File( directory, "config-file" ); store( config, dbConfigFile ); File serverConfigFile = new File( directory, "server-file" ); store( stringMap( Configurator.DB_TUNING_PROPERTY_FILE_KEY, dbConfigFile.getAbsolutePath() ), serverConfigFile ); return serverConfigFile; } private void startAndAssertJoined( Integer expectedAssignedPort, Map<String, String> configInConfigFile, Map<String, String> config ) throws Exception { File configFile = configFile( configInConfigFile ); CountDownLatch latch = new CountDownLatch( 1 ); AtomicInteger port = new AtomicInteger(); clients[0].addClusterListener( joinAwaitingListener( latch, port ) ); boolean clientStarted = startStandaloneClusterClient( configFile, config, latch ); if ( expectedAssignedPort == null ) { assertFalse( format( "Should not be able to start cluster client given config file:%s " + "and arguments:%s", configInConfigFile, config ), clientStarted ); } else { assertTrue( format( "Should be able to start client client given config file:%s " + "and arguments:%s", configInConfigFile, config ), clientStarted ); assertEquals( expectedAssignedPort.intValue(), port.get() ); } } private Adapter joinAwaitingListener( final CountDownLatch latch, final AtomicInteger port ) { return new ClusterListener.Adapter() { @Override public void joinedCluster( InstanceId member, URI memberUri ) { port.set( memberUri.getPort() ); latch.countDown(); clients[0].removeClusterListener( this ); } }; } private boolean startStandaloneClusterClient( File configFile, Map<String, String> config, CountDownLatch latch ) throws Exception { Process process = null; ProcessStreamHandler handler = null; try { process = startStandaloneClusterClientProcess( configFile, config ); new InputStreamAwaiter( process.getInputStream() ).awaitLine( START_SIGNAL, 20, SECONDS ); handler = new ProcessStreamHandler( process, false, "", IGNORE_FAILURES ); handler.launch(); // Latch is triggered when this cluster client we just spawned joins the cluster, // or rather when the first client sees it as joined. If the latch awaiting times out it // (most likely) means that this cluster client couldn't be started. The reason for not // being able to start is assumed in this test to be that the specified port already is in use. return latch.await( 5, SECONDS ); } finally { if ( process != null ) { kill( process ); process.waitFor(); } if ( handler != null ) { handler.done(); } } } private Process startStandaloneClusterClientProcess( File configFile, Map<String, String> config ) throws Exception { List<String> args = new ArrayList<String>( asList( "java", "-cp", getProperty( "java.class.path" ), "-Dneo4j.home=" + directory.getAbsolutePath() ) ); if ( configFile != null ) { args.add( "-D" + Configurator.NEO_SERVER_CONFIG_FILE_KEY + "=" + configFile.getAbsolutePath() ); } args.add( StandaloneClusterClientTestProxy.class.getName() ); for ( Map.Entry<String, String> entry : config.entrySet() ) { args.add( "-" + entry.getKey() + "=" + entry.getValue() ); } return getRuntime().exec( args.toArray( new String[args.size()] ) ); } private static void kill( Process process ) throws NoSuchFieldException, IllegalAccessException, IOException, InterruptedException { if ( osIsWindows() ) { process.destroy(); } else { int pid = ((Number) accessible( process.getClass().getDeclaredField( "pid" ) ).get( process )).intValue(); new ProcessBuilder( "kill", "-9", "" + pid ).start().waitFor(); } } private static <T extends AccessibleObject> T accessible( T obj ) { obj.setAccessible( true ); return obj; } }
1no label
enterprise_server-enterprise_src_test_java_org_neo4j_server_enterprise_StandaloneClusterClientIT.java
111
@Entity @Table(name = "BLC_PAGE_ITEM_CRITERIA") @Inheritance(strategy=InheritanceType.JOINED) @AdminPresentationClass(friendlyName = "PageItemCriteriaImpl_basePageItemCriteria") public class PageItemCriteriaImpl implements PageItemCriteria { public static final long serialVersionUID = 1L; @Id @GeneratedValue(generator= "PageItemCriteriaId") @GenericGenerator( name="PageItemCriteriaId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="PageItemCriteriaImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.cms.page.domain.PageItemCriteriaImpl") } ) @Column(name = "PAGE_ITEM_CRITERIA_ID") @AdminPresentation(friendlyName = "PageItemCriteriaImpl_Item_Criteria_Id", group = "PageItemCriteriaImpl_Description", visibility =VisibilityEnum.HIDDEN_ALL) protected Long id; @Column(name = "QUANTITY", nullable=false) @AdminPresentation(friendlyName = "PageItemCriteriaImpl_Quantity", group = "PageItemCriteriaImpl_Description", visibility =VisibilityEnum.HIDDEN_ALL) protected Integer quantity; @Lob @Type(type = "org.hibernate.type.StringClobType") @Column(name = "ORDER_ITEM_MATCH_RULE", length = Integer.MAX_VALUE - 1) @AdminPresentation(friendlyName = "PageItemCriteriaImpl_Order_Item_Match_Rule", group = "PageItemCriteriaImpl_Description", visibility = VisibilityEnum.HIDDEN_ALL) protected String orderItemMatchRule; @ManyToOne(targetEntity = PageImpl.class) @JoinTable(name = "BLC_QUAL_CRIT_PAGE_XREF", joinColumns = @JoinColumn(name = "PAGE_ITEM_CRITERIA_ID"), inverseJoinColumns = @JoinColumn(name = "PAGE_ID")) protected Page page; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public Integer getQuantity() { return quantity; } @Override public void setQuantity(Integer receiveQuantity) { this.quantity = receiveQuantity; } @Override public String getMatchRule() { return orderItemMatchRule; } @Override public void setMatchRule(String matchRule) { this.orderItemMatchRule = matchRule; } @Override public Page getPage() { return page; } @Override public void setPage(Page page) { this.page = page; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((orderItemMatchRule == null) ? 0 : orderItemMatchRule.hashCode()); result = prime * result + ((quantity == null) ? 0 : quantity.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; PageItemCriteriaImpl other = (PageItemCriteriaImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (orderItemMatchRule == null) { if (other.orderItemMatchRule != null) return false; } else if (!orderItemMatchRule.equals(other.orderItemMatchRule)) return false; if (quantity == null) { if (other.quantity != null) return false; } else if (!quantity.equals(other.quantity)) return false; return true; } @Override public PageItemCriteria cloneEntity() { PageItemCriteriaImpl newField = new PageItemCriteriaImpl(); newField.quantity = quantity; newField.orderItemMatchRule = orderItemMatchRule; return newField; } }
1no label
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_domain_PageItemCriteriaImpl.java
333
public class InsertChildrenOf extends BaseHandler { public Node[] merge(List<Node> nodeList1, List<Node> nodeList2, List<Node> exhaustedNodes) { if (CollectionUtils.isEmpty(nodeList1) || CollectionUtils.isEmpty(nodeList2)) { return null; } Node node1 = nodeList1.get(0); Node node2 = nodeList2.get(0); NodeList list2 = node2.getChildNodes(); for (int j = 0; j < list2.getLength(); j++) { node1.appendChild(node1.getOwnerDocument().importNode(list2.item(j).cloneNode(true), true)); } Node[] response = new Node[nodeList2.size()]; for (int j = 0; j < response.length; j++) { response[j] = nodeList2.get(j); } return response; } }
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_handlers_InsertChildrenOf.java
1,416
public static interface PutListener { void onResponse(PutResponse response); void onFailure(Throwable t); }
0true
src_main_java_org_elasticsearch_cluster_metadata_MetaDataIndexTemplateService.java
1,510
public class FailedShardsRoutingTests extends ElasticsearchAllocationTestCase { private final ESLogger logger = Loggers.getLogger(FailedShardsRoutingTests.class); @Test public void testFailedShardPrimaryRelocatingToAndFrom() { AllocationService allocation = createAllocationService(settingsBuilder() .put("cluster.routing.allocation.concurrent_recoveries", 10) .put("cluster.routing.allocation.allow_rebalance", "always") .build()); logger.info("--> building initial routing table"); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test").numberOfShards(1).numberOfReplicas(1)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("--> adding 2 nodes on same rack and do rerouting"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder() .put(newNode("node1")) .put(newNode("node2")) ).build(); RoutingAllocation.Result rerouteResult = allocation.reroute(clusterState); clusterState = ClusterState.builder(clusterState).routingTable(rerouteResult.routingTable()).build(); // starting primaries rerouteResult = allocation.applyStartedShards(clusterState, clusterState.routingNodes().shardsWithState(INITIALIZING)); clusterState = ClusterState.builder(clusterState).routingTable(rerouteResult.routingTable()).build(); // starting replicas rerouteResult = allocation.applyStartedShards(clusterState, clusterState.routingNodes().shardsWithState(INITIALIZING)); clusterState = ClusterState.builder(clusterState).routingTable(rerouteResult.routingTable()).build(); logger.info("--> verifying all is allocated"); assertThat(clusterState.routingNodes().node("node1").size(), equalTo(1)); assertThat(clusterState.routingNodes().node("node1").get(0).state(), equalTo(STARTED)); assertThat(clusterState.routingNodes().node("node2").size(), equalTo(1)); assertThat(clusterState.routingNodes().node("node2").get(0).state(), equalTo(STARTED)); logger.info("--> adding additional node"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()) .put(newNode("node3")) ).build(); rerouteResult = allocation.reroute(clusterState); clusterState = ClusterState.builder(clusterState).routingTable(rerouteResult.routingTable()).build(); assertThat(clusterState.routingNodes().node("node1").size(), equalTo(1)); assertThat(clusterState.routingNodes().node("node1").get(0).state(), equalTo(STARTED)); assertThat(clusterState.routingNodes().node("node2").size(), equalTo(1)); assertThat(clusterState.routingNodes().node("node2").get(0).state(), equalTo(STARTED)); assertThat(clusterState.routingNodes().node("node3").size(), equalTo(0)); String origPrimaryNodeId = clusterState.routingTable().index("test").shard(0).primaryShard().currentNodeId(); String origReplicaNodeId = clusterState.routingTable().index("test").shard(0).replicaShards().get(0).currentNodeId(); logger.info("--> moving primary shard to node3"); rerouteResult = allocation.reroute(clusterState, new AllocationCommands( new MoveAllocationCommand(clusterState.routingTable().index("test").shard(0).primaryShard().shardId(), clusterState.routingTable().index("test").shard(0).primaryShard().currentNodeId(), "node3")) ); assertThat(rerouteResult.changed(), equalTo(true)); clusterState = ClusterState.builder(clusterState).routingTable(rerouteResult.routingTable()).build(); assertThat(clusterState.routingNodes().node(origPrimaryNodeId).get(0).state(), equalTo(RELOCATING)); assertThat(clusterState.routingNodes().node("node3").get(0).state(), equalTo(INITIALIZING)); logger.info("--> fail primary shard recovering instance on node3 being initialized"); rerouteResult = allocation.applyFailedShard(clusterState, new ImmutableShardRouting(clusterState.routingNodes().node("node3").get(0))); clusterState = ClusterState.builder(clusterState).routingTable(rerouteResult.routingTable()).build(); assertThat(clusterState.routingNodes().node(origPrimaryNodeId).get(0).state(), equalTo(STARTED)); assertThat(clusterState.routingNodes().node("node3").size(), equalTo(0)); logger.info("--> moving primary shard to node3"); rerouteResult = allocation.reroute(clusterState, new AllocationCommands( new MoveAllocationCommand(clusterState.routingTable().index("test").shard(0).primaryShard().shardId(), clusterState.routingTable().index("test").shard(0).primaryShard().currentNodeId(), "node3")) ); assertThat(rerouteResult.changed(), equalTo(true)); clusterState = ClusterState.builder(clusterState).routingTable(rerouteResult.routingTable()).build(); assertThat(clusterState.routingNodes().node(origPrimaryNodeId).get(0).state(), equalTo(RELOCATING)); assertThat(clusterState.routingNodes().node("node3").get(0).state(), equalTo(INITIALIZING)); logger.info("--> fail primary shard recovering instance on node1 being relocated"); rerouteResult = allocation.applyFailedShard(clusterState, new ImmutableShardRouting(clusterState.routingNodes().node(origPrimaryNodeId).get(0))); clusterState = ClusterState.builder(clusterState).routingTable(rerouteResult.routingTable()).build(); // check promotion of replica to primary assertThat(clusterState.routingNodes().node(origReplicaNodeId).get(0).state(), equalTo(STARTED)); assertThat(clusterState.routingTable().index("test").shard(0).primaryShard().currentNodeId(), equalTo(origReplicaNodeId)); assertThat(clusterState.routingTable().index("test").shard(0).replicaShards().get(0).currentNodeId(), anyOf(equalTo(origPrimaryNodeId), equalTo("node3"))); } @Test public void failPrimaryStartedCheckReplicaElected() { AllocationService strategy = createAllocationService(settingsBuilder() .put("cluster.routing.allocation.concurrent_recoveries", 10) .put("cluster.routing.allocation.allow_rebalance", "always") .build()); logger.info("Building initial routing table"); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test").numberOfShards(1).numberOfReplicas(1)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("Adding two nodes and performing rerouting"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2"))).build(); RoutingTable prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); logger.info("Start the shards (primaries)"); RoutingNodes routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(1)); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(i).primaryShard().currentNodeId(), anyOf(equalTo("node1"), equalTo("node2"))); assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).currentNodeId(), anyOf(equalTo("node2"), equalTo("node1"))); } logger.info("Start the shards (backups)"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(1)); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(i).primaryShard().currentNodeId(), anyOf(equalTo("node1"), equalTo("node2"))); assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).currentNodeId(), anyOf(equalTo("node2"), equalTo("node1"))); } logger.info("fail the primary shard, will have no place to be rerouted to (single node), so stays unassigned"); ShardRouting shardToFail = new ImmutableShardRouting(routingTable.index("test").shard(0).primaryShard()); prevRoutingTable = routingTable; routingTable = strategy.applyFailedShard(clusterState, shardToFail).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shard(0).size(), equalTo(2)); assertThat(routingTable.index("test").shard(0).size(), equalTo(2)); assertThat(routingTable.index("test").shard(0).primaryShard().currentNodeId(), not(equalTo(shardToFail.currentNodeId()))); assertThat(routingTable.index("test").shard(0).primaryShard().state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(0).primaryShard().currentNodeId(), anyOf(equalTo("node1"), equalTo("node2"))); assertThat(routingTable.index("test").shard(0).replicaShards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(0).replicaShards().get(0).state(), equalTo(UNASSIGNED)); logger.info("fail the shard again, check that nothing happens"); assertThat(strategy.applyFailedShard(clusterState, shardToFail).changed(), equalTo(false)); } @Test public void firstAllocationFailureSingleNode() { AllocationService strategy = createAllocationService(settingsBuilder() .put("cluster.routing.allocation.concurrent_recoveries", 10) .put("cluster.routing.allocation.allow_rebalance", "always") .build()); logger.info("Building initial routing table"); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test").numberOfShards(1).numberOfReplicas(1)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("Adding single node and performing rerouting"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1"))).build(); RoutingTable prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(1)); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test").shard(i).primaryShard().currentNodeId(), equalTo("node1")); assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED)); } logger.info("fail the first shard, will have no place to be rerouted to (single node), so stays unassigned"); prevRoutingTable = routingTable; routingTable = strategy.applyFailedShard(clusterState, new ImmutableShardRouting("test", 0, "node1", true, INITIALIZING, 0)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); RoutingNodes routingNodes = clusterState.routingNodes(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(1)); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(UNASSIGNED)); assertThat(routingTable.index("test").shard(i).primaryShard().currentNodeId(), nullValue()); assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED)); } logger.info("fail the shard again, see that nothing happens"); assertThat(strategy.applyFailedShard(clusterState, new ImmutableShardRouting("test", 0, "node1", true, INITIALIZING, 0)).changed(), equalTo(false)); } @Test public void firstAllocationFailureTwoNodes() { AllocationService strategy = createAllocationService(settingsBuilder() .put("cluster.routing.allocation.concurrent_recoveries", 10) .put("cluster.routing.allocation.allow_rebalance", "always") .build()); logger.info("Building initial routing table"); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test").numberOfShards(1).numberOfReplicas(1)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("Adding two nodes and performing rerouting"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2"))).build(); RoutingTable prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); final String nodeHoldingPrimary = routingTable.index("test").shard(0).primaryShard().currentNodeId(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(1)); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test").shard(i).primaryShard().currentNodeId(), equalTo(nodeHoldingPrimary)); assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED)); } logger.info("fail the first shard, will start INITIALIZING on the second node"); prevRoutingTable = routingTable; routingTable = strategy.applyFailedShard(clusterState, new ImmutableShardRouting("test", 0, nodeHoldingPrimary, true, INITIALIZING, 0)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); RoutingNodes routingNodes = clusterState.routingNodes(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(1)); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test").shard(i).primaryShard().currentNodeId(), not(equalTo(nodeHoldingPrimary))); assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(UNASSIGNED)); } logger.info("fail the shard again, see that nothing happens"); assertThat(strategy.applyFailedShard(clusterState, new ImmutableShardRouting("test", 0, nodeHoldingPrimary, true, INITIALIZING, 0)).changed(), equalTo(false)); } @Test public void rebalanceFailure() { AllocationService strategy = createAllocationService(settingsBuilder() .put("cluster.routing.allocation.concurrent_recoveries", 10) .put("cluster.routing.allocation.allow_rebalance", "always") .build()); logger.info("Building initial routing table"); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test").numberOfShards(2).numberOfReplicas(1)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); logger.info("Adding two nodes and performing rerouting"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1")).put(newNode("node2"))).build(); RoutingTable prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); logger.info("Start the shards (primaries)"); RoutingNodes routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(2)); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(i).primaryShard().currentNodeId(), anyOf(equalTo("node1"), equalTo("node2"))); assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).currentNodeId(), anyOf(equalTo("node2"), equalTo("node1"))); } logger.info("Start the shards (backups)"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(2)); for (int i = 0; i < routingTable.index("test").shards().size(); i++) { assertThat(routingTable.index("test").shard(i).size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(i).primaryShard().state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(i).primaryShard().currentNodeId(), anyOf(equalTo("node1"), equalTo("node2"))); assertThat(routingTable.index("test").shard(i).replicaShards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(i).replicaShards().get(0).currentNodeId(), anyOf(equalTo("node2"), equalTo("node1"))); } logger.info("Adding third node and reroute"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node3"))).build(); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(2)); assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED, RELOCATING), equalTo(2)); assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), lessThan(3)); assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED, RELOCATING), equalTo(2)); assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), lessThan(3)); assertThat(routingNodes.node("node3").numberOfShardsWithState(INITIALIZING), equalTo(1)); logger.info("Fail the shards on node 3"); ShardRouting shardToFail = routingNodes.node("node3").get(0); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyFailedShard(clusterState, new ImmutableShardRouting(shardToFail)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); routingNodes = clusterState.routingNodes(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(2)); assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED, RELOCATING), equalTo(2)); assertThat(routingNodes.node("node1").numberOfShardsWithState(STARTED), lessThan(3)); assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED, RELOCATING), equalTo(2)); assertThat(routingNodes.node("node2").numberOfShardsWithState(STARTED), lessThan(3)); assertThat(routingNodes.node("node3").numberOfShardsWithState(INITIALIZING), equalTo(1)); // make sure the failedShard is not INITIALIZING again on node3 assertThat(routingNodes.node("node3").get(0).shardId(), not(equalTo(shardToFail.shardId()))); } }
0true
src_test_java_org_elasticsearch_cluster_routing_allocation_FailedShardsRoutingTests.java
154
assertTrueEventually(new AssertTask() { @Override public void run() { assertEquals(1, listener.events.size()); MembershipEvent event = listener.events.get(0); assertEquals(MembershipEvent.MEMBER_REMOVED, event.getEventType()); assertEquals(server2Member, event.getMember()); assertEquals(getMembers(server1), event.getMembers()); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_MembershipListenerTest.java
800
public class AlterAndGetRequest extends AbstractAlterRequest { public AlterAndGetRequest() { } public AlterAndGetRequest(String name, Data function) { super(name, function); } @Override protected Operation prepareOperation() { return new AlterAndGetOperation(name, getFunction()); } @Override public int getClassId() { return AtomicLongPortableHook.ALTER_AND_GET; } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_client_AlterAndGetRequest.java
156
public class OIntegerSerializer implements OBinarySerializer<Integer> { private static final OBinaryConverter CONVERTER = OBinaryConverterFactory.getConverter(); public static OIntegerSerializer INSTANCE = new OIntegerSerializer(); public static final byte ID = 8; /** * size of int value in bytes */ public static final int INT_SIZE = 4; public int getObjectSize(Integer object, Object... hints) { return INT_SIZE; } public void serialize(Integer object, byte[] stream, int startPosition, Object... hints) { final int value = object; stream[startPosition] = (byte) ((value >>> 24) & 0xFF); stream[startPosition + 1] = (byte) ((value >>> 16) & 0xFF); stream[startPosition + 2] = (byte) ((value >>> 8) & 0xFF); stream[startPosition + 3] = (byte) ((value >>> 0) & 0xFF); } public Integer deserialize(byte[] stream, int startPosition) { return (stream[startPosition]) << 24 | (0xff & stream[startPosition + 1]) << 16 | (0xff & stream[startPosition + 2]) << 8 | ((0xff & stream[startPosition + 3])); } public int getObjectSize(byte[] stream, int startPosition) { return INT_SIZE; } public byte getId() { return ID; } public int getObjectSizeNative(byte[] stream, int startPosition) { return INT_SIZE; } public void serializeNative(Integer object, byte[] stream, int startPosition, Object... hints) { CONVERTER.putInt(stream, startPosition, object, ByteOrder.nativeOrder()); } public Integer deserializeNative(byte[] stream, int startPosition) { return CONVERTER.getInt(stream, startPosition, ByteOrder.nativeOrder()); } @Override public void serializeInDirectMemory(Integer object, ODirectMemoryPointer pointer, long offset, Object... hints) { pointer.setInt(offset, object); } @Override public Integer deserializeFromDirectMemory(ODirectMemoryPointer pointer, long offset) { return pointer.getInt(offset); } @Override public int getObjectSizeInDirectMemory(ODirectMemoryPointer pointer, long offset) { return INT_SIZE; } public boolean isFixedLength() { return true; } public int getFixedLength() { return INT_SIZE; } @Override public Integer preprocess(Integer value, Object... hints) { return value; } }
0true
commons_src_main_java_com_orientechnologies_common_serialization_types_OIntegerSerializer.java
971
private class NodeTransportHandler extends BaseTransportRequestHandler<NodeRequest> { @Override public NodeRequest newInstance() { return newNodeRequest(); } @Override public void messageReceived(final NodeRequest request, final TransportChannel channel) throws Exception { channel.sendResponse(nodeOperation(request)); } @Override public String toString() { return transportNodeAction; } @Override public String executor() { return executor; } }
0true
src_main_java_org_elasticsearch_action_support_nodes_TransportNodesOperationAction.java
494
private static class IdentityRewriter<T> implements FieldRewriter<T> { @Override public T rewriteValue(T value) { return null; } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseImport.java
496
return scheduledExecutor.scheduleAtFixedRate(new Runnable() { public void run() { executeInternal(command); } }, initialDelay, period, unit);
1no label
hazelcast-client_src_main_java_com_hazelcast_client_spi_impl_ClientExecutionServiceImpl.java
2
Collection<Long> perm1Ids = BLCCollectionUtils.collect(perm1, new TypedTransformer<Long>() { @Override public Long transform(Object input) { return ((ProductOptionValue) input).getId(); } });
0true
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_server_service_AdminCatalogServiceImpl.java
180
@RunWith(HazelcastSerialClassRunner.class) @Category(QuickTest.class) public class ClientAtomicReferenceTest { static final String name = "test1"; static HazelcastInstance client; static HazelcastInstance server; static IAtomicReference<String> clientReference; static IAtomicReference<String> serverReference; @BeforeClass public static void init() { server = Hazelcast.newHazelcastInstance(); client = HazelcastClient.newHazelcastClient(); clientReference = client.getAtomicReference(name); serverReference = server.getAtomicReference(name); } @AfterClass public static void destroy() { client.shutdown(); Hazelcast.shutdownAll(); } @Before @After public void after() { serverReference.set(null); } @Test public void get() throws Exception { assertNull(clientReference.get()); serverReference.set("foo"); assertEquals("foo", clientReference.get()); } @Test public void isNull() throws Exception { assertTrue(clientReference.isNull()); serverReference.set("foo"); assertFalse(clientReference.isNull()); } @Test public void contains() { assertTrue(clientReference.contains(null)); assertFalse(clientReference.contains("foo")); serverReference.set("foo"); assertFalse(clientReference.contains(null)); assertTrue(clientReference.contains("foo")); assertFalse(clientReference.contains("bar")); } @Test public void set() throws Exception { clientReference.set(null); assertTrue(serverReference.isNull()); clientReference.set("foo"); assertEquals("foo", serverReference.get()); clientReference.set("foo"); assertEquals("foo", serverReference.get()); clientReference.set("bar"); assertEquals("bar", serverReference.get()); clientReference.set(null); assertTrue(serverReference.isNull()); } @Test public void clear() throws Exception { clientReference.clear(); assertTrue(serverReference.isNull()); serverReference.set("foo"); clientReference.clear(); assertTrue(serverReference.isNull()); } @Test public void getAndSet() throws Exception { assertNull(clientReference.getAndSet(null)); assertTrue(serverReference.isNull()); assertNull(clientReference.getAndSet("foo")); assertEquals("foo", serverReference.get()); assertEquals("foo", clientReference.getAndSet("foo")); assertEquals("foo", serverReference.get()); assertEquals("foo", clientReference.getAndSet("bar")); assertEquals("bar", serverReference.get()); assertEquals("bar", clientReference.getAndSet(null)); assertTrue(serverReference.isNull()); } @Test public void setAndGet() throws Exception { assertNull(clientReference.setAndGet(null)); assertTrue(serverReference.isNull()); assertEquals("foo", clientReference.setAndGet("foo")); assertEquals("foo", serverReference.get()); assertEquals("foo", clientReference.setAndGet("foo")); assertEquals("foo", serverReference.get()); assertEquals("bar", clientReference.setAndGet("bar")); assertEquals("bar", serverReference.get()); assertNull(clientReference.setAndGet(null)); assertTrue(serverReference.isNull()); } @Test public void compareAndSet() throws Exception { assertTrue(clientReference.compareAndSet(null, null)); assertTrue(serverReference.isNull()); assertFalse(clientReference.compareAndSet("foo", null)); assertTrue(serverReference.isNull()); assertTrue(clientReference.compareAndSet(null, "foo")); assertEquals("foo", serverReference.get()); assertTrue(clientReference.compareAndSet("foo", "foo")); assertEquals("foo", serverReference.get()); assertFalse(clientReference.compareAndSet("bar", "foo")); assertEquals("foo", serverReference.get()); assertTrue(clientReference.compareAndSet("foo", "bar")); assertEquals("bar", serverReference.get()); assertTrue(clientReference.compareAndSet("bar", null)); assertNull(serverReference.get()); } @Test(expected = IllegalArgumentException.class) public void apply_whenCalledWithNullFunction() { clientReference.apply(null); } @Test public void apply() { assertEquals("null",clientReference.apply(new AppendFunction(""))); assertEquals(null,clientReference.get()); clientReference.set("foo"); assertEquals("foobar", clientReference.apply(new AppendFunction("bar"))); assertEquals("foo",clientReference.get()); assertEquals(null, clientReference.apply(new NullFunction())); assertEquals("foo",clientReference.get()); } @Test(expected = IllegalArgumentException.class) public void alter_whenCalledWithNullFunction() { clientReference.alter(null); } @Test public void alter() { clientReference.alter(new NullFunction()); assertEquals(null,clientReference.get()); clientReference.set("foo"); clientReference.alter(new AppendFunction("bar")); assertEquals("foobar",clientReference.get()); clientReference.alter(new NullFunction()); assertEquals(null,clientReference.get()); } @Test(expected = IllegalArgumentException.class) public void alterAndGet_whenCalledWithNullFunction() { clientReference.alterAndGet(null); } @Test public void alterAndGet() { assertNull(clientReference.alterAndGet(new NullFunction())); assertEquals(null,clientReference.get()); clientReference.set("foo"); assertEquals("foobar",clientReference.alterAndGet(new AppendFunction("bar"))); assertEquals("foobar",clientReference.get()); assertEquals(null,clientReference.alterAndGet(new NullFunction())); assertEquals(null,clientReference.get()); } @Test(expected = IllegalArgumentException.class) public void getAndAlter_whenCalledWithNullFunction() { clientReference.alterAndGet(null); } @Test public void getAndAlter() { assertNull(clientReference.getAndAlter(new NullFunction())); assertEquals(null,clientReference.get()); clientReference.set("foo"); assertEquals("foo",clientReference.getAndAlter(new AppendFunction("bar"))); assertEquals("foobar",clientReference.get()); assertEquals("foobar",clientReference.getAndAlter(new NullFunction())); assertEquals(null,clientReference.get()); } private static class AppendFunction implements IFunction<String,String> { private String add; private AppendFunction(String add) { this.add = add; } @Override public String apply(String input) { return input+add; } } private static class NullFunction implements IFunction<String,String> { @Override public String apply(String input) { return null; } } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_atomicreference_ClientAtomicReferenceTest.java
141
(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_Striped64.java
884
threadPool.executor(ThreadPool.Names.SEARCH).execute(new Runnable() { @Override public void run() { executePhase(shardIndex, node, target.v2()); } });
0true
src_main_java_org_elasticsearch_action_search_type_TransportSearchScrollQueryAndFetchAction.java
95
public class RagManager implements Visitor<LineLogger, RuntimeException> { // if a runtime exception is thrown from any method it means that the // RWLock class hasn't kept the contract to the RagManager // The contract is: // o When a transaction gets a lock on a resource and both the readCount and // writeCount for that transaction on the resource was 0 // RagManager.lockAcquired( resource ) must be invoked // o When a tx releases a lock on a resource and both the readCount and // writeCount for that transaction on the resource goes down to zero // RagManager.lockReleased( resource ) must be invoked // o After invoke to the checkWaitOn( resource ) method that didn't result // in a DeadlockDetectedException the transaction must wait // o When the transaction wakes up from waiting on a resource the // stopWaitOn( resource ) method must be invoked private final Map<Object,List<Transaction>> resourceMap = new HashMap<Object,List<Transaction>>(); private final ArrayMap<Transaction,Object> waitingTxMap = new ArrayMap<Transaction,Object>( (byte)5, false, true ); private final AtomicInteger deadlockCount = new AtomicInteger(); long getDeadlockCount() { return deadlockCount.longValue(); } synchronized void lockAcquired( Object resource, Transaction tx ) { List<Transaction> lockingTxList = resourceMap.get( resource ); if ( lockingTxList != null ) { assert !lockingTxList.contains( tx ); lockingTxList.add( tx ); } else { lockingTxList = new LinkedList<Transaction>(); lockingTxList.add( tx ); resourceMap.put( resource, lockingTxList ); } } synchronized void lockReleased( Object resource, Transaction tx ) { List<Transaction> lockingTxList = resourceMap.get( resource ); if ( lockingTxList == null ) { throw new LockException( resource + " not found in resource map" ); } if ( !lockingTxList.remove( tx ) ) { throw new LockException( tx + "not found in locking tx list" ); } if ( lockingTxList.size() == 0 ) { resourceMap.remove( resource ); } } synchronized void stopWaitOn( Object resource, Transaction tx ) { if ( waitingTxMap.remove( tx ) == null ) { throw new LockException( tx + " not waiting on " + resource ); } } // after invoke the transaction must wait on the resource synchronized void checkWaitOn( Object resource, Transaction tx ) throws DeadlockDetectedException { List<Transaction> lockingTxList = resourceMap.get( resource ); if ( lockingTxList == null ) { throw new LockException( "Illegal resource[" + resource + "], not found in map" ); } if ( waitingTxMap.get( tx ) != null ) { throw new LockException( tx + " already waiting for resource" ); } Iterator<Transaction> itr = lockingTxList.iterator(); List<Transaction> checkedTransactions = new LinkedList<Transaction>(); Stack<Object> graphStack = new Stack<Object>(); // has resource,transaction interleaved graphStack.push( resource ); while ( itr.hasNext() ) { Transaction lockingTx = itr.next(); // the if statement bellow is valid because: // t1 -> r1 -> t1 (can happened with RW locks) is ok but, // t1 -> r1 -> t1&t2 where t2 -> r1 is a deadlock // think like this, we have two transactions and one resource // o t1 takes read lock on r1 // o t2 takes read lock on r1 // o t1 wanna take write lock on r1 but has to wait for t2 // to release the read lock ( t1->r1->(t1&t2), ok not deadlock yet // o t2 wanna take write lock on r1 but has to wait for t1 // to release read lock.... // DEADLOCK t1->r1->(t1&t2) and t2->r1->(t1&t2) ===> // t1->r1->t2->r1->t1, t2->r1->t1->r1->t2 etc... // to allow the first three steps above we check if lockingTx == // waitingTx on first level. // because of this special case we have to keep track on the // already "checked" tx since it is (now) legal for one type of // circular reference to exist (t1->r1->t1) otherwise we may // traverse t1->r1->t2->r1->t2->r1->t2... until SOE // ... KISS to you too if ( lockingTx.equals( tx ) ) { continue; } graphStack.push( lockingTx ); checkWaitOnRecursive( lockingTx, tx, checkedTransactions, graphStack ); graphStack.pop(); } // ok no deadlock, we can wait on resource waitingTxMap.put( tx, resource ); } private synchronized void checkWaitOnRecursive( Transaction lockingTx, Transaction waitingTx, List<Transaction> checkedTransactions, Stack<Object> graphStack ) throws DeadlockDetectedException { if ( lockingTx.equals( waitingTx ) ) { StringBuffer circle = null; Object resource; do { lockingTx = (Transaction) graphStack.pop(); resource = graphStack.pop(); if ( circle == null ) { circle = new StringBuffer(); circle.append( lockingTx ).append( " <-[:HELD_BY]- " ).append( resource ); } else { circle.append( " <-[:WAITING_FOR]- " ).append( lockingTx ).append( " <-[:HELD_BY]- " ).append( resource ); } } while ( !graphStack.isEmpty() ); deadlockCount.incrementAndGet(); throw new DeadlockDetectedException( waitingTx + " can't wait on resource " + resource + " since => " + circle ); } checkedTransactions.add( lockingTx ); Object resource = waitingTxMap.get( lockingTx ); if ( resource != null ) { graphStack.push( resource ); // if the resource doesn't exist in resorceMap that means all the // locks on the resource has been released // it is possible when this tx was in RWLock.acquire and // saw it had to wait for the lock the scheduler changes to some // other tx that will release the locks on the resource and // remove it from the map // this is ok since current tx or any other tx will wake // in the synchronized block and will be forced to do the deadlock // check once more if lock cannot be acquired List<Transaction> lockingTxList = resourceMap.get( resource ); if ( lockingTxList != null ) { for ( Transaction aLockingTxList : lockingTxList ) { lockingTx = aLockingTxList; // so we don't if ( !checkedTransactions.contains( lockingTx ) ) { graphStack.push( lockingTx ); checkWaitOnRecursive( lockingTx, waitingTx, checkedTransactions, graphStack ); graphStack.pop(); } } } graphStack.pop(); } } @Override public synchronized boolean visit( LineLogger logger ) { logger.logLine( "Waiting list: " ); Iterator<Transaction> transactions = waitingTxMap.keySet().iterator(); if ( !transactions.hasNext() ) { logger.logLine( "No transactions waiting on resources" ); } else { logger.logLine( "" ); // new line } while ( transactions.hasNext() ) { Transaction tx = transactions.next(); logger.logLine( "" + tx + "->" + waitingTxMap.get( tx ) ); } logger.logLine( "Resource lock list: " ); Iterator<?> resources = resourceMap.keySet().iterator(); if ( !resources.hasNext() ) { logger.logLine( "No locked resources found" ); } else { logger.logLine( "" ); } while ( resources.hasNext() ) { Object resource = resources.next(); logger.logLine( "" + resource + "->" ); Iterator<Transaction> itr = resourceMap.get( resource ).iterator(); if ( !itr.hasNext() ) { logger.logLine( " Error empty list found" ); } while ( itr.hasNext() ) { logger.logLine( "" + itr.next() ); if ( itr.hasNext() ) { logger.logLine( "," ); } else { logger.logLine( "" ); } } } return true; } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_RagManager.java
9
display.timerExec(100, new Runnable() { @Override public void run() { fCompleted= true; } });
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_browser_BrowserInformationControl.java
565
public class HibernateToolTask extends Task { public HibernateToolTask() { super(); } @SuppressWarnings("rawtypes") protected List configurationTasks = new ArrayList(); protected File destDir; @SuppressWarnings("rawtypes") protected List generators = new ArrayList(); protected List<Task> appContexts = new ArrayList<Task>(); protected Path classPath; protected boolean combinePersistenceUnits = true; protected boolean refineFileNames = true; public ExporterTask createHbm2DDL() { ExporterTask generator = new Hbm2DDLExporterTask(this); addGenerator( generator ); return generator; } public ClassPathApplicationContextTask createClassPathApplicationContext() { ClassPathApplicationContextTask task = new ClassPathApplicationContextTask(); appContexts.add(task); return task; } public FileSystemApplicationContextTask createFileSystemApplicationContext() { FileSystemApplicationContextTask task = new FileSystemApplicationContextTask(); appContexts.add(task); return task; } public JPAConfigurationTask createJPAConfiguration() { JPAConfigurationTask task = new JPAConfigurationTask(); addConfiguration(task); return task; } @SuppressWarnings("unchecked") protected boolean addConfiguration(ConfigurationTask config) { return configurationTasks.add(config); } @SuppressWarnings("unchecked") protected boolean addGenerator(ExporterTask generator) { return generators.add(generator); } /** * Set the classpath to be used when running the Java class * * @param s an Ant Path object containing the classpath. */ public void setClasspath(Path s) { classPath = s; } /** * Adds a path to the classpath. * * @return created classpath */ public Path createClasspath() { classPath = new Path(getProject() ); return classPath; } @Override public void execute() { MergeFileSystemAndClassPathXMLApplicationContext mergeContext; try { ConfigurationOnlyState state = new ConfigurationOnlyState(); state.setConfigurationOnly(true); ConfigurationOnlyState.setState(state); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); // launch the service merge application context to get the entity configuration for the entire framework String[] contexts = StandardConfigLocations.retrieveAll(StandardConfigLocations.TESTCONTEXTTYPE); LinkedHashMap<String, MergeFileSystemAndClassPathXMLApplicationContext.ResourceType> locations = new LinkedHashMap<String, MergeFileSystemAndClassPathXMLApplicationContext.ResourceType>(); for (String context : contexts) { locations.put(context, MergeFileSystemAndClassPathXMLApplicationContext.ResourceType.CLASSPATH); } for (Task task : appContexts) { if (task instanceof ClassPathApplicationContextTask) { locations.put(((ClassPathApplicationContextTask) task).getPath(), MergeFileSystemAndClassPathXMLApplicationContext.ResourceType.CLASSPATH); } else if (task instanceof FileSystemApplicationContextTask) { locations.put(((FileSystemApplicationContextTask) task).getPath(), MergeFileSystemAndClassPathXMLApplicationContext.ResourceType.FILESYSTEM); } } mergeContext = new MergeFileSystemAndClassPathXMLApplicationContext(locations, null); } catch (Exception e) { throw new BuildException(e, getLocation()); } finally { ConfigurationOnlyState.setState(null); } int count = 1; ExporterTask generatorTask = null; try { for (Object configuration : configurationTasks) { JPAConfigurationTask configurationTask = (JPAConfigurationTask) configuration; log("Executing Hibernate Tool with a " + configurationTask.getDescription()); @SuppressWarnings("rawtypes") Iterator iterator = generators.iterator(); while (iterator.hasNext()) { generatorTask = (ExporterTask) iterator.next(); log(count++ + ". task: " + generatorTask.getName()); generatorTask.setOutputFileName(configurationTask.getDialect() + "_" + configurationTask.getPersistenceUnit() + ".sql"); generatorTask.setDestdir(destDir); generatorTask.setConfiguration(configurationTask.createConfiguration(mergeContext)); generatorTask.execute(); } } } catch (RuntimeException re) { reportException(re, count, generatorTask); } try { if (combinePersistenceUnits) { ArrayList<File> combine = new ArrayList<File>(); for (Object configuration : configurationTasks) { JPAConfigurationTask configurationTask = (JPAConfigurationTask) configuration; File[] sqlFiles = destDir.listFiles(new SqlFileFilter()); for (File file : sqlFiles) { if (file.getName().startsWith(configurationTask.getDialect())){ combine.add(file); } } combineFiles(combine); combine.clear(); } } if (refineFileNames) { File[] sqlFiles = destDir.listFiles(new SqlFileFilter()); for (File file : sqlFiles) { String filename = file.getName(); String[] starters = {"org.hibernate.dialect.", "org.broadleafcommerce.profile.util.sql."}; for (String starter : starters) { if (filename.startsWith(starter)) { String newFileName = filename.substring(starter.length(), filename.length()); file.renameTo(new File(destDir, newFileName)); } } } } } catch (Exception e) { throw new BuildException(e, getLocation()); } } private void combineFiles(ArrayList<File> combine) throws Exception { Iterator<File> itr = combine.iterator(); File startFile = itr.next(); while(itr.hasNext()) { File nextFile = itr.next(); BufferedWriter writer = null; BufferedReader reader = null; try{ writer = new BufferedWriter(new FileWriter(startFile, true)); reader = new BufferedReader(new FileReader(nextFile)); boolean eof = false; String temp = null; while (!eof) { temp = reader.readLine(); if (temp == null) { eof = true; } else { writer.write(temp); writer.write("\n"); } } } finally { if (writer != null) { try{ writer.close(); } catch (Throwable e) {}; } if (reader != null) { try{ reader.close(); } catch (Throwable e) {}; } } try{ nextFile.delete(); } catch (Throwable e) {} } } private void reportException(Throwable re, int count, ExporterTask generatorTask) { log("An exception occurred while running exporter #" + count + ":" + generatorTask.getName(), Project.MSG_ERR); log("To get the full stack trace run ant with -verbose", Project.MSG_ERR); log(re.toString(), Project.MSG_ERR); String ex = new String(); Throwable cause = re.getCause(); while(cause!=null) { ex += cause.toString() + "\n"; if(cause==cause.getCause()) { break; // we reached the top. } else { cause=cause.getCause(); } } if(StringUtils.isNotEmpty(ex)) { log(ex, Project.MSG_ERR); } String newbieMessage = getProbableSolutionOrCause(re); if(newbieMessage!=null) { log(newbieMessage); } if(re instanceof BuildException) { throw (BuildException)re; } else { throw new BuildException(re, getLocation()); } } private String getProbableSolutionOrCause(Throwable re) { if(re==null) return null; if(re instanceof MappingNotFoundException) { MappingNotFoundException mnf = (MappingNotFoundException)re; if("resource".equals(mnf.getType())) { return "A " + mnf.getType() + " located at " + mnf.getPath() + " was not found.\n" + "Check the following:\n" + "\n" + "1) Is the spelling/casing correct ?\n" + "2) Is " + mnf.getPath() + " available via the classpath ?\n" + "3) Does it actually exist ?\n"; } else { return "A " + mnf.getType() + " located at " + mnf.getPath() + " was not found.\n" + "Check the following:\n" + "\n" + "1) Is the spelling/casing correct ?\n" + "2) Do you permission to access " + mnf.getPath() + " ?\n" + "3) Does it actually exist ?\n"; } } if(re instanceof ClassNotFoundException || re instanceof NoClassDefFoundError) { return "A class were not found in the classpath of the Ant task.\n" + "Ensure that the classpath contains the classes needed for Hibernate and your code are in the classpath.\n"; } if(re instanceof UnsupportedClassVersionError) { return "You are most likely running the ant task with a JRE that is older than the JRE required to use the classes.\n" + "e.g. running with JRE 1.3 or 1.4 when using JDK 1.5 annotations is not possible.\n" + "Ensure that you are using a correct JRE."; } if(re.getCause()!=re) { return getProbableSolutionOrCause( re.getCause() ); } return null; } public File getDestdir() { return destDir; } public void setDestdir(File destDir) { this.destDir = destDir; } public boolean isCombinePersistenceUnits() { return combinePersistenceUnits; } public void setCombinePersistenceUnits(boolean combinePersistenceUnits) { this.combinePersistenceUnits = combinePersistenceUnits; } public boolean isRefineFileNames() { return refineFileNames; } public void setRefineFileNames(boolean refineFileNames) { this.refineFileNames = refineFileNames; } private class SqlFileFilter implements FilenameFilter { @Override public boolean accept(File dir, String name) { return name.endsWith(".sql"); } } }
0true
common_src_main_java_org_broadleafcommerce_common_util_sql_HibernateToolTask.java
659
public class ORemoteIndexEngine implements OIndexEngine { @Override public void init() { } @Override public void flush() { } @Override public void create(String indexName, OIndexDefinition indexDefinition, String clusterIndexName, OStreamSerializer valueSerializer, boolean isAutomatic) { } @Override public void deleteWithoutLoad(String indexName) { } @Override public void delete() { } @Override public void load(ORID indexRid, String indexName, OIndexDefinition indexDefinition, boolean isAutomatic) { } @Override public boolean contains(Object key) { return false; } @Override public boolean remove(Object key) { return false; } @Override public ORID getIdentity() { return null; } @Override public void clear() { } @Override public Iterator<Map.Entry> iterator() { return null; } @Override public Iterator<Map.Entry> inverseIterator() { return null; } @Override public Iterator valuesIterator() { return null; } @Override public Iterator inverseValuesIterator() { return null; } @Override public Iterable<Object> keys() { return null; } @Override public void unload() { } @Override public void startTransaction() { } @Override public void stopTransaction() { } @Override public void afterTxRollback() { } @Override public void afterTxCommit() { } @Override public void closeDb() { } @Override public void close() { } @Override public void beforeTxBegin() { } @Override public Object get(Object key) { return null; } @Override public void put(Object key, Object value) { } @Override public void getValuesBetween(Object rangeFrom, boolean fromInclusive, Object rangeTo, boolean toInclusive, ValuesTransformer transformer, ValuesResultListener resultListener) { } @Override public void getValuesMajor(Object fromKey, boolean isInclusive, ValuesTransformer transformer, ValuesResultListener valuesResultListener) { } @Override public void getValuesMinor(Object toKey, boolean isInclusive, ValuesTransformer transformer, ValuesResultListener valuesResultListener) { } @Override public void getEntriesMajor(Object fromKey, boolean isInclusive, ValuesTransformer transformer, EntriesResultListener entriesResultListener) { } @Override public void getEntriesMinor(Object toKey, boolean isInclusive, ValuesTransformer transformer, EntriesResultListener entriesResultListener) { } @Override public void getEntriesBetween(Object iRangeFrom, Object iRangeTo, boolean iInclusive, ValuesTransformer transformer, EntriesResultListener entriesResultListener) { } @Override public long size(ValuesTransformer transformer) { return 0; } @Override public long count(Object rangeFrom, boolean fromInclusive, Object rangeTo, boolean toInclusive, int maxValuesToFetch, ValuesTransformer transformer) { return 0; } @Override public boolean hasRangeQuerySupport() { return false; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_index_engine_ORemoteIndexEngine.java
177
public static final List<EntryMetaData> IDENTIFYING_METADATA = new ArrayList<EntryMetaData>(3) {{ for (EntryMetaData meta : values()) if (meta.isIdentifying()) add(meta); }};
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_EntryMetaData.java
721
public class DeleteResponse extends ActionResponse { private String index; private String id; private String type; private long version; private boolean found; public DeleteResponse() { } public DeleteResponse(String index, String type, String id, long version, boolean found) { this.index = index; this.id = id; this.type = type; this.version = version; this.found = found; } /** * The index the document was deleted from. */ public String getIndex() { return this.index; } /** * The type of the document deleted. */ public String getType() { return this.type; } /** * The id of the document deleted. */ public String getId() { return this.id; } /** * The version of the delete operation. */ public long getVersion() { return this.version; } /** * Returns <tt>true</tt> if a doc was found to delete. */ public boolean isFound() { return found; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); index = in.readSharedString(); type = in.readSharedString(); id = in.readString(); version = in.readLong(); found = in.readBoolean(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeSharedString(index); out.writeSharedString(type); out.writeString(id); out.writeLong(version); out.writeBoolean(found); } }
0true
src_main_java_org_elasticsearch_action_delete_DeleteResponse.java
392
public interface Media extends Serializable { public Long getId(); public void setId(Long id); public String getUrl(); public void setUrl(String url); public String getTitle(); public void setTitle(String title); public String getAltText(); public void setAltText(String altText); public String getTags(); public void setTags(String tags); }
0true
common_src_main_java_org_broadleafcommerce_common_media_domain_Media.java
1,074
indexAction.execute(indexRequest, new ActionListener<IndexResponse>() { @Override public void onResponse(IndexResponse response) { UpdateResponse update = new UpdateResponse(response.getIndex(), response.getType(), response.getId(), response.getVersion(), response.isCreated()); update.setGetResult(updateHelper.extractGetResult(request, response.getVersion(), result.updatedSourceAsMap(), result.updateSourceContentType(), indexSourceBytes)); listener.onResponse(update); } @Override public void onFailure(Throwable e) { e = ExceptionsHelper.unwrapCause(e); if (e instanceof VersionConflictEngineException) { if (retryCount < request.retryOnConflict()) { threadPool.executor(executor()).execute(new Runnable() { @Override public void run() { shardOperation(request, listener, retryCount + 1); } }); return; } } listener.onFailure(e); } });
1no label
src_main_java_org_elasticsearch_action_update_TransportUpdateAction.java
686
constructors[COLLECTION_CLEAR_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new CollectionClearBackupOperation(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
1,333
@ClusterScope(scope = TEST) public class AckClusterUpdateSettingsTests extends ElasticsearchIntegrationTest { @Override protected Settings nodeSettings(int nodeOrdinal) { //to test that the acknowledgement mechanism is working we better disable the wait for publish //otherwise the operation is most likely acknowledged even if it doesn't support ack return ImmutableSettings.builder().put("discovery.zen.publish_timeout", 0).build(); } @Test public void testClusterUpdateSettingsAcknowledgement() { client().admin().indices().prepareCreate("test") .setSettings(settingsBuilder() .put("number_of_shards", atLeast(cluster().size())) .put("number_of_replicas", 0)).get(); ensureGreen(); NodesInfoResponse nodesInfo = client().admin().cluster().prepareNodesInfo().get(); String excludedNodeId = null; for (NodeInfo nodeInfo : nodesInfo) { if (nodeInfo.getNode().isDataNode()) { excludedNodeId = nodesInfo.getAt(0).getNode().id(); break; } } assertNotNull(excludedNodeId); ClusterUpdateSettingsResponse clusterUpdateSettingsResponse = client().admin().cluster().prepareUpdateSettings() .setTransientSettings(settingsBuilder().put("cluster.routing.allocation.exclude._id", excludedNodeId)).get(); assertAcked(clusterUpdateSettingsResponse); assertThat(clusterUpdateSettingsResponse.getTransientSettings().get("cluster.routing.allocation.exclude._id"), equalTo(excludedNodeId)); for (Client client : clients()) { ClusterState clusterState = getLocalClusterState(client); assertThat(clusterState.routingNodes().metaData().transientSettings().get("cluster.routing.allocation.exclude._id"), equalTo(excludedNodeId)); for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) { for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) { for (ShardRouting shardRouting : indexShardRoutingTable) { if (clusterState.nodes().get(shardRouting.currentNodeId()).id().equals(excludedNodeId)) { //if the shard is still there it must be relocating and all nodes need to know, since the request was acknowledged assertThat(shardRouting.relocating(), equalTo(true)); } } } } } //let's wait for the relocation to be completed, otherwise there can be issues with after test checks (mock directory wrapper etc.) waitForRelocation(); //removes the allocation exclude settings client().admin().cluster().prepareUpdateSettings().setTransientSettings(settingsBuilder().put("cluster.routing.allocation.exclude._id", "")).get(); } @Test public void testClusterUpdateSettingsNoAcknowledgement() { client().admin().indices().prepareCreate("test") .setSettings(settingsBuilder() .put("number_of_shards", atLeast(cluster().size())) .put("number_of_replicas", 0)).get(); ensureGreen(); NodesInfoResponse nodesInfo = client().admin().cluster().prepareNodesInfo().get(); String excludedNodeId = null; for (NodeInfo nodeInfo : nodesInfo) { if (nodeInfo.getNode().isDataNode()) { excludedNodeId = nodesInfo.getAt(0).getNode().id(); break; } } assertNotNull(excludedNodeId); ClusterUpdateSettingsResponse clusterUpdateSettingsResponse = client().admin().cluster().prepareUpdateSettings().setTimeout("0s") .setTransientSettings(settingsBuilder().put("cluster.routing.allocation.exclude._id", excludedNodeId)).get(); assertThat(clusterUpdateSettingsResponse.isAcknowledged(), equalTo(false)); assertThat(clusterUpdateSettingsResponse.getTransientSettings().get("cluster.routing.allocation.exclude._id"), equalTo(excludedNodeId)); //let's wait for the relocation to be completed, otherwise there can be issues with after test checks (mock directory wrapper etc.) waitForRelocation(); //removes the allocation exclude settings client().admin().cluster().prepareUpdateSettings().setTransientSettings(settingsBuilder().put("cluster.routing.allocation.exclude._id", "")).get(); } private static ClusterState getLocalClusterState(Client client) { return client.admin().cluster().prepareState().setLocal(true).get().getState(); } }
0true
src_test_java_org_elasticsearch_cluster_ack_AckClusterUpdateSettingsTests.java
16
static class A { private int c = 0; private final Object o; A(final Object o) { this.o = o; } public void inc() { c++; } }
0true
titan-test_src_main_java_com_thinkaurelius_titan_TestBed.java
1,312
class ApplySettings implements NodeSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { TimeValue newUpdateFrequency = settings.getAsTime(INTERNAL_CLUSTER_INFO_UPDATE_INTERVAL, null); // ClusterInfoService is only enabled if the DiskThresholdDecider is enabled Boolean newEnabled = settings.getAsBoolean(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, null); if (newUpdateFrequency != null) { if (newUpdateFrequency.getMillis() < TimeValue.timeValueSeconds(10).getMillis()) { logger.warn("[{}] set too low [{}] (< 10s)", INTERNAL_CLUSTER_INFO_UPDATE_INTERVAL, newUpdateFrequency); throw new IllegalStateException("Unable to set " + INTERNAL_CLUSTER_INFO_UPDATE_INTERVAL + " less than 10 seconds"); } else { logger.info("updating [{}] from [{}] to [{}]", INTERNAL_CLUSTER_INFO_UPDATE_INTERVAL, updateFrequency, newUpdateFrequency); InternalClusterInfoService.this.updateFrequency = newUpdateFrequency; } } // We don't log about enabling it here, because the DiskThresholdDecider will already be logging about enable/disable if (newEnabled != null) { InternalClusterInfoService.this.enabled = newEnabled; } } }
0true
src_main_java_org_elasticsearch_cluster_InternalClusterInfoService.java
1,507
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(); } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_sideeffect_GroupCountMapReduce.java
544
flushAction.execute(Requests.flushRequest(request.indices()), new ActionListener<FlushResponse>() { @Override public void onResponse(FlushResponse flushResponse) { // get all types that need to be deleted. ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> result = clusterService.state().metaData().findMappings( request.indices(), request.types() ); // create OrFilter with type filters within to account for different types BoolFilterBuilder filterBuilder = new BoolFilterBuilder(); Set<String> types = new HashSet<String>(); for (ObjectObjectCursor<String, ImmutableOpenMap<String, MappingMetaData>> typesMeta : result) { for (ObjectObjectCursor<String, MappingMetaData> type : typesMeta.value) { filterBuilder.should(new TypeFilterBuilder(type.key)); types.add(type.key); } } if (types.size() == 0) { throw new TypeMissingException(new Index("_all"), request.types(), "No index has the type."); } request.types(types.toArray(new String[types.size()])); QuerySourceBuilder querySourceBuilder = new QuerySourceBuilder() .setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), filterBuilder)); deleteByQueryAction.execute(Requests.deleteByQueryRequest(request.indices()).source(querySourceBuilder), new ActionListener<DeleteByQueryResponse>() { @Override public void onResponse(DeleteByQueryResponse deleteByQueryResponse) { refreshAction.execute(Requests.refreshRequest(request.indices()), new ActionListener<RefreshResponse>() { @Override public void onResponse(RefreshResponse refreshResponse) { removeMapping(); } @Override public void onFailure(Throwable e) { removeMapping(); } protected void removeMapping() { DeleteMappingClusterStateUpdateRequest clusterStateUpdateRequest = new DeleteMappingClusterStateUpdateRequest() .indices(request.indices()).types(request.types()) .ackTimeout(request.timeout()) .masterNodeTimeout(request.masterNodeTimeout()); metaDataMappingService.removeMapping(clusterStateUpdateRequest, new ClusterStateUpdateListener() { @Override public void onResponse(ClusterStateUpdateResponse response) { listener.onResponse(new DeleteMappingResponse(response.isAcknowledged())); } @Override public void onFailure(Throwable t) { listener.onFailure(t); } }); } }); } @Override public void onFailure(Throwable t) { listener.onFailure(t); } }); } @Override public void onFailure(Throwable t) { listener.onFailure(t); } });
1no label
src_main_java_org_elasticsearch_action_admin_indices_mapping_delete_TransportDeleteMappingAction.java
224
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface OAccess { public enum OAccessType { FIELD, PROPERTY } public OAccessType value() default OAccessType.PROPERTY; }
0true
core_src_main_java_com_orientechnologies_orient_core_annotation_OAccess.java
327
EntryListener listener1 = new EntryAdapter() { public void entryAdded(EntryEvent event) { latch1Add.countDown(); } public void entryRemoved(EntryEvent event) { latch1Remove.countDown(); } };
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java
1,487
public class RoutingValidationException extends RoutingException { private final RoutingTableValidation validation; public RoutingValidationException(RoutingTableValidation validation) { super(validation.toString()); this.validation = validation; } public RoutingTableValidation validation() { return this.validation; } }
0true
src_main_java_org_elasticsearch_cluster_routing_RoutingValidationException.java
808
public class GetAndAlterRequest extends AbstractAlterRequest { public GetAndAlterRequest() { } public GetAndAlterRequest(String name, Data function) { super(name, function); } @Override protected Operation prepareOperation() { return new GetAndAlterOperation(name, getFunction()); } @Override public int getClassId() { return AtomicLongPortableHook.GET_AND_ALTER; } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_client_GetAndAlterRequest.java
688
public class CollectionEventFilter implements EventFilter, IdentifiedDataSerializable { boolean includeValue; public CollectionEventFilter() { } public CollectionEventFilter(boolean includeValue) { this.includeValue = includeValue; } public boolean isIncludeValue() { return includeValue; } @Override public boolean eval(Object arg) { return false; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeBoolean(includeValue); } @Override public void readData(ObjectDataInput in) throws IOException { includeValue = in.readBoolean(); } @Override public int getFactoryId() { return CollectionDataSerializerHook.F_ID; } @Override public int getId() { return CollectionDataSerializerHook.COLLECTION_EVENT_FILTER; } }
1no label
hazelcast_src_main_java_com_hazelcast_collection_CollectionEventFilter.java
366
public interface Translation { public Long getId(); public void setId(Long id); public TranslatedEntity getEntityType(); public void setEntityType(TranslatedEntity entityType); public String getEntityId(); public void setEntityId(String entityId); public String getFieldName(); public void setFieldName(String fieldName); public String getLocaleCode(); public void setLocaleCode(String localeCode); public String getTranslatedValue(); public void setTranslatedValue(String translatedValue); }
0true
common_src_main_java_org_broadleafcommerce_common_i18n_domain_Translation.java
160
public interface StructuredContentService extends SandBoxItemListener { /** * Returns the StructuredContent item associated with the passed in id. * * @param contentId - The id of the content item. * @return The associated structured content item. */ public StructuredContent findStructuredContentById(Long contentId); /** * Returns the <code>StructuredContentType</code> associated with the passed in id. * * @param id - The id of the content type. * @return The associated <code>StructuredContentType</code>. */ public StructuredContentType findStructuredContentTypeById(Long id); /** * Returns the <code>StructuredContentType</code> associated with the passed in * String value. * * @param name - The name of the content type. * @return The associated <code>StructuredContentType</code>. */ public StructuredContentType findStructuredContentTypeByName(String name); /** * * @return a list of all <code>StructuredContentType</code>s */ public List<StructuredContentType> retrieveAllStructuredContentTypes(); /** * Returns the fields associated with the passed in contentId. * This is preferred over the direct access from the ContentItem so that the * two items can be cached distinctly * * @param contentId - The id of the content. * @return Map of fields for this content id */ public Map<String,StructuredContentField> findFieldsByContentId(Long contentId); /** * This method is intended to be called solely from the CMS admin. Similar methods * exist that are intended for other clients (e.g. lookupStructuredContentItemsBy.... * <br> * Returns content items for the passed in sandbox that match the passed in criteria. * The criteria acts as a where clause to be used in the search for content items. * Implementations should automatically add criteria such that no archived items * are returned from this method. * <br> * The SandBox parameter impacts the results as follows. If a <code>SandBoxType</code> of * production is passed in, only those items in that SandBox are returned. * <br> * If a non-production SandBox is passed in, then the method will return the items associatd * with the related production SandBox and then merge in the results of the passed in SandBox. * * @param sandbox - the sandbox to find structured content items (null indicates items that are in production for * sites that are single tenant. * @param criteria - the criteria used to search for content * @return */ public List<StructuredContent> findContentItems(SandBox sandbox, Criteria criteria); /** * Finds all content items regardless of the {@link Sandbox} they are a member of * @return */ public List<StructuredContent> findAllContentItems(); /** * Follows the same rules as {@link #findContentItems(org.broadleafcommerce.common.sandbox.domain.SandBox, org.hibernate.Criteria) findContentItems}. * * @return the count of items in this sandbox that match the passed in Criteria */ public Long countContentItems(SandBox sandBox, Criteria c); /** * This method is intended to be called from within the CMS * admin only. * * Adds the passed in contentItem to the DB. * * Creates a sandbox/site if one doesn't already exist. */ public StructuredContent addStructuredContent(StructuredContent content, SandBox destinationSandbox); /** * This method is intended to be called from within the CMS * admin only. * * Updates the structuredContent according to the following rules: * * 1. If sandbox has changed from null to a value * This means that the user is editing an item in production and * the edit is taking place in a sandbox. * * Clone the item and add it to the new sandbox and set the cloned * item's originalItemId to the id of the item being updated. * * 2. If the sandbox has changed from one value to another * This means that the user is moving the item from one sandbox * to another. * * Update the siteId for the item to the one associated with the * new sandbox * * 3. If the sandbox has changed from a value to null * This means that the item is moving from the sandbox to production. * * If the item has an originalItemId, then update that item by * setting it's archived flag to true. * * Then, update the siteId of the item being updated to be the * siteId of the original item. * * 4. If the sandbox is the same then just update the item. */ public StructuredContent updateStructuredContent(StructuredContent content, SandBox sandbox); /** * Saves the given <b>type</b> and returns the merged instance */ public StructuredContentType saveStructuredContentType(StructuredContentType type); /** * If deleting and item where content.originalItemId != null * then the item is deleted from the database. * * If the originalItemId is null, then this method marks * the items as deleted within the passed in sandbox. * * @param content * @param destinationSandbox * @return */ public void deleteStructuredContent(StructuredContent content, SandBox destinationSandbox); /** * This method returns content * <br> * Returns active content items for the passed in sandbox that match the passed in type. * <br> * The SandBox parameter impacts the results as follows. If a <code>SandBoxType</code> of * production is passed in, only those items in that SandBox are returned. * <br> * If a non-production SandBox is passed in, then the method will return the items associatd * with the related production SandBox and then merge in the results of the passed in SandBox. * <br> * The secure item is used in cases where the structured content item contains an image path that needs * to be rewritten to use https. * * @param sandBox - the sandbox to find structured content items (null indicates items that are in production for * sites that are single tenant. * @param contentType - the type of content to return * @param count - the max number of content items to return * @param ruleDTOs - a Map of objects that will be used in MVEL processing. * @param secure - set to true if the request is being served over https * @return - The matching items * @see org.broadleafcommerce.cms.web.structure.DisplayContentTag */ public List<StructuredContentDTO> lookupStructuredContentItemsByType(SandBox sandBox, StructuredContentType contentType, Locale locale, Integer count, Map<String,Object> ruleDTOs, boolean secure); /** * This method returns content by name only. * <br> * Returns active content items for the passed in sandbox that match the passed in type. * <br> * The SandBox parameter impacts the results as follows. If a <code>SandBoxType</code> of * production is passed in, only those items in that SandBox are returned. * <br> * If a non-production SandBox is passed in, then the method will return the items associatd * with the related production SandBox and then merge in the results of the passed in SandBox. * * @param sandBox - the sandbox to find structured content items (null indicates items that are in production for * sites that are single tenant. * @param contentName - the name of content to return * @param count - the max number of content items to return * @param ruleDTOs - a Map of objects that will be used in MVEL processing. * @param secure - set to true if the request is being served over https * @return - The matching items * @see org.broadleafcommerce.cms.web.structure.DisplayContentTag */ public List<StructuredContentDTO> lookupStructuredContentItemsByName(SandBox sandBox, String contentName, Locale locale, Integer count, Map<String,Object> ruleDTOs, boolean secure); /** * This method returns content by name and type. * <br> * Returns active content items for the passed in sandbox that match the passed in type. * <br> * The SandBox parameter impacts the results as follows. If a <code>SandBoxType</code> of * production is passed in, only those items in that SandBox are returned. * <br> * If a non-production SandBox is passed in, then the method will return the items associatd * with the related production SandBox and then merge in the results of the passed in SandBox. * * @param sandBox - the sandbox to find structured content items (null indicates items that are in production for * sites that are single tenant. * @param contentType - the type of content to return * @param contentName - the name of content to return * @param count - the max number of content items to return * @param ruleDTOs - a Map of objects that will be used in MVEL processing. * @param secure - set to true if the request is being served over https * @return - The matching items * @see org.broadleafcommerce.cms.web.structure.DisplayContentTag */ public List<StructuredContentDTO> lookupStructuredContentItemsByName(SandBox sandBox, StructuredContentType contentType, String contentName, Locale locale, Integer count, Map<String,Object> ruleDTOs, boolean secure); /** * Removes the items from cache that match the passed in name and page keys. * @param nameKey - key for a specific content item * @param typeKey - key for a type of content item */ public void removeItemFromCache(String nameKey, String typeKey); public boolean isAutomaticallyApproveAndPromoteStructuredContent(); public void setAutomaticallyApproveAndPromoteStructuredContent(boolean automaticallyApproveAndPromoteStructuredContent); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_service_StructuredContentService.java
539
public abstract class ODocumentHookAbstract implements ORecordHook { private String[] includeClasses; private String[] excludeClasses; protected ODocumentHookAbstract() { } /** * It's called just before to create the new document. * * @param iDocument * The document to create * @return True if the document has been modified and a new marshalling is required, otherwise false */ public RESULT onRecordBeforeCreate(final ODocument iDocument) { return RESULT.RECORD_NOT_CHANGED; } /** * It's called just after the document is created. * * @param iDocument * The document is going to be created */ public void onRecordAfterCreate(final ODocument iDocument) { } /** * It's called just after the document creation was failed. * * @param iDocument * The document just created */ public void onRecordCreateFailed(final ODocument iDocument) { } /** * It's called just after the document creation was replicated on another node. * * @param iDocument * The document just created */ public void onRecordCreateReplicated(final ODocument iDocument) { } /** * It's called just before to read the document. * * @param iDocument * The document to read * @return True if the document has been modified and a new marshalling is required, otherwise false */ public RESULT onRecordBeforeRead(final ODocument iDocument) { return RESULT.RECORD_NOT_CHANGED; } /** * It's called just after the document is read. * * @param iDocument * The document just read */ public void onRecordAfterRead(final ODocument iDocument) { } /** * It's called just after the document read was failed. * * @param iDocument * The document just created */ public void onRecordReadFailed(final ODocument iDocument) { } /** * It's called just after the document read was replicated on another node. * * @param iDocument * The document just created */ public void onRecordReadReplicated(final ODocument iDocument) { } /** * It's called just before to update the document. * * @param iDocument * The document to update * @return True if the document has been modified and a new marshalling is required, otherwise false */ public RESULT onRecordBeforeUpdate(final ODocument iDocument) { return RESULT.RECORD_NOT_CHANGED; } /** * It's called just after the document is updated. * * @param iDocument * The document just updated */ public void onRecordAfterUpdate(final ODocument iDocument) { } /** * It's called just after the document updated was failed. * * @param iDocument * The document is going to be updated */ public void onRecordUpdateFailed(final ODocument iDocument) { } /** * It's called just after the document updated was replicated. * * @param iDocument * The document is going to be updated */ public void onRecordUpdateReplicated(final ODocument iDocument) { } /** * It's called just before to delete the document. * * @param iDocument * The document to delete * @return True if the document has been modified and a new marshalling is required, otherwise false */ public RESULT onRecordBeforeDelete(final ODocument iDocument) { return RESULT.RECORD_NOT_CHANGED; } /** * It's called just after the document is deleted. * * @param iDocument * The document just deleted */ public void onRecordAfterDelete(final ODocument iDocument) { } /** * It's called just after the document deletion was failed. * * @param iDocument * The document is going to be deleted */ public void onRecordDeleteFailed(final ODocument iDocument) { } /** * It's called just after the document deletion was replicated. * * @param iDocument * The document is going to be deleted */ public void onRecordDeleteReplicated(final ODocument iDocument) { } public RESULT onRecordBeforeReplicaAdd(final ODocument iDocument) { return RESULT.RECORD_NOT_CHANGED; } public void onRecordAfterReplicaAdd(final ODocument iDocument) { } public void onRecordReplicaAddFailed(final ODocument iDocument) { } public RESULT onRecordBeforeReplicaUpdate(final ODocument iDocument) { return RESULT.RECORD_NOT_CHANGED; } public void onRecordAfterReplicaUpdate(final ODocument iDocument) { } public void onRecordReplicaUpdateFailed(final ODocument iDocument) { } public RESULT onRecordBeforeReplicaDelete(final ODocument iDocument) { return RESULT.RECORD_NOT_CHANGED; } public void onRecordAfterReplicaDelete(final ODocument iDocument) { } public void onRecordReplicaDeleteFailed(final ODocument iDocument) { } public RESULT onTrigger(final TYPE iType, final ORecord<?> iRecord) { if (ODatabaseRecordThreadLocal.INSTANCE.isDefined() && ODatabaseRecordThreadLocal.INSTANCE.get().getStatus() != STATUS.OPEN) return RESULT.RECORD_NOT_CHANGED; if (!(iRecord instanceof ODocument)) return RESULT.RECORD_NOT_CHANGED; final ODocument document = (ODocument) iRecord; if (!filterBySchemaClass(document)) return RESULT.RECORD_NOT_CHANGED; switch (iType) { case BEFORE_CREATE: return onRecordBeforeCreate(document); case AFTER_CREATE: onRecordAfterCreate(document); break; case CREATE_FAILED: onRecordCreateFailed(document); break; case CREATE_REPLICATED: onRecordCreateReplicated(document); break; case BEFORE_READ: return onRecordBeforeRead(document); case AFTER_READ: onRecordAfterRead(document); break; case READ_FAILED: onRecordReadFailed(document); break; case READ_REPLICATED: onRecordReadReplicated(document); break; case BEFORE_UPDATE: return onRecordBeforeUpdate(document); case AFTER_UPDATE: onRecordAfterUpdate(document); break; case UPDATE_FAILED: onRecordUpdateFailed(document); break; case UPDATE_REPLICATED: onRecordUpdateReplicated(document); break; case BEFORE_DELETE: return onRecordBeforeDelete(document); case AFTER_DELETE: onRecordAfterDelete(document); break; case DELETE_FAILED: onRecordDeleteFailed(document); break; case DELETE_REPLICATED: onRecordDeleteReplicated(document); break; case BEFORE_REPLICA_ADD: return onRecordBeforeReplicaAdd(document); case AFTER_REPLICA_ADD: onRecordAfterReplicaAdd(document); break; case REPLICA_ADD_FAILED: onRecordReplicaAddFailed(document); break; case BEFORE_REPLICA_UPDATE: return onRecordBeforeReplicaUpdate(document); case AFTER_REPLICA_UPDATE: onRecordAfterReplicaUpdate(document); break; case REPLICA_UPDATE_FAILED: onRecordReplicaUpdateFailed(document); break; case BEFORE_REPLICA_DELETE: return onRecordBeforeReplicaDelete(document); case AFTER_REPLICA_DELETE: onRecordAfterReplicaDelete(document); break; case REPLICA_DELETE_FAILED: onRecordReplicaDeleteFailed(document); break; default: throw new IllegalStateException("Hook method " + iType + " is not managed"); } return RESULT.RECORD_NOT_CHANGED; } public String[] getIncludeClasses() { return includeClasses; } public ODocumentHookAbstract setIncludeClasses(final String... includeClasses) { if (excludeClasses != null) throw new IllegalStateException("Cannot include classes if exclude classes has been set"); this.includeClasses = includeClasses; return this; } public String[] getExcludeClasses() { return excludeClasses; } public ODocumentHookAbstract setExcludeClasses(final String... excludeClasses) { if (includeClasses != null) throw new IllegalStateException("Cannot exclude classes if include classes has been set"); this.excludeClasses = excludeClasses; return this; } protected boolean filterBySchemaClass(final ODocument iDocument) { if (includeClasses == null && excludeClasses == null) return true; final OClass clazz = iDocument.getSchemaClass(); if (clazz == null) return false; if (includeClasses != null) { // FILTER BY CLASSES for (String cls : includeClasses) if (clazz.isSubClassOf(cls)) return true; return false; } if (excludeClasses != null) { // FILTER BY CLASSES for (String cls : excludeClasses) if (clazz.isSubClassOf(cls)) return false; } return true; } }
0true
core_src_main_java_com_orientechnologies_orient_core_hook_ODocumentHookAbstract.java
161
private static final class SingleTargetCallback implements Callback<Object> { final Address target; final MultiTargetCallback parent; private SingleTargetCallback(Address target, MultiTargetCallback parent) { this.target = target; this.parent = parent; } @Override public void notify(Object object) { parent.notify(target, object); } }
0true
hazelcast_src_main_java_com_hazelcast_client_MultiTargetClientRequest.java
818
public class ClearScrollResponse extends ActionResponse { private boolean succeeded; public ClearScrollResponse(boolean succeeded) { this.succeeded = succeeded; } ClearScrollResponse() { } public boolean isSucceeded() { return succeeded; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); succeeded = in.readBoolean(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeBoolean(succeeded); } }
1no label
src_main_java_org_elasticsearch_action_search_ClearScrollResponse.java
611
@Component("blSandBoxResolver") public class BroadleafSandBoxResolverImpl implements BroadleafSandBoxResolver { private final Log LOG = LogFactory.getLog(BroadleafSandBoxResolverImpl.class); /** * Property used to disable sandbox mode. Some implementations will want to * turn off sandboxes in production. */ protected Boolean sandBoxPreviewEnabled = true; // Request Parameters and Attributes for Sandbox Mode properties - mostly values to manage dates. private static String SANDBOX_ID_VAR = "blSandboxId"; private static String SANDBOX_DATE_TIME_VAR = "blSandboxDateTime"; private static final SimpleDateFormat CONTENT_DATE_FORMATTER = new SimpleDateFormat("yyyyMMddHHmm"); private static final SimpleDateFormat CONTENT_DATE_DISPLAY_FORMATTER = new SimpleDateFormat("MM/dd/yyyy"); private static final SimpleDateFormat CONTENT_DATE_DISPLAY_HOURS_FORMATTER = new SimpleDateFormat("h"); private static final SimpleDateFormat CONTENT_DATE_DISPLAY_MINUTES_FORMATTER = new SimpleDateFormat("mm"); private static final SimpleDateFormat CONTENT_DATE_PARSE_FORMAT = new SimpleDateFormat("MM/dd/yyyy hh:mm aa"); private static String SANDBOX_DATE_TIME_RIBBON_OVERRIDE_PARAM = "blSandboxDateTimeRibbonOverride"; private static final String SANDBOX_DISPLAY_DATE_TIME_DATE_PARAM = "blSandboxDisplayDateTimeDate"; private static final String SANDBOX_DISPLAY_DATE_TIME_HOURS_PARAM = "blSandboxDisplayDateTimeHours"; private static final String SANDBOX_DISPLAY_DATE_TIME_MINUTES_PARAM = "blSandboxDisplayDateTimeMinutes"; private static final String SANDBOX_DISPLAY_DATE_TIME_AMPM_PARAM = "blSandboxDisplayDateTimeAMPM"; /** * Request attribute to store the current sandbox */ public static String SANDBOX_VAR = "blSandbox"; @Resource(name = "blSandBoxDao") private SandBoxDao sandBoxDao; /** * Determines the current sandbox based on other parameters on the request such as * the blSandBoxId parameters. * * If the {@link #getSandBoxPreviewEnabled()}, then this method will not return a user * SandBox. * */ @Override public SandBox resolveSandBox(HttpServletRequest request, Site site) { return resolveSandBox(new ServletWebRequest(request), site); } @Override public SandBox resolveSandBox(WebRequest request, Site site) { SandBox currentSandbox = null; if (!sandBoxPreviewEnabled) { if (LOG.isTraceEnabled()) { LOG.trace("Sandbox preview disabled. Setting sandbox to production"); } request.setAttribute(SANDBOX_VAR, currentSandbox, WebRequest.SCOPE_REQUEST); } else { Long sandboxId = null; // Clear the sandBox - second parameter is to support legacy implementations. if ( (request.getParameter("blClearSandBox") == null) || (request.getParameter("blSandboxDateTimeRibbonProduction") == null)) { sandboxId = lookupSandboxId(request); } else { if (LOG.isTraceEnabled()) { LOG.trace("Removing sandbox from session."); } if (BLCRequestUtils.isOKtoUseSession(request)) { request.removeAttribute(SANDBOX_DATE_TIME_VAR, WebRequest.SCOPE_GLOBAL_SESSION); request.removeAttribute(SANDBOX_ID_VAR, WebRequest.SCOPE_GLOBAL_SESSION); } } if (sandboxId != null) { currentSandbox = sandBoxDao.retrieve(sandboxId); request.setAttribute(SANDBOX_VAR, currentSandbox, WebRequest.SCOPE_REQUEST); if (currentSandbox != null && !SandBoxType.PRODUCTION.equals(currentSandbox.getSandBoxType())) { setContentTime(request); } } if (currentSandbox == null && site != null) { currentSandbox = site.getProductionSandbox(); } } if (LOG.isTraceEnabled()) { if (currentSandbox != null) { LOG.trace("Serving request using sandbox: " + currentSandbox); } else { LOG.trace("Serving request without a sandbox."); } } Date currentSystemDateTime = SystemTime.asDate(true); Calendar sandboxDateTimeCalendar = Calendar.getInstance(); sandboxDateTimeCalendar.setTime(currentSystemDateTime); request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_DATE_PARAM, CONTENT_DATE_DISPLAY_FORMATTER.format(currentSystemDateTime), WebRequest.SCOPE_REQUEST); request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_HOURS_PARAM, CONTENT_DATE_DISPLAY_HOURS_FORMATTER.format(currentSystemDateTime), WebRequest.SCOPE_REQUEST); request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_MINUTES_PARAM, CONTENT_DATE_DISPLAY_MINUTES_FORMATTER.format(currentSystemDateTime), WebRequest.SCOPE_REQUEST); request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_AMPM_PARAM, sandboxDateTimeCalendar.get(Calendar.AM_PM), WebRequest.SCOPE_REQUEST); return currentSandbox; } /** * If another filter has already set the language as a request attribute, that will be honored. * Otherwise, the request parameter is checked followed by the session attribute. * * @param request * @param site * @return */ private Long lookupSandboxId(WebRequest request) { String sandboxIdStr = request.getParameter(SANDBOX_ID_VAR); Long sandboxId = null; if (sandboxIdStr != null) { try { sandboxId = Long.valueOf(sandboxIdStr); if (LOG.isTraceEnabled()) { LOG.trace("SandboxId found on request " + sandboxId); } } catch (NumberFormatException nfe) { LOG.warn("blcSandboxId parameter could not be converted into a Long", nfe); } } if (BLCRequestUtils.isOKtoUseSession(request)) { if (sandboxId == null) { // check the session sandboxId = (Long) request.getAttribute(SANDBOX_ID_VAR, WebRequest.SCOPE_GLOBAL_SESSION); if (LOG.isTraceEnabled()) { if (sandboxId != null) { LOG.trace("SandboxId found in session " + sandboxId); } } } else { request.setAttribute(SANDBOX_ID_VAR, sandboxId, WebRequest.SCOPE_GLOBAL_SESSION); } } return sandboxId; } /** * Allows a user in SandBox mode to override the current time and date being used by the system. * * @param request */ private void setContentTime(WebRequest request) { String sandboxDateTimeParam = request.getParameter(SANDBOX_DATE_TIME_VAR); if (sandBoxPreviewEnabled) { sandboxDateTimeParam = null; } Date overrideTime = null; try { if (request.getParameter(SANDBOX_DATE_TIME_RIBBON_OVERRIDE_PARAM) != null) { overrideTime = readDateFromRequest(request); } else if (sandboxDateTimeParam != null) { if (LOG.isDebugEnabled()) { LOG.debug("Setting date/time using " + sandboxDateTimeParam); } overrideTime = CONTENT_DATE_FORMATTER.parse(sandboxDateTimeParam); } } catch (ParseException e) { LOG.debug(e); } if (BLCRequestUtils.isOKtoUseSession(request)) { if (overrideTime == null) { overrideTime = (Date) request.getAttribute(SANDBOX_DATE_TIME_VAR, WebRequest.SCOPE_GLOBAL_SESSION); } else { if (LOG.isDebugEnabled()) { LOG.debug("Setting date-time for sandbox mode to " + overrideTime + " for sandboxDateTimeParam = " + sandboxDateTimeParam); } request.setAttribute(SANDBOX_DATE_TIME_VAR, overrideTime, WebRequest.SCOPE_GLOBAL_SESSION); } } if (overrideTime != null) { FixedTimeSource ft = new FixedTimeSource(overrideTime.getTime()); SystemTime.setLocalTimeSource(ft); } else { SystemTime.resetLocalTimeSource(); } } private Date readDateFromRequest(WebRequest request) throws ParseException { String date = request.getParameter(SANDBOX_DISPLAY_DATE_TIME_DATE_PARAM); String minutes = request.getParameter(SANDBOX_DISPLAY_DATE_TIME_MINUTES_PARAM); String hours = request.getParameter(SANDBOX_DISPLAY_DATE_TIME_HOURS_PARAM); String ampm = request.getParameter(SANDBOX_DISPLAY_DATE_TIME_AMPM_PARAM); if (StringUtils.isEmpty(minutes)) { minutes = Integer.toString(SystemTime.asCalendar().get(Calendar.MINUTE)); } if (StringUtils.isEmpty(hours)) { hours = Integer.toString(SystemTime.asCalendar().get(Calendar.HOUR_OF_DAY)); } String dateString = date + " " + hours + ":" + minutes + " " + ampm; if (LOG.isDebugEnabled()) { LOG.debug("Setting date/time using " + dateString); } Date parsedDate = CONTENT_DATE_PARSE_FORMAT.parse(dateString); return parsedDate; } /** * Sets whether or not the site can be viewed in preview mode. * @return */ public Boolean getSandBoxPreviewEnabled() { return sandBoxPreviewEnabled; } public void setSandBoxPreviewEnabled(Boolean sandBoxPreviewEnabled) { this.sandBoxPreviewEnabled = sandBoxPreviewEnabled; } }
1no label
common_src_main_java_org_broadleafcommerce_common_web_BroadleafSandBoxResolverImpl.java
577
public interface IndexValuesResultListener { boolean addResult(OIdentifiable value); }
0true
core_src_main_java_com_orientechnologies_orient_core_index_OIndex.java
366
@SuppressWarnings("unchecked") public class OGraphDatabasePooled extends OGraphDatabase implements ODatabasePooled { private OGraphDatabasePool ownerPool; public OGraphDatabasePooled(final OGraphDatabasePool iOwnerPool, final String iURL, final String iUserName, final String iUserPassword) { super(iURL); ownerPool = iOwnerPool; super.open(iUserName, iUserPassword); } public void reuse(final Object iOwner, final Object[] iAdditionalArgs) { ownerPool = (OGraphDatabasePool) iOwner; if (isClosed()) open((String) iAdditionalArgs[0], (String) iAdditionalArgs[1]); getLevel1Cache().invalidate(); // getMetadata().reload(); ODatabaseRecordThreadLocal.INSTANCE.set(this); checkForGraphSchema(); try { ODatabase current = underlying; while (!(current instanceof ODatabaseRaw) && ((ODatabaseComplex<?>) current).getUnderlying() != null) current = ((ODatabaseComplex<?>) current).getUnderlying(); ((ODatabaseRaw) current).callOnOpenListeners(); } catch (Exception e) { OLogManager.instance().error(this, "Error on reusing database '%s' in pool", e, getName()); } } @Override public OGraphDatabasePooled open(String iUserName, String iUserPassword) { throw new UnsupportedOperationException( "Database instance was retrieved from a pool. You cannot open the database in this way. Use directly a OGraphDatabase instance if you want to manually open the connection"); } @Override public OGraphDatabasePooled create() { throw new UnsupportedOperationException( "Database instance was retrieved from a pool. You cannot open the database in this way. Use directly a OGraphDatabase instance if you want to manually open the connection"); } public boolean isUnderlyingOpen() { return !super.isClosed(); } @Override public boolean isClosed() { return ownerPool == null || super.isClosed(); } /** * Avoid to close it but rather release itself to the owner pool. */ @Override public void close() { if (isClosed()) return; vertexBaseClass = null; edgeBaseClass = null; checkOpeness(); try { rollback(); } catch (Exception e) { OLogManager.instance().error(this, "Error on releasing database '%s' in pool", e, getName()); } try { ODatabase current = underlying; while (!(current instanceof ODatabaseRaw) && ((ODatabaseComplex<?>) current).getUnderlying() != null) current = ((ODatabaseComplex<?>) current).getUnderlying(); ((ODatabaseRaw) current).callOnCloseListeners(); } catch (Exception e) { OLogManager.instance().error(this, "Error on releasing database '%s' in pool", e, getName()); } getLevel1Cache().clear(); if (ownerPool != null) { final OGraphDatabasePool pool = ownerPool; ownerPool = null; pool.release(this); } } public void forceClose() { super.close(); } @Override protected void checkOpeness() { if (ownerPool == null) throw new ODatabaseException( "Database instance has been released to the pool. Get another database instance from the pool with the right username and password"); super.checkOpeness(); } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_graph_OGraphDatabasePooled.java
1,540
@Service("blUpdateCartService") public class UpdateCartServiceImpl implements UpdateCartService { protected static final Log LOG = LogFactory.getLog(UpdateCartServiceImpl.class); protected static BroadleafCurrency savedCurrency; @Resource(name="blOrderService") protected OrderService orderService; @Resource(name = "blUpdateCartServiceExtensionManager") protected UpdateCartServiceExtensionManager extensionManager; @Override public boolean currencyHasChanged() { BroadleafCurrency currency = findActiveCurrency(); if (getSavedCurrency() == null) { setSavedCurrency(currency); } else if (getSavedCurrency() != currency){ return true; } return false; } @Override public UpdateCartResponse copyCartToCurrentContext(Order currentCart) { if(currentCart.getOrderItems() == null){ return null; } BroadleafCurrency currency = findActiveCurrency(); if(currency == null){ return null; } //Reprice order logic List<AddToCartItem> itemsToReprice = new ArrayList<AddToCartItem>(); List<OrderItem> itemsToRemove = new ArrayList<OrderItem>(); List<OrderItem> itemsToReset = new ArrayList<OrderItem>(); boolean repriceOrder = true; for(OrderItem orderItem: currentCart.getOrderItems()){ //Lookup price in price list, if null, then add to itemsToRemove if (orderItem instanceof DiscreteOrderItem){ DiscreteOrderItem doi = (DiscreteOrderItem) orderItem; if(checkAvailabilityInLocale(doi, currency)){ AddToCartItem itemRequest = new AddToCartItem(); itemRequest.setProductId(doi.getProduct().getId()); itemRequest.setQuantity(doi.getQuantity()); itemsToReprice.add(itemRequest); itemsToReset.add(orderItem); } else { itemsToRemove.add(orderItem); } } else if (orderItem instanceof BundleOrderItem) { BundleOrderItem boi = (BundleOrderItem) orderItem; for (DiscreteOrderItem doi : boi.getDiscreteOrderItems()) { if(checkAvailabilityInLocale(doi, currency)){ AddToCartItem itemRequest = new AddToCartItem(); itemRequest.setProductId(doi.getProduct().getId()); itemRequest.setQuantity(doi.getQuantity()); itemsToReprice.add(itemRequest); itemsToReset.add(orderItem); } else { itemsToRemove.add(orderItem); } } } } for(OrderItem orderItem: itemsToReset){ try { currentCart = orderService.removeItem(currentCart.getId(), orderItem.getId(), false); } catch (RemoveFromCartException e) { e.printStackTrace(); } } for(AddToCartItem itemRequest: itemsToReprice){ try { currentCart = orderService.addItem(currentCart.getId(), itemRequest, false); } catch (AddToCartException e) { e.printStackTrace(); } } // Reprice and save the cart try { currentCart = orderService.save(currentCart, repriceOrder); } catch (PricingException e) { e.printStackTrace(); } setSavedCurrency(currency); UpdateCartResponse updateCartResponse = new UpdateCartResponse(); updateCartResponse.setRemovedItems(itemsToRemove); updateCartResponse.setOrder(currentCart); return updateCartResponse; } @Override public void validateCart(Order cart) { // hook to allow override } @Override public void updateAndValidateCart(Order cart) { if (extensionManager != null) { ExtensionResultHolder erh = new ExtensionResultHolder(); extensionManager.getProxy().updateAndValidateCart(cart, erh); Boolean clearCart = (Boolean) erh.getContextMap().get("clearCart"); Boolean repriceCart = (Boolean) erh.getContextMap().get("repriceCart"); Boolean saveCart = (Boolean) erh.getContextMap().get("saveCart"); if (clearCart != null && clearCart.booleanValue()) { orderService.cancelOrder(cart); cart = orderService.createNewCartForCustomer(cart.getCustomer()); } else { try { if (repriceCart != null && repriceCart.booleanValue()) { cart.updatePrices(); orderService.save(cart, true); } else if (saveCart != null && saveCart.booleanValue()) { orderService.save(cart, false); } } catch (PricingException pe) { LOG.error("Pricing Exception while validating cart. Clearing cart.", pe); orderService.cancelOrder(cart); cart = orderService.createNewCartForCustomer(cart.getCustomer()); } } } } protected BroadleafCurrency findActiveCurrency(){ if(BroadleafRequestContext.hasLocale()){ return BroadleafRequestContext.getBroadleafRequestContext().getBroadleafCurrency(); } return null; } protected boolean checkAvailabilityInLocale(DiscreteOrderItem doi, BroadleafCurrency currency) { if (doi.getSku() != null && extensionManager != null) { Sku sku = doi.getSku(); return sku.isAvailable(); } return false; } @Override public void setSavedCurrency(BroadleafCurrency savedCurrency) { this.savedCurrency = savedCurrency; } @Override public BroadleafCurrency getSavedCurrency() { return savedCurrency; } }
1no label
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_service_UpdateCartServiceImpl.java
183
futures.add(es.submit(new Callable<Void>() { @Override public Void call() { try { getBlock(); } catch (BackendException e) { throw new RuntimeException(e); } return null; } private void getBlock() throws BackendException { for (int i = 0; i < blocksPerThread; i++) { IDBlock block = targetAuthority.getIDBlock(targetPartition,targetNamespace, GET_ID_BLOCK_TIMEOUT); Assert.assertNotNull(block); blocks.add(block); } } }));
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_IDAuthorityTest.java
85
public abstract class OConsoleCommandCollection { protected OConsoleApplication context; void setContext(OConsoleApplication context){ this.context = context; } }
0true
commons_src_main_java_com_orientechnologies_common_console_OConsoleCommandCollection.java
6,303
public static final class ElasticsearchMockDirectoryWrapper extends MockDirectoryWrapper { private final ESLogger logger; private final boolean failOnClose; public ElasticsearchMockDirectoryWrapper(Random random, Directory delegate, ESLogger logger, boolean failOnClose) { super(random, delegate); this.logger = logger; this.failOnClose = failOnClose; } @Override public void close() throws IOException { try { super.close(); } catch (RuntimeException ex) { if (failOnClose) { throw ex; } // we catch the exception on close to properly close shards even if there are open files // the test framework will call closeWithRuntimeException after the test exits to fail // on unclosed files. logger.debug("MockDirectoryWrapper#close() threw exception", ex); } } public void closeWithRuntimeException() throws IOException { super.close(); // force fail if open files etc. called in tear down of ElasticsearchIntegrationTest } }
1no label
src_test_java_org_elasticsearch_test_store_MockDirectoryHelper.java
694
class Flush implements Runnable { @Override public void run() { synchronized (BulkProcessor.this) { if (closed) { return; } if (bulkRequest.numberOfActions() == 0) { return; } execute(); } } }
0true
src_main_java_org_elasticsearch_action_bulk_BulkProcessor.java
463
public class IndicesAliasesClusterStateUpdateRequest extends ClusterStateUpdateRequest<IndicesAliasesClusterStateUpdateRequest> { AliasAction[] actions; IndicesAliasesClusterStateUpdateRequest() { } /** * Returns the alias actions to be performed */ public AliasAction[] actions() { return actions; } /** * Sets the alias actions to be executed */ public IndicesAliasesClusterStateUpdateRequest actions(AliasAction[] actions) { this.actions = actions; return this; } }
0true
src_main_java_org_elasticsearch_action_admin_indices_alias_IndicesAliasesClusterStateUpdateRequest.java
1,122
public class ScriptsScorePayloadSumBenchmark extends BasicScriptBenchmark { public static void main(String[] args) throws Exception { int minTerms = 1; int maxTerms = 50; int maxIter = 100; int warmerIter = 10; init(maxTerms); List<Results> allResults = new ArrayList<BasicScriptBenchmark.Results>(); Settings settings = settingsBuilder().put("plugin.types", NativeScriptExamplesPlugin.class.getName()).build(); String clusterName = ScriptsScoreBenchmark.class.getSimpleName(); Node node1 = nodeBuilder().clusterName(clusterName).settings(settingsBuilder().put(settings).put("name", "node1")).node(); Client client = node1.client(); client.admin().cluster().prepareHealth("test").setWaitForGreenStatus().setTimeout("10s").execute().actionGet(); indexData(10000, client, false); client.admin().cluster().prepareHealth("test").setWaitForGreenStatus().setTimeout("10s").execute().actionGet(); Results results = new Results(); // init script searches results.init(maxTerms - minTerms, "native payload sum script score", "Results for native script score:", "green", ":"); List<Entry<String, RequestInfo>> searchRequests = initNativeSearchRequests(minTerms, maxTerms, NativePayloadSumScoreScript.NATIVE_PAYLOAD_SUM_SCRIPT_SCORE, true); // run actual benchmark runBenchmark(client, maxIter, results, searchRequests, minTerms, warmerIter); allResults.add(results); results = new Results(); // init script searches results.init(maxTerms - minTerms, "native payload sum script score no record", "Results for native script score:", "black", ":"); searchRequests = initNativeSearchRequests(minTerms, maxTerms, NativePayloadSumNoRecordScoreScript.NATIVE_PAYLOAD_SUM_NO_RECORD_SCRIPT_SCORE, true); // run actual benchmark runBenchmark(client, maxIter, results, searchRequests, minTerms, warmerIter); allResults.add(results); printOctaveScript(allResults, args); client.close(); node1.close(); } }
0true
src_test_java_org_elasticsearch_benchmark_scripts_score_ScriptsScorePayloadSumBenchmark.java
787
return new DataSerializableFactory() { @Override public IdentifiedDataSerializable create(int typeId) { switch (typeId) { case ADD_BACKUP: return new AddBackupOperation(); case ADD_AND_GET: return new AddAndGetOperation(); case ALTER: return new AlterOperation(); case ALTER_AND_GET: return new AlterAndGetOperation(); case APPLY: return new ApplyOperation(); case COMPARE_AND_SET: return new CompareAndSetOperation(); case GET: return new GetOperation(); case GET_AND_SET: return new GetAndSetOperation(); case GET_AND_ALTER: return new GetAndAlterOperation(); case GET_AND_ADD: return new GetAndAddOperation(); case SET_OPERATION: return new SetOperation(); case SET_BACKUP: return new SetBackupOperation(); case REPLICATION: return new AtomicLongReplicationOperation(); default: return null; } } };
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_AtomicLongDataSerializerHook.java
140
public static class FileSizePruneStrategy extends AbstractPruneStrategy { private final int maxSize; public FileSizePruneStrategy( FileSystemAbstraction fileystem, int maxSizeBytes ) { super( fileystem ); this.maxSize = maxSizeBytes; } @Override protected Threshold newThreshold() { return new Threshold() { private int size; @Override public boolean reached( File file, long version, LogLoader source ) { size += fileSystem.getFileSize( file ); return size >= maxSize; } }; } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogPruneStrategies.java
407
@Component("blEntityConfiguration") public class EntityConfiguration implements ApplicationContextAware { private static final Log LOG = LogFactory.getLog(EntityConfiguration.class); private ApplicationContext webApplicationContext; private final HashMap<String, Class<?>> entityMap = new HashMap<String, Class<?>>(50); private ApplicationContext applicationcontext; private Resource[] entityContexts; @javax.annotation.Resource(name="blMergedEntityContexts") protected Set<String> mergedEntityContexts; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.webApplicationContext = applicationContext; } @PostConstruct public void configureMergedItems() { Set<Resource> temp = new LinkedHashSet<Resource>(); if (mergedEntityContexts != null && !mergedEntityContexts.isEmpty()) { for (String location : mergedEntityContexts) { temp.add(webApplicationContext.getResource(location)); } } if (entityContexts != null) { for (Resource resource : entityContexts) { temp.add(resource); } } entityContexts = temp.toArray(new Resource[temp.size()]); applicationcontext = new GenericXmlApplicationContext(entityContexts); } public Class<?> lookupEntityClass(String beanId) { Class<?> clazz; if (entityMap.containsKey(beanId)) { clazz = entityMap.get(beanId); } else { Object object = applicationcontext.getBean(beanId); clazz = object.getClass(); entityMap.put(beanId, clazz); } if (LOG.isDebugEnabled()) { LOG.debug("Returning class (" + clazz.getName() + ") configured with bean id (" + beanId + ')'); } return clazz; } public String[] getEntityBeanNames() { return applicationcontext.getBeanDefinitionNames(); } public <T> Class<T> lookupEntityClass(String beanId, Class<T> resultClass) { Class<T> clazz; if (entityMap.containsKey(beanId)) { clazz = (Class<T>) entityMap.get(beanId); } else { Object object = applicationcontext.getBean(beanId); clazz = (Class<T>) object.getClass(); entityMap.put(beanId, clazz); } if (LOG.isDebugEnabled()) { LOG.debug("Returning class (" + clazz.getName() + ") configured with bean id (" + beanId + ')'); } return clazz; } public Object createEntityInstance(String beanId) { Object bean = applicationcontext.getBean(beanId); if (LOG.isDebugEnabled()) { LOG.debug("Returning instance of class (" + bean.getClass().getName() + ") configured with bean id (" + beanId + ')'); } return bean; } public <T> T createEntityInstance(String beanId, Class<T> resultClass) { T bean = (T) applicationcontext.getBean(beanId); if (LOG.isDebugEnabled()) { LOG.debug("Returning instance of class (" + bean.getClass().getName() + ") configured with bean id (" + beanId + ')'); } return bean; } public Resource[] getEntityContexts() { return entityContexts; } public void setEntityContexts(Resource[] entityContexts) { this.entityContexts = entityContexts; } }
0true
common_src_main_java_org_broadleafcommerce_common_persistence_EntityConfiguration.java
332
new Thread() { public void run() { boolean result = map.tryRemove("key2", 1, TimeUnit.SECONDS); if (!result) { latch.countDown(); } } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java
198
public interface Authenticator { void auth(ClientConnection connection) throws AuthenticationException, IOException; }
0true
hazelcast-client_src_main_java_com_hazelcast_client_connection_Authenticator.java
0
public class BerkeleyStorageSetup extends StorageSetup { public static ModifiableConfiguration getBerkeleyJEConfiguration(String dir) { return buildConfiguration() .set(STORAGE_BACKEND,"berkeleyje") .set(STORAGE_DIRECTORY, dir); } public static ModifiableConfiguration getBerkeleyJEConfiguration() { return getBerkeleyJEConfiguration(getHomeDir()); } public static WriteConfiguration getBerkeleyJEGraphConfiguration() { return getBerkeleyJEConfiguration().getConfiguration(); } public static ModifiableConfiguration getBerkeleyJEPerformanceConfiguration() { return getBerkeleyJEConfiguration() .set(STORAGE_TRANSACTIONAL,false) .set(TX_CACHE_SIZE,1000); } }
0true
titan-berkeleyje_src_test_java_com_thinkaurelius_titan_BerkeleyStorageSetup.java
1,586
public class Entity implements Serializable { protected static final long serialVersionUID = 1L; protected String[] type; protected Property[] properties; protected boolean isDirty = false; protected Boolean isDeleted = false; protected Boolean isInactive = false; protected Boolean isActive = false; protected Boolean isLocked = false; protected String lockedBy; protected String lockedDate; protected boolean multiPartAvailableOnThread = false; protected boolean isValidationFailure = false; protected Map<String, List<String>> validationErrors = new HashMap<String, List<String>>(); protected Map<String, Property> pMap = null; public String[] getType() { return type; } public void setType(String[] type) { if (type != null && type.length > 0) { Arrays.sort(type); } this.type = type; } public Map<String, Property> getPMap() { if (pMap == null) { pMap = BLCMapUtils.keyedMap(properties, new TypedClosure<String, Property>() { @Override public String getKey(Property value) { return value.getName(); } }); } return pMap; } public Property[] getProperties() { return properties; } public void setProperties(Property[] properties) { this.properties = properties; pMap = null; } public void mergeProperties(String prefix, Entity entity) { int j = 0; Property[] merged = new Property[properties.length + entity.getProperties().length]; for (Property property : properties) { merged[j] = property; j++; } for (Property property : entity.getProperties()) { property.setName(prefix!=null?prefix+"."+property.getName():""+property.getName()); merged[j] = property; j++; } properties = merged; } /** * Replaces all property values in this entity with the values from the given entity. This also resets the {@link #pMap} * * @param entity */ public void overridePropertyValues(Entity entity) { for (Property property : entity.getProperties()) { Property myProperty = findProperty(property.getName()); if (myProperty != null) { myProperty.setValue(property.getValue()); myProperty.setRawValue(property.getRawValue()); } } pMap = null; } public Property findProperty(String name) { Arrays.sort(properties, new Comparator<Property>() { @Override public int compare(Property o1, Property o2) { if (o1 == null && o2 == null) { return 0; } else if (o1 == null) { return 1; } else if (o2 == null) { return -1; } return o1.getName().compareTo(o2.getName()); } }); Property searchProperty = new Property(); searchProperty.setName(name); int index = Arrays.binarySearch(properties, searchProperty, new Comparator<Property>() { @Override public int compare(Property o1, Property o2) { if (o1 == null && o2 == null) { return 0; } else if (o1 == null) { return 1; } else if (o2 == null) { return -1; } return o1.getName().compareTo(o2.getName()); } }); if (index >= 0) { return properties[index]; } return null; } public void addProperty(Property property) { Property[] allProps = getProperties(); Property[] newProps = new Property[allProps.length + 1]; for (int j=0;j<allProps.length;j++) { newProps[j] = allProps[j]; } newProps[newProps.length - 1] = property; setProperties(newProps); } /** * Adds a single validation error to this entity. This will also set the entire * entity in an error state by invoking {@link #setValidationFailure(boolean)}. * * @param fieldName - the field that is in error. This works on top-level properties (like a 'manufacturer' field on a * Product entity) but can also work on properties gleaned from a related entity (like * 'defaultSku.weight.weightUnitOfMeasure' on a Product entity) * @param errorOrErrorKey - the error message to present to a user. Could be the actual error message or a key to a * property in messages.properties to support different locales */ public void addValidationError(String fieldName, String errorOrErrorKey) { Map<String, List<String>> fieldErrors = getValidationErrors(); List<String> errorMessages = fieldErrors.get(fieldName); if (errorMessages == null) { errorMessages = new ArrayList<String>(); fieldErrors.put(fieldName, errorMessages); } errorMessages.add(errorOrErrorKey); setValidationFailure(true); } public boolean isDirty() { return isDirty; } public void setDirty(boolean dirty) { isDirty = dirty; } public boolean isMultiPartAvailableOnThread() { return multiPartAvailableOnThread; } public void setMultiPartAvailableOnThread(boolean multiPartAvailableOnThread) { this.multiPartAvailableOnThread = multiPartAvailableOnThread; } /** * * @return if this entity has failed validation. This will also check the {@link #getValidationErrors()} map if this * boolean has not been explicitly set */ public boolean isValidationFailure() { if (!getValidationErrors().isEmpty()) { isValidationFailure = true; } return isValidationFailure; } public void setValidationFailure(boolean validationFailure) { isValidationFailure = validationFailure; } /** * Validation error map where the key corresponds to the property that failed validation (which could be dot-separated) * and the value corresponds to a list of the error messages, in the case of multiple errors on the same field. * * For instance, you might have a configuration where the field is both a Required validator and a regex validator. * The validation map in this case might contain something like: * * defaultSku.name => ['This field is required', 'Cannot have numbers in name'] * * @return a map keyed by property name to the list of error messages for that property */ public Map<String, List<String>> getValidationErrors() { return validationErrors; } /** * Completely reset the validation errors for this Entity. In most cases it is more appropriate to use the convenience * method for adding a single error via {@link #addValidationError(String, String)}. This will also set the entire * entity in an error state by invoking {@link #setValidationFailure(boolean)}. * * @param validationErrors * @see #addValidationError(String, String) */ public void setValidationErrors(Map<String, List<String>> validationErrors) { if (MapUtils.isNotEmpty(validationErrors)) { setValidationFailure(true); } this.validationErrors = validationErrors; } public Boolean getActive() { return isActive; } public void setActive(Boolean active) { isActive = active; } public Boolean getDeleted() { return isDeleted; } public void setDeleted(Boolean deleted) { isDeleted = deleted; } public Boolean getInactive() { return isInactive; } public void setInactive(Boolean inactive) { isInactive = inactive; } public Boolean getLocked() { return isLocked; } public void setLocked(Boolean locked) { isLocked = locked; } public String getLockedBy() { return lockedBy; } public void setLockedBy(String lockedBy) { this.lockedBy = lockedBy; } public String getLockedDate() { return lockedDate; } public void setLockedDate(String lockedDate) { this.lockedDate = lockedDate; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Entity)) return false; Entity entity = (Entity) o; if (isDirty != entity.isDirty) return false; if (isValidationFailure != entity.isValidationFailure) return false; if (multiPartAvailableOnThread != entity.multiPartAvailableOnThread) return false; if (isActive != null ? !isActive.equals(entity.isActive) : entity.isActive != null) return false; if (isDeleted != null ? !isDeleted.equals(entity.isDeleted) : entity.isDeleted != null) return false; if (isInactive != null ? !isInactive.equals(entity.isInactive) : entity.isInactive != null) return false; if (isLocked != null ? !isLocked.equals(entity.isLocked) : entity.isLocked != null) return false; if (lockedBy != null ? !lockedBy.equals(entity.lockedBy) : entity.lockedBy != null) return false; if (lockedDate != null ? !lockedDate.equals(entity.lockedDate) : entity.lockedDate != null) return false; if (!Arrays.equals(properties, entity.properties)) return false; if (!Arrays.equals(type, entity.type)) return false; return true; } @Override public int hashCode() { int result = type != null ? Arrays.hashCode(type) : 0; result = 31 * result + (properties != null ? Arrays.hashCode(properties) : 0); result = 31 * result + (isDirty ? 1 : 0); result = 31 * result + (isDeleted != null ? isDeleted.hashCode() : 0); result = 31 * result + (isInactive != null ? isInactive.hashCode() : 0); result = 31 * result + (isActive != null ? isActive.hashCode() : 0); result = 31 * result + (isLocked != null ? isLocked.hashCode() : 0); result = 31 * result + (lockedBy != null ? lockedBy.hashCode() : 0); result = 31 * result + (lockedDate != null ? lockedDate.hashCode() : 0); result = 31 * result + (multiPartAvailableOnThread ? 1 : 0); result = 31 * result + (isValidationFailure ? 1 : 0); return result; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_Entity.java
318
public class OStorageDataConfiguration extends OStorageSegmentConfiguration { private static final long serialVersionUID = 1L; public OStorageDataHoleConfiguration holeFile; private static final String START_SIZE = "1Mb"; private static final String INCREMENT_SIZE = "100%"; public OStorageDataConfiguration(final OStorageConfiguration iRoot, final String iSegmentName, final int iId) { super(iRoot, iSegmentName, iId); fileStartSize = START_SIZE; fileIncrementSize = INCREMENT_SIZE; } public OStorageDataConfiguration(final OStorageConfiguration iRoot, final String iSegmentName, final int iId, final String iDirectory) { super(iRoot, iSegmentName, iId, iDirectory); fileStartSize = START_SIZE; fileIncrementSize = INCREMENT_SIZE; } @Override public void setRoot(final OStorageConfiguration root) { super.setRoot(root); holeFile.parent = this; } }
0true
core_src_main_java_com_orientechnologies_orient_core_config_OStorageDataConfiguration.java
147
public class TestLogPruneStrategy { @Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule(); private EphemeralFileSystemAbstraction FS; private File directory; @Before public void before() { FS = fs.get(); directory = TargetDirectory.forTest( FS, getClass() ).cleanDirectory( "prune" ); } @Test public void noPruning() throws Exception { MockedLogLoader log = new MockedLogLoader( LogPruneStrategies.NO_PRUNING ); for ( int i = 0; i < 100; i++ ) { log.addTransactionsUntilRotationHappens(); assertLogsRangeExists( log, 0, log.getHighestLogVersion()-1 ); } assertEquals( 100, log.getHighestLogVersion() ); } @Test public void pruneByFileCountWhereAllContainsFilesTransactions() throws Exception { int fileCount = 5; MockedLogLoader log = new MockedLogLoader( LogPruneStrategies.nonEmptyFileCount( FS, fileCount ) ); for ( int i = 0; i < 100; i++ ) { log.addTransactionsUntilRotationHappens(); long from = Math.max( 0, log.getHighestLogVersion()-fileCount ); assertLogsRangeExists( log, from, log.getHighestLogVersion()-1 ); } } @Test public void pruneByFileCountWhereSomeAreEmpty() throws Exception { MockedLogLoader log = new MockedLogLoader( LogPruneStrategies.nonEmptyFileCount( FS, 3 ) ); // v0 with transactions in it log.addTransactionsUntilRotationHappens(); assertLogsRangeExists( log, 0, 0 ); // v1 empty log.rotate(); assertLogsRangeExists( log, 0, 1, empty( 1 ) ); // v2 empty log.rotate(); assertLogsRangeExists( log, 0, 2, empty( 1, 2 ) ); // v3 with transactions in it log.addTransactionsUntilRotationHappens(); assertLogsRangeExists( log, 0, 3, empty( 1, 2 ) ); // v4 with transactions in it log.addTransactionsUntilRotationHappens(); assertLogsRangeExists( log, 0, 4, empty( 1, 2 ) ); // v5 empty log.rotate(); assertLogsRangeExists( log, 0, 5, empty( 1, 2, 5 ) ); // v6 with transactions in it log.addTransactionsUntilRotationHappens(); assertLogsRangeExists( log, 3, 6, empty( 5 ) ); } @Test public void pruneByFileSize() throws Exception { int maxSize = MAX_LOG_SIZE*5; MockedLogLoader log = new MockedLogLoader( LogPruneStrategies.totalFileSize( FS, maxSize ) ); for ( int i = 0; i < 100; i++ ) { log.addTransactionsUntilRotationHappens(); assertTrue( log.getTotalSizeOfAllExistingLogFiles() < (maxSize+MAX_LOG_SIZE) ); } } @Test public void pruneByTransactionCount() throws Exception { MockedLogLoader log = new MockedLogLoader( 10000, LogPruneStrategies.transactionCount( FS, 1000 ) ); for ( int i = 1; i < 100; i++ ) { log.addTransactionsUntilRotationHappens(); int avg = (int)(log.getLastCommittedTxId()/i); assertTrue( log.getTotalTransactionCountOfAllExistingLogFiles() < avg*(i+1 /*+1 here is because the whole log which a transaction spills over in is kept also*/) ); } } @Test public void pruneByTransactionTimeSpan() throws Exception { /* * T: -----------------------------------------> * 0 ======= * 1 ======== * 2 ============ * A ======= * KEEP <----------------------> * * Prune 0 in the example above */ int seconds = 1; int millisToKeep = (int) (SECONDS.toMillis( seconds ) / 10); MockedLogLoader log = new MockedLogLoader( LogPruneStrategies.transactionTimeSpan( FS, millisToKeep, MILLISECONDS ) ); long end = System.currentTimeMillis() + SECONDS.toMillis( seconds ); long lastTimestamp = System.currentTimeMillis(); while ( true ) { lastTimestamp = System.currentTimeMillis(); if ( log.addTransaction( 15, lastTimestamp ) ) { assertLogRangeByTimestampExists( log, millisToKeep, lastTimestamp ); if ( System.currentTimeMillis() > end ) { break; } } } } @Test public void makeSureOneLogStaysEvenWhenZeroFilesIsConfigured() throws Exception { makeSureOneLogStaysEvenWhenZeroConfigured( new MockedLogLoader( LogPruneStrategies.nonEmptyFileCount( FS, 0 ) ) ); } @Test public void makeSureOneLogStaysEvenWhenZeroSpaceIsConfigured() throws Exception { makeSureOneLogStaysEvenWhenZeroConfigured( new MockedLogLoader( LogPruneStrategies.totalFileSize( FS, 0 ) ) ); } @Test public void makeSureOneLogStaysEvenWhenZeroTransactionsIsConfigured() throws Exception { makeSureOneLogStaysEvenWhenZeroConfigured( new MockedLogLoader( LogPruneStrategies.transactionCount( FS, 0 ) ) ); } @Test public void makeSureOneLogStaysEvenWhenZeroTimeIsConfigured() throws Exception { makeSureOneLogStaysEvenWhenZeroConfigured( new MockedLogLoader( LogPruneStrategies.transactionTimeSpan( FS, 0, SECONDS ) ) ); } private void makeSureOneLogStaysEvenWhenZeroConfigured( MockedLogLoader mockedLogLoader ) throws Exception { MockedLogLoader log = new MockedLogLoader( LogPruneStrategies.nonEmptyFileCount( FS, 0 ) ); log.rotate(); assertLogsRangeExists( log, 0, 0, empty( 0 ) ); log.rotate(); assertLogsRangeExists( log, 0, 1, empty( 0, 1 ) ); log.addTransactionsUntilRotationHappens(); assertLogsRangeExists( log, 2, 2, empty() ); log.addTransactionsUntilRotationHappens(); assertLogsRangeExists( log, 3, 3, empty() ); } private void assertLogRangeByTimestampExists( MockedLogLoader log, int millisToKeep, long lastTimestamp ) { long lowerLimit = lastTimestamp - millisToKeep; for ( long version = log.getHighestLogVersion() - 1; version >= 0; version-- ) { Long firstTimestamp = log.getFirstStartRecordTimestamp( version+1 ); if ( firstTimestamp == null ) { break; } assertTrue( "Log " + version + " should've been deleted by now. first of " + (version+1) + ":" + firstTimestamp + ", highestVersion:" + log.getHighestLogVersion() + ", lowerLimit:" + lowerLimit + ", timestamp:" + lastTimestamp, firstTimestamp >= lowerLimit ); } } private void assertLogsRangeExists( MockedLogLoader log, long from, long to ) { assertLogsRangeExists( log, from, to, empty() ); } private void assertLogsRangeExists( MockedLogLoader log, long from, long to, Set<Long> empty ) { assertTrue( log.getHighestLogVersion() >= to ); for ( long i = 0; i < from; i++ ) { assertFalse( "Log v" + i + " shouldn't exist when highest version is " + log.getHighestLogVersion() + " and prune strategy " + log.pruning, FS.fileExists( log.getFileName( i ) ) ); } for ( long i = from; i <= to; i++ ) { File file = log.getFileName( i ); assertTrue( "Log v" + i + " should exist when highest version is " + log.getHighestLogVersion() + " and prune strategy " + log.pruning, FS.fileExists( file ) ); if ( empty.contains( i ) ) { assertEquals( "Log v" + i + " should be empty", LogIoUtils.LOG_HEADER_SIZE, FS.getFileSize( file ) ); empty.remove( i ); } else { assertTrue( "Log v" + i + " should be at least size " + log.getLogSize(), FS.getFileSize( file ) >= log.getLogSize() ); } } assertTrue( "Expected to find empty logs: " + empty, empty.isEmpty() ); } private Set<Long> empty( long... items ) { Set<Long> result = new HashSet<Long>(); for ( long item : items ) { result.add( item ); } return result; } private static final int MAX_LOG_SIZE = 1000; private static final byte[] RESOURCE_XID = new byte[] { 5,6,7,8,9 }; /** * A subset of what XaLogicaLog is. It's a LogLoader, add transactions to it's active log file, * and also rotate when max file size is reached. It uses the real xa command * serialization/deserialization so it's only the {@link LogLoader} aspect that is mocked. */ private class MockedLogLoader implements LogLoader { private long version; private long tx; private final File baseFile; private final ByteBuffer activeBuffer; private final int identifier = 1; private final LogPruneStrategy pruning; private final Map<Long, Long> lastCommittedTxs = new HashMap<Long, Long>(); private final Map<Long, Long> timestamps = new HashMap<Long, Long>(); private final int logSize; MockedLogLoader( LogPruneStrategy pruning ) { this( MAX_LOG_SIZE, pruning ); } MockedLogLoader( int logSize, LogPruneStrategy pruning ) { this.logSize = logSize; this.pruning = pruning; activeBuffer = ByteBuffer.allocate( logSize*10 ); baseFile = new File( directory, "log" ); clearAndWriteHeader(); } public int getLogSize() { return logSize; } private void clearAndWriteHeader() { activeBuffer.clear(); LogIoUtils.writeLogHeader( activeBuffer, version, tx ); // Because writeLogHeader does flip() activeBuffer.limit( activeBuffer.capacity() ); activeBuffer.position( LogIoUtils.LOG_HEADER_SIZE ); } @Override public ReadableByteChannel getLogicalLogOrMyselfCommitted( long version, long position ) throws IOException { throw new UnsupportedOperationException(); } @Override public long getHighestLogVersion() { return version; } @Override public File getFileName( long version ) { File file = new File( baseFile + ".v" + version ); return file; } /** * @param date start record date. * @return whether or not this caused a rotation to happen. * @throws IOException */ public boolean addTransaction( int commandSize, long date ) throws IOException { InMemoryLogBuffer tempLogBuffer = new InMemoryLogBuffer(); XidImpl xid = new XidImpl( getNewGlobalId( DEFAULT_SEED, 0 ), RESOURCE_XID ); LogIoUtils.writeStart( tempLogBuffer, identifier, xid, -1, -1, date, Long.MAX_VALUE ); LogIoUtils.writeCommand( tempLogBuffer, identifier, new TestXaCommand( commandSize ) ); LogIoUtils.writeCommit( false, tempLogBuffer, identifier, ++tx, date ); LogIoUtils.writeDone( tempLogBuffer, identifier ); tempLogBuffer.read( activeBuffer ); if ( !timestamps.containsKey( version ) ) { timestamps.put( version, date ); // The first tx timestamp for this version } boolean rotate = (activeBuffer.capacity() - activeBuffer.remaining()) >= logSize; if ( rotate ) { rotate(); } return rotate; } /** * @return the total size of the previous log (currently {@link #getHighestLogVersion()}-1 */ public void addTransactionsUntilRotationHappens() throws IOException { int size = 10; while ( true ) { if ( addTransaction( size, System.currentTimeMillis() ) ) { return; } size = Math.max( 10, (size + 7)%100 ); } } public void rotate() throws IOException { lastCommittedTxs.put( version, tx ); writeBufferToFile( activeBuffer, getFileName( version++ ) ); pruning.prune( this ); clearAndWriteHeader(); } private void writeBufferToFile( ByteBuffer buffer, File fileName ) throws IOException { StoreChannel channel = null; try { buffer.flip(); channel = FS.open( fileName, "rw" ); channel.write( buffer ); } finally { if ( channel != null ) { channel.close(); } } } public int getTotalSizeOfAllExistingLogFiles() { int size = 0; for ( long version = getHighestLogVersion()-1; version >= 0; version-- ) { File file = getFileName( version ); if ( FS.fileExists( file ) ) { size += FS.getFileSize( file ); } else { break; } } return size; } public int getTotalTransactionCountOfAllExistingLogFiles() { if ( getHighestLogVersion() == 0 ) { return 0; } long upper = getHighestLogVersion()-1; long lower = upper; while ( lower >= 0 ) { File file = getFileName( lower-1 ); if ( !FS.fileExists( file ) ) { break; } else { lower--; } } return (int) (getLastCommittedTxId() - getFirstCommittedTxId( lower )); } @Override public Long getFirstCommittedTxId( long version ) { return lastCommittedTxs.get( version ); } @Override public Long getFirstStartRecordTimestamp( long version ) { return timestamps.get( version ); } @Override public long getLastCommittedTxId() { return tx; } } private static class TestXaCommand extends XaCommand { private final int totalSize; public TestXaCommand( int totalSize ) { this.totalSize = totalSize; } @Override public void execute() { // Do nothing } @Override public void writeToFile( LogBuffer buffer ) throws IOException { buffer.putInt( totalSize ); buffer.put( new byte[totalSize-4/*size of the totalSize integer*/] ); } } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestLogPruneStrategy.java
1,284
public class ClusterModule extends AbstractModule implements SpawnModules { private final Settings settings; public ClusterModule(Settings settings) { this.settings = settings; } @Override public Iterable<? extends Module> spawnModules() { return ImmutableList.of(new AllocationModule(settings), new OperationRoutingModule(settings), new ClusterDynamicSettingsModule(), new IndexDynamicSettingsModule()); } @Override protected void configure() { bind(DiscoveryNodeService.class).asEagerSingleton(); bind(ClusterService.class).to(InternalClusterService.class).asEagerSingleton(); bind(MetaDataService.class).asEagerSingleton(); bind(MetaDataCreateIndexService.class).asEagerSingleton(); bind(MetaDataDeleteIndexService.class).asEagerSingleton(); bind(MetaDataIndexStateService.class).asEagerSingleton(); bind(MetaDataMappingService.class).asEagerSingleton(); bind(MetaDataIndexAliasesService.class).asEagerSingleton(); bind(MetaDataUpdateSettingsService.class).asEagerSingleton(); bind(MetaDataIndexTemplateService.class).asEagerSingleton(); bind(RoutingService.class).asEagerSingleton(); bind(ShardStateAction.class).asEagerSingleton(); bind(NodeIndexDeletedAction.class).asEagerSingleton(); bind(NodeMappingRefreshAction.class).asEagerSingleton(); bind(MappingUpdatedAction.class).asEagerSingleton(); bind(ClusterInfoService.class).to(InternalClusterInfoService.class).asEagerSingleton(); } }
0true
src_main_java_org_elasticsearch_cluster_ClusterModule.java
1,576
public class BasicCollectionMetadata extends CollectionMetadata { private AddMethodType addMethodType; public AddMethodType getAddMethodType() { return addMethodType; } public void setAddMethodType(AddMethodType addMethodType) { this.addMethodType = addMethodType; } @Override public void accept(MetadataVisitor visitor) { visitor.visit(this); } @Override protected FieldMetadata populate(FieldMetadata metadata) { ((BasicCollectionMetadata) metadata).addMethodType = addMethodType; return super.populate(metadata); } @Override public FieldMetadata cloneFieldMetadata() { BasicCollectionMetadata basicCollectionMetadata = new BasicCollectionMetadata(); return populate(basicCollectionMetadata); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof BasicCollectionMetadata)) return false; if (!super.equals(o)) return false; BasicCollectionMetadata that = (BasicCollectionMetadata) o; if (addMethodType != that.addMethodType) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (addMethodType != null ? addMethodType.hashCode() : 0); return result; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_dto_BasicCollectionMetadata.java
1,158
threads[i] = new Thread(new Runnable() { @Override public void run() { if (USE_NANO_TIME) { for (long i = 0; i < NUMBER_OF_ITERATIONS; i++) { System.nanoTime(); } } else { for (long i = 0; i < NUMBER_OF_ITERATIONS; i++) { System.currentTimeMillis(); } } latch.countDown(); } });
0true
src_test_java_org_elasticsearch_benchmark_time_SimpleTimeBenchmark.java
99
private static class DeadlockProneTransactionStateFactory extends TransactionStateFactory { private DoubleLatch latch; DeadlockProneTransactionStateFactory( Logging logging ) { super( logging ); } public DoubleLatch installDeadlockLatch() { return this.latch = new DoubleLatch(); } @Override public TransactionState create( javax.transaction.Transaction tx ) { if ( latch != null ) { return new DeadlockProneTransactionState( lockManager, nodeManager, logging, tx, txHook, txIdGenerator, latch ); } return super.create( tx ); } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestCacheUpdateDeadlock.java
373
public class PutRepositoryAction extends ClusterAction<PutRepositoryRequest, PutRepositoryResponse, PutRepositoryRequestBuilder> { public static final PutRepositoryAction INSTANCE = new PutRepositoryAction(); public static final String NAME = "cluster/repository/put"; private PutRepositoryAction() { super(NAME); } @Override public PutRepositoryResponse newResponse() { return new PutRepositoryResponse(); } @Override public PutRepositoryRequestBuilder newRequestBuilder(ClusterAdminClient client) { return new PutRepositoryRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_repositories_put_PutRepositoryAction.java
1
public final class OAlwaysGreaterKey implements Comparable<Comparable<?>>{ public int compareTo(Comparable<?> o) { return 1; } }
0true
commons_src_main_java_com_orientechnologies_common_collection_OAlwaysGreaterKey.java
102
private static class FindNamedArgumentsVisitor extends Visitor implements NaturalVisitor { Tree.NamedArgumentList argumentList; int offset; private Tree.NamedArgumentList getArgumentList() { return argumentList; } private FindNamedArgumentsVisitor(int offset) { this.offset = offset; } @Override public void visit(Tree.NamedArgumentList that) { if (offset>=that.getStartIndex() && offset<=that.getStopIndex()+1) { argumentList = that; } super.visit(that); } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ConvertToPositionalArgumentsProposal.java
75
public interface StaticAsset extends Serializable { /** * Returns the id of the static asset. * @return */ public Long getId(); /** * Sets the id of the static asset. * @param id */ public void setId(Long id); /** * The name of the static asset. * @return */ public String getName(); /** * Sets the name of the static asset. Used primarily for * @param name */ public void setName(String name); /** * Returns the altText of this asset. * * @return */ public String getAltText(); /** * Set the altText of the static asset. * @param title */ public void setAltText(String altText); /** * Returns the title of this asset. * * @return */ public String getTitle(); /** * Set the title of the static asset. * @param title */ public void setTitle(String title); /** * URL used to retrieve this asset. * @return */ public String getFullUrl(); /** * Sets the URL for the asset * @param fullUrl */ public void setFullUrl(String fullUrl); /** * Filesize of the asset. * @return */ public Long getFileSize(); /** * Sets the filesize of the asset * @param fileSize */ public void setFileSize(Long fileSize); /** * @deprecated - Use {@link #getTitle()} or {@link #getAltText()}getAltText() instead. * @return */ public Map<String, StaticAssetDescription> getContentMessageValues(); /** * @deprecated - Use {@link #setTitle(String)} or {@link #setAltText(String)} instead. * @param contentMessageValues */ public void setContentMessageValues(Map<String, StaticAssetDescription> contentMessageValues); /** * Returns the mimeType of the asset. * @return */ public String getMimeType(); /** * Sets the mimeType of the asset. * @return */ public void setMimeType(String mimeType); /** * Returns the file extension of the asset. * @return */ public String getFileExtension(); /** * Sets the fileExtension of the asset. * @param fileExtension */ public void setFileExtension(String fileExtension); /** * Returns how the underlying asset is stored. Typically on the FileSystem or the Database. * * If null, this method returns <code>StorageType.DATABASE</code> for backwards compatibility. * * @see {@link StaticAssetService} * @return */ public StorageType getStorageType(); /** * Returns how the asset was stored in the backend (e.g. DATABASE or FILESYSTEM) * @param storageType */ public void setStorageType(StorageType storageType); /** * @deprecated - not currently used * @return */ public Site getSite(); /** * @deprecated - not currently used * @param site */ public void setSite(Site site); public SandBox getOriginalSandBox(); public void setOriginalSandBox(SandBox originalSandBox); public AdminAuditable getAuditable(); public void setAuditable(AdminAuditable auditable); public Boolean getLockedFlag(); public void setLockedFlag(Boolean lockedFlag); public Boolean getDeletedFlag(); public void setDeletedFlag(Boolean deletedFlag); public Boolean getArchivedFlag(); public void setArchivedFlag(Boolean archivedFlag); public Long getOriginalAssetId(); public void setOriginalAssetId(Long originalPageId); public SandBox getSandbox(); public void setSandbox(SandBox sandbox); public StaticAsset cloneEntity(); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_domain_StaticAsset.java
966
private class AsyncAction { private final Request request; private final String[] nodesIds; private final ActionListener<Response> listener; private final ClusterState clusterState; private final AtomicReferenceArray<Object> responses; private final AtomicInteger counter = new AtomicInteger(); private AsyncAction(Request request, ActionListener<Response> listener) { this.request = request; this.listener = listener; clusterState = clusterService.state(); String[] nodesIds = clusterState.nodes().resolveNodesIds(request.nodesIds()); this.nodesIds = filterNodeIds(clusterState.nodes(), nodesIds); this.responses = new AtomicReferenceArray<Object>(this.nodesIds.length); } private void start() { if (nodesIds.length == 0) { // nothing to notify threadPool.generic().execute(new Runnable() { @Override public void run() { listener.onResponse(newResponse(request, responses)); } }); return; } TransportRequestOptions transportRequestOptions = TransportRequestOptions.options(); if (request.timeout() != null) { transportRequestOptions.withTimeout(request.timeout()); } transportRequestOptions.withCompress(transportCompress()); for (int i = 0; i < nodesIds.length; i++) { final String nodeId = nodesIds[i]; final int idx = i; final DiscoveryNode node = clusterState.nodes().nodes().get(nodeId); try { if (nodeId.equals("_local") || nodeId.equals(clusterState.nodes().localNodeId())) { threadPool.executor(executor()).execute(new Runnable() { @Override public void run() { try { onOperation(idx, nodeOperation(newNodeRequest(clusterState.nodes().localNodeId(), request))); } catch (Throwable e) { onFailure(idx, clusterState.nodes().localNodeId(), e); } } }); } else if (nodeId.equals("_master")) { threadPool.executor(executor()).execute(new Runnable() { @Override public void run() { try { onOperation(idx, nodeOperation(newNodeRequest(clusterState.nodes().masterNodeId(), request))); } catch (Throwable e) { onFailure(idx, clusterState.nodes().masterNodeId(), e); } } }); } else { if (node == null) { onFailure(idx, nodeId, new NoSuchNodeException(nodeId)); } else { NodeRequest nodeRequest = newNodeRequest(nodeId, request); transportService.sendRequest(node, transportNodeAction, nodeRequest, transportRequestOptions, new BaseTransportResponseHandler<NodeResponse>() { @Override public NodeResponse newInstance() { return newNodeResponse(); } @Override public void handleResponse(NodeResponse response) { onOperation(idx, response); } @Override public void handleException(TransportException exp) { onFailure(idx, node.id(), exp); } @Override public String executor() { return ThreadPool.Names.SAME; } }); } } } catch (Throwable t) { onFailure(idx, nodeId, t); } } } private void onOperation(int idx, NodeResponse nodeResponse) { responses.set(idx, nodeResponse); if (counter.incrementAndGet() == responses.length()) { finishHim(); } } private void onFailure(int idx, String nodeId, Throwable t) { if (logger.isDebugEnabled()) { logger.debug("failed to execute on node [{}]", t, nodeId); } if (accumulateExceptions()) { responses.set(idx, new FailedNodeException(nodeId, "Failed node [" + nodeId + "]", t)); } if (counter.incrementAndGet() == responses.length()) { finishHim(); } } private void finishHim() { Response finalResponse; try { finalResponse = newResponse(request, responses); } catch (Throwable t) { logger.debug("failed to combine responses from nodes", t); listener.onFailure(t); return; } listener.onResponse(finalResponse); } }
0true
src_main_java_org_elasticsearch_action_support_nodes_TransportNodesOperationAction.java
1,479
public final static class UnassignedShards implements Iterable<MutableShardRouting> { private final List<MutableShardRouting> unassigned; private int primaries = 0; private long transactionId = 0; private final UnassignedShards source; private final long sourceTransactionId; public UnassignedShards(UnassignedShards other) { source = other; sourceTransactionId = other.transactionId; unassigned = new ArrayList<MutableShardRouting>(other.unassigned); primaries = other.primaries; } public UnassignedShards() { unassigned = new ArrayList<MutableShardRouting>(); source = null; sourceTransactionId = -1; } public void add(MutableShardRouting mutableShardRouting) { if(mutableShardRouting.primary()) { primaries++; } unassigned.add(mutableShardRouting); transactionId++; } public void addAll(Collection<MutableShardRouting> mutableShardRoutings) { for (MutableShardRouting r : mutableShardRoutings) { add(r); } } public int size() { return unassigned.size(); } public int numPrimaries() { return primaries; } @Override public Iterator<MutableShardRouting> iterator() { final Iterator<MutableShardRouting> iterator = unassigned.iterator(); return new Iterator<MutableShardRouting>() { private MutableShardRouting current; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public MutableShardRouting next() { return current = iterator.next(); } @Override public void remove() { iterator.remove(); if (current.primary()) { primaries--; } transactionId++; } }; } public boolean isEmpty() { return unassigned.isEmpty(); } public void shuffle() { Collections.shuffle(unassigned); } public void clear() { transactionId++; unassigned.clear(); primaries = 0; } public void transactionEnd(UnassignedShards shards) { assert shards.source == this && shards.sourceTransactionId == transactionId : "Expected ID: " + shards.sourceTransactionId + " actual: " + transactionId + " Expected Source: " + shards.source + " actual: " + this; transactionId++; this.unassigned.clear(); this.unassigned.addAll(shards.unassigned); this.primaries = shards.primaries; } public UnassignedShards transactionBegin() { return new UnassignedShards(this); } public MutableShardRouting[] drain() { MutableShardRouting[] mutableShardRoutings = unassigned.toArray(new MutableShardRouting[unassigned.size()]); unassigned.clear(); primaries = 0; transactionId++; return mutableShardRoutings; } }
0true
src_main_java_org_elasticsearch_cluster_routing_RoutingNodes.java
731
public class DeleteByQueryAction extends Action<DeleteByQueryRequest, DeleteByQueryResponse, DeleteByQueryRequestBuilder> { public static final DeleteByQueryAction INSTANCE = new DeleteByQueryAction(); public static final String NAME = "deleteByQuery"; private DeleteByQueryAction() { super(NAME); } @Override public DeleteByQueryResponse newResponse() { return new DeleteByQueryResponse(); } @Override public DeleteByQueryRequestBuilder newRequestBuilder(Client client) { return new DeleteByQueryRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_deletebyquery_DeleteByQueryAction.java
390
new Thread(){ public void run() { mm.forceUnlock(key); forceUnlock.countDown(); } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_multimap_ClientMultiMapLockTest.java
134
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_SC_FLD") @EntityListeners(value = { AdminAuditableListener.class }) public class StructuredContentFieldImpl implements StructuredContentField { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "StructuredContentFieldId") @GenericGenerator( name="StructuredContentFieldId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="StructuredContentFieldImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.cms.structure.domain.StructuredContentFieldImpl") } ) @Column(name = "SC_FLD_ID") protected Long id; @Embedded @AdminPresentation(excluded = true) protected AdminAuditable auditable = new AdminAuditable(); @Column (name = "FLD_KEY") protected String fieldKey; @ManyToOne(targetEntity = StructuredContentImpl.class) @JoinColumn(name="SC_ID") protected StructuredContent structuredContent; @Column (name = "VALUE") protected String stringValue; @Column (name = "LOB_VALUE", length = Integer.MAX_VALUE - 1) @Lob @Type(type = "org.hibernate.type.StringClobType") protected String lobValue; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getFieldKey() { return fieldKey; } @Override public void setFieldKey(String fieldKey) { this.fieldKey = fieldKey; } @Override public StructuredContent getStructuredContent() { return structuredContent; } @Override public void setStructuredContent(StructuredContent structuredContent) { this.structuredContent = structuredContent; } @Override public String getValue() { if (stringValue != null && stringValue.length() > 0) { return stringValue; } else { return lobValue; } } @Override public void setValue(String value) { if (value != null) { if (value.length() <= 256) { stringValue = value; lobValue = null; } else { stringValue = null; lobValue = value; } } else { lobValue = null; stringValue = null; } } @Override public StructuredContentField cloneEntity() { StructuredContentFieldImpl newContentField = new StructuredContentFieldImpl(); newContentField.fieldKey = fieldKey; newContentField.structuredContent = structuredContent; newContentField.lobValue = lobValue; newContentField.stringValue = stringValue; return newContentField; } @Override public AdminAuditable getAuditable() { return auditable; } @Override public void setAuditable(AdminAuditable auditable) { this.auditable = auditable; } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_domain_StructuredContentFieldImpl.java
1,094
threads[i] = new Thread() { @Override public void run() { try { latch.await(); } catch (InterruptedException e) { return; } while (recycles.getAndDecrement() > 0) { final Recycler.V<?> v = recycler.obtain(); v.release(); } } };
0true
src_test_java_org_elasticsearch_benchmark_common_recycler_RecyclerBenchmark.java