Unnamed: 0
int64
0
6.45k
func
stringlengths
37
143k
target
class label
2 classes
project
stringlengths
33
157
1,510
@Component("blCartStateRequestProcessor") public class CartStateRequestProcessor extends AbstractBroadleafWebRequestProcessor { /** Logger for this class and subclasses */ protected final Log LOG = LogFactory.getLog(getClass()); public static final String BLC_RULE_MAP_PARAM = "blRuleMap"; private String mergeCartResponseKey = "bl_merge_cart_response"; @Resource(name = "blOrderService") protected OrderService orderService; @Resource(name = "blUpdateCartService") protected UpdateCartService updateCartService; @Resource(name = "blMergeCartService") protected MergeCartService mergeCartService; @Resource(name = "blCustomerStateRequestProcessor") protected CustomerStateRequestProcessor customerStateRequestProcessor; protected static String cartRequestAttributeName = "cart"; protected static String anonymousCartSessionAttributeName = "anonymousCart"; @Override public void process(WebRequest request) { Customer customer = CustomerState.getCustomer(); if (customer == null) { LOG.warn("No customer was found on the current request, no cart will be added to the current request. Ensure that the" + " blCustomerStateFilter occurs prior to the blCartStateFilter"); return; } Order cart = null; if (mergeCartNeeded(customer, request)) { if (LOG.isDebugEnabled()) { LOG.debug("Merge cart required, calling mergeCart " + customer.getId()); } cart = mergeCart(customer, request); } else { cart = orderService.findCartForCustomer(customer); } if (cart == null) { cart = orderService.getNullOrder(); } else { updateCartService.updateAndValidateCart(cart); } request.setAttribute(cartRequestAttributeName, cart, WebRequest.SCOPE_REQUEST); // Setup cart for content rule processing Map<String, Object> ruleMap = (Map<String, Object>) request.getAttribute(BLC_RULE_MAP_PARAM, WebRequest.SCOPE_REQUEST); if (ruleMap == null) { ruleMap = new HashMap<String, Object>(); } ruleMap.put("order", cart); // Leaving the following line in for backwards compatibility, but all rules should use order as the // variable name. ruleMap.put("cart", cart); request.setAttribute(BLC_RULE_MAP_PARAM, ruleMap, WebRequest.SCOPE_REQUEST); } public boolean mergeCartNeeded(Customer customer, WebRequest request) { Customer anonymousCustomer = customerStateRequestProcessor.getAnonymousCustomer(request); return (anonymousCustomer != null && customer.getId() != null && !customer.getId().equals(anonymousCustomer.getId())); } public Order mergeCart(Customer customer, WebRequest request) { Customer anonymousCustomer = customerStateRequestProcessor.getAnonymousCustomer(request); MergeCartResponse mergeCartResponse; try { Order cart = orderService.findCartForCustomer(anonymousCustomer); mergeCartResponse = mergeCartService.mergeCart(customer, cart); } catch (PricingException e) { throw new RuntimeException(e); } catch (RemoveFromCartException e) { throw new RuntimeException(e); } // The anonymous customer from session is no longer needed; it can be safely removed request.removeAttribute(CustomerStateRequestProcessor.getAnonymousCustomerSessionAttributeName(), WebRequest.SCOPE_GLOBAL_SESSION); request.removeAttribute(CustomerStateRequestProcessor.getAnonymousCustomerIdSessionAttributeName(), WebRequest.SCOPE_GLOBAL_SESSION); request.setAttribute(mergeCartResponseKey, mergeCartResponse, WebRequest.SCOPE_GLOBAL_SESSION); return mergeCartResponse.getOrder(); } public static String getCartRequestAttributeName() { return cartRequestAttributeName; } public static void setCartRequestAttributeName(String cartRequestAttributeName) { CartStateRequestProcessor.cartRequestAttributeName = cartRequestAttributeName; } }
1no label
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_order_security_CartStateRequestProcessor.java
246
assertTrueEventually(new AssertTask() { public void run() throws Exception { assertTrue(map.containsKey(member.getUuid())); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceSubmitTest.java
5,426
static class BytesValues extends org.elasticsearch.index.fielddata.BytesValues { private final FieldDataSource source; private final SearchScript script; private final BytesRef scratch; public BytesValues(FieldDataSource source, SearchScript script) { super(true); this.source = source; this.script = script; scratch = new BytesRef(); } @Override public int setDocument(int docId) { return source.bytesValues().setDocument(docId); } @Override public BytesRef nextValue() { BytesRef value = source.bytesValues().nextValue(); script.setNextVar("_value", value.utf8ToString()); scratch.copyChars(script.run().toString()); return scratch; } }
1no label
src_main_java_org_elasticsearch_search_aggregations_support_FieldDataSource.java
92
public class ReadOnlyTxManager extends AbstractTransactionManager implements Lifecycle { private ThreadLocalWithSize<ReadOnlyTransactionImpl> txThreadMap; private int eventIdentifierCounter = 0; private XaDataSourceManager xaDsManager = null; private final StringLogger logger; private final Factory<byte[]> xidGlobalIdFactory; public ReadOnlyTxManager( XaDataSourceManager xaDsManagerToUse, Factory<byte[]> xidGlobalIdFactory, StringLogger logger ) { xaDsManager = xaDsManagerToUse; this.xidGlobalIdFactory = xidGlobalIdFactory; this.logger = logger; } synchronized int getNextEventIdentifier() { return eventIdentifierCounter++; } @Override public void init() { } @Override public void start() { txThreadMap = new ThreadLocalWithSize<>(); } @Override public void stop() { } @Override public void shutdown() { } @Override public void begin() throws NotSupportedException { if ( txThreadMap.get() != null ) { throw new NotSupportedException( "Nested transactions not supported" ); } txThreadMap.set( new ReadOnlyTransactionImpl( xidGlobalIdFactory.newInstance(), this, logger ) ); } @Override public void commit() throws RollbackException, HeuristicMixedException, IllegalStateException { ReadOnlyTransactionImpl tx = txThreadMap.get(); if ( tx == null ) { throw new IllegalStateException( "Not in transaction" ); } if ( tx.getStatus() != Status.STATUS_ACTIVE && tx.getStatus() != Status.STATUS_MARKED_ROLLBACK ) { throw new IllegalStateException( "Tx status is: " + getTxStatusAsString( tx.getStatus() ) ); } tx.doBeforeCompletion(); if ( tx.getStatus() == Status.STATUS_ACTIVE ) { commit( tx ); } else if ( tx.getStatus() == Status.STATUS_MARKED_ROLLBACK ) { rollbackCommit( tx ); } else { throw new IllegalStateException( "Tx status is: " + getTxStatusAsString( tx.getStatus() ) ); } } private void commit( ReadOnlyTransactionImpl tx ) { if ( tx.getResourceCount() == 0 ) { tx.setStatus( Status.STATUS_COMMITTED ); } tx.doAfterCompletion(); txThreadMap.remove(); tx.setStatus( Status.STATUS_NO_TRANSACTION ); } private void rollbackCommit( ReadOnlyTransactionImpl tx ) throws HeuristicMixedException, RollbackException { try { tx.doRollback(); } catch ( XAException e ) { logger.error( "Unable to rollback marked transaction. " + "Some resources may be commited others not. " + "Neo4j kernel should be SHUTDOWN for " + "resource maintance and transaction recovery ---->", e ); throw Exceptions.withCause( new HeuristicMixedException( "Unable to rollback " + " ---> error code for rollback: " + e.errorCode ), e ); } tx.doAfterCompletion(); txThreadMap.remove(); tx.setStatus( Status.STATUS_NO_TRANSACTION ); throw new RollbackException( "Failed to commit, transaction rolled back" ); } @Override public void rollback() throws IllegalStateException, SystemException { ReadOnlyTransactionImpl tx = txThreadMap.get(); if ( tx == null ) { throw new IllegalStateException( "Not in transaction" ); } if ( tx.getStatus() == Status.STATUS_ACTIVE || tx.getStatus() == Status.STATUS_MARKED_ROLLBACK || tx.getStatus() == Status.STATUS_PREPARING ) { tx.doBeforeCompletion(); try { tx.doRollback(); } catch ( XAException e ) { logger.error("Unable to rollback marked or active transaction. " + "Some resources may be commited others not. " + "Neo4j kernel should be SHUTDOWN for " + "resource maintance and transaction recovery ---->", e ); throw Exceptions.withCause( new SystemException( "Unable to rollback " + " ---> error code for rollback: " + e.errorCode ), e ); } tx.doAfterCompletion(); txThreadMap.remove(); tx.setStatus( Status.STATUS_NO_TRANSACTION ); } else { throw new IllegalStateException( "Tx status is: " + getTxStatusAsString( tx.getStatus() ) ); } } @Override public int getStatus() { ReadOnlyTransactionImpl tx = txThreadMap.get(); if ( tx != null ) { return tx.getStatus(); } return Status.STATUS_NO_TRANSACTION; } @Override public Transaction getTransaction() { return txThreadMap.get(); } @Override public void resume( Transaction tx ) throws IllegalStateException { if ( txThreadMap.get() != null ) { throw new IllegalStateException( "Transaction already associated" ); } if ( tx != null ) { ReadOnlyTransactionImpl txImpl = (ReadOnlyTransactionImpl) tx; if ( txImpl.getStatus() != Status.STATUS_NO_TRANSACTION ) { txImpl.markAsActive(); txThreadMap.set( txImpl ); } } } @Override public Transaction suspend() { ReadOnlyTransactionImpl tx = txThreadMap.get(); txThreadMap.remove(); if ( tx != null ) { tx.markAsSuspended(); } return tx; } @Override public void setRollbackOnly() throws IllegalStateException { ReadOnlyTransactionImpl tx = txThreadMap.get(); if ( tx == null ) { throw new IllegalStateException( "Not in transaction" ); } tx.setRollbackOnly(); } @Override public void setTransactionTimeout( int seconds ) { } byte[] getBranchId( XAResource xaRes ) { if ( xaRes instanceof XaResource ) { byte branchId[] = ((XaResource) xaRes).getBranchId(); if ( branchId != null ) { return branchId; } } return xaDsManager.getBranchId( xaRes ); } String getTxStatusAsString( int status ) { switch ( status ) { case Status.STATUS_ACTIVE: return "STATUS_ACTIVE"; case Status.STATUS_NO_TRANSACTION: return "STATUS_NO_TRANSACTION"; case Status.STATUS_PREPARING: return "STATUS_PREPARING"; case Status.STATUS_PREPARED: return "STATUS_PREPARED"; case Status.STATUS_COMMITTING: return "STATUS_COMMITING"; case Status.STATUS_COMMITTED: return "STATUS_COMMITED"; case Status.STATUS_ROLLING_BACK: return "STATUS_ROLLING_BACK"; case Status.STATUS_ROLLEDBACK: return "STATUS_ROLLEDBACK"; case Status.STATUS_UNKNOWN: return "STATUS_UNKNOWN"; case Status.STATUS_MARKED_ROLLBACK: return "STATUS_MARKED_ROLLBACK"; default: return "STATUS_UNKNOWN(" + status + ")"; } } @Override public int getEventIdentifier() { TransactionImpl tx = (TransactionImpl) getTransaction(); if ( tx != null ) { return tx.getEventIdentifier(); } return -1; } @Override public void doRecovery() throws Throwable { } @Override public TransactionState getTransactionState() { return TransactionState.NO_STATE; } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_ReadOnlyTxManager.java
166
public class SpeedTestData { protected static final int TIME_WAIT = 200; protected long cycles = 1; protected long cyclesDone = 0; protected final static int DUMP_PERCENT = 10; protected String currentTestName; protected long currentTestTimer; protected long currentTestHeapCommittedMemory; protected long currentTestHeapUsedMemory; protected long currentTestHeapMaxMemory; protected long currentTestNonHeapCommittedMemory; protected long currentTestNonHeapUsedMemory; protected long currentTestNonHeapMaxMemory; protected SpeedTestGroup testGroup; protected Object[] configuration; protected boolean printResults = true; protected long partialTimer = 0; protected int partialTimerCounter = 0; private long cyclesElapsed; protected SpeedTestData() { } protected SpeedTestData(final long iCycles) { cycles = iCycles; } protected SpeedTestData(final SpeedTestGroup iGroup) { setTestGroup(iGroup); } public SpeedTestData config(final Object... iArgs) { configuration = iArgs; return this; } public void go(final SpeedTest iTarget) { currentTestName = iTarget.getClass().getSimpleName(); try { if (SpeedTestData.executeInit(iTarget, configuration)) executeTest(iTarget, configuration); } finally { collectResults(takeTimer()); SpeedTestData.executeDeinit(iTarget, configuration); } } /* * (non-Javadoc) * * @see com.orientechnologies.common.test.SpeedTest#startTimer(java.lang.String) */ public void startTimer(final String iName) { Runtime.getRuntime().runFinalization(); Runtime.getRuntime().gc(); try { Thread.sleep(TIME_WAIT); } catch (InterruptedException e) { } final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); final MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage(); final MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage(); currentTestName = iName; currentTestHeapCommittedMemory = heapMemoryUsage.getCommitted(); currentTestHeapUsedMemory = heapMemoryUsage.getUsed(); currentTestHeapMaxMemory = heapMemoryUsage.getMax(); currentTestNonHeapCommittedMemory = nonHeapMemoryUsage.getCommitted(); currentTestNonHeapUsedMemory = nonHeapMemoryUsage.getUsed(); currentTestNonHeapMaxMemory = nonHeapMemoryUsage.getMax(); System.out.println("-> Started the test of '" + currentTestName + "' (" + cycles + " cycles)"); currentTestTimer = System.currentTimeMillis(); } /* * (non-Javadoc) * * @see com.orientechnologies.common.test.SpeedTest#takeTimer() */ public long takeTimer() { return System.currentTimeMillis() - currentTestTimer; } /* * (non-Javadoc) * * @see com.orientechnologies.common.test.SpeedTest#collectResults(long) */ public void collectResults(final long elapsed) { Runtime.getRuntime().runFinalization(); Runtime.getRuntime().gc(); final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); final MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage(); final MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage(); final int objectsPendingFinalizationCount = memoryMXBean.getObjectPendingFinalizationCount(); final long nowHeapCommittedMemory = heapMemoryUsage.getCommitted(); final long nowHeapUsedMemory = heapMemoryUsage.getUsed(); final long nowHeapMaxMemory = heapMemoryUsage.getMax(); final long heapCommittedMemory = nowHeapCommittedMemory - currentTestHeapCommittedMemory; final long heapUsedMemory = nowHeapUsedMemory - currentTestHeapUsedMemory; final long heapMaxMemory = nowHeapMaxMemory - currentTestHeapMaxMemory; final long nowNonHeapCommittedMemory = nonHeapMemoryUsage.getCommitted(); final long nowNonHeapUsedMemory = nonHeapMemoryUsage.getUsed(); final long nowNonHeapMaxMemory = nonHeapMemoryUsage.getMax(); final long nonHeapCommittedMemory = nowNonHeapCommittedMemory - currentTestNonHeapCommittedMemory; final long nonHeapUsedMemory = nowNonHeapUsedMemory - currentTestNonHeapUsedMemory; final long nonHeapMaxMemory = nowNonHeapMaxMemory - currentTestNonHeapMaxMemory; if (printResults) { System.out.println(); System.out.println(" Completed the test of '" + currentTestName + "' in " + elapsed + " ms. Heap memory used: " + nowHeapUsedMemory + " bytes. Non heap memory used: " + nowNonHeapUsedMemory + " ."); System.out.println(" Cycles done.......................: " + cyclesDone + "/" + cycles); System.out.println(" Cycles Elapsed....................: " + cyclesElapsed + " ms"); System.out.println(" Elapsed...........................: " + elapsed + " ms"); System.out.println(" Medium cycle elapsed:.............: " + new BigDecimal((float) elapsed / cyclesDone).toPlainString()); System.out.println(" Cycles per second.................: " + new BigDecimal((float) cyclesDone / elapsed * 1000).toPlainString()); System.out.println(" Committed heap memory diff........: " + heapCommittedMemory + " (" + currentTestHeapCommittedMemory + "->" + nowHeapCommittedMemory + ")"); System.out.println(" Used heap memory diff.............: " + heapUsedMemory + " (" + currentTestHeapUsedMemory + "->" + nowHeapUsedMemory + ")"); System.out.println(" Max heap memory diff..............: " + heapMaxMemory + " (" + currentTestHeapMaxMemory + "->" + nowHeapMaxMemory + ")"); System.out.println(" Committed non heap memory diff....: " + nonHeapCommittedMemory + " (" + currentTestNonHeapCommittedMemory + "->" + nowNonHeapCommittedMemory + ")"); System.out.println(" Used non heap memory diff.........: " + nonHeapUsedMemory + " (" + currentTestNonHeapUsedMemory + "->" + nowNonHeapUsedMemory + ")"); System.out.println(" Max non heap memory diff..........: " + nonHeapMaxMemory + " (" + currentTestNonHeapMaxMemory + "->" + nowNonHeapMaxMemory + ")"); System.out.println(" Objects pending finalization......: " + objectsPendingFinalizationCount); System.out.println(); } if (testGroup != null) { testGroup.setResult("Execution time", currentTestName, elapsed); testGroup.setResult("Free memory", currentTestName, heapCommittedMemory); } currentTestHeapCommittedMemory = heapCommittedMemory; currentTestHeapUsedMemory = heapUsedMemory; currentTestHeapMaxMemory = heapMaxMemory; currentTestNonHeapCommittedMemory = nonHeapCommittedMemory; currentTestNonHeapUsedMemory = nonHeapUsedMemory; currentTestNonHeapMaxMemory = nonHeapMaxMemory; } /* * (non-Javadoc) * * @see com.orientechnologies.common.test.SpeedTest#printSnapshot() */ public long printSnapshot() { final long e = takeTimer(); StringBuilder buffer = new StringBuilder(); buffer.append("Partial timer #"); buffer.append(++partialTimerCounter); buffer.append(" elapsed: "); buffer.append(e); buffer.append(" ms"); if (partialTimer > 0) { buffer.append(" (from last partial: "); buffer.append(e - partialTimer); buffer.append(" ms)"); } System.out.println(buffer); partialTimer = e; return partialTimer; } public long getCycles() { return cycles; } public SpeedTestData setCycles(final long cycles) { this.cycles = cycles; return this; } public SpeedTestGroup getTestGroup() { return testGroup; } public SpeedTestData setTestGroup(final SpeedTestGroup testGroup) { this.testGroup = testGroup; return this; } public Object[] getConfiguration() { return configuration; } protected static boolean executeInit(final SpeedTest iTarget, final Object... iArgs) { try { iTarget.init(); return true; } catch (Throwable t) { System.err.println("Exception caught when executing INIT: " + iTarget.getClass().getSimpleName()); t.printStackTrace(); return false; } } protected long executeTest(final SpeedTest iTarget, final Object... iArgs) { try { startTimer(iTarget.getClass().getSimpleName()); cyclesElapsed = 0; long previousLapTimerElapsed = 0; long lapTimerElapsed = 0; int delta; lapTimerElapsed = System.nanoTime(); for (cyclesDone = 0; cyclesDone < cycles; ++cyclesDone) { iTarget.beforeCycle(); iTarget.cycle(); iTarget.afterCycle(); if (cycles > DUMP_PERCENT && (cyclesDone + 1) % (cycles / DUMP_PERCENT) == 0) { lapTimerElapsed = (System.nanoTime() - lapTimerElapsed) / 1000000; cyclesElapsed += lapTimerElapsed; delta = (int) (previousLapTimerElapsed > 0 ? lapTimerElapsed * 100 / previousLapTimerElapsed - 100 : 0); System.out.print(String.format("\n%3d%% lap elapsed: %7dms, total: %7dms, delta: %+3d%%, forecast: %7dms", (cyclesDone + 1) * 100 / cycles, lapTimerElapsed, cyclesElapsed, delta, cyclesElapsed * cycles / cyclesDone)); previousLapTimerElapsed = lapTimerElapsed; lapTimerElapsed = System.nanoTime(); } } return takeTimer(); } catch (Throwable t) { System.err.println("Exception caught when executing CYCLE test: " + iTarget.getClass().getSimpleName()); t.printStackTrace(); } return -1; } protected static void executeDeinit(final SpeedTest iTarget, final Object... iArgs) { try { iTarget.deinit(); } catch (Throwable t) { System.err.println("Exception caught when executing DEINIT: " + iTarget.getClass().getSimpleName()); t.printStackTrace(); } } public long getCyclesDone() { return cyclesDone; } }
0true
commons_src_test_java_com_orientechnologies_common_test_SpeedTestData.java
334
new Thread() { public void run() { map.tryPut("key1", "value2", 5, TimeUnit.SECONDS); latch.countDown(); } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java
74
public class OSharedResourceAdaptive { private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private final AtomicInteger users = new AtomicInteger(0); private final boolean concurrent; private final int timeout; private final boolean ignoreThreadInterruption; protected OSharedResourceAdaptive() { this.concurrent = true; this.timeout = 0; this.ignoreThreadInterruption = false; } protected OSharedResourceAdaptive(final int iTimeout) { this.concurrent = true; this.timeout = iTimeout; this.ignoreThreadInterruption = false; } protected OSharedResourceAdaptive(final boolean iConcurrent) { this.concurrent = iConcurrent; this.timeout = 0; this.ignoreThreadInterruption = false; } protected OSharedResourceAdaptive(final boolean iConcurrent, final int iTimeout, boolean ignoreThreadInterruption) { this.concurrent = iConcurrent; this.timeout = iTimeout; this.ignoreThreadInterruption = ignoreThreadInterruption; } protected void acquireExclusiveLock() { if (concurrent) if (timeout > 0) { try { if (lock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS)) // OK return; } catch (InterruptedException e) { if (ignoreThreadInterruption) { // IGNORE THE THREAD IS INTERRUPTED: TRY TO RE-LOCK AGAIN try { if (lock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS)) { // OK, RESET THE INTERRUPTED STATE Thread.currentThread().interrupt(); return; } } catch (InterruptedException e2) { Thread.currentThread().interrupt(); } } throw new OLockException("Thread interrupted while waiting for resource of class '" + getClass() + "' with timeout=" + timeout); } throw new OTimeoutException("Timeout on acquiring exclusive lock against resource of class: " + getClass() + " with timeout=" + timeout); } else lock.writeLock().lock(); } protected boolean tryAcquireExclusiveLock() { return !concurrent || lock.writeLock().tryLock(); } protected void acquireSharedLock() { if (concurrent) if (timeout > 0) { try { if (lock.readLock().tryLock(timeout, TimeUnit.MILLISECONDS)) // OK return; } catch (InterruptedException e) { if (ignoreThreadInterruption) { // IGNORE THE THREAD IS INTERRUPTED: TRY TO RE-LOCK AGAIN try { if (lock.readLock().tryLock(timeout, TimeUnit.MILLISECONDS)) { // OK, RESET THE INTERRUPTED STATE Thread.currentThread().interrupt(); return; } } catch (InterruptedException e2) { Thread.currentThread().interrupt(); } } throw new OLockException("Thread interrupted while waiting for resource of class '" + getClass() + "' with timeout=" + timeout); } throw new OTimeoutException("Timeout on acquiring shared lock against resource of class : " + getClass() + " with timeout=" + timeout); } else lock.readLock().lock(); } protected boolean tryAcquireSharedLock() { return !concurrent || lock.readLock().tryLock(); } protected void releaseExclusiveLock() { if (concurrent) lock.writeLock().unlock(); } protected void releaseSharedLock() { if (concurrent) lock.readLock().unlock(); } public int getUsers() { return users.get(); } public int addUser() { return users.incrementAndGet(); } public int removeUser() { if (users.get() < 1) throw new IllegalStateException("Cannot remove user of the shared resource " + toString() + " because no user is using it"); return users.decrementAndGet(); } public boolean isConcurrent() { return concurrent; } /** To use in assert block. */ public boolean assertExclusiveLockHold() { return lock.getWriteHoldCount() > 0; } /** To use in assert block. */ public boolean assertSharedLockHold() { return lock.getReadHoldCount() > 0; } }
1no label
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResourceAdaptive.java
520
public class TypesExistsAction extends IndicesAction<TypesExistsRequest, TypesExistsResponse, TypesExistsRequestBuilder> { public static final TypesExistsAction INSTANCE = new TypesExistsAction(); public static final String NAME = "indices/types/exists"; private TypesExistsAction() { super(NAME); } @Override public TypesExistsResponse newResponse() { return new TypesExistsResponse(); } @Override public TypesExistsRequestBuilder newRequestBuilder(IndicesAdminClient client) { return new TypesExistsRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_exists_types_TypesExistsAction.java
22
static class Edge { private final Vertex start; private final Vertex end; private final String label; private final Map<String, Object> properties = new HashMap<String, Object>(); Edge(Vertex start, String label, Vertex end) { this.label = label; this.end = end; this.start = start; } public String getLabel() { return label; } void setProperty(String key, Object value) { properties.put(key, value); } public Object getProperty(String key) { return properties.get(key); } public Vertex getStart() { return start; } public Vertex getEnd() { return end; } public Vertex getOther(Vertex v) { if (start.equals(v)) return end; else if (end.equals(v)) return start; throw new IllegalArgumentException(); } }
0true
titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java
1,273
@SuppressWarnings("unchecked") public class InternalTransportIndicesAdminClient extends AbstractIndicesAdminClient implements IndicesAdminClient { private final TransportClientNodesService nodesService; private final ThreadPool threadPool; private final ImmutableMap<IndicesAction, TransportActionNodeProxy> actions; @Inject public InternalTransportIndicesAdminClient(Settings settings, TransportClientNodesService nodesService, TransportService transportService, ThreadPool threadPool, Map<String, GenericAction> actions) { this.nodesService = nodesService; this.threadPool = threadPool; MapBuilder<IndicesAction, TransportActionNodeProxy> actionsBuilder = new MapBuilder<IndicesAction, TransportActionNodeProxy>(); for (GenericAction action : actions.values()) { if (action instanceof IndicesAction) { actionsBuilder.put((IndicesAction) action, new TransportActionNodeProxy(settings, action, transportService)); } } this.actions = actionsBuilder.immutableMap(); } @Override public ThreadPool threadPool() { return this.threadPool; } @SuppressWarnings("unchecked") @Override public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> ActionFuture<Response> execute(final IndicesAction<Request, Response, RequestBuilder> action, final Request request) { final TransportActionNodeProxy<Request, Response> proxy = actions.get(action); return nodesService.execute(new TransportClientNodesService.NodeCallback<ActionFuture<Response>>() { @Override public ActionFuture<Response> doWithNode(DiscoveryNode node) throws ElasticsearchException { return proxy.execute(node, request); } }); } @SuppressWarnings("unchecked") @Override public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void execute(final IndicesAction<Request, Response, RequestBuilder> action, final Request request, ActionListener<Response> listener) { final TransportActionNodeProxy<Request, Response> proxy = actions.get(action); nodesService.execute(new TransportClientNodesService.NodeListenerCallback<Response>() { @Override public void doWithNode(DiscoveryNode node, ActionListener<Response> listener) throws ElasticsearchException { proxy.execute(node, request, listener); } }, listener); } }
1no label
src_main_java_org_elasticsearch_client_transport_support_InternalTransportIndicesAdminClient.java
415
private static final class MultiExecutionCallbackWrapper implements MultiExecutionCallback { private final AtomicInteger members; private final MultiExecutionCallback multiExecutionCallback; private final Map<Member, Object> values; private MultiExecutionCallbackWrapper(int memberSize, MultiExecutionCallback multiExecutionCallback) { this.multiExecutionCallback = multiExecutionCallback; this.members = new AtomicInteger(memberSize); values = new HashMap<Member, Object>(memberSize); } public void onResponse(Member member, Object value) { multiExecutionCallback.onResponse(member, value); values.put(member, value); int waitingResponse = members.decrementAndGet(); if (waitingResponse == 0) { onComplete(values); } } public void onComplete(Map<Member, Object> values) { multiExecutionCallback.onComplete(values); } }
0true
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientExecutorServiceProxy.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
325
@Component("blMultiTenantMergeBeanStatusProvider") public class MultiTenantMergeBeanStatusProvider implements MergeBeanStatusProvider { @Override public boolean isProcessingEnabled(Object bean, String beanName, ApplicationContext appCtx) { return appCtx.containsBean("blMultiTenantClassTransformer"); } }
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_MultiTenantMergeBeanStatusProvider.java
1,992
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_ID_GENERATION") public class IdGenerationImpl implements IdGeneration { private static final long serialVersionUID = 1L; @Id @Column(name = "ID_TYPE", nullable=false) protected String type; @Column(name = "ID_MIN", nullable = true) protected Long begin; @Column(name = "ID_MAX", nullable = true) protected Long end; @Column(name = "BATCH_START", nullable = false) protected Long batchStart; @Column(name = "BATCH_SIZE", nullable=false) protected Long batchSize; @Version protected Integer version; public String getType() { return type; } public void setType(String type) { this.type = type; } public Long getBegin() { return begin; } public void setBegin(Long begin) { this.begin = begin; } public Long getEnd() { return end; } public void setEnd(Long end) { this.end = end; } public Long getBatchStart() { return batchStart; } public void setBatchStart(Long batchStart) { this.batchStart = batchStart; } public Long getBatchSize() { return batchSize; } public void setBatchSize(Long batchSize) { this.batchSize = batchSize; } public Integer getVersion() { return version; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((batchSize == null) ? 0 : batchSize.hashCode()); result = prime * result + ((batchStart == null) ? 0 : batchStart.hashCode()); result = prime * result + ((begin == null) ? 0 : begin.hashCode()); result = prime * result + ((end == null) ? 0 : end.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); result = prime * result + ((version == null) ? 0 : version.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; IdGenerationImpl other = (IdGenerationImpl) obj; if (batchSize == null) { if (other.batchSize != null) return false; } else if (!batchSize.equals(other.batchSize)) return false; if (batchStart == null) { if (other.batchStart != null) return false; } else if (!batchStart.equals(other.batchStart)) return false; if (begin == null) { if (other.begin != null) return false; } else if (!begin.equals(other.begin)) return false; if (end == null) { if (other.end != null) return false; } else if (!end.equals(other.end)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } }
1no label
core_broadleaf-profile_src_main_java_org_broadleafcommerce_profile_core_domain_IdGenerationImpl.java
495
public class CloseIndexClusterStateUpdateRequest extends IndicesClusterStateUpdateRequest<CloseIndexClusterStateUpdateRequest> { CloseIndexClusterStateUpdateRequest() { } }
0true
src_main_java_org_elasticsearch_action_admin_indices_close_CloseIndexClusterStateUpdateRequest.java
2,092
public class PutIfAbsentOperation extends BasePutOperation { private boolean successful; public PutIfAbsentOperation(String name, Data dataKey, Data value, long ttl) { super(name, dataKey, value, ttl); } public PutIfAbsentOperation() { } public void run() { dataOldValue = mapService.toData(recordStore.putIfAbsent(dataKey, dataValue, ttl)); successful = dataOldValue == null; } public void afterRun() { if (successful) super.afterRun(); } @Override public Object getResponse() { return dataOldValue; } public boolean shouldBackup() { return successful; } @Override public String toString() { return "PutIfAbsentOperation{" + name + "}"; } }
1no label
hazelcast_src_main_java_com_hazelcast_map_operation_PutIfAbsentOperation.java
360
public class TransportNodesStatsAction extends TransportNodesOperationAction<NodesStatsRequest, NodesStatsResponse, TransportNodesStatsAction.NodeStatsRequest, NodeStats> { private final NodeService nodeService; @Inject public TransportNodesStatsAction(Settings settings, ClusterName clusterName, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, NodeService nodeService) { super(settings, clusterName, threadPool, clusterService, transportService); this.nodeService = nodeService; } @Override protected String executor() { return ThreadPool.Names.MANAGEMENT; } @Override protected String transportAction() { return NodesStatsAction.NAME; } @Override protected NodesStatsResponse newResponse(NodesStatsRequest nodesInfoRequest, AtomicReferenceArray responses) { final List<NodeStats> nodeStats = Lists.newArrayList(); for (int i = 0; i < responses.length(); i++) { Object resp = responses.get(i); if (resp instanceof NodeStats) { nodeStats.add((NodeStats) resp); } } return new NodesStatsResponse(clusterName, nodeStats.toArray(new NodeStats[nodeStats.size()])); } @Override protected NodesStatsRequest newRequest() { return new NodesStatsRequest(); } @Override protected NodeStatsRequest newNodeRequest() { return new NodeStatsRequest(); } @Override protected NodeStatsRequest newNodeRequest(String nodeId, NodesStatsRequest request) { return new NodeStatsRequest(nodeId, request); } @Override protected NodeStats newNodeResponse() { return new NodeStats(); } @Override protected NodeStats nodeOperation(NodeStatsRequest nodeStatsRequest) throws ElasticsearchException { NodesStatsRequest request = nodeStatsRequest.request; return nodeService.stats(request.indices(), request.os(), request.process(), request.jvm(), request.threadPool(), request.network(), request.fs(), request.transport(), request.http(), request.breaker()); } @Override protected boolean accumulateExceptions() { return false; } static class NodeStatsRequest extends NodeOperationRequest { NodesStatsRequest request; NodeStatsRequest() { } NodeStatsRequest(String nodeId, NodesStatsRequest request) { super(request, nodeId); this.request = request; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); request = new NodesStatsRequest(); request.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); request.writeTo(out); } } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_stats_TransportNodesStatsAction.java
260
.around(new NoInstanceHooksOverridesRule() { @Override protected boolean verify(Method key) { String name = key.getName(); return !(name.equals("setUp") || name.equals("tearDown")); } })
0true
src_test_java_org_apache_lucene_util_AbstractRandomizedTest.java
5,959
public class SuggestBuilder implements ToXContent { private final String name; private String globalText; private final List<SuggestionBuilder<?>> suggestions = new ArrayList<SuggestionBuilder<?>>(); public SuggestBuilder() { this.name = null; } public SuggestBuilder(String name) { this.name = name; } /** * Sets the text to provide suggestions for. The suggest text is a required option that needs * to be set either via this setter or via the {@link org.elasticsearch.search.suggest.SuggestBuilder.SuggestionBuilder#setText(String)} method. * <p/> * The suggest text gets analyzed by the suggest analyzer or the suggest field search analyzer. * For each analyzed token, suggested terms are suggested if possible. */ public SuggestBuilder setText(String globalText) { this.globalText = globalText; return this; } /** * Adds an {@link org.elasticsearch.search.suggest.SuggestBuilder.TermSuggestionBuilder} instance under a user defined name. * The order in which the <code>Suggestions</code> are added, is the same as in the response. */ public SuggestBuilder addSuggestion(SuggestionBuilder<?> suggestion) { suggestions.add(suggestion); return this; } /** * Returns all suggestions with the defined names. */ public List<SuggestionBuilder<?>> getSuggestion() { return suggestions; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { if(name == null) { builder.startObject(); } else { builder.startObject(name); } if (globalText != null) { builder.field("text", globalText); } for (SuggestionBuilder<?> suggestion : suggestions) { builder = suggestion.toXContent(builder, params); } builder.endObject(); return builder; } /** * Convenience factory method. * * @param name The name of this suggestion. This is a required parameter. */ public static TermSuggestionBuilder termSuggestion(String name) { return new TermSuggestionBuilder(name); } /** * Convenience factory method. * * @param name The name of this suggestion. This is a required parameter. */ public static PhraseSuggestionBuilder phraseSuggestion(String name) { return new PhraseSuggestionBuilder(name); } public static abstract class SuggestionBuilder<T> implements ToXContent { private String name; private String suggester; private String text; private String field; private String analyzer; private Integer size; private Integer shardSize; public SuggestionBuilder(String name, String suggester) { this.name = name; this.suggester = suggester; } /** * Same as in {@link SuggestBuilder#setText(String)}, but in the suggestion scope. */ @SuppressWarnings("unchecked") public T text(String text) { this.text = text; return (T) this; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(name); if (text != null) { builder.field("text", text); } builder.startObject(suggester); if (analyzer != null) { builder.field("analyzer", analyzer); } if (field != null) { builder.field("field", field); } if (size != null) { builder.field("size", size); } if (shardSize != null) { builder.field("shard_size", shardSize); } builder = innerToXContent(builder, params); builder.endObject(); builder.endObject(); return builder; } protected abstract XContentBuilder innerToXContent(XContentBuilder builder, Params params) throws IOException; /** * Sets from what field to fetch the candidate suggestions from. This is an * required option and needs to be set via this setter or * {@link org.elasticsearch.search.suggest.SuggestBuilder.TermSuggestionBuilder#setField(String)} * method */ @SuppressWarnings("unchecked") public T field(String field) { this.field = field; return (T)this; } /** * Sets the analyzer to analyse to suggest text with. Defaults to the search * analyzer of the suggest field. */ @SuppressWarnings("unchecked") public T analyzer(String analyzer) { this.analyzer = analyzer; return (T)this; } /** * Sets the maximum suggestions to be returned per suggest text term. */ @SuppressWarnings("unchecked") public T size(int size) { if (size <= 0) { throw new ElasticsearchIllegalArgumentException("Size must be positive"); } this.size = size; return (T)this; } /** * Sets the maximum number of suggested term to be retrieved from each * individual shard. During the reduce phase the only the top N suggestions * are returned based on the <code>size</code> option. Defaults to the * <code>size</code> option. * <p/> * Setting this to a value higher than the `size` can be useful in order to * get a more accurate document frequency for suggested terms. Due to the * fact that terms are partitioned amongst shards, the shard level document * frequencies of suggestions may not be precise. Increasing this will make * these document frequencies more precise. */ @SuppressWarnings("unchecked") public T shardSize(Integer shardSize) { this.shardSize = shardSize; return (T)this; } } }
1no label
src_main_java_org_elasticsearch_search_suggest_SuggestBuilder.java
108
static class StaticMemberListener implements MembershipListener, InitialMembershipListener { final CountDownLatch latch; StaticMemberListener(CountDownLatch latch) { this.latch = latch; } public void init(InitialMembershipEvent event) { latch.countDown(); } public void memberAdded(MembershipEvent membershipEvent) { } public void memberRemoved(MembershipEvent membershipEvent) { } public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) { } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_ClientIssueTest.java
779
getAction.execute(getRequest, new ActionListener<GetResponse>() { @Override public void onResponse(GetResponse getResponse) { if (!getResponse.isExists()) { listener.onFailure(new DocumentMissingException(null, request.type(), request.id())); return; } final BoolQueryBuilder boolBuilder = boolQuery(); try { final DocumentMapper docMapper = indicesService.indexServiceSafe(concreteIndex).mapperService().documentMapper(request.type()); if (docMapper == null) { throw new ElasticsearchException("No DocumentMapper found for type [" + request.type() + "]"); } final Set<String> fields = newHashSet(); if (request.fields() != null) { for (String field : request.fields()) { FieldMappers fieldMappers = docMapper.mappers().smartName(field); if (fieldMappers != null) { fields.add(fieldMappers.mapper().names().indexName()); } else { fields.add(field); } } } if (!fields.isEmpty()) { // if fields are not empty, see if we got them in the response for (Iterator<String> it = fields.iterator(); it.hasNext(); ) { String field = it.next(); GetField getField = getResponse.getField(field); if (getField != null) { for (Object value : getField.getValues()) { addMoreLikeThis(request, boolBuilder, getField.getName(), value.toString(), true); } it.remove(); } } if (!fields.isEmpty()) { // if we don't get all the fields in the get response, see if we can parse the source parseSource(getResponse, boolBuilder, docMapper, fields, request); } } else { // we did not ask for any fields, try and get it from the source parseSource(getResponse, boolBuilder, docMapper, fields, request); } if (!boolBuilder.hasClauses()) { // no field added, fail listener.onFailure(new ElasticsearchException("No fields found to fetch the 'likeText' from")); return; } // exclude myself Term uidTerm = docMapper.uidMapper().term(request.type(), request.id()); boolBuilder.mustNot(termQuery(uidTerm.field(), uidTerm.text())); boolBuilder.adjustPureNegative(false); } catch (Throwable e) { listener.onFailure(e); return; } String[] searchIndices = request.searchIndices(); if (searchIndices == null) { searchIndices = new String[]{request.index()}; } String[] searchTypes = request.searchTypes(); if (searchTypes == null) { searchTypes = new String[]{request.type()}; } int size = request.searchSize() != 0 ? request.searchSize() : 10; int from = request.searchFrom() != 0 ? request.searchFrom() : 0; SearchRequest searchRequest = searchRequest(searchIndices) .types(searchTypes) .searchType(request.searchType()) .scroll(request.searchScroll()) .extraSource(searchSource() .query(boolBuilder) .from(from) .size(size) ) .listenerThreaded(request.listenerThreaded()); if (request.searchSource() != null) { searchRequest.source(request.searchSource(), request.searchSourceUnsafe()); } searchAction.execute(searchRequest, new ActionListener<SearchResponse>() { @Override public void onResponse(SearchResponse response) { listener.onResponse(response); } @Override public void onFailure(Throwable e) { listener.onFailure(e); } }); } @Override public void onFailure(Throwable e) { listener.onFailure(e); } });
1no label
src_main_java_org_elasticsearch_action_mlt_TransportMoreLikeThisAction.java
412
public class ClientCountDownLatchProxy extends ClientProxy implements ICountDownLatch { private volatile Data key; public ClientCountDownLatchProxy(String instanceName, String serviceName, String objectId) { super(instanceName, serviceName, objectId); } public boolean await(long timeout, TimeUnit unit) throws InterruptedException { AwaitRequest request = new AwaitRequest(getName(), getTimeInMillis(timeout, unit)); Boolean result = invoke(request); return result; } public void countDown() { CountDownRequest request = new CountDownRequest(getName()); invoke(request); } public int getCount() { GetCountRequest request = new GetCountRequest(getName()); Integer result = invoke(request); return result; } public boolean trySetCount(int count) { SetCountRequest request = new SetCountRequest(getName(), count); Boolean result = invoke(request); return result; } protected void onDestroy() { } private Data getKey() { if (key == null) { key = toData(getName()); } return key; } private long getTimeInMillis(final long time, final TimeUnit timeunit) { return timeunit != null ? timeunit.toMillis(time) : time; } protected <T> T invoke(ClientRequest req) { return super.invoke(req, getKey()); } @Override public String toString() { return "ICountDownLatch{" + "name='" + getName() + '\'' + '}'; } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientCountDownLatchProxy.java
917
public class IndicesOptions { private static final IndicesOptions[] VALUES; static { byte max = 1 << 4; VALUES = new IndicesOptions[max]; for (byte id = 0; id < max; id++) { VALUES[id] = new IndicesOptions(id); } } private final byte id; private IndicesOptions(byte id) { this.id = id; } /** * @return Whether specified concrete indices should be ignored when unavailable (missing or closed) */ public boolean ignoreUnavailable() { return (id & 1) != 0; } /** * @return Whether to ignore if a wildcard indices expression resolves into no concrete indices. * The `_all` string or when no indices have been specified also count as wildcard expressions. */ public boolean allowNoIndices() { return (id & 2) != 0; } /** * @return Whether wildcard indices expressions should expanded into open indices should be */ public boolean expandWildcardsOpen() { return (id & 4) != 0; } /** * @return Whether wildcard indices expressions should expanded into closed indices should be */ public boolean expandWildcardsClosed() { return (id & 8) != 0; } public void writeIndicesOptions(StreamOutput out) throws IOException { out.write(id); } public static IndicesOptions readIndicesOptions(StreamInput in) throws IOException { byte id = in.readByte(); if (id >= VALUES.length) { throw new ElasticsearchIllegalArgumentException("No valid missing index type id: " + id); } return VALUES[id]; } public static IndicesOptions fromOptions(boolean ignoreUnavailable, boolean allowNoIndices, boolean expandToOpenIndices, boolean expandToClosedIndices) { byte id = toByte(ignoreUnavailable, allowNoIndices, expandToOpenIndices, expandToClosedIndices); return VALUES[id]; } public static IndicesOptions fromRequest(RestRequest request, IndicesOptions defaultSettings) { String sWildcards = request.param("expand_wildcards"); String sIgnoreUnavailable = request.param("ignore_unavailable"); String sAllowNoIndices = request.param("allow_no_indices"); if (sWildcards == null && sIgnoreUnavailable == null && sAllowNoIndices == null) { return defaultSettings; } boolean expandWildcardsOpen = defaultSettings.expandWildcardsOpen(); boolean expandWildcardsClosed = defaultSettings.expandWildcardsClosed(); if (sWildcards != null) { String[] wildcards = Strings.splitStringByCommaToArray(sWildcards); for (String wildcard : wildcards) { if ("open".equals(wildcard)) { expandWildcardsOpen = true; } else if ("closed".equals(wildcard)) { expandWildcardsClosed = true; } else { throw new ElasticsearchIllegalArgumentException("No valid expand wildcard value [" + wildcard + "]"); } } } return fromOptions( toBool(sIgnoreUnavailable, defaultSettings.ignoreUnavailable()), toBool(sAllowNoIndices, defaultSettings.allowNoIndices()), expandWildcardsOpen, expandWildcardsClosed ); } /** * @return indices options that requires any specified index to exists, expands wildcards only to open indices and * allow that no indices are resolved from wildcard expressions (not returning an error). */ public static IndicesOptions strict() { return VALUES[6]; } /** * @return indices options that ignore unavailable indices, expand wildcards only to open indices and * allow that no indices are resolved from wildcard expressions (not returning an error). */ public static IndicesOptions lenient() { return VALUES[7]; } private static byte toByte(boolean ignoreUnavailable, boolean allowNoIndices, boolean wildcardExpandToOpen, boolean wildcardExpandToClosed) { byte id = 0; if (ignoreUnavailable) { id |= 1; } if (allowNoIndices) { id |= 2; } if (wildcardExpandToOpen) { id |= 4; } if (wildcardExpandToClosed) { id |= 8; } return id; } private static boolean toBool(String sValue, boolean defaultValue) { if (sValue == null) { return defaultValue; } return !(sValue.equals("false") || sValue.equals("0") || sValue.equals("off")); } }
1no label
src_main_java_org_elasticsearch_action_support_IndicesOptions.java
404
snapshotsService.createSnapshot(snapshotRequest, new SnapshotsService.CreateSnapshotListener() { @Override public void onResponse() { if (request.waitForCompletion()) { snapshotsService.addListener(new SnapshotsService.SnapshotCompletionListener() { SnapshotId snapshotId = new SnapshotId(request.repository(), request.snapshot()); @Override public void onSnapshotCompletion(SnapshotId snapshotId, SnapshotInfo snapshot) { if (this.snapshotId.equals(snapshotId)) { listener.onResponse(new CreateSnapshotResponse(snapshot)); snapshotsService.removeListener(this); } } @Override public void onSnapshotFailure(SnapshotId snapshotId, Throwable t) { if (this.snapshotId.equals(snapshotId)) { listener.onFailure(t); snapshotsService.removeListener(this); } } }); } else { listener.onResponse(new CreateSnapshotResponse()); } } @Override public void onFailure(Throwable t) { listener.onFailure(t); } });
0true
src_main_java_org_elasticsearch_action_admin_cluster_snapshots_create_TransportCreateSnapshotAction.java
3,221
public abstract class AbstractReplicatedRecordStore<K, V> extends AbstractBaseReplicatedRecordStore<K, V> { static final String CLEAR_REPLICATION_MAGIC_KEY = ReplicatedMapService.SERVICE_NAME + "$CLEAR$MESSAGE$"; public AbstractReplicatedRecordStore(String name, NodeEngine nodeEngine, CleanerRegistrator cleanerRegistrator, ReplicatedMapService replicatedMapService) { super(name, nodeEngine, cleanerRegistrator, replicatedMapService); } @Override public Object remove(Object key) { ValidationUtil.isNotNull(key, "key"); long time = System.currentTimeMillis(); storage.checkState(); V oldValue; K marshalledKey = (K) marshallKey(key); synchronized (getMutex(marshalledKey)) { final ReplicatedRecord current = storage.get(marshalledKey); final VectorClock vectorClock; if (current == null) { oldValue = null; } else { vectorClock = current.getVectorClock(); oldValue = (V) current.getValue(); // Force removal of the underlying stored entry storage.remove(marshalledKey, current); vectorClock.incrementClock(localMember); ReplicationMessage message = buildReplicationMessage(key, null, vectorClock, -1); replicationPublisher.publishReplicatedMessage(message); } cancelTtlEntry(marshalledKey); } Object unmarshalledOldValue = unmarshallValue(oldValue); fireEntryListenerEvent(key, unmarshalledOldValue, null); if (replicatedMapConfig.isStatisticsEnabled()) { mapStats.incrementRemoves(System.currentTimeMillis() - time); } return unmarshalledOldValue; } @Override public Object get(Object key) { ValidationUtil.isNotNull(key, "key"); long time = System.currentTimeMillis(); storage.checkState(); ReplicatedRecord replicatedRecord = storage.get(marshallKey(key)); // Force return null on ttl expiration (but before cleanup thread run) long ttlMillis = replicatedRecord == null ? 0 : replicatedRecord.getTtlMillis(); if (ttlMillis > 0 && System.currentTimeMillis() - replicatedRecord.getUpdateTime() >= ttlMillis) { replicatedRecord = null; } Object value = replicatedRecord == null ? null : unmarshallValue(replicatedRecord.getValue()); if (replicatedMapConfig.isStatisticsEnabled()) { mapStats.incrementGets(System.currentTimeMillis() - time); } return value; } @Override public Object put(Object key, Object value) { ValidationUtil.isNotNull(key, "key"); ValidationUtil.isNotNull(value, "value"); storage.checkState(); return put(key, value, 0, TimeUnit.MILLISECONDS); } @Override public Object put(Object key, Object value, long ttl, TimeUnit timeUnit) { ValidationUtil.isNotNull(key, "key"); ValidationUtil.isNotNull(value, "value"); ValidationUtil.isNotNull(timeUnit, "timeUnit"); if (ttl < 0) { throw new IllegalArgumentException("ttl must be a positive integer"); } long time = System.currentTimeMillis(); storage.checkState(); V oldValue = null; K marshalledKey = (K) marshallKey(key); V marshalledValue = (V) marshallValue(value); synchronized (getMutex(marshalledKey)) { final long ttlMillis = ttl == 0 ? 0 : timeUnit.toMillis(ttl); final ReplicatedRecord old = storage.get(marshalledKey); final VectorClock vectorClock; if (old == null) { vectorClock = new VectorClock(); ReplicatedRecord<K, V> record = buildReplicatedRecord(marshalledKey, marshalledValue, vectorClock, ttlMillis); storage.put(marshalledKey, record); } else { oldValue = (V) old.getValue(); vectorClock = old.getVectorClock(); storage.get(marshalledKey).setValue(marshalledValue, localMemberHash, ttlMillis); } if (ttlMillis > 0) { scheduleTtlEntry(ttlMillis, marshalledKey, null); } else { cancelTtlEntry(marshalledKey); } vectorClock.incrementClock(localMember); ReplicationMessage message = buildReplicationMessage(key, value, vectorClock, ttlMillis); replicationPublisher.publishReplicatedMessage(message); } Object unmarshalledOldValue = unmarshallValue(oldValue); fireEntryListenerEvent(key, unmarshalledOldValue, value); if (replicatedMapConfig.isStatisticsEnabled()) { mapStats.incrementPuts(System.currentTimeMillis() - time); } return unmarshalledOldValue; } @Override public boolean containsKey(Object key) { ValidationUtil.isNotNull(key, "key"); storage.checkState(); mapStats.incrementOtherOperations(); return storage.containsKey(marshallKey(key)); } @Override public boolean containsValue(Object value) { ValidationUtil.isNotNull(value, "value"); storage.checkState(); mapStats.incrementOtherOperations(); for (Map.Entry<K, ReplicatedRecord<K, V>> entry : storage.entrySet()) { V entryValue = entry.getValue().getValue(); if (value == entryValue || (entryValue != null && unmarshallValue(entryValue).equals(value))) { return true; } } return false; } @Override public Set keySet() { storage.checkState(); Set keySet = new HashSet(storage.size()); for (K key : storage.keySet()) { keySet.add(unmarshallKey(key)); } mapStats.incrementOtherOperations(); return keySet; } @Override public Collection values() { storage.checkState(); List values = new ArrayList(storage.size()); for (ReplicatedRecord record : storage.values()) { values.add(unmarshallValue(record.getValue())); } mapStats.incrementOtherOperations(); return values; } @Override public Collection values(Comparator comparator) { List values = (List) values(); Collections.sort(values, comparator); return values; } @Override public Set entrySet() { storage.checkState(); Set entrySet = new HashSet(storage.size()); for (Map.Entry<K, ReplicatedRecord<K, V>> entry : storage.entrySet()) { Object key = unmarshallKey(entry.getKey()); Object value = unmarshallValue(entry.getValue().getValue()); entrySet.add(new AbstractMap.SimpleEntry(key, value)); } mapStats.incrementOtherOperations(); return entrySet; } @Override public ReplicatedRecord getReplicatedRecord(Object key) { ValidationUtil.isNotNull(key, "key"); storage.checkState(); return storage.get(marshallKey(key)); } @Override public boolean isEmpty() { mapStats.incrementOtherOperations(); return storage.isEmpty(); } @Override public int size() { mapStats.incrementOtherOperations(); return storage.size(); } @Override public void clear(boolean distribute, boolean emptyReplicationQueue) { storage.checkState(); if (emptyReplicationQueue) { replicationPublisher.emptyReplicationQueue(); } storage.clear(); if (distribute) { replicationPublisher.distributeClear(emptyReplicationQueue); } mapStats.incrementOtherOperations(); } @Override public String addEntryListener(EntryListener listener, Object key) { ValidationUtil.isNotNull(listener, "listener"); EventFilter eventFilter = new ReplicatedEntryEventFilter(marshallKey(key)); mapStats.incrementOtherOperations(); return replicatedMapService.addEventListener(listener, eventFilter, getName()); } @Override public String addEntryListener(EntryListener listener, Predicate predicate, Object key) { ValidationUtil.isNotNull(listener, "listener"); EventFilter eventFilter = new ReplicatedQueryEventFilter(marshallKey(key), predicate); mapStats.incrementOtherOperations(); return replicatedMapService.addEventListener(listener, eventFilter, getName()); } @Override public boolean removeEntryListenerInternal(String id) { ValidationUtil.isNotNull(id, "id"); mapStats.incrementOtherOperations(); return replicatedMapService.removeEventListener(getName(), id); } private ReplicationMessage buildReplicationMessage(Object key, Object value, VectorClock vectorClock, long ttlMillis) { return new ReplicationMessage(getName(), key, value, vectorClock, localMember, localMemberHash, ttlMillis); } private ReplicatedRecord buildReplicatedRecord(Object key, Object value, VectorClock vectorClock, long ttlMillis) { return new ReplicatedRecord(key, value, vectorClock, localMemberHash, ttlMillis); } }
1no label
hazelcast_src_main_java_com_hazelcast_replicatedmap_record_AbstractReplicatedRecordStore.java
801
public static class CriteriaOfferXrefPK implements Serializable { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; @ManyToOne(targetEntity = OfferImpl.class, optional=false) @JoinColumn(name = "OFFER_ID") protected Offer offer = new OfferImpl(); @ManyToOne(targetEntity = OfferItemCriteriaImpl.class, optional=false) @JoinColumn(name = "OFFER_ITEM_CRITERIA_ID") protected OfferItemCriteria offerCriteria = new OfferItemCriteriaImpl(); public Offer getOffer() { return offer; } public void setOffer(Offer offer) { this.offer = offer; } public OfferItemCriteria getOfferCriteria() { return offerCriteria; } public void setOfferCriteria(OfferItemCriteria offerCriteria) { this.offerCriteria = offerCriteria; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((offer == null) ? 0 : offer.hashCode()); result = prime * result + ((offerCriteria == null) ? 0 : offerCriteria.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; CriteriaOfferXrefPK other = (CriteriaOfferXrefPK) obj; if (offer == null) { if (other.offer != null) return false; } else if (!offer.equals(other.offer)) return false; if (offerCriteria == null) { if (other.offerCriteria != null) return false; } else if (!offerCriteria.equals(other.offerCriteria)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_CriteriaOfferXref.java
351
transportService.sendRequest(node, NodeShutdownRequestHandler.ACTION, new NodeShutdownRequest(request), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleResponse(TransportResponse.Empty response) { logger.trace("[partial_cluster_shutdown]: received shutdown response from [{}]", node); latch.countDown(); } @Override public void handleException(TransportException exp) { logger.warn("[partial_cluster_shutdown]: received failed shutdown response from [{}]", exp, node); latch.countDown(); } });
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_shutdown_TransportNodesShutdownAction.java
169
public static interface ForkJoinWorkerThreadFactory { /** * Returns a new worker thread operating in the given pool. * * @param pool the pool this thread works in * @throws NullPointerException if the pool is null */ public ForkJoinWorkerThread newThread(ForkJoinPool pool); }
0true
src_main_java_jsr166y_ForkJoinPool.java
156
public class MockSimpleClient implements SimpleClient { private static final AtomicInteger port = new AtomicInteger(9000); private final ClientEngineImpl clientEngine; private final MockConnection connection; public MockSimpleClient(ClientEngineImpl clientEngine) throws UnknownHostException { this.clientEngine = clientEngine; this.connection = new MockConnection(port.incrementAndGet()); } public void auth() throws IOException { //we need to call this so that the endpoint is created for the connection. Normally this is done from //the ConnectionManager. clientEngine.getConnectionListener().connectionAdded(connection); AuthenticationRequest auth = new AuthenticationRequest(new UsernamePasswordCredentials("dev", "dev-pass")); send(auth); receive(); } public void send(Object o) throws IOException { Data data = getSerializationService().toData(o); ClientPacket packet = new ClientPacket(data); packet.setConn(connection); clientEngine.handlePacket(packet); } public Object receive() throws IOException { DataAdapter adapter = null; try { adapter = (DataAdapter)connection.q.take(); } catch (InterruptedException e) { throw new HazelcastException(e); } ClientResponse clientResponse = getSerializationService().toObject(adapter.getData()); return getSerializationService().toObject(clientResponse.getResponse()); } public void close() { clientEngine.removeEndpoint(connection, true); connection.close(); } public SerializationService getSerializationService() { return clientEngine.getSerializationService(); } class MockConnection implements Connection { volatile boolean live = true; final int port; MockConnection(int port) { this.port = port; } BlockingQueue<SocketWritable> q = new LinkedBlockingQueue<SocketWritable>(); public boolean write(SocketWritable packet) { return q.offer(packet); } @Override public Address getEndPoint() { return null; } @Override public boolean live() { return live; } @Override public long lastReadTime() { return 0; } @Override public long lastWriteTime() { return 0; } @Override public void close() { live = false; } @Override public boolean isClient() { return true; } @Override public ConnectionType getType() { return ConnectionType.BINARY_CLIENT; } @Override public InetAddress getInetAddress() { return null; } @Override public InetSocketAddress getRemoteSocketAddress() { return null; } @Override public int getPort() { return port; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MockConnection)) return false; MockConnection that = (MockConnection) o; if (port != that.port) return false; return true; } @Override public int hashCode() { return port; } } }
1no label
hazelcast_src_test_java_com_hazelcast_client_MockSimpleClient.java
2,030
public class LocaleType implements Serializable, BroadleafEnumerationType { public static void main(String[] items) { System.out.println(Locale.TAIWAN.toString()); } private static final long serialVersionUID = 1L; private static final Map<String, LocaleType> TYPES = new LinkedHashMap<String, LocaleType>(); public static final LocaleType US_ENGLISH = new LocaleType("en_US", "US English", Locale.US); public static final LocaleType CANADA = new LocaleType("en_CA", "Canada English", Locale.CANADA); public static final LocaleType CANADA_FRENCH = new LocaleType("fr_CA", "Canada French", Locale.CANADA_FRENCH); public static final LocaleType CHINA = new LocaleType("zh_CN", "China", Locale.CHINA); public static final LocaleType CHINA_ENGLISH = new LocaleType("en_CN", "China English", new Locale("CN", "en")); public static final LocaleType FRANCE = new LocaleType("fr_FR", "France", Locale.FRANCE); public static final LocaleType FRANCE_ENGLISH = new LocaleType("en_FR", "France English", new Locale("FR", "en")); public static final LocaleType GERMANY = new LocaleType("de_DE", "Germany", Locale.GERMANY); public static final LocaleType GERMANY_ENGLISH = new LocaleType("en_DE", "Germany English", new Locale("DE", "en")); public static final LocaleType ITALY = new LocaleType("it_IT", "Italy", Locale.ITALY); public static final LocaleType ITALY_ENGLISH = new LocaleType("en_IT", "Italy English", new Locale("IT", "en")); public static final LocaleType JAPAN = new LocaleType("ja_JP", "Japan", Locale.JAPAN); public static final LocaleType JAPAN_ENGLISH = new LocaleType("en_JP", "Japan English", new Locale("JP", "en")); public static final LocaleType KOREA = new LocaleType("ko_KR", "Korea", Locale.KOREA); public static final LocaleType KOREA_ENGLISH = new LocaleType("en_KR", "Korea English", new Locale("KR", "en")); public static final LocaleType INDIA_HINDI = new LocaleType("hi_IN", "India Hindi", new Locale("IN", "hi")); public static final LocaleType INDIA_ENGLISH = new LocaleType("en_IN", "India English", new Locale("IN", "en")); public static final LocaleType UK_ENGLISH = new LocaleType("en_UK", "UK English", Locale.UK); public static final LocaleType TAIWAN = new LocaleType("zh_TW", "Taiwan", Locale.TAIWAN); public static final LocaleType TAIWAN_ENGLISH = new LocaleType("en_TW", "Taiwan English", new Locale("TW", "en")); public static LocaleType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; private Locale locale; public LocaleType() { //do nothing } public LocaleType(final String type, final String friendlyType, final Locale locale) { this.friendlyType = friendlyType; this.locale = locale; setType(type); } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } public Locale getLocale() { return locale; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LocaleType other = (LocaleType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
core_broadleaf-profile_src_main_java_org_broadleafcommerce_profile_core_service_type_LocaleType.java
1,709
public class PermissionType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, PermissionType> TYPES = new LinkedHashMap<String, PermissionType>(); public static final PermissionType READ = new PermissionType("READ", "Read"); public static final PermissionType CREATE = new PermissionType("CREATE", "Create"); public static final PermissionType UPDATE = new PermissionType("UPDATE", "Update"); public static final PermissionType DELETE = new PermissionType("DELETE", "Delete"); public static final PermissionType ALL = new PermissionType("ALL", "All"); public static final PermissionType OTHER = new PermissionType("OTHER", "Other"); public static PermissionType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public PermissionType() { //do nothing } public PermissionType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } else { throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName()); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PermissionType other = (PermissionType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_security_service_type_PermissionType.java
151
public class ODateSerializer implements OBinarySerializer<Date> { public static ODateSerializer INSTANCE = new ODateSerializer(); public static final byte ID = 4; public int getObjectSize(Date object, Object... hints) { return OLongSerializer.LONG_SIZE; } public void serialize(Date object, byte[] stream, int startPosition, Object... hints) { Calendar calendar = Calendar.getInstance(); calendar.setTime(object); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer.INSTANCE; dateTimeSerializer.serialize(calendar.getTime(), stream, startPosition); } public Date deserialize(byte[] stream, int startPosition) { ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer.INSTANCE; return dateTimeSerializer.deserialize(stream, startPosition); } public int getObjectSize(byte[] stream, int startPosition) { return OLongSerializer.LONG_SIZE; } public byte getId() { return ID; } public int getObjectSizeNative(byte[] stream, int startPosition) { return OLongSerializer.LONG_SIZE; } public void serializeNative(Date object, byte[] stream, int startPosition, Object... hints) { Calendar calendar = Calendar.getInstance(); calendar.setTime(object); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer.INSTANCE; dateTimeSerializer.serializeNative(calendar.getTime(), stream, startPosition); } public Date deserializeNative(byte[] stream, int startPosition) { ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer.INSTANCE; return dateTimeSerializer.deserializeNative(stream, startPosition); } @Override public void serializeInDirectMemory(Date object, ODirectMemoryPointer pointer, long offset, Object... hints) { Calendar calendar = Calendar.getInstance(); calendar.setTime(object); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer.INSTANCE; dateTimeSerializer.serializeInDirectMemory(calendar.getTime(), pointer, offset); } @Override public Date deserializeFromDirectMemory(ODirectMemoryPointer pointer, long offset) { ODateTimeSerializer dateTimeSerializer = ODateTimeSerializer.INSTANCE; return dateTimeSerializer.deserializeFromDirectMemory(pointer, offset); } @Override public int getObjectSizeInDirectMemory(ODirectMemoryPointer pointer, long offset) { return OLongSerializer.LONG_SIZE; } public boolean isFixedLength() { return true; } public int getFixedLength() { return OLongSerializer.LONG_SIZE; } @Override public Date preprocess(Date value, Object... hints) { final Calendar calendar = Calendar.getInstance(); calendar.setTime(value); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } }
0true
commons_src_main_java_com_orientechnologies_common_serialization_types_ODateSerializer.java
1,195
public class Message<E> extends EventObject { private final E messageObject; private final long publishTime; private final Member publishingMember; public Message(String topicName, E messageObject, long publishTime, Member publishingMember) { super(topicName); this.messageObject = messageObject; this.publishTime = publishTime; this.publishingMember = publishingMember; } /** * Returns published message * * @return message object */ public E getMessageObject() { return messageObject; } /** * Return the time when the message is published * * @return publish time */ public long getPublishTime() { return publishTime; } /** * Returns the member that published the message * * @return publishing member */ public Member getPublishingMember() { return publishingMember; } }
1no label
hazelcast_src_main_java_com_hazelcast_core_Message.java
252
public final class RateLimitedFSDirectory extends FilterDirectory{ private final StoreRateLimiting.Provider rateLimitingProvider; private final StoreRateLimiting.Listener rateListener; public RateLimitedFSDirectory(FSDirectory wrapped, StoreRateLimiting.Provider rateLimitingProvider, StoreRateLimiting.Listener rateListener) { super(wrapped); this.rateLimitingProvider = rateLimitingProvider; this.rateListener = rateListener; } @Override public IndexOutput createOutput(String name, IOContext context) throws IOException { final IndexOutput output = in.createOutput(name, context); StoreRateLimiting rateLimiting = rateLimitingProvider.rateLimiting(); StoreRateLimiting.Type type = rateLimiting.getType(); RateLimiter limiter = rateLimiting.getRateLimiter(); if (type == StoreRateLimiting.Type.NONE || limiter == null) { return output; } if (context.context == Context.MERGE) { // we are mering, and type is either MERGE or ALL, rate limit... return new RateLimitedIndexOutput(limiter, rateListener, output); } if (type == StoreRateLimiting.Type.ALL) { return new RateLimitedIndexOutput(limiter, rateListener, output); } // we shouldn't really get here... return output; } @Override public void close() throws IOException { in.close(); } @Override public String toString() { StoreRateLimiting rateLimiting = rateLimitingProvider.rateLimiting(); StoreRateLimiting.Type type = rateLimiting.getType(); RateLimiter limiter = rateLimiting.getRateLimiter(); if (type == StoreRateLimiting.Type.NONE || limiter == null) { return StoreUtils.toString(in); } else { return "rate_limited(" + StoreUtils.toString(in) + ", type=" + type.name() + ", rate=" + limiter.getMbPerSec() + ")"; } } static final class RateLimitedIndexOutput extends BufferedIndexOutput { private final IndexOutput delegate; private final BufferedIndexOutput bufferedDelegate; private final RateLimiter rateLimiter; private final StoreRateLimiting.Listener rateListener; RateLimitedIndexOutput(final RateLimiter rateLimiter, final StoreRateLimiting.Listener rateListener, final IndexOutput delegate) { super(delegate instanceof BufferedIndexOutput ? ((BufferedIndexOutput) delegate).getBufferSize() : BufferedIndexOutput.DEFAULT_BUFFER_SIZE); if (delegate instanceof BufferedIndexOutput) { bufferedDelegate = (BufferedIndexOutput) delegate; this.delegate = delegate; } else { this.delegate = delegate; bufferedDelegate = null; } this.rateLimiter = rateLimiter; this.rateListener = rateListener; } @Override protected void flushBuffer(byte[] b, int offset, int len) throws IOException { rateListener.onPause(rateLimiter.pause(len)); if (bufferedDelegate != null) { bufferedDelegate.flushBuffer(b, offset, len); } else { delegate.writeBytes(b, offset, len); } } @Override public long length() throws IOException { return delegate.length(); } @Override public void seek(long pos) throws IOException { flush(); delegate.seek(pos); } @Override public void flush() throws IOException { try { super.flush(); } finally { delegate.flush(); } } @Override public void setLength(long length) throws IOException { delegate.setLength(length); } @Override public void close() throws IOException { try { super.close(); } finally { delegate.close(); } } } }
1no label
src_main_java_org_apache_lucene_store_RateLimitedFSDirectory.java
26
final class ImportVisitor extends Visitor { private final String prefix; private final CommonToken token; private final int offset; private final Node node; private final CeylonParseController cpc; private final List<ICompletionProposal> result; ImportVisitor(String prefix, CommonToken token, int offset, Node node, CeylonParseController cpc, List<ICompletionProposal> result) { this.prefix = prefix; this.token = token; this.offset = offset; this.node = node; this.cpc = cpc; this.result = result; } @Override public void visit(Tree.ModuleDescriptor that) { super.visit(that); if (that.getImportPath()==node) { addCurrentPackageNameCompletion(cpc, offset, fullPath(offset, prefix, that.getImportPath()) + prefix, result); } } public void visit(Tree.PackageDescriptor that) { super.visit(that); if (that.getImportPath()==node) { addCurrentPackageNameCompletion(cpc, offset, fullPath(offset, prefix, that.getImportPath()) + prefix, result); } } @Override public void visit(Tree.Import that) { super.visit(that); if (that.getImportPath()==node) { addPackageCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node, result, nextTokenType(cpc, token)!=CeylonLexer.LBRACE); } } @Override public void visit(Tree.PackageLiteral that) { super.visit(that); if (that.getImportPath()==node) { addPackageCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node, result, false); } } @Override public void visit(Tree.ImportModule that) { super.visit(that); if (that.getImportPath()==node) { addModuleCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node, result, nextTokenType(cpc, token)!=CeylonLexer.STRING_LITERAL); } } @Override public void visit(Tree.ModuleLiteral that) { super.visit(that); if (that.getImportPath()==node) { addModuleCompletions(cpc, offset, prefix, (Tree.ImportPath) node, node, result, false); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ImportVisitor.java
34
@SuppressWarnings("unchecked") public abstract class OMVRBTreeEntry<K, V> implements Map.Entry<K, V>, Comparable<OMVRBTreeEntry<K, V>> { protected OMVRBTree<K, V> tree; private int pageSplitItems; public static final int BINARY_SEARCH_THRESHOLD = 10; /** * Constructor called on unmarshalling. * */ protected OMVRBTreeEntry(final OMVRBTree<K, V> iTree) { tree = iTree; } public abstract void setLeft(OMVRBTreeEntry<K, V> left); public abstract OMVRBTreeEntry<K, V> getLeft(); public abstract void setRight(OMVRBTreeEntry<K, V> right); public abstract OMVRBTreeEntry<K, V> getRight(); public abstract OMVRBTreeEntry<K, V> setParent(OMVRBTreeEntry<K, V> parent); public abstract OMVRBTreeEntry<K, V> getParent(); protected abstract OMVRBTreeEntry<K, V> getLeftInMemory(); protected abstract OMVRBTreeEntry<K, V> getParentInMemory(); protected abstract OMVRBTreeEntry<K, V> getRightInMemory(); protected abstract OMVRBTreeEntry<K, V> getNextInMemory(); /** * Returns the first Entry only by traversing the memory, or null if no such. */ public OMVRBTreeEntry<K, V> getFirstInMemory() { OMVRBTreeEntry<K, V> node = this; OMVRBTreeEntry<K, V> prev = this; while (node != null) { prev = node; node = node.getPreviousInMemory(); } return prev; } /** * Returns the previous of the current Entry only by traversing the memory, or null if no such. */ public OMVRBTreeEntry<K, V> getPreviousInMemory() { OMVRBTreeEntry<K, V> t = this; OMVRBTreeEntry<K, V> p = null; if (t.getLeftInMemory() != null) { p = t.getLeftInMemory(); while (p.getRightInMemory() != null) p = p.getRightInMemory(); } else { p = t.getParentInMemory(); while (p != null && t == p.getLeftInMemory()) { t = p; p = p.getParentInMemory(); } } return p; } protected OMVRBTree<K, V> getTree() { return tree; } public int getDepth() { int level = 0; OMVRBTreeEntry<K, V> entry = this; while (entry.getParent() != null) { level++; entry = entry.getParent(); } return level; } /** * Returns the key. * * @return the key */ public K getKey() { return getKey(tree.pageIndex); } public K getKey(final int iIndex) { if (iIndex >= getSize()) throw new IndexOutOfBoundsException("Requested index " + iIndex + " when the range is 0-" + getSize()); tree.pageIndex = iIndex; return getKeyAt(iIndex); } protected abstract K getKeyAt(final int iIndex); /** * Returns the value associated with the key. * * @return the value associated with the key */ public V getValue() { if (tree.pageIndex == -1) return getValueAt(0); return getValueAt(tree.pageIndex); } public V getValue(final int iIndex) { tree.pageIndex = iIndex; return getValueAt(iIndex); } protected abstract V getValueAt(int iIndex); public int getFreeSpace() { return getPageSize() - getSize(); } /** * Execute a binary search between the keys of the node. The keys are always kept ordered. It update the pageIndex attribute with * the most closer key found (useful for the next inserting). * * @param iKey * Key to find * @return The value found if any, otherwise null */ protected V search(final K iKey) { tree.pageItemFound = false; int size = getSize(); if (size == 0) return null; // CHECK THE LOWER LIMIT if (tree.comparator != null) tree.pageItemComparator = tree.comparator.compare(iKey, getKeyAt(0)); else tree.pageItemComparator = ((Comparable<? super K>) iKey).compareTo(getKeyAt(0)); if (tree.pageItemComparator == 0) { // FOUND: SET THE INDEX AND RETURN THE NODE tree.pageItemFound = true; tree.pageIndex = 0; return getValueAt(tree.pageIndex); } else if (tree.pageItemComparator < 0) { // KEY OUT OF FIRST ITEM: AVOID SEARCH AND RETURN THE FIRST POSITION tree.pageIndex = 0; return null; } else { // CHECK THE UPPER LIMIT if (tree.comparator != null) tree.pageItemComparator = tree.comparator.compare((K) iKey, getKeyAt(size - 1)); else tree.pageItemComparator = ((Comparable<? super K>) iKey).compareTo(getKeyAt(size - 1)); if (tree.pageItemComparator > 0) { // KEY OUT OF LAST ITEM: AVOID SEARCH AND RETURN THE LAST POSITION tree.pageIndex = size; return null; } } if (size < BINARY_SEARCH_THRESHOLD) return linearSearch(iKey); else return binarySearch(iKey); } /** * Linear search inside the node * * @param iKey * Key to search * @return Value if found, otherwise null and the tree.pageIndex updated with the closest-after-first position valid for further * inserts. */ private V linearSearch(final K iKey) { V value = null; int i = 0; tree.pageItemComparator = -1; for (int s = getSize(); i < s; ++i) { if (tree.comparator != null) tree.pageItemComparator = tree.comparator.compare(getKeyAt(i), iKey); else tree.pageItemComparator = ((Comparable<? super K>) getKeyAt(i)).compareTo(iKey); if (tree.pageItemComparator == 0) { // FOUND: SET THE INDEX AND RETURN THE NODE tree.pageItemFound = true; value = getValueAt(i); break; } else if (tree.pageItemComparator > 0) break; } tree.pageIndex = i; return value; } /** * Binary search inside the node * * @param iKey * Key to search * @return Value if found, otherwise null and the tree.pageIndex updated with the closest-after-first position valid for further * inserts. */ private V binarySearch(final K iKey) { int low = 0; int high = getSize() - 1; int mid = 0; while (low <= high) { mid = (low + high) >>> 1; Object midVal = getKeyAt(mid); if (tree.comparator != null) tree.pageItemComparator = tree.comparator.compare((K) midVal, iKey); else tree.pageItemComparator = ((Comparable<? super K>) midVal).compareTo(iKey); if (tree.pageItemComparator == 0) { // FOUND: SET THE INDEX AND RETURN THE NODE tree.pageItemFound = true; tree.pageIndex = mid; return getValueAt(tree.pageIndex); } if (low == high) break; if (tree.pageItemComparator < 0) low = mid + 1; else high = mid; } tree.pageIndex = mid; return null; } protected abstract void insert(final int iPosition, final K key, final V value); protected abstract void remove(); protected abstract void setColor(boolean iColor); public abstract boolean getColor(); public abstract int getSize(); public K getLastKey() { return getKey(getSize() - 1); } public K getFirstKey() { return getKey(0); } protected abstract void copyFrom(final OMVRBTreeEntry<K, V> iSource); public int getPageSplitItems() { return pageSplitItems; } protected void init() { pageSplitItems = (int) (getPageSize() * tree.pageLoadFactor); } public abstract int getPageSize(); /** * Compares two nodes by their first keys. */ public int compareTo(final OMVRBTreeEntry<K, V> o) { if (o == null) return 1; if (o == this) return 0; if (getSize() == 0) return -1; if (o.getSize() == 0) return 1; if (tree.comparator != null) return tree.comparator.compare(getFirstKey(), o.getFirstKey()); return ((Comparable<K>) getFirstKey()).compareTo(o.getFirstKey()); } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { int idx = tree.pageIndex; if (idx > -1 && idx < getSize()) return getKeyAt(idx) + "=" + getValueAt(idx); return null; } }
0true
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTreeEntry.java
1,441
public class TitanGraphOutputMapReduce { public enum Counters { VERTICES_ADDED, VERTICES_REMOVED, VERTEX_PROPERTIES_ADDED, VERTEX_PROPERTIES_REMOVED, EDGES_ADDED, EDGES_REMOVED, EDGE_PROPERTIES_ADDED, EDGE_PROPERTIES_REMOVED, NULL_VERTEX_EDGES_IGNORED, NULL_VERTICES_IGNORED, NULL_RELATIONS_IGNORED, SUCCESSFUL_TRANSACTIONS, FAILED_TRANSACTIONS, } public static final Logger LOGGER = LoggerFactory.getLogger(TitanGraphOutputMapReduce.class); // TODO move this out-of-band // some random property that will 'never' be used by anyone public static final String TITAN_ID = "_bId0192834"; public static final String ID_MAP_KEY = "_iDMaPKeY"; private static final String HADOOP_VERTEX = "hadoopVertex"; private static final String HADOOP_EDGE = "hadoopEdge"; private static final String TITAN_OUT_VERTEX = "titanOutVertex"; private static final String TITAN_IN_VERTEX = "titanInVertex"; private static final String GRAPH = "graph"; private static final String MAP_CONTEXT = "mapContext"; /*private static final String FAUNUS_VERTEX = "faunusVertex"; private static final String GRAPH = "graph"; private static final String MAP_CONTEXT = "mapContext"; */ public static TitanGraph generateGraph(final ModifiableHadoopConfiguration titanConf) { final Class<? extends OutputFormat> format = titanConf.getClass(OUTPUT_FORMAT, OutputFormat.class, OutputFormat.class); if (TitanOutputFormat.class.isAssignableFrom(format)) { ModifiableConfiguration mc = titanConf.getOutputConf(); boolean present = mc.has(AbstractCassandraStoreManager.CASSANDRA_KEYSPACE); LOGGER.trace("Keyspace in_config=" + present + " value=" + mc.get(AbstractCassandraStoreManager.CASSANDRA_KEYSPACE)); return TitanFactory.open(mc); } else { throw new RuntimeException("The provide graph output format is not a supported TitanOutputFormat: " + format.getName()); } } //UTILITY METHODS private static Object getValue(TitanRelation relation, TitanGraph graph) { if (relation.isProperty()) return ((TitanProperty)relation).getValue(); else return graph.getVertex(((TitanEdge) relation).getVertex(IN).getLongId()); } // WRITE ALL THE VERTICES AND THEIR PROPERTIES public static class VertexMap extends Mapper<NullWritable, FaunusVertex, LongWritable, Holder<FaunusVertex>> { private TitanGraph graph; private boolean trackState; private ModifiableHadoopConfiguration faunusConf; private LoaderScriptWrapper loaderScript; private final Holder<FaunusVertex> vertexHolder = new Holder<FaunusVertex>(); private final LongWritable longWritable = new LongWritable(); @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { faunusConf = ModifiableHadoopConfiguration.of(DEFAULT_COMPAT.getContextConfiguration(context)); graph = TitanGraphOutputMapReduce.generateGraph(faunusConf); trackState = context.getConfiguration().getBoolean(Tokens.TITAN_HADOOP_PIPELINE_TRACK_STATE, false); // Check whether a script is defined in the config if (faunusConf.has(OUTPUT_LOADER_SCRIPT_FILE)) { Path scriptPath = new Path(faunusConf.get(OUTPUT_LOADER_SCRIPT_FILE)); FileSystem scriptFS = FileSystem.get(DEFAULT_COMPAT.getJobContextConfiguration(context)); loaderScript = new LoaderScriptWrapper(scriptFS, scriptPath); } } @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, LongWritable, Holder<FaunusVertex>>.Context context) throws IOException, InterruptedException { try { final TitanVertex titanVertex = this.getCreateOrDeleteVertex(value, context); if (null != titanVertex) { // the vertex was state != deleted (if it was we know incident edges are deleted too) // Propagate shell vertices with Titan ids final FaunusVertex shellVertex = new FaunusVertex(faunusConf, value.getLongId()); shellVertex.setProperty(TITAN_ID, titanVertex.getLongId()); for (final TitanEdge edge : value.query().direction(OUT).titanEdges()) { if (!trackState || edge.isNew()) { //Only need to propagate ids for new edges this.longWritable.set(edge.getVertex(IN).getLongId()); context.write(this.longWritable, this.vertexHolder.set('s', shellVertex)); } } this.longWritable.set(value.getLongId()); // value.getPropertiesWithState().clear(); // no longer needed in reduce phase value.setProperty(TITAN_ID, titanVertex.getLongId()); // need this for id resolution in edge-map phase // value.removeEdges(Tokens.Action.DROP, OUT); // no longer needed in reduce phase context.write(this.longWritable, this.vertexHolder.set('v', value)); } } catch (final Exception e) { graph.rollback(); DEFAULT_COMPAT.incrementContextCounter(context, Counters.FAILED_TRANSACTIONS, 1L); throw new IOException(e.getMessage(), e); } } @Override public void cleanup(final Mapper<NullWritable, FaunusVertex, LongWritable, Holder<FaunusVertex>>.Context context) throws IOException, InterruptedException { try { graph.commit(); DEFAULT_COMPAT.incrementContextCounter(context, Counters.SUCCESSFUL_TRANSACTIONS, 1L); } catch (Exception e) { LOGGER.error("Could not commit transaction during Map.cleanup(): ", e); graph.rollback(); DEFAULT_COMPAT.incrementContextCounter(context, Counters.FAILED_TRANSACTIONS, 1L); throw new IOException(e.getMessage(), e); } graph.shutdown(); } public TitanVertex getCreateOrDeleteVertex(final FaunusVertex faunusVertex, final Mapper<NullWritable, FaunusVertex, LongWritable, Holder<FaunusVertex>>.Context context) throws InterruptedException { if (this.trackState && faunusVertex.isRemoved()) { final Vertex titanVertex = graph.getVertex(faunusVertex.getLongId()); if (null == titanVertex) DEFAULT_COMPAT.incrementContextCounter(context, Counters.NULL_VERTICES_IGNORED, 1L); else { titanVertex.remove(); DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_REMOVED, 1L); } return null; } else { final TitanVertex titanVertex; if (faunusVertex.isNew()) { // Vertex is new to this faunus run, but might already exist in Titan titanVertex = getTitanVertex(faunusVertex, context); } else { titanVertex = (TitanVertex) graph.getVertex(faunusVertex.getLongId()); if (titanVertex==null) { DEFAULT_COMPAT.incrementContextCounter(context, Counters.NULL_VERTICES_IGNORED, 1L); return null; } } if (faunusVertex.isNew() || faunusVertex.isModified()) { //Synchronize properties for (final TitanProperty p : faunusVertex.query().queryAll().properties()) { if (null != loaderScript && loaderScript.hasVPropMethod()) { loaderScript.getVProp(p, titanVertex, graph, context); } else { getCreateOrDeleteRelation(graph, trackState, OUT, faunusVertex, titanVertex, (StandardFaunusProperty) p, context); } } } return titanVertex; } } private TitanVertex getTitanVertex(FaunusVertex faunusVertex, Mapper<NullWritable, FaunusVertex, LongWritable, Holder<FaunusVertex>>.Context context) { if (null != loaderScript && loaderScript.hasVertexMethod()) { return loaderScript.getVertex(faunusVertex, graph, context); } else { VertexLabel titanLabel = BaseVertexLabel.DEFAULT_VERTEXLABEL; FaunusVertexLabel faunusLabel = faunusVertex.getVertexLabel(); if (!faunusLabel.isDefault()) titanLabel = graph.getVertexLabel(faunusLabel.getName()); TitanVertex tv = graph.addVertexWithLabel(titanLabel); DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_ADDED, 1L); return tv; } } } private static TitanRelation getCreateOrDeleteRelation(final TitanGraph graph, final boolean trackState, final Direction dir, final FaunusVertex faunusVertex, final TitanVertex titanVertex, final StandardFaunusRelation faunusRelation, final Mapper.Context context) { assert dir==IN || dir==OUT; final TitanRelation titanRelation; if (trackState && (faunusRelation.isModified() || faunusRelation.isRemoved())) { //Modify existing Map<Long, Long> idMap = getIdMap(faunusVertex); titanRelation = getIncidentRelation(graph, dir, titanVertex, faunusRelation, faunusRelation.isEdge()?idMap.get(((FaunusEdge)faunusRelation).getVertexId(dir.opposite())):null); if (null == titanRelation) { DEFAULT_COMPAT.incrementContextCounter(context, Counters.NULL_RELATIONS_IGNORED, 1L); return null; } else if (faunusRelation.isRemoved()) { titanRelation.remove(); DEFAULT_COMPAT.incrementContextCounter(context, faunusRelation.isEdge() ? Counters.EDGES_REMOVED : Counters.VERTEX_PROPERTIES_REMOVED, 1L); return null; } } else if (trackState && faunusRelation.isLoaded()) { return null; } else { //Create new assert faunusRelation.isNew(); if (faunusRelation.isEdge()) { StandardFaunusEdge faunusEdge = (StandardFaunusEdge)faunusRelation; TitanVertex otherVertex = getOtherTitanVertex(faunusVertex, faunusEdge, dir.opposite(), graph); if (dir==IN) { titanRelation = otherVertex.addEdge(faunusEdge.getLabel(), titanVertex); } else { titanRelation = titanVertex.addEdge(faunusEdge.getLabel(), otherVertex); } DEFAULT_COMPAT.incrementContextCounter(context, Counters.EDGES_ADDED, 1L); } else { StandardFaunusProperty faunusProperty = (StandardFaunusProperty)faunusRelation; assert dir==OUT; titanRelation = titanVertex.addProperty(faunusProperty.getTypeName(),faunusProperty.getValue()); DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTEX_PROPERTIES_ADDED, 1L); } } synchronizeRelationProperties(graph, faunusRelation, titanRelation, context); return titanRelation; } private static TitanRelation synchronizeRelationProperties(final TitanGraph graph, final StandardFaunusRelation faunusRelation, final TitanRelation titanRelation, final Mapper.Context context) { if (faunusRelation.isModified() || faunusRelation.isNew()) { //Synchronize incident properties + unidirected edges for (TitanRelation faunusProp : faunusRelation.query().queryAll().relations()) { if (faunusProp.isRemoved()) { titanRelation.removeProperty(faunusProp.getType().getName()); DEFAULT_COMPAT.incrementContextCounter(context, Counters.EDGE_PROPERTIES_REMOVED, 1L); } } for (TitanRelation faunusProp : faunusRelation.query().queryAll().relations()) { if (faunusProp.isNew()) { Object value; if (faunusProp.isProperty()) { value = ((FaunusProperty)faunusProp).getValue(); } else { //TODO: ensure that the adjacent vertex has been previous assigned an id since ids don't propagate along unidirected edges value = graph.getVertex(((FaunusEdge)faunusProp).getVertexId(IN)); } titanRelation.setProperty(faunusProp.getType().getName(),value); DEFAULT_COMPAT.incrementContextCounter(context, Counters.EDGE_PROPERTIES_ADDED, 1L); } } } return titanRelation; } private static TitanVertex getOtherTitanVertex(final FaunusVertex faunusVertex, final FaunusEdge faunusEdge, final Direction otherDir, final TitanGraph graph) { Map<Long, Long> idMap = getIdMap(faunusVertex); Long othervertexid = faunusEdge.getVertexId(otherDir); if (null != idMap && idMap.containsKey(othervertexid)) othervertexid = idMap.get(othervertexid); TitanVertex otherVertex = (TitanVertex)graph.getVertex(othervertexid); //TODO: check that other vertex has valid id assignment for unidirected edges return otherVertex; } private static Map<Long, Long> getIdMap(final FaunusVertex faunusVertex) { Map<Long, Long> idMap = faunusVertex.getProperty(ID_MAP_KEY); if (null == idMap) idMap = ImmutableMap.of(); return idMap; } private static TitanRelation getIncidentRelation(final TitanGraph graph, final Direction dir, final TitanVertex titanVertex, final StandardFaunusRelation faunusRelation, Long otherTitanVertexId) { TitanVertexQuery qb = titanVertex.query().direction(dir).types(graph.getRelationType(faunusRelation.getTypeName())); if (faunusRelation.isEdge()) { TitanVertex otherVertex; if (otherTitanVertexId!=null) { otherVertex = (TitanVertex)graph.getVertex(otherTitanVertexId); } else { StandardFaunusEdge edge = (StandardFaunusEdge)faunusRelation; otherVertex = (TitanVertex) graph.getVertex(edge.getVertexId(dir.opposite())); } if (otherVertex!=null) qb.adjacent(otherVertex); else return null; } // qb.has(ImplicitKey.TITANID.getName(), Cmp.EQUAL, faunusRelation.getLongId()); TODO: must check for multiplicity constraints TitanRelation titanRelation = (TitanRelation)Iterables.getFirst(Iterables.filter(faunusRelation.isEdge()?qb.titanEdges():qb.properties(),new Predicate<TitanRelation>() { @Override public boolean apply(@Nullable TitanRelation rel) { return rel.getLongId()==faunusRelation.getLongId(); } }),null); assert titanRelation==null || titanRelation.getLongId()==faunusRelation.getLongId(); return titanRelation; } //MAPS FAUNUS VERTEXIDs to TITAN VERTEXIDs public static class Reduce extends Reducer<LongWritable, Holder<FaunusVertex>, NullWritable, FaunusVertex> { @Override public void reduce(final LongWritable key, final Iterable<Holder<FaunusVertex>> values, final Reducer<LongWritable, Holder<FaunusVertex>, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { FaunusVertex faunusVertex = null; // generate a map of the Titan/Hadoop id with the Titan id for all shell vertices (vertices incoming adjacent) final java.util.Map<Long, Object> idMap = new HashMap<Long, Object>(); for (final Holder<FaunusVertex> holder : values) { if (holder.getTag() == 's') { idMap.put(holder.get().getLongId(), holder.get().getProperty(TITAN_ID)); } else { faunusVertex = holder.get(); } } if (null != faunusVertex) { faunusVertex.setProperty(ID_MAP_KEY, idMap); context.write(NullWritable.get(), faunusVertex); } else { LOGGER.warn("No source vertex: hadoopVertex[" + key.get() + "]"); DEFAULT_COMPAT.incrementContextCounter(context, Counters.NULL_VERTICES_IGNORED, 1L); } } } // WRITE ALL THE EDGES CONNECTING THE VERTICES public static class EdgeMap extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> { private TitanGraph graph; private boolean trackState; private ModifiableHadoopConfiguration faunusConf; private LoaderScriptWrapper loaderScript; @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { faunusConf = ModifiableHadoopConfiguration.of(DEFAULT_COMPAT.getContextConfiguration(context)); graph = TitanGraphOutputMapReduce.generateGraph(faunusConf); trackState = context.getConfiguration().getBoolean(Tokens.TITAN_HADOOP_PIPELINE_TRACK_STATE, false); // Check whether a script is defined in the config if (faunusConf.has(OUTPUT_LOADER_SCRIPT_FILE)) { Path scriptPath = new Path(faunusConf.get(OUTPUT_LOADER_SCRIPT_FILE)); FileSystem scriptFS = FileSystem.get(DEFAULT_COMPAT.getJobContextConfiguration(context)); loaderScript = new LoaderScriptWrapper(scriptFS, scriptPath); } } @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { try { for (final TitanEdge edge : value.query().queryAll().direction(IN).titanEdges()) { this.getCreateOrDeleteEdge(value, (StandardFaunusEdge)edge, context); } } catch (final Exception e) { graph.rollback(); DEFAULT_COMPAT.incrementContextCounter(context, Counters.FAILED_TRANSACTIONS, 1L); throw new IOException(e.getMessage(), e); } } @Override public void cleanup(final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { try { graph.commit(); DEFAULT_COMPAT.incrementContextCounter(context, Counters.SUCCESSFUL_TRANSACTIONS, 1L); } catch (Exception e) { LOGGER.error("Could not commit transaction during Reduce.cleanup(): ", e); graph.rollback(); DEFAULT_COMPAT.incrementContextCounter(context, Counters.FAILED_TRANSACTIONS, 1L); throw new IOException(e.getMessage(), e); } graph.shutdown(); } public TitanEdge getCreateOrDeleteEdge(final FaunusVertex faunusVertex, final StandardFaunusEdge faunusEdge, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws InterruptedException { final Direction dir = IN; final TitanVertex titanVertex = (TitanVertex) this.graph.getVertex(faunusVertex.getProperty(TITAN_ID)); if (null != loaderScript && loaderScript.hasEdgeMethod()) { TitanEdge te = loaderScript.getEdge(faunusEdge, titanVertex, getOtherTitanVertex(faunusVertex, faunusEdge, dir.opposite(), graph), graph, context); synchronizeRelationProperties(graph, faunusEdge, te, context); return te; } else { return (TitanEdge) getCreateOrDeleteRelation(graph, trackState, dir, faunusVertex, titanVertex, faunusEdge, context); } } } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_formats_util_TitanGraphOutputMapReduce.java
247
public static class XBuilder { private Builder<Pair<Long, BytesRef>> builder; private int maxSurfaceFormsPerAnalyzedForm; private IntsRef scratchInts = new IntsRef(); private final PairOutputs<Long, BytesRef> outputs; private boolean hasPayloads; private BytesRef analyzed = new BytesRef(); private final SurfaceFormAndPayload[] surfaceFormsAndPayload; private int count; private ObjectIntOpenHashMap<BytesRef> seenSurfaceForms = HppcMaps.Object.Integer.ensureNoNullKeys(256, 0.75f); private int payloadSep; public XBuilder(int maxSurfaceFormsPerAnalyzedForm, boolean hasPayloads, int payloadSep) { this.payloadSep = payloadSep; this.outputs = new PairOutputs<Long, BytesRef>(PositiveIntOutputs.getSingleton(), ByteSequenceOutputs.getSingleton()); this.builder = new Builder<Pair<Long, BytesRef>>(FST.INPUT_TYPE.BYTE1, outputs); this.maxSurfaceFormsPerAnalyzedForm = maxSurfaceFormsPerAnalyzedForm; this.hasPayloads = hasPayloads; surfaceFormsAndPayload = new SurfaceFormAndPayload[maxSurfaceFormsPerAnalyzedForm]; } public void startTerm(BytesRef analyzed) { this.analyzed.copyBytes(analyzed); this.analyzed.grow(analyzed.length+2); } private final static class SurfaceFormAndPayload implements Comparable<SurfaceFormAndPayload> { BytesRef payload; long weight; public SurfaceFormAndPayload(BytesRef payload, long cost) { super(); this.payload = payload; this.weight = cost; } @Override public int compareTo(SurfaceFormAndPayload o) { int res = compare(weight, o.weight); if (res == 0 ){ return payload.compareTo(o.payload); } return res; } public static int compare(long x, long y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); } } public void addSurface(BytesRef surface, BytesRef payload, long cost) throws IOException { int surfaceIndex = -1; long encodedWeight = cost == -1 ? cost : encodeWeight(cost); /* * we need to check if we have seen this surface form, if so only use the * the surface form with the highest weight and drop the rest no matter if * the payload differs. */ if (count >= maxSurfaceFormsPerAnalyzedForm) { // More than maxSurfaceFormsPerAnalyzedForm // dups: skip the rest: return; } BytesRef surfaceCopy; if (count > 0 && seenSurfaceForms.containsKey(surface)) { surfaceIndex = seenSurfaceForms.lget(); SurfaceFormAndPayload surfaceFormAndPayload = surfaceFormsAndPayload[surfaceIndex]; if (encodedWeight >= surfaceFormAndPayload.weight) { return; } surfaceCopy = BytesRef.deepCopyOf(surface); } else { surfaceIndex = count++; surfaceCopy = BytesRef.deepCopyOf(surface); seenSurfaceForms.put(surfaceCopy, surfaceIndex); } BytesRef payloadRef; if (!hasPayloads) { payloadRef = surfaceCopy; } else { int len = surface.length + 1 + payload.length; final BytesRef br = new BytesRef(len); System.arraycopy(surface.bytes, surface.offset, br.bytes, 0, surface.length); br.bytes[surface.length] = (byte) payloadSep; System.arraycopy(payload.bytes, payload.offset, br.bytes, surface.length + 1, payload.length); br.length = len; payloadRef = br; } if (surfaceFormsAndPayload[surfaceIndex] == null) { surfaceFormsAndPayload[surfaceIndex] = new SurfaceFormAndPayload(payloadRef, encodedWeight); } else { surfaceFormsAndPayload[surfaceIndex].payload = payloadRef; surfaceFormsAndPayload[surfaceIndex].weight = encodedWeight; } } public void finishTerm(long defaultWeight) throws IOException { ArrayUtil.timSort(surfaceFormsAndPayload, 0, count); int deduplicator = 0; analyzed.bytes[analyzed.offset + analyzed.length] = 0; analyzed.length += 2; for (int i = 0; i < count; i++) { analyzed.bytes[analyzed.offset + analyzed.length - 1 ] = (byte) deduplicator++; Util.toIntsRef(analyzed, scratchInts); SurfaceFormAndPayload candiate = surfaceFormsAndPayload[i]; long cost = candiate.weight == -1 ? encodeWeight(Math.min(Integer.MAX_VALUE, defaultWeight)) : candiate.weight; builder.add(scratchInts, outputs.newPair(cost, candiate.payload)); } seenSurfaceForms.clear(); count = 0; } public FST<Pair<Long, BytesRef>> build() throws IOException { return builder.finish(); } public boolean hasPayloads() { return hasPayloads; } public int maxSurfaceFormsPerAnalyzedForm() { return maxSurfaceFormsPerAnalyzedForm; } }
0true
src_main_java_org_apache_lucene_search_suggest_analyzing_XAnalyzingSuggester.java
359
public class NodesStatsResponse extends NodesOperationResponse<NodeStats> implements ToXContent { NodesStatsResponse() { } public NodesStatsResponse(ClusterName clusterName, NodeStats[] nodes) { super(clusterName, nodes); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); nodes = new NodeStats[in.readVInt()]; for (int i = 0; i < nodes.length; i++) { nodes[i] = NodeStats.readNodeStats(in); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(nodes.length); for (NodeStats node : nodes) { node.writeTo(out); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.field("cluster_name", getClusterName().value()); builder.startObject("nodes"); for (NodeStats nodeStats : this) { builder.startObject(nodeStats.getNode().id(), XContentBuilder.FieldCaseConversion.NONE); builder.field("timestamp", nodeStats.getTimestamp()); nodeStats.toXContent(builder, params); builder.endObject(); } builder.endObject(); return builder; } @Override public String toString() { try { XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint(); builder.startObject(); toXContent(builder, EMPTY_PARAMS); builder.endObject(); return builder.string(); } catch (IOException e) { return "{ \"error\" : \"" + e.getMessage() + "\"}"; } } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_stats_NodesStatsResponse.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
99
LifecycleListener listener = new LifecycleListener() { public void stateChanged(LifecycleEvent event) { final LifecycleState state = list.poll(); if (state != null && state.equals(event.getState())) { latch.countDown(); } } };
0true
hazelcast-client_src_test_java_com_hazelcast_client_ClientIssueTest.java
1,218
public class TitanSchemaVertex extends CacheVertex implements SchemaSource { public TitanSchemaVertex(StandardTitanTx tx, long id, byte lifecycle) { super(tx, id, lifecycle); } private String name = null; @Override public String getName() { if (name == null) { TitanProperty p; if (isLoaded()) { StandardTitanTx tx = tx(); p = (TitanProperty) Iterables.getOnlyElement(RelationConstructor.readRelation(this, tx.getGraph().getSchemaCache().getSchemaRelations(getLongId(), BaseKey.SchemaName, Direction.OUT, tx()), tx), null); } else { p = Iterables.getOnlyElement(query().type(BaseKey.SchemaName).properties(), null); } Preconditions.checkState(p!=null,"Could not find type for id: %s", getLongId()); name = p.getValue(); } assert name != null; return TitanSchemaCategory.getName(name); } @Override protected Vertex getVertexLabelInternal() { return null; } private TypeDefinitionMap definition = null; @Override public TypeDefinitionMap getDefinition() { TypeDefinitionMap def = definition; if (def == null) { def = new TypeDefinitionMap(); Iterable<TitanProperty> ps; if (isLoaded()) { StandardTitanTx tx = tx(); ps = (Iterable)RelationConstructor.readRelation(this, tx.getGraph().getSchemaCache().getSchemaRelations(getLongId(), BaseKey.SchemaDefinitionProperty, Direction.OUT, tx()), tx); } else { ps = query().type(BaseKey.SchemaDefinitionProperty).properties(); } for (TitanProperty property : ps) { TypeDefinitionDescription desc = property.getProperty(BaseKey.SchemaDefinitionDesc); Preconditions.checkArgument(desc!=null && desc.getCategory().isProperty()); def.setValue(desc.getCategory(), property.getValue()); } assert def.size()>0; definition = def; } assert def!=null; return def; } private ListMultimap<TypeDefinitionCategory,Entry> outRelations = null; private ListMultimap<TypeDefinitionCategory,Entry> inRelations = null; @Override public Iterable<Entry> getRelated(TypeDefinitionCategory def, Direction dir) { assert dir==Direction.OUT || dir==Direction.IN; ListMultimap<TypeDefinitionCategory,Entry> rels = dir==Direction.OUT?outRelations:inRelations; if (rels==null) { ImmutableListMultimap.Builder<TypeDefinitionCategory,Entry> b = ImmutableListMultimap.builder(); Iterable<TitanEdge> edges; if (isLoaded()) { StandardTitanTx tx = tx(); edges = (Iterable)RelationConstructor.readRelation(this, tx.getGraph().getSchemaCache().getSchemaRelations(getLongId(), BaseLabel.SchemaDefinitionEdge, dir, tx()), tx); } else { edges = query().type(BaseLabel.SchemaDefinitionEdge).direction(dir).titanEdges(); } for (TitanEdge edge: edges) { TitanVertex oth = edge.getVertex(dir.opposite()); assert oth instanceof TitanSchemaVertex; TypeDefinitionDescription desc = edge.getProperty(BaseKey.SchemaDefinitionDesc); Object modifier = null; if (desc.getCategory().hasDataType()) { assert desc.getModifier()!=null && desc.getModifier().getClass().equals(desc.getCategory().getDataType()); modifier = desc.getModifier(); } b.put(desc.getCategory(), new Entry((TitanSchemaVertex) oth, modifier)); } rels = b.build(); if (dir==Direction.OUT) outRelations=rels; else inRelations=rels; } assert rels!=null; return rels.get(def); } /** * Resets the internal caches used to speed up lookups on this index type. * This is needed when the type gets modified in the {@link com.thinkaurelius.titan.graphdb.database.management.ManagementSystem}. */ public void resetCache() { name = null; definition=null; outRelations=null; inRelations=null; } public Iterable<TitanEdge> getEdges(final TypeDefinitionCategory def, final Direction dir) { return getEdges(def,dir,null); } public Iterable<TitanEdge> getEdges(final TypeDefinitionCategory def, final Direction dir, TitanSchemaVertex other) { TitanVertexQuery query = query().type(BaseLabel.SchemaDefinitionEdge).direction(dir); if (other!=null) query.adjacent(other); return Iterables.filter(query.titanEdges(),new Predicate<TitanEdge>() { @Override public boolean apply(@Nullable TitanEdge edge) { TypeDefinitionDescription desc = edge.getProperty(BaseKey.SchemaDefinitionDesc); return desc.getCategory()==def; } }); } @Override public String toString() { return getName(); } @Override public SchemaStatus getStatus() { return getDefinition().getValue(TypeDefinitionCategory.STATUS,SchemaStatus.class); } @Override public IndexType asIndexType() { Preconditions.checkArgument(getDefinition().containsKey(TypeDefinitionCategory.INTERNAL_INDEX),"Schema vertex is not a type vertex: [%s,%s]", getLongId(),getName()); if (getDefinition().getValue(TypeDefinitionCategory.INTERNAL_INDEX)) { return new CompositeIndexTypeWrapper(this); } else { return new MixedIndexTypeWrapper(this); } } }
1no label
titan-core_src_main_java_com_thinkaurelius_titan_graphdb_types_vertices_TitanSchemaVertex.java
226
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) /** * Tells to OrientDB to call the method AFTER the record is read and unmarshalled from database. * Applies only to the entity Objects reachable by the OrientDB engine after have registered them. */ public @interface OAfterDeserialization { }
0true
core_src_main_java_com_orientechnologies_orient_core_annotation_OAfterDeserialization.java
608
@Component("blRequestProcessor") public class BroadleafRequestProcessor extends AbstractBroadleafWebRequestProcessor { protected final Log LOG = LogFactory.getLog(getClass()); private static String REQUEST_DTO_PARAM_NAME = BroadleafRequestFilter.REQUEST_DTO_PARAM_NAME; @Resource(name = "blSiteResolver") protected BroadleafSiteResolver siteResolver; @Resource(name = "blLocaleResolver") protected BroadleafLocaleResolver localeResolver; @Resource(name = "blCurrencyResolver") protected BroadleafCurrencyResolver currencyResolver; @Resource(name = "blSandBoxResolver") protected BroadleafSandBoxResolver sandboxResolver; @Resource(name = "blThemeResolver") protected BroadleafThemeResolver themeResolver; @Resource(name = "messageSource") protected MessageSource messageSource; @Resource(name = "blTimeZoneResolver") protected BroadleafTimeZoneResolver broadleafTimeZoneResolver; @Override public void process(WebRequest request) { Site site = siteResolver.resolveSite(request); BroadleafRequestContext brc = new BroadleafRequestContext(); brc.setSite(site); brc.setWebRequest(request); if (site == null) { brc.setIgnoreSite(true); } BroadleafRequestContext.setBroadleafRequestContext(brc); Locale locale = localeResolver.resolveLocale(request); TimeZone timeZone = broadleafTimeZoneResolver.resolveTimeZone(request); BroadleafCurrency currency = currencyResolver.resolveCurrency(request); // Assumes BroadleafProcess RequestDTO requestDTO = (RequestDTO) request.getAttribute(REQUEST_DTO_PARAM_NAME, WebRequest.SCOPE_REQUEST); if (requestDTO == null) { requestDTO = new RequestDTOImpl(request); } SandBox currentSandbox = sandboxResolver.resolveSandBox(request, site); if (currentSandbox != null) { SandBoxContext previewSandBoxContext = new SandBoxContext(); previewSandBoxContext.setSandBoxId(currentSandbox.getId()); previewSandBoxContext.setPreviewMode(true); SandBoxContext.setSandBoxContext(previewSandBoxContext); } // Note that this must happen after the request context is set up as resolving a theme is dependent on site Theme theme = themeResolver.resolveTheme(request); brc.setLocale(locale); brc.setBroadleafCurrency(currency); brc.setSandbox(currentSandbox); brc.setTheme(theme); brc.setMessageSource(messageSource); brc.setTimeZone(timeZone); brc.setRequestDTO(requestDTO); Map<String, Object> ruleMap = (Map<String, Object>) request.getAttribute("blRuleMap", WebRequest.SCOPE_REQUEST); if (ruleMap == null) { LOG.trace("Creating ruleMap and adding in Locale."); ruleMap = new HashMap<String, Object>(); request.setAttribute("blRuleMap", ruleMap, WebRequest.SCOPE_REQUEST); } else { LOG.trace("Using pre-existing ruleMap - added by non standard BLC process."); } ruleMap.put("locale", locale); } @Override public void postProcess(WebRequest request) { ThreadLocalManager.remove(); //temporary workaround for Thymeleaf issue #18 (resolved in version 2.1) //https://github.com/thymeleaf/thymeleaf-spring3/issues/18 try { Field currentProcessLocale = TemplateEngine.class.getDeclaredField("currentProcessLocale"); currentProcessLocale.setAccessible(true); ((ThreadLocal) currentProcessLocale.get(null)).remove(); Field currentProcessTemplateEngine = TemplateEngine.class.getDeclaredField("currentProcessTemplateEngine"); currentProcessTemplateEngine.setAccessible(true); ((ThreadLocal) currentProcessTemplateEngine.get(null)).remove(); Field currentProcessTemplateName = TemplateEngine.class.getDeclaredField("currentProcessTemplateName"); currentProcessTemplateName.setAccessible(true); ((ThreadLocal) currentProcessTemplateName.get(null)).remove(); } catch (Throwable e) { LOG.warn("Unable to remove Thymeleaf threadlocal variables from request thread", e); } } }
1no label
common_src_main_java_org_broadleafcommerce_common_web_BroadleafRequestProcessor.java
990
@SuppressWarnings("serial") public class ORecordSerializerJSON extends ORecordSerializerStringAbstract { public static final String NAME = "json"; public static final ORecordSerializerJSON INSTANCE = new ORecordSerializerJSON(); public static final String ATTRIBUTE_FIELD_TYPES = "@fieldTypes"; public static final char[] PARAMETER_SEPARATOR = new char[] { ':', ',' }; private static final Long MAX_INT = new Long(Integer.MAX_VALUE); private static final Long MIN_INT = new Long(Integer.MIN_VALUE); private static final Double MAX_FLOAT = new Double(Float.MAX_VALUE); private static final Double MIN_FLOAT = new Double(Float.MIN_VALUE); public class FormatSettings { public boolean includeVer; public boolean includeType; public boolean includeId; public boolean includeClazz; public boolean attribSameRow; public boolean alwaysFetchEmbeddedDocuments; public int indentLevel; public String fetchPlan = null; public boolean keepTypes = true; public boolean dateAsLong = false; public boolean prettyPrint = false; public FormatSettings(final String iFormat) { if (iFormat == null) { includeType = true; includeVer = true; includeId = true; includeClazz = true; attribSameRow = true; indentLevel = 1; fetchPlan = ""; keepTypes = true; alwaysFetchEmbeddedDocuments = true; } else { includeType = false; includeVer = false; includeId = false; includeClazz = false; attribSameRow = false; alwaysFetchEmbeddedDocuments = false; indentLevel = 1; keepTypes = false; final String[] format = iFormat.split(","); for (String f : format) if (f.equals("type")) includeType = true; else if (f.equals("rid")) includeId = true; else if (f.equals("version")) includeVer = true; else if (f.equals("class")) includeClazz = true; else if (f.equals("attribSameRow")) attribSameRow = true; else if (f.startsWith("indent")) indentLevel = Integer.parseInt(f.substring(f.indexOf(':') + 1)); else if (f.startsWith("fetchPlan")) fetchPlan = f.substring(f.indexOf(':') + 1); else if (f.startsWith("keepTypes")) keepTypes = true; else if (f.startsWith("alwaysFetchEmbedded")) alwaysFetchEmbeddedDocuments = true; else if (f.startsWith("dateAsLong")) dateAsLong = true; else if (f.startsWith("prettyPrint")) prettyPrint = true; } } } public ORecordInternal<?> fromString(String iSource, ORecordInternal<?> iRecord, final String[] iFields, boolean needReload) { return fromString(iSource, iRecord, iFields, null, needReload); } @Override public ORecordInternal<?> fromString(String iSource, ORecordInternal<?> iRecord, final String[] iFields) { return fromString(iSource, iRecord, iFields, null, false); } public ORecordInternal<?> fromString(String iSource, ORecordInternal<?> iRecord, final String[] iFields, final String iOptions, boolean needReload) { if (iSource == null) throw new OSerializationException("Error on unmarshalling JSON content: content is null"); iSource = iSource.trim(); if (!iSource.startsWith("{") || !iSource.endsWith("}")) throw new OSerializationException("Error on unmarshalling JSON content: content must be between { }"); if (iRecord != null) // RESET ALL THE FIELDS iRecord.clear(); iSource = iSource.substring(1, iSource.length() - 1).trim(); // PARSE OPTIONS boolean noMap = false; if (iOptions != null) { final String[] format = iOptions.split(","); for (String f : format) if (f.equals("noMap")) noMap = true; } final List<String> fields = OStringSerializerHelper.smartSplit(iSource, PARAMETER_SEPARATOR, 0, -1, true, true, false, ' ', '\n', '\r', '\t'); if (fields.size() % 2 != 0) throw new OSerializationException("Error on unmarshalling JSON content: wrong format. Use <field> : <value>"); Map<String, Character> fieldTypes = null; if (fields != null && fields.size() > 0) { // SEARCH FOR FIELD TYPES IF ANY for (int i = 0; i < fields.size(); i += 2) { final String fieldName = OStringSerializerHelper.getStringContent(fields.get(i)); final String fieldValue = fields.get(i + 1); final String fieldValueAsString = OStringSerializerHelper.getStringContent(fieldValue); if (fieldName.equals(ATTRIBUTE_FIELD_TYPES) && iRecord instanceof ODocument) { // LOAD THE FIELD TYPE MAP final String[] fieldTypesParts = fieldValueAsString.split(","); if (fieldTypesParts.length > 0) { fieldTypes = new HashMap<String, Character>(); String[] part; for (String f : fieldTypesParts) { part = f.split("="); if (part.length == 2) fieldTypes.put(part[0], part[1].charAt(0)); } } } else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_TYPE)) { if (iRecord == null || iRecord.getRecordType() != fieldValueAsString.charAt(0)) { // CREATE THE RIGHT RECORD INSTANCE iRecord = Orient.instance().getRecordFactoryManager().newInstance((byte) fieldValueAsString.charAt(0)); } } else if (needReload && fieldName.equals(ODocumentHelper.ATTRIBUTE_RID) && iRecord instanceof ODocument) { if (fieldValue != null && fieldValue.length() > 0) { ORecordInternal<?> localRecord = ODatabaseRecordThreadLocal.INSTANCE.get().load(new ORecordId(fieldValueAsString)); if (localRecord != null) iRecord = localRecord; } } else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_CLASS) && iRecord instanceof ODocument) { ((ODocument) iRecord).setClassNameIfExists("null".equals(fieldValueAsString) ? null : fieldValueAsString); } } try { int recordVersion = 0; long timestamp = 0L; long macAddress = 0L; for (int i = 0; i < fields.size(); i += 2) { final String fieldName = OStringSerializerHelper.getStringContent(fields.get(i)); final String fieldValue = fields.get(i + 1); final String fieldValueAsString = OStringSerializerHelper.getStringContent(fieldValue); // RECORD ATTRIBUTES if (fieldName.equals(ODocumentHelper.ATTRIBUTE_RID)) iRecord.setIdentity(new ORecordId(fieldValueAsString)); else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_VERSION)) if (OGlobalConfiguration.DB_USE_DISTRIBUTED_VERSION.getValueAsBoolean()) recordVersion = Integer.parseInt(fieldValue); else iRecord.getRecordVersion().setCounter(Integer.parseInt(fieldValue)); else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_VERSION_TIMESTAMP)) { if (OGlobalConfiguration.DB_USE_DISTRIBUTED_VERSION.getValueAsBoolean()) timestamp = Long.parseLong(fieldValue); } else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_VERSION_MACADDRESS)) { if (OGlobalConfiguration.DB_USE_DISTRIBUTED_VERSION.getValueAsBoolean()) macAddress = Long.parseLong(fieldValue); } else if (fieldName.equals(ODocumentHelper.ATTRIBUTE_TYPE)) { continue; } else if (fieldName.equals(ATTRIBUTE_FIELD_TYPES) && iRecord instanceof ODocument) // JUMP IT continue; // RECORD VALUE(S) else if (fieldName.equals("value") && !(iRecord instanceof ODocument)) { if ("null".equals(fieldValue)) iRecord.fromStream(new byte[] {}); else if (iRecord instanceof ORecordBytes) { // BYTES iRecord.fromStream(OBase64Utils.decode(fieldValueAsString)); } else if (iRecord instanceof ORecordStringable) { ((ORecordStringable) iRecord).value(fieldValueAsString); } } else { if (iRecord instanceof ODocument) { final ODocument doc = ((ODocument) iRecord); // DETERMINE THE TYPE FROM THE SCHEMA OType type = null; final OClass cls = doc.getSchemaClass(); if (cls != null) { final OProperty prop = cls.getProperty(fieldName); if (prop != null) type = prop.getType(); } final Object v = getValue(doc, fieldName, fieldValue, fieldValueAsString, type, null, fieldTypes, noMap, iOptions); if (v != null) if (v instanceof Collection<?> && !((Collection<?>) v).isEmpty()) { if (v instanceof ORecordLazyMultiValue) ((ORecordLazyMultiValue) v).setAutoConvertToRecord(false); // CHECK IF THE COLLECTION IS EMBEDDED if (type == null) { // TRY TO UNDERSTAND BY FIRST ITEM Object first = ((Collection<?>) v).iterator().next(); if (first != null && first instanceof ORecord<?> && !((ORecord<?>) first).getIdentity().isValid()) type = v instanceof Set<?> ? OType.EMBEDDEDSET : OType.EMBEDDEDLIST; } if (type != null) { // TREAT IT AS EMBEDDED doc.field(fieldName, v, type); continue; } } else if (v instanceof Map<?, ?> && !((Map<?, ?>) v).isEmpty()) { // CHECK IF THE MAP IS EMBEDDED Object first = ((Map<?, ?>) v).values().iterator().next(); if (first != null && first instanceof ORecord<?> && !((ORecord<?>) first).getIdentity().isValid()) { doc.field(fieldName, v, OType.EMBEDDEDMAP); continue; } } else if (v instanceof ODocument && type != null && type.isLink()) { String className = ((ODocument) v).getClassName(); if (className != null && className.length() > 0) ((ODocument) v).save(); } if (type == null && fieldTypes != null && fieldTypes.containsKey(fieldName)) type = ORecordSerializerStringAbstract.getType(fieldValue, fieldTypes.get(fieldName)); if (type != null) doc.field(fieldName, v, type); else doc.field(fieldName, v); } } } if (timestamp != 0 && OGlobalConfiguration.DB_USE_DISTRIBUTED_VERSION.getValueAsBoolean()) { ((ODistributedVersion) iRecord.getRecordVersion()).update(recordVersion, timestamp, macAddress); } } catch (Exception e) { e.printStackTrace(); throw new OSerializationException("Error on unmarshalling JSON content for record " + iRecord.getIdentity(), e); } } return iRecord; } @SuppressWarnings("unchecked") private Object getValue(final ODocument iRecord, String iFieldName, String iFieldValue, String iFieldValueAsString, OType iType, OType iLinkedType, final Map<String, Character> iFieldTypes, final boolean iNoMap, final String iOptions) { if (iFieldValue.equals("null")) return null; if (iFieldName != null) if (iRecord.getSchemaClass() != null) { final OProperty p = iRecord.getSchemaClass().getProperty(iFieldName); if (p != null) { iType = p.getType(); iLinkedType = p.getLinkedType(); } } if (iFieldValue.startsWith("{") && iFieldValue.endsWith("}")) { // OBJECT OR MAP. CHECK THE TYPE ATTRIBUTE TO KNOW IT iFieldValueAsString = iFieldValue.substring(1, iFieldValue.length() - 1); final String[] fields = OStringParser.getWords(iFieldValueAsString, ":,", true); if (fields == null || fields.length == 0) // EMPTY, RETURN an EMPTY HASHMAP return new HashMap<String, Object>(); if (iNoMap || hasTypeField(fields)) { // OBJECT final ORecordInternal<?> recordInternal = fromString(iFieldValue, new ODocument(), null, iOptions, false); if (iType != null && iType.isLink()) { } else if (recordInternal instanceof ODocument) ((ODocument) recordInternal).addOwner(iRecord); return recordInternal; } else { if (fields.length % 2 == 1) throw new OSerializationException("Bad JSON format on map. Expected pairs of field:value but received '" + iFieldValueAsString + "'"); // MAP final Map<String, Object> embeddedMap = new LinkedHashMap<String, Object>(); for (int i = 0; i < fields.length; i += 2) { iFieldName = fields[i]; if (iFieldName.length() >= 2) iFieldName = iFieldName.substring(1, iFieldName.length() - 1); iFieldValue = fields[i + 1]; iFieldValueAsString = OStringSerializerHelper.getStringContent(iFieldValue); embeddedMap.put(iFieldName, getValue(iRecord, null, iFieldValue, iFieldValueAsString, iLinkedType, null, iFieldTypes, iNoMap, iOptions)); } return embeddedMap; } } else if (iFieldValue.startsWith("[") && iFieldValue.endsWith("]")) { // EMBEDDED VALUES final Collection<?> embeddedCollection; if (iType == OType.LINKSET) embeddedCollection = new OMVRBTreeRIDSet(iRecord); else if (iType == OType.EMBEDDEDSET) embeddedCollection = new OTrackedSet<Object>(iRecord); else if (iType == OType.LINKLIST) embeddedCollection = new ORecordLazyList(iRecord); else embeddedCollection = new OTrackedList<Object>(iRecord); iFieldValue = iFieldValue.substring(1, iFieldValue.length() - 1); if (!iFieldValue.isEmpty()) { // EMBEDDED VALUES List<String> items = OStringSerializerHelper.smartSplit(iFieldValue, ','); Object collectionItem; for (String item : items) { iFieldValue = item.trim(); if (!(iLinkedType == OType.DATE || iLinkedType == OType.BYTE || iLinkedType == OType.INTEGER || iLinkedType == OType.LONG || iLinkedType == OType.DATETIME || iLinkedType == OType.DECIMAL || iLinkedType == OType.DOUBLE || iLinkedType == OType.FLOAT)) iFieldValueAsString = iFieldValue.length() >= 2 ? iFieldValue.substring(1, iFieldValue.length() - 1) : iFieldValue; else iFieldValueAsString = iFieldValue; collectionItem = getValue(iRecord, null, iFieldValue, iFieldValueAsString, iLinkedType, null, iFieldTypes, iNoMap, iOptions); if (iType != null && iType.isLink()) { // LINK } else if (collectionItem instanceof ODocument && iRecord instanceof ODocument) // SET THE OWNER ((ODocument) collectionItem).addOwner(iRecord); if (collectionItem instanceof String && ((String) collectionItem).length() == 0) continue; ((Collection<Object>) embeddedCollection).add(collectionItem); } } return embeddedCollection; } if (iType == null) // TRY TO DETERMINE THE CONTAINED TYPE from THE FIRST VALUE if (iFieldValue.charAt(0) != '\"' && iFieldValue.charAt(0) != '\'') { if (iFieldValue.equalsIgnoreCase("false") || iFieldValue.equalsIgnoreCase("true")) iType = OType.BOOLEAN; else { Character c = null; if (iFieldTypes != null) { c = iFieldTypes.get(iFieldName); if (c != null) iType = ORecordSerializerStringAbstract.getType(iFieldValue + c); } if (c == null && !iFieldValue.isEmpty()) { // TRY TO AUTODETERMINE THE BEST TYPE if (iFieldValue.charAt(0) == ORID.PREFIX && iFieldValue.contains(":")) iType = OType.LINK; else if (OStringSerializerHelper.contains(iFieldValue, '.')) { // DECIMAL FORMAT: DETERMINE IF DOUBLE OR FLOAT final Double v = new Double(OStringSerializerHelper.getStringContent(iFieldValue)); if (v.doubleValue() > 0) { // POSITIVE NUMBER if (v.compareTo(MAX_FLOAT) <= 0) return v.floatValue(); } else if (v.compareTo(MIN_FLOAT) >= 0) // NEGATIVE NUMBER return v.floatValue(); return v; } else { final Long v = new Long(OStringSerializerHelper.getStringContent(iFieldValue)); // INTEGER FORMAT: DETERMINE IF DOUBLE OR FLOAT if (v.longValue() > 0) { // POSITIVE NUMBER if (v.compareTo(MAX_INT) <= 0) return v.intValue(); } else if (v.compareTo(MIN_INT) >= 0) // NEGATIVE NUMBER return v.intValue(); return v; } } } } else if (iFieldValue.startsWith("{") && iFieldValue.endsWith("}")) iType = OType.EMBEDDED; else { if (iFieldValueAsString.length() >= 4 && iFieldValueAsString.charAt(0) == ORID.PREFIX && iFieldValueAsString.contains(":")) { // IS IT A LINK? final List<String> parts = OStringSerializerHelper.split(iFieldValueAsString, 1, -1, ':'); if (parts.size() == 2) try { Short.parseShort(parts.get(0)); // YES, IT'S A LINK if (parts.get(1).matches("\\d+")) { iType = OType.LINK; } } catch (Exception e) { } } if (iFieldTypes != null) { Character c = null; c = iFieldTypes.get(iFieldName); if (c != null) iType = ORecordSerializerStringAbstract.getType(iFieldValueAsString, c); } if (iType == null) { if (iFieldValueAsString.length() == ODateHelper.getDateFormat().length()) // TRY TO PARSE AS DATE try { return ODateHelper.getDateFormatInstance().parseObject(iFieldValueAsString); } catch (Exception e) { // IGNORE IT } if (iFieldValueAsString.length() == ODateHelper.getDateTimeFormat().length()) // TRY TO PARSE AS DATETIME try { return ODateHelper.getDateTimeFormatInstance().parseObject(iFieldValueAsString); } catch (Exception e) { // IGNORE IT } iType = OType.STRING; } } if (iType != null) switch (iType) { case STRING: return decodeJSON(iFieldValueAsString); case LINK: final int pos = iFieldValueAsString.indexOf('@'); if (pos > -1) // CREATE DOCUMENT return new ODocument(iFieldValueAsString.substring(1, pos), new ORecordId(iFieldValueAsString.substring(pos + 1))); else { // CREATE SIMPLE RID return new ORecordId(iFieldValueAsString); } case EMBEDDED: return fromString(iFieldValueAsString); case DATE: if (iFieldValueAsString == null || iFieldValueAsString.equals("")) return null; try { // TRY TO PARSE AS LONG return Long.parseLong(iFieldValueAsString); } catch (NumberFormatException e) { try { // TRY TO PARSE AS DATE return ODateHelper.getDateFormatInstance().parseObject(iFieldValueAsString); } catch (ParseException ex) { throw new OSerializationException("Unable to unmarshall date (format=" + ODateHelper.getDateFormat() + ") : " + iFieldValueAsString, e); } } case DATETIME: if (iFieldValueAsString == null || iFieldValueAsString.equals("")) return null; try { // TRY TO PARSE AS LONG return Long.parseLong(iFieldValueAsString); } catch (NumberFormatException e) { try { // TRY TO PARSE AS DATETIME return ODateHelper.getDateTimeFormatInstance().parseObject(iFieldValueAsString); } catch (ParseException ex) { throw new OSerializationException("Unable to unmarshall datetime (format=" + ODateHelper.getDateTimeFormat() + ") : " + iFieldValueAsString, e); } } case BINARY: return OStringSerializerHelper.fieldTypeFromStream(iRecord, iType, iFieldValueAsString); default: return OStringSerializerHelper.fieldTypeFromStream(iRecord, iType, iFieldValue); } return iFieldValueAsString; } private String decodeJSON(String iFieldValueAsString) { iFieldValueAsString = OStringParser.replaceAll(iFieldValueAsString, "\\\\", "\\"); iFieldValueAsString = OStringParser.replaceAll(iFieldValueAsString, "\\\"", "\""); iFieldValueAsString = OStringParser.replaceAll(iFieldValueAsString, "\\/", "/"); return iFieldValueAsString; } @Override public StringBuilder toString(final ORecordInternal<?> iRecord, final StringBuilder iOutput, final String iFormat, final OUserObject2RecordHandler iObjHandler, final Set<ODocument> iMarshalledRecords, boolean iOnlyDelta, boolean autoDetectCollectionType) { try { final StringWriter buffer = new StringWriter(); final OJSONWriter json = new OJSONWriter(buffer, iFormat); final FormatSettings settings = new FormatSettings(iFormat); json.beginObject(); OJSONFetchContext context = new OJSONFetchContext(json, settings); context.writeSignature(json, iRecord); if (iRecord instanceof ORecordSchemaAware<?>) { OFetchHelper.fetch(iRecord, null, OFetchHelper.buildFetchPlan(settings.fetchPlan), new OJSONFetchListener(), context, iFormat); } else if (iRecord instanceof ORecordStringable) { // STRINGABLE final ORecordStringable record = (ORecordStringable) iRecord; json.writeAttribute(settings.indentLevel + 1, true, "value", record.value()); } else if (iRecord instanceof ORecordBytes) { // BYTES final ORecordBytes record = (ORecordBytes) iRecord; json.writeAttribute(settings.indentLevel + 1, true, "value", OBase64Utils.encodeBytes(record.toStream())); } else throw new OSerializationException("Error on marshalling record of type '" + iRecord.getClass() + "' to JSON. The record type cannot be exported to JSON"); json.endObject(0, true); iOutput.append(buffer); return iOutput; } catch (IOException e) { throw new OSerializationException("Error on marshalling of record to JSON", e); } } private boolean hasTypeField(final String[] fields) { for (int i = 0; i < fields.length; i = i + 2) { if (fields[i].equals("\"@type\"") || fields[i].equals("'@type'")) { return true; } } return false; } @Override public String toString() { return NAME; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_serialization_serializer_record_string_ORecordSerializerJSON.java
177
public class MersenneTwisterFast implements Serializable, Cloneable { // Serialization private static final long serialVersionUID = -8219700664442619525L; // locked as of Version 15 // Period parameters private static final int N = 624; private static final int M = 397; private static final int MATRIX_A = 0x9908b0df; // private static final * constant vector a private static final int UPPER_MASK = 0x80000000; // most significant w-r bits private static final int LOWER_MASK = 0x7fffffff; // least significant r bits // Tempering parameters private static final int TEMPERING_MASK_B = 0x9d2c5680; private static final int TEMPERING_MASK_C = 0xefc60000; private int mt[]; // the array for the state vector private int mti; // mti==N+1 means mt[N] is not initialized private int mag01[]; // a good initial seed (of int size, though stored in a long) //private static final long GOOD_SEED = 4357; private double __nextNextGaussian; private boolean __haveNextNextGaussian; /* We're overriding all internal data, to my knowledge, so this should be okay */ public Object clone() { try { MersenneTwisterFast f = (MersenneTwisterFast)(super.clone()); f.mt = (int[])(mt.clone()); f.mag01 = (int[])(mag01.clone()); return f; } catch (CloneNotSupportedException e) { throw new InternalError(); } // should never happen } public boolean stateEquals(Object o) { if (o==this) return true; if (o == null || !(o instanceof MersenneTwisterFast)) return false; MersenneTwisterFast other = (MersenneTwisterFast) o; if (mti != other.mti) return false; for(int x=0;x<mag01.length;x++) if (mag01[x] != other.mag01[x]) return false; for(int x=0;x<mt.length;x++) if (mt[x] != other.mt[x]) return false; return true; } /** Reads the entire state of the MersenneTwister RNG from the stream */ public void readState(DataInputStream stream) throws IOException { int len = mt.length; for(int x=0;x<len;x++) mt[x] = stream.readInt(); len = mag01.length; for(int x=0;x<len;x++) mag01[x] = stream.readInt(); mti = stream.readInt(); __nextNextGaussian = stream.readDouble(); __haveNextNextGaussian = stream.readBoolean(); } /** Writes the entire state of the MersenneTwister RNG to the stream */ public void writeState(DataOutputStream stream) throws IOException { int len = mt.length; for(int x=0;x<len;x++) stream.writeInt(mt[x]); len = mag01.length; for(int x=0;x<len;x++) stream.writeInt(mag01[x]); stream.writeInt(mti); stream.writeDouble(__nextNextGaussian); stream.writeBoolean(__haveNextNextGaussian); } /** * Constructor using the default seed. */ public MersenneTwisterFast() { this(System.currentTimeMillis()); } /** * Constructor using a given seed. Though you pass this seed in * as a long, it's best to make sure it's actually an integer. * */ public MersenneTwisterFast(final long seed) { setSeed(seed); } /** * Constructor using an array of integers as seed. * Your array must have a non-zero length. Only the first 624 integers * in the array are used; if the array is shorter than this then * integers are repeatedly used in a wrap-around fashion. */ public MersenneTwisterFast(final int[] array) { setSeed(array); } /** * Initalize the pseudo random number generator. Don't * pass in a long that's bigger than an int (Mersenne Twister * only uses the first 32 bits for its seed). */ synchronized public void setSeed(final long seed) { // Due to a bug in java.util.Random clear up to 1.2, we're // doing our own Gaussian variable. __haveNextNextGaussian = false; mt = new int[N]; mag01 = new int[2]; mag01[0] = 0x0; mag01[1] = MATRIX_A; mt[0]= (int)(seed & 0xffffffff); for (mti=1; mti<N; mti++) { mt[mti] = (1812433253 * (mt[mti-1] ^ (mt[mti-1] >>> 30)) + mti); /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array mt[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ mt[mti] &= 0xffffffff; /* for >32 bit machines */ } } /** * Sets the seed of the MersenneTwister using an array of integers. * Your array must have a non-zero length. Only the first 624 integers * in the array are used; if the array is shorter than this then * integers are repeatedly used in a wrap-around fashion. */ synchronized public void setSeed(final int[] array) { if (array.length == 0) throw new IllegalArgumentException("Array length must be greater than zero"); int i, j, k; setSeed(19650218); i=1; j=0; k = (N>array.length ? N : array.length); for (; k!=0; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * 1664525)) + array[j] + j; /* non linear */ mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */ i++; j++; if (i>=N) { mt[0] = mt[N-1]; i=1; } if (j>=array.length) j=0; } for (k=N-1; k!=0; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * 1566083941)) - i; /* non linear */ mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */ i++; if (i>=N) { mt[0] = mt[N-1]; i=1; } } mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ } public final int nextInt() { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return y; } public final short nextShort() { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (short)(y >>> 16); } public final char nextChar() { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (char)(y >>> 16); } public final boolean nextBoolean() { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (boolean)((y >>> 31) != 0); } /** This generates a coin flip with a probability <tt>probability</tt> of returning true, else returning false. <tt>probability</tt> must be between 0.0 and 1.0, inclusive. Not as precise a random real event as nextBoolean(double), but twice as fast. To explicitly use this, remember you may need to cast to float first. */ public final boolean nextBoolean(final float probability) { int y; if (probability < 0.0f || probability > 1.0f) throw new IllegalArgumentException ("probability must be between 0.0 and 1.0 inclusive."); if (probability==0.0f) return false; // fix half-open issues else if (probability==1.0f) return true; // fix half-open issues if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (y >>> 8) / ((float)(1 << 24)) < probability; } /** This generates a coin flip with a probability <tt>probability</tt> of returning true, else returning false. <tt>probability</tt> must be between 0.0 and 1.0, inclusive. */ public final boolean nextBoolean(final double probability) { int y; int z; if (probability < 0.0 || probability > 1.0) throw new IllegalArgumentException ("probability must be between 0.0 and 1.0 inclusive."); if (probability==0.0) return false; // fix half-open issues else if (probability==1.0) return true; // fix half-open issues if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1]; } for (; kk < N-1; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1]; } z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1]; mti = 0; } z = mt[mti++]; z ^= z >>> 11; // TEMPERING_SHIFT_U(z) z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z) z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z) z ^= (z >>> 18); // TEMPERING_SHIFT_L(z) /* derived from nextDouble documentation in jdk 1.2 docs, see top */ return ((((long)(y >>> 6)) << 27) + (z >>> 5)) / (double)(1L << 53) < probability; } public final byte nextByte() { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (byte)(y >>> 24); } public final void nextBytes(byte[] bytes) { int y; for (int x=0;x<bytes.length;x++) { if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) bytes[x] = (byte)(y >>> 24); } } public final long nextLong() { int y; int z; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1]; } for (; kk < N-1; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1]; } z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1]; mti = 0; } z = mt[mti++]; z ^= z >>> 11; // TEMPERING_SHIFT_U(z) z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z) z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z) z ^= (z >>> 18); // TEMPERING_SHIFT_L(z) return (((long)y) << 32) + (long)z; } /** Returns a long drawn uniformly from 0 to n-1. Suffice it to say, n must be > 0, or an IllegalArgumentException is raised. */ public final long nextLong(final long n) { if (n<=0) throw new IllegalArgumentException("n must be positive, got: " + n); long bits, val; do { int y; int z; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1]; } for (; kk < N-1; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1]; } z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1]; mti = 0; } z = mt[mti++]; z ^= z >>> 11; // TEMPERING_SHIFT_U(z) z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z) z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z) z ^= (z >>> 18); // TEMPERING_SHIFT_L(z) bits = (((((long)y) << 32) + (long)z) >>> 1); val = bits % n; } while (bits - val + (n-1) < 0); return val; } /** Returns a random double in the half-open range from [0.0,1.0). Thus 0.0 is a valid result but 1.0 is not. */ public final double nextDouble() { int y; int z; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1]; } for (; kk < N-1; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1]; } z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1]; mti = 0; } z = mt[mti++]; z ^= z >>> 11; // TEMPERING_SHIFT_U(z) z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z) z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z) z ^= (z >>> 18); // TEMPERING_SHIFT_L(z) /* derived from nextDouble documentation in jdk 1.2 docs, see top */ return ((((long)(y >>> 6)) << 27) + (z >>> 5)) / (double)(1L << 53); } /** Returns a double in the range from 0.0 to 1.0, possibly inclusive of 0.0 and 1.0 themselves. Thus: <p><table border=0> <th><td>Expression<td>Interval <tr><td>nextDouble(false, false)<td>(0.0, 1.0) <tr><td>nextDouble(true, false)<td>[0.0, 1.0) <tr><td>nextDouble(false, true)<td>(0.0, 1.0] <tr><td>nextDouble(true, true)<td>[0.0, 1.0] </table> <p>This version preserves all possible random values in the double range. */ public double nextDouble(boolean includeZero, boolean includeOne) { double d = 0.0; do { d = nextDouble(); // grab a value, initially from half-open [0.0, 1.0) if (includeOne && nextBoolean()) d += 1.0; // if includeOne, with 1/2 probability, push to [1.0, 2.0) } while ( (d > 1.0) || // everything above 1.0 is always invalid (!includeZero && d == 0.0)); // if we're not including zero, 0.0 is invalid return d; } public final double nextGaussian() { if (__haveNextNextGaussian) { __haveNextNextGaussian = false; return __nextNextGaussian; } else { double v1, v2, s; do { int y; int z; int a; int b; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (z >>> 1) ^ mag01[z & 0x1]; } for (; kk < N-1; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (z >>> 1) ^ mag01[z & 0x1]; } z = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (z >>> 1) ^ mag01[z & 0x1]; mti = 0; } z = mt[mti++]; z ^= z >>> 11; // TEMPERING_SHIFT_U(z) z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z) z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z) z ^= (z >>> 18); // TEMPERING_SHIFT_L(z) if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { a = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (a >>> 1) ^ mag01[a & 0x1]; } for (; kk < N-1; kk++) { a = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (a >>> 1) ^ mag01[a & 0x1]; } a = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (a >>> 1) ^ mag01[a & 0x1]; mti = 0; } a = mt[mti++]; a ^= a >>> 11; // TEMPERING_SHIFT_U(a) a ^= (a << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(a) a ^= (a << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(a) a ^= (a >>> 18); // TEMPERING_SHIFT_L(a) if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { b = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (b >>> 1) ^ mag01[b & 0x1]; } for (; kk < N-1; kk++) { b = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (b >>> 1) ^ mag01[b & 0x1]; } b = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (b >>> 1) ^ mag01[b & 0x1]; mti = 0; } b = mt[mti++]; b ^= b >>> 11; // TEMPERING_SHIFT_U(b) b ^= (b << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(b) b ^= (b << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(b) b ^= (b >>> 18); // TEMPERING_SHIFT_L(b) /* derived from nextDouble documentation in jdk 1.2 docs, see top */ v1 = 2 * (((((long)(y >>> 6)) << 27) + (z >>> 5)) / (double)(1L << 53)) - 1; v2 = 2 * (((((long)(a >>> 6)) << 27) + (b >>> 5)) / (double)(1L << 53)) - 1; s = v1 * v1 + v2 * v2; } while (s >= 1 || s==0); double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s); __nextNextGaussian = v2 * multiplier; __haveNextNextGaussian = true; return v1 * multiplier; } } /** Returns a random float in the half-open range from [0.0f,1.0f). Thus 0.0f is a valid result but 1.0f is not. */ public final float nextFloat() { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (y >>> 8) / ((float)(1 << 24)); } /** Returns a float in the range from 0.0f to 1.0f, possibly inclusive of 0.0f and 1.0f themselves. Thus: <p><table border=0> <th><td>Expression<td>Interval <tr><td>nextFloat(false, false)<td>(0.0f, 1.0f) <tr><td>nextFloat(true, false)<td>[0.0f, 1.0f) <tr><td>nextFloat(false, true)<td>(0.0f, 1.0f] <tr><td>nextFloat(true, true)<td>[0.0f, 1.0f] </table> <p>This version preserves all possible random values in the float range. */ public double nextFloat(boolean includeZero, boolean includeOne) { float d = 0.0f; do { d = nextFloat(); // grab a value, initially from half-open [0.0f, 1.0f) if (includeOne && nextBoolean()) d += 1.0f; // if includeOne, with 1/2 probability, push to [1.0f, 2.0f) } while ( (d > 1.0f) || // everything above 1.0f is always invalid (!includeZero && d == 0.0f)); // if we're not including zero, 0.0f is invalid return d; } /** Returns an integer drawn uniformly from 0 to n-1. Suffice it to say, n must be > 0, or an IllegalArgumentException is raised. */ public final int nextInt(final int n) { if (n<=0) throw new IllegalArgumentException("n must be positive, got: " + n); if ((n & -n) == n) // i.e., n is a power of 2 { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (int)((n * (long) (y >>> 1) ) >> 31); } int bits, val; do { int y; if (mti >= N) // generate N words at one time { int kk; final int[] mt = this.mt; // locals are slightly faster final int[] mag01 = this.mag01; // locals are slightly faster for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N-1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) bits = (y >>> 1); val = bits % n; } while(bits - val + (n-1) < 0); return val; } }
0true
commons_src_main_java_com_orientechnologies_common_util_MersenneTwisterFast.java
699
@Entity @Inheritance(strategy = InheritanceType.JOINED) @javax.persistence.Table(name="BLC_PRODUCT") //multi-column indexes don't appear to get exported correctly when declared at the field level, so declaring here as a workaround @org.hibernate.annotations.Table(appliesTo = "BLC_PRODUCT", indexes = { @Index(name = "PRODUCT_URL_INDEX", columnNames = {"URL","URL_KEY"} ) }) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "baseProduct") @SQLDelete(sql="UPDATE BLC_PRODUCT SET ARCHIVED = 'Y' WHERE PRODUCT_ID = ?") public class ProductImpl implements Product, Status, AdminMainEntity { private static final Log LOG = LogFactory.getLog(ProductImpl.class); /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** The id. */ @Id @GeneratedValue(generator= "ProductId") @GenericGenerator( name="ProductId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="ProductImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.catalog.domain.ProductImpl") } ) @Column(name = "PRODUCT_ID") @AdminPresentation(friendlyName = "ProductImpl_Product_ID", visibility = VisibilityEnum.HIDDEN_ALL) protected Long id; @Column(name = "URL") @AdminPresentation(friendlyName = "ProductImpl_Product_Url", order = Presentation.FieldOrder.URL, group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General, prominent = true, gridOrder = 3, columnWidth = "200px", requiredOverride = RequiredOverride.REQUIRED, validationConfigurations = { @ValidationConfiguration(validationImplementation = "blUriPropertyValidator") }) protected String url; @Column(name = "URL_KEY") @AdminPresentation(friendlyName = "ProductImpl_Product_UrlKey", tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General, excluded = true) protected String urlKey; @Column(name = "DISPLAY_TEMPLATE") @AdminPresentation(friendlyName = "ProductImpl_Product_Display_Template", tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced) protected String displayTemplate; @Column(name = "MODEL") @AdminPresentation(friendlyName = "ProductImpl_Product_Model", tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced) protected String model; @Column(name = "MANUFACTURE") @AdminPresentation(friendlyName = "ProductImpl_Product_Manufacturer", order = Presentation.FieldOrder.MANUFACTURER, group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General, prominent = true, gridOrder = 4) protected String manufacturer; @Column(name = "TAX_CODE") protected String taxCode; @Column(name = "IS_FEATURED_PRODUCT", nullable=false) @AdminPresentation(friendlyName = "ProductImpl_Is_Featured_Product", requiredOverride = RequiredOverride.NOT_REQUIRED, tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing, group = Presentation.Group.Name.Badges, groupOrder = Presentation.Group.Order.Badges) protected Boolean isFeaturedProduct = false; @OneToOne(optional = false, targetEntity = SkuImpl.class, cascade={CascadeType.ALL}, mappedBy = "defaultProduct") @Cascade(value={org.hibernate.annotations.CascadeType.ALL}) protected Sku defaultSku; @Column(name = "CAN_SELL_WITHOUT_OPTIONS") @AdminPresentation(friendlyName = "ProductImpl_Can_Sell_Without_Options", tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, group = Presentation.Group.Name.Advanced, groupOrder = Presentation.Group.Order.Advanced) protected Boolean canSellWithoutOptions = false; @Transient protected List<Sku> skus = new ArrayList<Sku>(); @Transient protected String promoMessage; @OneToMany(mappedBy = "product", targetEntity = CrossSaleProductImpl.class, cascade = {CascadeType.ALL}) @Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @OrderBy(value="sequence") @AdminPresentationAdornedTargetCollection(friendlyName = "crossSaleProductsTitle", order = 1000, tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing, targetObjectProperty = "relatedSaleProduct", sortProperty = "sequence", maintainedAdornedTargetFields = { "promotionMessage" }, gridVisibleFields = { "defaultSku.name", "promotionMessage" }) protected List<RelatedProduct> crossSaleProducts = new ArrayList<RelatedProduct>(); @OneToMany(mappedBy = "product", targetEntity = UpSaleProductImpl.class, cascade = {CascadeType.ALL}) @Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @OrderBy(value="sequence") @AdminPresentationAdornedTargetCollection(friendlyName = "upsaleProductsTitle", order = 2000, tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing, targetObjectProperty = "relatedSaleProduct", sortProperty = "sequence", maintainedAdornedTargetFields = { "promotionMessage" }, gridVisibleFields = { "defaultSku.name", "promotionMessage" }) protected List<RelatedProduct> upSaleProducts = new ArrayList<RelatedProduct>(); @OneToMany(fetch = FetchType.LAZY, targetEntity = SkuImpl.class, mappedBy="product") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @BatchSize(size = 50) @AdminPresentationCollection(friendlyName="ProductImpl_Additional_Skus", order = 1000, tab = Presentation.Tab.Name.ProductOptions, tabOrder = Presentation.Tab.Order.ProductOptions) protected List<Sku> additionalSkus = new ArrayList<Sku>(); @ManyToOne(targetEntity = CategoryImpl.class) @JoinColumn(name = "DEFAULT_CATEGORY_ID") @Index(name="PRODUCT_CATEGORY_INDEX", columnNames={"DEFAULT_CATEGORY_ID"}) @AdminPresentation(friendlyName = "ProductImpl_Product_Default_Category", order = Presentation.FieldOrder.DEFAULT_CATEGORY, group = Presentation.Group.Name.General, groupOrder = Presentation.Group.Order.General, prominent = true, gridOrder = 2, requiredOverride = RequiredOverride.REQUIRED) @AdminPresentationToOneLookup() protected Category defaultCategory; @OneToMany(targetEntity = CategoryProductXrefImpl.class, mappedBy = "categoryProductXref.product") @Cascade(value={org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.PERSIST}) @OrderBy(value="displayOrder") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @BatchSize(size = 50) @AdminPresentationAdornedTargetCollection(friendlyName = "allParentCategoriesTitle", order = 3000, tab = Presentation.Tab.Name.Marketing, tabOrder = Presentation.Tab.Order.Marketing, joinEntityClass = "org.broadleafcommerce.core.catalog.domain.CategoryProductXrefImpl", targetObjectProperty = "categoryProductXref.category", parentObjectProperty = "categoryProductXref.product", sortProperty = "displayOrder", gridVisibleFields = { "name" }) protected List<CategoryProductXref> allParentCategoryXrefs = new ArrayList<CategoryProductXref>(); @OneToMany(mappedBy = "product", targetEntity = ProductAttributeImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true) @Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blStandardElements") @MapKey(name="name") @BatchSize(size = 50) @AdminPresentationMap(friendlyName = "productAttributesTitle", tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced, deleteEntityUponRemove = true, forceFreeFormKeys = true, keyPropertyFriendlyName = "ProductAttributeImpl_Attribute_Name" ) protected Map<String, ProductAttribute> productAttributes = new HashMap<String, ProductAttribute>(); @ManyToMany(fetch = FetchType.LAZY, targetEntity = ProductOptionImpl.class) @JoinTable(name = "BLC_PRODUCT_OPTION_XREF", joinColumns = @JoinColumn(name = "PRODUCT_ID", referencedColumnName = "PRODUCT_ID"), inverseJoinColumns = @JoinColumn(name = "PRODUCT_OPTION_ID", referencedColumnName = "PRODUCT_OPTION_ID")) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @BatchSize(size = 50) @AdminPresentationCollection(friendlyName = "productOptionsTitle", tab = Presentation.Tab.Name.ProductOptions, tabOrder = Presentation.Tab.Order.ProductOptions, addType = AddMethodType.LOOKUP, manyToField = "products", operationTypes = @AdminPresentationOperationTypes(removeType = OperationType.NONDESTRUCTIVEREMOVE)) protected List<ProductOption> productOptions = new ArrayList<ProductOption>(); @Embedded protected ArchiveStatus archiveStatus = new ArchiveStatus(); @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getName() { return getDefaultSku().getName(); } @Override public void setName(String name) { getDefaultSku().setName(name); } @Override public String getDescription() { return getDefaultSku().getDescription(); } @Override public void setDescription(String description) { getDefaultSku().setDescription(description); } @Override public String getLongDescription() { return getDefaultSku().getLongDescription(); } @Override public void setLongDescription(String longDescription) { getDefaultSku().setLongDescription(longDescription); } @Override public Date getActiveStartDate() { return getDefaultSku().getActiveStartDate(); } @Override public void setActiveStartDate(Date activeStartDate) { getDefaultSku().setActiveStartDate(activeStartDate); } @Override public Date getActiveEndDate() { return getDefaultSku().getActiveEndDate(); } @Override public void setActiveEndDate(Date activeEndDate) { getDefaultSku().setActiveEndDate(activeEndDate); } @Override public boolean isActive() { if (LOG.isDebugEnabled()) { if (!DateUtil.isActive(getActiveStartDate(), getActiveEndDate(), true)) { LOG.debug("product, " + id + ", inactive due to date"); } if ('Y'==getArchived()) { LOG.debug("product, " + id + ", inactive due to archived status"); } } return DateUtil.isActive(getActiveStartDate(), getActiveEndDate(), true) && 'Y'!=getArchived(); } @Override public String getModel() { return model; } @Override public void setModel(String model) { this.model = model; } @Override public String getManufacturer() { return manufacturer; } @Override public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } @Override public boolean isFeaturedProduct() { return isFeaturedProduct; } @Override public void setFeaturedProduct(boolean isFeaturedProduct) { this.isFeaturedProduct = isFeaturedProduct; } @Override public Sku getDefaultSku() { return defaultSku; } @Override public Boolean getCanSellWithoutOptions() { return canSellWithoutOptions == null ? false : canSellWithoutOptions; } @Override public void setCanSellWithoutOptions(Boolean canSellWithoutOptions) { this.canSellWithoutOptions = canSellWithoutOptions; } @Override public void setDefaultSku(Sku defaultSku) { defaultSku.setDefaultProduct(this); this.defaultSku = defaultSku; } @Override public String getPromoMessage() { return promoMessage; } @Override public void setPromoMessage(String promoMessage) { this.promoMessage = promoMessage; } @Override public List<Sku> getAllSkus() { List<Sku> allSkus = new ArrayList<Sku>(); allSkus.add(getDefaultSku()); for (Sku additionalSku : additionalSkus) { if (!additionalSku.getId().equals(getDefaultSku().getId())) { allSkus.add(additionalSku); } } return allSkus; } @Override public List<Sku> getSkus() { if (skus.size() == 0) { List<Sku> additionalSkus = getAdditionalSkus(); for (Sku sku : additionalSkus) { if (sku.isActive()) { skus.add(sku); } } } return skus; } @Override public List<Sku> getAdditionalSkus() { return additionalSkus; } @Override public void setAdditionalSkus(List<Sku> skus) { this.additionalSkus.clear(); for(Sku sku : skus){ this.additionalSkus.add(sku); } //this.skus.clear(); } @Override public Category getDefaultCategory() { return defaultCategory; } @Override public Map<String, Media> getMedia() { return getDefaultSku().getSkuMedia(); } @Override public void setMedia(Map<String, Media> media) { getDefaultSku().setSkuMedia(media); } @Override public Map<String, Media> getAllSkuMedia() { Map<String, Media> result = new HashMap<String, Media>(); result.putAll(getMedia()); for (Sku additionalSku : getAdditionalSkus()) { if (!additionalSku.getId().equals(getDefaultSku().getId())) { result.putAll(additionalSku.getSkuMedia()); } } return result; } @Override public void setDefaultCategory(Category defaultCategory) { this.defaultCategory = defaultCategory; } @Override public List<CategoryProductXref> getAllParentCategoryXrefs() { return allParentCategoryXrefs; } @Override public void setAllParentCategoryXrefs(List<CategoryProductXref> allParentCategories) { this.allParentCategoryXrefs.clear(); allParentCategoryXrefs.addAll(allParentCategories); } @Override @Deprecated public List<Category> getAllParentCategories() { List<Category> parents = new ArrayList<Category>(); for (CategoryProductXref xref : allParentCategoryXrefs) { parents.add(xref.getCategory()); } return Collections.unmodifiableList(parents); } @Override @Deprecated public void setAllParentCategories(List<Category> allParentCategories) { throw new UnsupportedOperationException("Not Supported - Use setAllParentCategoryXrefs()"); } @Override public Dimension getDimension() { return getDefaultSku().getDimension(); } @Override public void setDimension(Dimension dimension) { getDefaultSku().setDimension(dimension); } @Override public BigDecimal getWidth() { return getDefaultSku().getDimension().getWidth(); } @Override public void setWidth(BigDecimal width) { getDefaultSku().getDimension().setWidth(width); } @Override public BigDecimal getHeight() { return getDefaultSku().getDimension().getHeight(); } @Override public void setHeight(BigDecimal height) { getDefaultSku().getDimension().setHeight(height); } @Override public BigDecimal getDepth() { return getDefaultSku().getDimension().getDepth(); } @Override public void setDepth(BigDecimal depth) { getDefaultSku().getDimension().setDepth(depth); } @Override public BigDecimal getGirth() { return getDefaultSku().getDimension().getGirth(); } @Override public void setGirth(BigDecimal girth) { getDefaultSku().getDimension().setGirth(girth); } @Override public ContainerSizeType getSize() { return getDefaultSku().getDimension().getSize(); } @Override public void setSize(ContainerSizeType size) { getDefaultSku().getDimension().setSize(size); } @Override public ContainerShapeType getContainer() { return getDefaultSku().getDimension().getContainer(); } @Override public void setContainer(ContainerShapeType container) { getDefaultSku().getDimension().setContainer(container); } @Override public String getDimensionString() { return getDefaultSku().getDimension().getDimensionString(); } @Override public Weight getWeight() { return getDefaultSku().getWeight(); } @Override public void setWeight(Weight weight) { getDefaultSku().setWeight(weight); } @Override public List<RelatedProduct> getCrossSaleProducts() { List<RelatedProduct> returnProducts = new ArrayList<RelatedProduct>(); if (crossSaleProducts != null) { returnProducts.addAll(crossSaleProducts); CollectionUtils.filter(returnProducts, new Predicate() { @Override public boolean evaluate(Object arg) { return 'Y'!=((Status)((CrossSaleProductImpl) arg).getRelatedProduct()).getArchived(); } }); } return returnProducts; } @Override public void setCrossSaleProducts(List<RelatedProduct> crossSaleProducts) { this.crossSaleProducts.clear(); for(RelatedProduct relatedProduct : crossSaleProducts){ this.crossSaleProducts.add(relatedProduct); } } @Override public List<RelatedProduct> getUpSaleProducts() { List<RelatedProduct> returnProducts = new ArrayList<RelatedProduct>(); if (upSaleProducts != null) { returnProducts.addAll(upSaleProducts); CollectionUtils.filter(returnProducts, new Predicate() { @Override public boolean evaluate(Object arg) { return 'Y'!=((Status)((UpSaleProductImpl) arg).getRelatedProduct()).getArchived(); } }); } return returnProducts; } @Override public void setUpSaleProducts(List<RelatedProduct> upSaleProducts) { this.upSaleProducts.clear(); for(RelatedProduct relatedProduct : upSaleProducts){ this.upSaleProducts.add(relatedProduct); } this.upSaleProducts = upSaleProducts; } @Override public List<RelatedProduct> getCumulativeCrossSaleProducts() { List<RelatedProduct> returnProducts = getCrossSaleProducts(); if (defaultCategory != null) { List<RelatedProduct> categoryProducts = defaultCategory.getCumulativeCrossSaleProducts(); if (categoryProducts != null) { returnProducts.addAll(categoryProducts); } } Iterator<RelatedProduct> itr = returnProducts.iterator(); while(itr.hasNext()) { RelatedProduct relatedProduct = itr.next(); if (relatedProduct.getRelatedProduct().equals(this)) { itr.remove(); } } return returnProducts; } @Override public List<RelatedProduct> getCumulativeUpSaleProducts() { List<RelatedProduct> returnProducts = getUpSaleProducts(); if (defaultCategory != null) { List<RelatedProduct> categoryProducts = defaultCategory.getCumulativeUpSaleProducts(); if (categoryProducts != null) { returnProducts.addAll(categoryProducts); } } Iterator<RelatedProduct> itr = returnProducts.iterator(); while(itr.hasNext()) { RelatedProduct relatedProduct = itr.next(); if (relatedProduct.getRelatedProduct().equals(this)) { itr.remove(); } } return returnProducts; } @Override public Map<String, ProductAttribute> getProductAttributes() { return productAttributes; } @Override public void setProductAttributes(Map<String, ProductAttribute> productAttributes) { this.productAttributes = productAttributes; } @Override public List<ProductOption> getProductOptions() { return productOptions; } @Override public void setProductOptions(List<ProductOption> productOptions) { this.productOptions = productOptions; } @Override public String getUrl() { if (url == null) { return getGeneratedUrl(); } else { return url; } } @Override public void setUrl(String url) { this.url = url; } @Override public String getDisplayTemplate() { return displayTemplate; } @Override public void setDisplayTemplate(String displayTemplate) { this.displayTemplate = displayTemplate; } @Override public Character getArchived() { if (archiveStatus == null) { archiveStatus = new ArchiveStatus(); } return archiveStatus.getArchived(); } @Override public void setArchived(Character archived) { if (archiveStatus == null) { archiveStatus = new ArchiveStatus(); } archiveStatus.setArchived(archived); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((skus == null) ? 0 : skus.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; ProductImpl other = (ProductImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (skus == null) { if (other.skus != null) return false; } else if (!skus.equals(other.skus)) return false; return true; } @Override public String getUrlKey() { if (urlKey != null) { return urlKey; } else { if (getName() != null) { String returnKey = getName().toLowerCase(); returnKey = returnKey.replaceAll(" ","-"); return returnKey.replaceAll("[^A-Za-z0-9/-]", ""); } } return null; } @Override public void setUrlKey(String urlKey) { this.urlKey = urlKey; } @Override public String getGeneratedUrl() { if (getDefaultCategory() != null && getDefaultCategory().getGeneratedUrl() != null) { String generatedUrl = getDefaultCategory().getGeneratedUrl(); if (generatedUrl.endsWith("//")) { return generatedUrl + getUrlKey(); } else { return generatedUrl + "//" + getUrlKey(); } } return null; } @Override public void clearDynamicPrices() { for (Sku sku : getAllSkus()) { sku.clearDynamicPrices(); } } @Override public String getMainEntityName() { String manufacturer = getManufacturer(); return StringUtils.isBlank(manufacturer) ? getName() : manufacturer + " " + getName(); } public static class Presentation { public static class Tab { public static class Name { public static final String Marketing = "ProductImpl_Marketing_Tab"; public static final String Media = "SkuImpl_Media_Tab"; public static final String ProductOptions = "ProductImpl_Product_Options_Tab"; public static final String Inventory = "ProductImpl_Inventory_Tab"; public static final String Shipping = "ProductImpl_Shipping_Tab"; public static final String Advanced = "ProductImpl_Advanced_Tab"; } public static class Order { public static final int Marketing = 2000; public static final int Media = 3000; public static final int ProductOptions = 4000; public static final int Inventory = 5000; public static final int Shipping = 6000; public static final int Advanced = 7000; } } public static class Group { public static class Name { public static final String General = "ProductImpl_Product_Description"; public static final String Price = "SkuImpl_Price"; public static final String ActiveDateRange = "ProductImpl_Product_Active_Date_Range"; public static final String Advanced = "ProductImpl_Advanced"; public static final String Inventory = "SkuImpl_Sku_Inventory"; public static final String Badges = "ProductImpl_Badges"; public static final String Shipping = "ProductWeight_Shipping"; public static final String Financial = "ProductImpl_Financial"; } public static class Order { public static final int General = 1000; public static final int Price = 2000; public static final int ActiveDateRange = 3000; public static final int Advanced = 1000; public static final int Inventory = 1000; public static final int Badges = 1000; public static final int Shipping = 1000; } } public static class FieldOrder { public static final int NAME = 1000; public static final int SHORT_DESCRIPTION = 2000; public static final int PRIMARY_MEDIA = 3000; public static final int LONG_DESCRIPTION = 4000; public static final int DEFAULT_CATEGORY = 5000; public static final int MANUFACTURER = 6000; public static final int URL = 7000; } } @Override public String getTaxCode() { if (StringUtils.isEmpty(taxCode) && getDefaultCategory() != null) { return getDefaultCategory().getTaxCode(); } return taxCode; } @Override public void setTaxCode(String taxCode) { this.taxCode = taxCode; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_ProductImpl.java
984
public class UnlockOperation extends BaseLockOperation implements Notifier, BackupAwareOperation { private boolean force; private boolean shouldNotify; public UnlockOperation() { } public UnlockOperation(ObjectNamespace namespace, Data key, long threadId) { super(namespace, key, threadId); } public UnlockOperation(ObjectNamespace namespace, Data key, long threadId, boolean force) { super(namespace, key, threadId); this.force = force; } @Override public void run() throws Exception { if (force) { forceUnlock(); } else { unlock(); } } private void unlock() { LockStoreImpl lockStore = getLockStore(); boolean unlocked = lockStore.unlock(key, getCallerUuid(), threadId); response = unlocked; ensureUnlocked(lockStore, unlocked); } private void ensureUnlocked(LockStoreImpl lockStore, boolean unlocked) { if (!unlocked) { String ownerInfo = lockStore.getOwnerInfo(key); throw new IllegalMonitorStateException("Current thread is not owner of the lock! -> " + ownerInfo); } } private void forceUnlock() { LockStoreImpl lockStore = getLockStore(); response = lockStore.forceUnlock(key); } @Override public void afterRun() throws Exception { LockStoreImpl lockStore = getLockStore(); AwaitOperation awaitResponse = lockStore.pollExpiredAwaitOp(key); if (awaitResponse != null) { OperationService operationService = getNodeEngine().getOperationService(); operationService.runOperationOnCallingThread(awaitResponse); } shouldNotify = awaitResponse == null; } @Override public Operation getBackupOperation() { return new UnlockBackupOperation(namespace, key, threadId, getCallerUuid(), force); } @Override public boolean shouldBackup() { return Boolean.TRUE.equals(response); } @Override public boolean shouldNotify() { return shouldNotify; } @Override public final WaitNotifyKey getNotifiedKey() { LockStoreImpl lockStore = getLockStore(); ConditionKey conditionKey = lockStore.getSignalKey(key); if (conditionKey == null) { return new LockWaitNotifyKey(namespace, key); } else { return conditionKey; } } @Override public int getId() { return LockDataSerializerHook.UNLOCK; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeBoolean(force); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); force = in.readBoolean(); } }
1no label
hazelcast_src_main_java_com_hazelcast_concurrent_lock_operations_UnlockOperation.java
4,679
final static class MatchAndScore extends QueryCollector { final PercolateContext context; final HighlightPhase highlightPhase; final List<BytesRef> matches = new ArrayList<BytesRef>(); final List<Map<String, HighlightField>> hls = new ArrayList<Map<String, HighlightField>>(); // TODO: Use thread local in order to cache the scores lists? final FloatArrayList scores = new FloatArrayList(); final boolean limit; final int size; long counter = 0; private Scorer scorer; MatchAndScore(ESLogger logger, PercolateContext context, HighlightPhase highlightPhase) { super(logger, context); this.limit = context.limit; this.size = context.size; this.context = context; this.highlightPhase = highlightPhase; } @Override public void collect(int doc) throws IOException { final Query query = getQuery(doc); if (query == null) { // log??? return; } // run the query try { collector.reset(); if (context.highlight() != null) { context.parsedQuery(new ParsedQuery(query, ImmutableMap.<String, Filter>of())); context.hitContext().cache().clear(); } searcher.search(query, collector); if (collector.exists()) { if (!limit || counter < size) { matches.add(values.copyShared()); scores.add(scorer.score()); if (context.highlight() != null) { highlightPhase.hitExecute(context, context.hitContext()); hls.add(context.hitContext().hit().getHighlightFields()); } } counter++; if (facetAndAggregatorCollector != null) { facetAndAggregatorCollector.collect(doc); } } } catch (IOException e) { logger.warn("[" + spare.bytes.utf8ToString() + "] failed to execute query", e); } } @Override public void setScorer(Scorer scorer) throws IOException { this.scorer = scorer; } long counter() { return counter; } List<BytesRef> matches() { return matches; } FloatArrayList scores() { return scores; } List<Map<String, HighlightField>> hls() { return hls; } }
1no label
src_main_java_org_elasticsearch_percolator_QueryCollector.java
254
public class OCaseInsensitiveCollate extends ODefaultComparator implements OCollate { public String getName() { return "ci"; } public Object transform(final Object obj) { if (obj instanceof String) return ((String) obj).toLowerCase(); return obj; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_collate_OCaseInsensitiveCollate.java
621
static final class Fields { static final XContentBuilderString INDICES = new XContentBuilderString("indices"); static final XContentBuilderString SHARDS = new XContentBuilderString("shards"); }
0true
src_main_java_org_elasticsearch_action_admin_indices_stats_IndicesStatsResponse.java
3,660
public class BoostFieldMapper extends NumberFieldMapper<Float> implements InternalMapper, RootMapper { public static final String CONTENT_TYPE = "_boost"; public static final String NAME = "_boost"; public static class Defaults extends NumberFieldMapper.Defaults { public static final String NAME = "_boost"; public static final Float NULL_VALUE = null; public static final FieldType FIELD_TYPE = new FieldType(NumberFieldMapper.Defaults.FIELD_TYPE); static { FIELD_TYPE.setIndexed(false); FIELD_TYPE.setStored(false); } } public static class Builder extends NumberFieldMapper.Builder<Builder, BoostFieldMapper> { protected Float nullValue = Defaults.NULL_VALUE; public Builder(String name) { super(name, new FieldType(Defaults.FIELD_TYPE)); builder = this; } public Builder nullValue(float nullValue) { this.nullValue = nullValue; return this; } @Override public BoostFieldMapper build(BuilderContext context) { return new BoostFieldMapper(name, buildIndexName(context), precisionStep, boost, fieldType, docValues, nullValue, postingsProvider, docValuesProvider, fieldDataSettings, context.indexSettings()); } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String fieldName, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { String name = node.get("name") == null ? BoostFieldMapper.Defaults.NAME : node.get("name").toString(); BoostFieldMapper.Builder builder = MapperBuilders.boost(name); parseNumberField(builder, name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String propName = Strings.toUnderscoreCase(entry.getKey()); Object propNode = entry.getValue(); if (propName.equals("null_value")) { builder.nullValue(nodeFloatValue(propNode)); } } return builder; } } private final Float nullValue; public BoostFieldMapper() { this(Defaults.NAME, Defaults.NAME); } protected BoostFieldMapper(String name, String indexName) { this(name, indexName, Defaults.PRECISION_STEP, Defaults.BOOST, new FieldType(Defaults.FIELD_TYPE), null, Defaults.NULL_VALUE, null, null, null, ImmutableSettings.EMPTY); } protected BoostFieldMapper(String name, String indexName, int precisionStep, float boost, FieldType fieldType, Boolean docValues, Float nullValue, PostingsFormatProvider postingsProvider, DocValuesFormatProvider docValuesProvider, @Nullable Settings fieldDataSettings, Settings indexSettings) { super(new Names(name, indexName, indexName, name), precisionStep, boost, fieldType, docValues, Defaults.IGNORE_MALFORMED, Defaults.COERCE, NumericFloatAnalyzer.buildNamedAnalyzer(precisionStep), NumericFloatAnalyzer.buildNamedAnalyzer(Integer.MAX_VALUE), postingsProvider, docValuesProvider, null, null, fieldDataSettings, indexSettings, MultiFields.empty(), null); this.nullValue = nullValue; } @Override public FieldType defaultFieldType() { return Defaults.FIELD_TYPE; } @Override public FieldDataType defaultFieldDataType() { return new FieldDataType("float"); } @Override public boolean hasDocValues() { return false; } @Override protected int maxPrecisionStep() { return 32; } @Override public Float value(Object value) { if (value == null) { return null; } if (value instanceof Number) { return ((Number) value).floatValue(); } if (value instanceof BytesRef) { return Numbers.bytesToFloat((BytesRef) value); } return Float.parseFloat(value.toString()); } @Override public BytesRef indexedValueForSearch(Object value) { int intValue = NumericUtils.floatToSortableInt(parseValue(value)); BytesRef bytesRef = new BytesRef(); NumericUtils.intToPrefixCoded(intValue, precisionStep(), bytesRef); return bytesRef; } private float parseValue(Object value) { if (value instanceof Number) { return ((Number) value).floatValue(); } if (value instanceof BytesRef) { return Float.parseFloat(((BytesRef) value).utf8ToString()); } return Float.parseFloat(value.toString()); } @Override public Query fuzzyQuery(String value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions) { float iValue = Float.parseFloat(value); float iSim = fuzziness.asFloat(); return NumericRangeQuery.newFloatRange(names.indexName(), precisionStep, iValue - iSim, iValue + iSim, true, true); } @Override public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return NumericRangeQuery.newFloatRange(names.indexName(), precisionStep, lowerTerm == null ? null : parseValue(lowerTerm), upperTerm == null ? null : parseValue(upperTerm), includeLower, includeUpper); } @Override public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return NumericRangeFilter.newFloatRange(names.indexName(), precisionStep, lowerTerm == null ? null : parseValue(lowerTerm), upperTerm == null ? null : parseValue(upperTerm), includeLower, includeUpper); } @Override public Filter rangeFilter(IndexFieldDataService fieldData, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return NumericRangeFieldDataFilter.newFloatRange((IndexNumericFieldData) fieldData.getForField(this), lowerTerm == null ? null : parseValue(lowerTerm), upperTerm == null ? null : parseValue(upperTerm), includeLower, includeUpper); } @Override public Filter nullValueFilter() { if (nullValue == null) { return null; } return NumericRangeFilter.newFloatRange(names.indexName(), precisionStep, nullValue, nullValue, true, true); } @Override public void preParse(ParseContext context) throws IOException { } @Override public void postParse(ParseContext context) throws IOException { } @Override public void validate(ParseContext context) throws MapperParsingException { } @Override public boolean includeInObject() { return true; } @Override public void parse(ParseContext context) throws IOException { // we override parse since we want to handle cases where it is not indexed and not stored (the default) float value = parseFloatValue(context); if (!Float.isNaN(value)) { context.docBoost(value); } super.parse(context); } @Override protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException { final float value = parseFloatValue(context); if (Float.isNaN(value)) { return; } context.docBoost(value); fields.add(new FloatFieldMapper.CustomFloatNumericField(this, value, fieldType)); } private float parseFloatValue(ParseContext context) throws IOException { float value; if (context.parser().currentToken() == XContentParser.Token.VALUE_NULL) { if (nullValue == null) { return Float.NaN; } value = nullValue; } else { value = context.parser().floatValue(coerce.value()); } return value; } @Override protected String contentType() { return CONTENT_TYPE; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { boolean includeDefaults = params.paramAsBoolean("include_defaults", false); // all are defaults, don't write it at all if (!includeDefaults && name().equals(Defaults.NAME) && nullValue == null && fieldType.indexed() == Defaults.FIELD_TYPE.indexed() && fieldType.stored() == Defaults.FIELD_TYPE.stored() && customFieldDataSettings == null) { return builder; } builder.startObject(contentType()); if (includeDefaults || !name().equals(Defaults.NAME)) { builder.field("name", name()); } if (includeDefaults || nullValue != null) { builder.field("null_value", nullValue); } if (includeDefaults || fieldType.indexed() != Defaults.FIELD_TYPE.indexed()) { builder.field("index", fieldType.indexed()); } if (includeDefaults || fieldType.stored() != Defaults.FIELD_TYPE.stored()) { builder.field("store", fieldType.stored()); } if (customFieldDataSettings != null) { builder.field("fielddata", (Map) customFieldDataSettings.getAsMap()); } else if (includeDefaults) { builder.field("fielddata", (Map) fieldDataType.getSettings().getAsMap()); } builder.endObject(); return builder; } @Override public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException { // do nothing here, no merging, but also no exception } }
1no label
src_main_java_org_elasticsearch_index_mapper_internal_BoostFieldMapper.java
788
public class StandardSchemaCache implements SchemaCache { public static final int MAX_CACHED_TYPES_DEFAULT = 10000; private static final int INITIAL_CAPACITY = 128; private static final int INITIAL_CACHE_SIZE = 16; private static final int CACHE_RELATION_MULTIPLIER = 3; // 1) type-name, 2) type-definitions, 3) modifying edges [index, lock] private static final int CONCURRENCY_LEVEL = 2; // private static final int SCHEMAID_FORW_SHIFT = 4; //Number of bits at the end to append the id of the system type private static final int SCHEMAID_TOTALFORW_SHIFT = 3; //Total number of bits appended - the 1 is for the 1 bit direction private static final int SCHEMAID_BACK_SHIFT = 2; //Number of bits to remove from end of schema id since its just the padding { assert IDManager.VertexIDType.Schema.removePadding(1l<<SCHEMAID_BACK_SHIFT)==1; assert SCHEMAID_TOTALFORW_SHIFT-SCHEMAID_BACK_SHIFT>=0; } private final int maxCachedTypes; private final int maxCachedRelations; private final StoreRetrieval retriever; private volatile ConcurrentMap<String,Long> typeNames; private final Cache<String,Long> typeNamesBackup; private volatile ConcurrentMap<Long,EntryList> schemaRelations; private final Cache<Long,EntryList> schemaRelationsBackup; public StandardSchemaCache(final StoreRetrieval retriever) { this(MAX_CACHED_TYPES_DEFAULT,retriever); } public StandardSchemaCache(final int size, final StoreRetrieval retriever) { Preconditions.checkArgument(size>0,"Size must be positive"); Preconditions.checkNotNull(retriever); maxCachedTypes = size; maxCachedRelations = maxCachedTypes *CACHE_RELATION_MULTIPLIER; this.retriever=retriever; typeNamesBackup = CacheBuilder.newBuilder() .concurrencyLevel(CONCURRENCY_LEVEL).initialCapacity(INITIAL_CACHE_SIZE) .maximumSize(maxCachedTypes).build(); typeNames = new ConcurrentHashMap<String, Long>(INITIAL_CAPACITY,0.75f,CONCURRENCY_LEVEL); schemaRelationsBackup = CacheBuilder.newBuilder() .concurrencyLevel(CONCURRENCY_LEVEL).initialCapacity(INITIAL_CACHE_SIZE *CACHE_RELATION_MULTIPLIER) .maximumSize(maxCachedRelations).build(); // typeRelations = new ConcurrentHashMap<Long, EntryList>(INITIAL_CAPACITY*CACHE_RELATION_MULTIPLIER,0.75f,CONCURRENCY_LEVEL); schemaRelations = new NonBlockingHashMapLong<EntryList>(INITIAL_CAPACITY*CACHE_RELATION_MULTIPLIER); //TODO: Is this data structure safe or should we go with ConcurrentHashMap (line above)? } @Override public Long getSchemaId(final String schemaName, final StandardTitanTx tx) { ConcurrentMap<String,Long> types = typeNames; Long id; if (types==null) { id = typeNamesBackup.getIfPresent(schemaName); if (id==null) { id = retriever.retrieveSchemaByName(schemaName, tx); if (id!=null) { //only cache if type exists typeNamesBackup.put(schemaName,id); } } } else { id = types.get(schemaName); if (id==null) { //Retrieve it if (types.size()> maxCachedTypes) { /* Safe guard against the concurrent hash map growing to large - this would be a VERY rare event as it only happens for graph databases with thousands of types. */ typeNames = null; return getSchemaId(schemaName, tx); } else { //Expand map id = retriever.retrieveSchemaByName(schemaName, tx); if (id!=null) { //only cache if type exists types.put(schemaName,id); } } } } return id; } private long getIdentifier(final long schemaId, final SystemRelationType type, final Direction dir) { int edgeDir = EdgeDirection.position(dir); assert edgeDir==0 || edgeDir==1; long typeid = (schemaId >>> SCHEMAID_BACK_SHIFT); int systemTypeId; if (type== BaseLabel.SchemaDefinitionEdge) systemTypeId=0; else if (type== BaseKey.SchemaName) systemTypeId=1; else if (type== BaseKey.SchemaCategory) systemTypeId=2; else if (type== BaseKey.SchemaDefinitionProperty) systemTypeId=3; else throw new AssertionError("Unexpected SystemType encountered in StandardSchemaCache: " + type.getName()); //Ensure that there is enough padding assert (systemTypeId<(1<<2)); return (((typeid<<2)+systemTypeId)<<1)+edgeDir; } @Override public EntryList getSchemaRelations(final long schemaId, final BaseRelationType type, final Direction dir, final StandardTitanTx tx) { assert IDManager.isSystemRelationTypeId(type.getLongId()) && type.getLongId()>0; Preconditions.checkArgument(IDManager.VertexIDType.Schema.is(schemaId)); Preconditions.checkArgument((Long.MAX_VALUE>>>(SCHEMAID_TOTALFORW_SHIFT-SCHEMAID_BACK_SHIFT))>= schemaId); int edgeDir = EdgeDirection.position(dir); assert edgeDir==0 || edgeDir==1; final long typePlusRelation = getIdentifier(schemaId,type,dir); ConcurrentMap<Long,EntryList> types = schemaRelations; EntryList entries; if (types==null) { entries = schemaRelationsBackup.getIfPresent(typePlusRelation); if (entries==null) { entries = retriever.retrieveSchemaRelations(schemaId, type, dir, tx); if (!entries.isEmpty()) { //only cache if type exists schemaRelationsBackup.put(typePlusRelation, entries); } } } else { entries = types.get(typePlusRelation); if (entries==null) { //Retrieve it if (types.size()> maxCachedRelations) { /* Safe guard against the concurrent hash map growing to large - this would be a VERY rare event as it only happens for graph databases with thousands of types. */ schemaRelations = null; return getSchemaRelations(schemaId, type, dir, tx); } else { //Expand map entries = retriever.retrieveSchemaRelations(schemaId, type, dir, tx); types.put(typePlusRelation,entries); } } } assert entries!=null; return entries; } // @Override // public void expireSchemaName(final String name) { // ConcurrentMap<String,Long> types = typeNames; // if (types!=null) types.remove(name); // typeNamesBackup.invalidate(name); // } @Override public void expireSchemaElement(final long schemaId) { //1) expire relations final long cuttypeid = (schemaId >>> SCHEMAID_BACK_SHIFT); ConcurrentMap<Long,EntryList> types = schemaRelations; if (types!=null) { Iterator<Long> keys = types.keySet().iterator(); while (keys.hasNext()) { long key = keys.next(); if ((key>>>SCHEMAID_TOTALFORW_SHIFT)==cuttypeid) keys.remove(); } } Iterator<Long> keys = schemaRelationsBackup.asMap().keySet().iterator(); while (keys.hasNext()) { long key = keys.next(); if ((key>>>SCHEMAID_TOTALFORW_SHIFT)==cuttypeid) schemaRelationsBackup.invalidate(key); } //2) expire names ConcurrentMap<String,Long> names = typeNames; if (names!=null) { for (Iterator<Map.Entry<String, Long>> iter = names.entrySet().iterator(); iter.hasNext(); ) { Map.Entry<String, Long> next = iter.next(); if (next.getValue().equals(schemaId)) iter.remove(); } } for (Map.Entry<String,Long> entry : typeNamesBackup.asMap().entrySet()) { if (entry.getValue().equals(schemaId)) typeNamesBackup.invalidate(entry.getKey()); } } }
1no label
titan-core_src_main_java_com_thinkaurelius_titan_graphdb_database_cache_StandardSchemaCache.java
3,234
public final static class Strings extends ScriptDocValues { private final BytesValues values; private final CharsRef spare = new CharsRef(); private SlicedObjectList<String> list; public Strings(BytesValues values) { this.values = values; list = new SlicedObjectList<String>(values.isMultiValued() ? new String[10] : new String[1]) { @Override public void grow(int newLength) { assert offset == 0; // NOTE: senseless if offset != 0 if (values.length >= newLength) { return; } final String[] current = values; values = new String[ArrayUtil.oversize(newLength, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; System.arraycopy(current, 0, values, 0, current.length); } }; } @Override public boolean isEmpty() { return values.setDocument(docId) == 0; } public BytesValues getInternalValues() { return this.values; } public BytesRef getBytesValue() { int numValues = values.setDocument(docId); if (numValues == 0) { return null; } return values.nextValue(); } public String getValue() { String value = null; if (values.setDocument(docId) > 0) { UnicodeUtil.UTF8toUTF16(values.nextValue(), spare); value = spare.toString(); } return value; } public List<String> getValues() { if (!listLoaded) { final int numValues = values.setDocument(docId); list.offset = 0; list.grow(numValues); list.length = numValues; for (int i = 0; i < numValues; i++) { BytesRef next = values.nextValue(); UnicodeUtil.UTF8toUTF16(next, spare); list.values[i] = spare.toString(); } listLoaded = true; } return list; } }
1no label
src_main_java_org_elasticsearch_index_fielddata_ScriptDocValues.java
3,145
public class TxnPollBackupOperation extends QueueOperation { long itemId; public TxnPollBackupOperation() { } public TxnPollBackupOperation(String name, long itemId) { super(name); this.itemId = itemId; } @Override public void run() throws Exception { response = getOrCreateContainer().txnCommitPollBackup(itemId); } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeLong(itemId); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); itemId = in.readLong(); } @Override public int getId() { return QueueDataSerializerHook.TXN_POLL_BACKUP; } }
1no label
hazelcast_src_main_java_com_hazelcast_queue_tx_TxnPollBackupOperation.java
2,580
class ApplySettings implements NodeSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { int minimumMasterNodes = settings.getAsInt("discovery.zen.minimum_master_nodes", ZenDiscovery.this.electMaster.minimumMasterNodes()); if (minimumMasterNodes != ZenDiscovery.this.electMaster.minimumMasterNodes()) { logger.info("updating discovery.zen.minimum_master_nodes from [{}] to [{}]", ZenDiscovery.this.electMaster.minimumMasterNodes(), minimumMasterNodes); handleMinimumMasterNodesChanged(minimumMasterNodes); } } }
1no label
src_main_java_org_elasticsearch_discovery_zen_ZenDiscovery.java
22
class ControlStructureCompletionProposal extends CompletionProposal { static void addForProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d) { if (d instanceof Value) { TypedDeclaration td = (TypedDeclaration) d; if (td.getType()!=null && d.getUnit().isIterableType(td.getType())) { String elemName; String name = d.getName(); if (name.length()==1) { elemName = "element"; } else if (name.endsWith("s")) { elemName = name.substring(0, name.length()-1); } else { elemName = name.substring(0, 1); } Unit unit = cpc.getRootNode().getUnit(); result.add(new ControlStructureCompletionProposal(offset, prefix, "for (" + elemName + " in " + getDescriptionFor(d, unit) + ")", "for (" + elemName + " in " + getTextFor(d, unit) + ") {}", d, cpc)); } } } static void addIfExistsProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d) { if (!dwp.isUnimported()) { if (d instanceof Value) { TypedDeclaration v = (TypedDeclaration) d; if (v.getType()!=null && d.getUnit().isOptionalType(v.getType()) && !v.isVariable()) { Unit unit = cpc.getRootNode().getUnit(); result.add(new ControlStructureCompletionProposal(offset, prefix, "if (exists " + getDescriptionFor(d, unit) + ")", "if (exists " + getTextFor(d, unit) + ") {}", d, cpc)); } } } } static void addIfNonemptyProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d) { if (!dwp.isUnimported()) { if (d instanceof Value) { TypedDeclaration v = (TypedDeclaration) d; if (v.getType()!=null && d.getUnit().isPossiblyEmptyType(v.getType()) && !v.isVariable()) { Unit unit = cpc.getRootNode().getUnit(); result.add(new ControlStructureCompletionProposal(offset, prefix, "if (nonempty " + getDescriptionFor(d, unit) + ")", "if (nonempty " + getTextFor(d, unit) + ") {}", d, cpc)); } } } } static void addTryProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d) { if (!dwp.isUnimported()) { if (d instanceof Value) { TypedDeclaration v = (TypedDeclaration) d; if (v.getType()!=null && v.getType().getDeclaration() .inherits(d.getUnit().getObtainableDeclaration()) && !v.isVariable()) { Unit unit = cpc.getRootNode().getUnit(); result.add(new ControlStructureCompletionProposal(offset, prefix, "try (" + getDescriptionFor(d, unit) + ")", "try (" + getTextFor(d, unit) + ") {}", d, cpc)); } } } } static void addSwitchProposal(int offset, String prefix, CeylonParseController cpc, List<ICompletionProposal> result, DeclarationWithProximity dwp, Declaration d, Node node, IDocument doc) { if (!dwp.isUnimported()) { if (d instanceof Value) { TypedDeclaration v = (TypedDeclaration) d; if (v.getType()!=null && v.getType().getCaseTypes()!=null && !v.isVariable()) { StringBuilder body = new StringBuilder(); String indent = getIndent(node, doc); for (ProducedType pt: v.getType().getCaseTypes()) { body.append(indent).append("case ("); if (!pt.getDeclaration().isAnonymous()) { body.append("is "); } body.append(pt.getProducedTypeName(node.getUnit())) .append(") {}") .append(getDefaultLineDelimiter(doc)); } body.append(indent); Unit unit = cpc.getRootNode().getUnit(); result.add(new ControlStructureCompletionProposal(offset, prefix, "switch (" + getDescriptionFor(d, unit) + ")", "switch (" + getTextFor(d, unit) + ")" + getDefaultLineDelimiter(doc) + body, d, cpc)); } } } } private final CeylonParseController cpc; private final Declaration declaration; private ControlStructureCompletionProposal(int offset, String prefix, String desc, String text, Declaration dec, CeylonParseController cpc) { super(offset, prefix, CeylonLabelProvider.MINOR_CHANGE, desc, text); this.cpc = cpc; this.declaration = dec; } public String getAdditionalProposalInfo() { return getDocumentationFor(cpc, declaration); } @Override public Point getSelection(IDocument document) { return new Point(offset + text.indexOf('}') - prefix.length(), 0); } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_ControlStructureCompletionProposal.java
610
Runnable recreateIndexesTask = new Runnable() { @Override public void run() { try { // START IT IN BACKGROUND newDb.setProperty(ODatabase.OPTIONS.SECURITY.toString(), Boolean.FALSE); newDb.open("admin", "nopass"); ODatabaseRecordThreadLocal.INSTANCE.set(newDb); try { // DROP AND RE-CREATE 'INDEX' DATA-SEGMENT AND CLUSTER IF ANY final int dataId = newDb.getStorage().getDataSegmentIdByName(OMetadataDefault.DATASEGMENT_INDEX_NAME); if (dataId > -1) newDb.getStorage().dropDataSegment(OMetadataDefault.DATASEGMENT_INDEX_NAME); final int clusterId = newDb.getStorage().getClusterIdByName(OMetadataDefault.CLUSTER_INDEX_NAME); if (clusterId > -1) newDb.dropCluster(clusterId, false); newDb.addDataSegment(OMetadataDefault.DATASEGMENT_INDEX_NAME, null); newDb.getStorage().addCluster(OClusterLocal.TYPE, OMetadataDefault.CLUSTER_INDEX_NAME, null, OMetadataDefault.DATASEGMENT_INDEX_NAME, true); } catch (IllegalArgumentException ex) { // OLD DATABASE: CREATE SEPARATE DATASEGMENT AND LET THE INDEX CLUSTER TO POINT TO IT OLogManager.instance().info(this, "Creating 'index' data-segment to store all the index content..."); newDb.addDataSegment(OMetadataDefault.DATASEGMENT_INDEX_NAME, null); final OCluster indexCluster = newDb.getStorage().getClusterById( newDb.getStorage().getClusterIdByName(OMetadataDefault.CLUSTER_INDEX_NAME)); try { indexCluster.set(ATTRIBUTES.DATASEGMENT, OMetadataDefault.DATASEGMENT_INDEX_NAME); OLogManager.instance().info(this, "Data-segment 'index' create correctly. Indexes will store content into this data-segment"); } catch (IOException e) { OLogManager.instance().error(this, "Error changing data segment for cluster 'index'", e); } } final Collection<ODocument> idxs = doc.field(CONFIG_INDEXES); if (idxs == null) { OLogManager.instance().warn(this, "List of indexes is empty."); return; } int ok = 0; int errors = 0; for (ODocument idx : idxs) { try { String indexType = idx.field(OIndexInternal.CONFIG_TYPE); String algorithm = idx.field(OIndexInternal.ALGORITHM); String valueContainerAlgorithm = idx.field(OIndexInternal.VALUE_CONTAINER_ALGORITHM); if (indexType == null) { OLogManager.instance().error(this, "Index type is null, will process other record."); errors++; continue; } final OIndexInternal<?> index = OIndexes.createIndex(newDb, indexType, algorithm, valueContainerAlgorithm); OIndexInternal.IndexMetadata indexMetadata = index.loadMetadata(idx); OIndexDefinition indexDefinition = indexMetadata.getIndexDefinition(); if (indexDefinition == null || !indexDefinition.isAutomatic()) { OLogManager.instance().info(this, "Index %s is not automatic index and will be added as is.", indexMetadata.getName()); if (index.loadFromConfiguration(idx)) { addIndexInternal(index); setDirty(); save(); ok++; } else { getDatabase().unregisterListener(index.getInternal()); index.delete(); errors++; } OLogManager.instance().info(this, "Index %s was added in DB index list.", index.getName()); } else { String indexName = indexMetadata.getName(); Set<String> clusters = indexMetadata.getClustersToIndex(); String type = indexMetadata.getType(); if (indexName != null && indexDefinition != null && clusters != null && !clusters.isEmpty() && type != null) { OLogManager.instance().info(this, "Start creation of index %s", indexName); if (algorithm.equals(ODefaultIndexFactory.SBTREE_ALGORITHM) || indexType.endsWith("HASH_INDEX")) index.deleteWithoutIndexLoad(indexName); index.create(indexName, indexDefinition, defaultClusterName, clusters, false, new OIndexRebuildOutputListener( index)); index.setRebuildingFlag(); addIndexInternal(index); OLogManager.instance().info(this, "Index %s was successfully created and rebuild is going to be started.", indexName); index.rebuild(new OIndexRebuildOutputListener(index)); index.flush(); setDirty(); save(); ok++; OLogManager.instance().info(this, "Rebuild of %s index was successfully finished.", indexName); } else { errors++; OLogManager.instance().error( this, "Information about index was restored incorrectly, following data were loaded : " + "index name - %s, index definition %s, clusters %s, type %s.", indexName, indexDefinition, clusters, type); } } } catch (Exception e) { OLogManager.instance().error(this, "Error during addition of index %s", e, idx); errors++; } } rebuildCompleted = true; newDb.close(); OLogManager.instance().info(this, "%d indexes were restored successfully, %d errors", ok, errors); } catch (Exception e) { OLogManager.instance().error(this, "Error when attempt to restore indexes after crash was performed.", e); } } };
1no label
core_src_main_java_com_orientechnologies_orient_core_index_OIndexManagerShared.java
1,019
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name="BLC_ORDER_ATTRIBUTE") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blOrderElements") @AdminPresentationMergeOverrides( { @AdminPresentationMergeOverride(name = "", mergeEntries = @AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.READONLY, booleanOverrideValue = true)) } ) @AdminPresentationClass(friendlyName = "OrderAttributeImpl_baseProductAttribute") public class OrderAttributeImpl implements OrderAttribute { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator= "OrderAttributeId") @GenericGenerator( name="OrderAttributeId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="OrderAttributeImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.catalog.domain.OrderAttributeImpl") } ) @Column(name = "ORDER_ATTRIBUTE_ID") protected Long id; @Column(name = "NAME", nullable=false) @AdminPresentation(friendlyName = "OrderAttributeImpl_Attribute_Name", order=1000, prominent=true) protected String name; /** The value. */ @Column(name = "VALUE") @AdminPresentation(friendlyName = "OrderAttributeImpl_Attribute_Value", order=2000, prominent=true) protected String value; @ManyToOne(targetEntity = OrderImpl.class, optional=false) @JoinColumn(name = "ORDER_ID") protected Order order; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getValue() { return value; } @Override public void setValue(String value) { this.value = value; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String toString() { return value; } @Override public Order getOrder() { return order; } @Override public void setOrder(Order order) { this.order = order; } @Override public int hashCode() { return value.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; if (value == null) { return false; } return value.equals(((OrderAttribute) obj).getValue()); } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_OrderAttributeImpl.java
69
{ @Override public int compare( Record r1, Record r2 ) { return r1.getSequenceNumber() - r2.getSequenceNumber(); } } );
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TxLog.java
470
public class SandBoxType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, SandBoxType> TYPES = new LinkedHashMap<String, SandBoxType>(); public static final SandBoxType USER = new SandBoxType("USER", "User"); public static final SandBoxType APPROVAL = new SandBoxType("APPROVAL", "Approval"); public static final SandBoxType PRODUCTION = new SandBoxType("PRODUCTION", "Production"); public static SandBoxType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public SandBoxType() { //do nothing } public SandBoxType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } else { throw new RuntimeException("Cannot add the type: (" + type + "). It already exists as a type via " + getInstance(type).getClass().getName()); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SandBoxType other = (SandBoxType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
common_src_main_java_org_broadleafcommerce_common_sandbox_domain_SandBoxType.java
740
public class TransportIndexDeleteByQueryAction extends TransportIndexReplicationOperationAction<IndexDeleteByQueryRequest, IndexDeleteByQueryResponse, ShardDeleteByQueryRequest, ShardDeleteByQueryRequest, ShardDeleteByQueryResponse> { @Inject public TransportIndexDeleteByQueryAction(Settings settings, ClusterService clusterService, TransportService transportService, ThreadPool threadPool, TransportShardDeleteByQueryAction shardDeleteByQueryAction) { super(settings, transportService, clusterService, threadPool, shardDeleteByQueryAction); } @Override protected IndexDeleteByQueryRequest newRequestInstance() { return new IndexDeleteByQueryRequest(); } @Override protected IndexDeleteByQueryResponse newResponseInstance(IndexDeleteByQueryRequest request, AtomicReferenceArray shardsResponses) { int successfulShards = 0; int failedShards = 0; List<ShardOperationFailedException> failures = new ArrayList<ShardOperationFailedException>(3); for (int i = 0; i < shardsResponses.length(); i++) { Object shardResponse = shardsResponses.get(i); if (shardResponse instanceof Throwable) { failedShards++; failures.add(new DefaultShardOperationFailedException(request.index(), -1, (Throwable) shardResponse)); } else { successfulShards++; } } return new IndexDeleteByQueryResponse(request.index(), successfulShards, failedShards, failures); } @Override protected boolean accumulateExceptions() { return true; } @Override protected String transportAction() { return DeleteByQueryAction.NAME + "/index"; } @Override protected ClusterBlockException checkGlobalBlock(ClusterState state, IndexDeleteByQueryRequest request) { return state.blocks().globalBlockedException(ClusterBlockLevel.WRITE); } @Override protected ClusterBlockException checkRequestBlock(ClusterState state, IndexDeleteByQueryRequest request) { return state.blocks().indexBlockedException(ClusterBlockLevel.WRITE, request.index()); } @Override protected GroupShardsIterator shards(IndexDeleteByQueryRequest request) { return clusterService.operationRouting().deleteByQueryShards(clusterService.state(), request.index(), request.routing()); } @Override protected ShardDeleteByQueryRequest newShardRequestInstance(IndexDeleteByQueryRequest request, int shardId) { return new ShardDeleteByQueryRequest(request, shardId); } }
0true
src_main_java_org_elasticsearch_action_deletebyquery_TransportIndexDeleteByQueryAction.java
131
public class LongMaxUpdater extends Striped64 implements Serializable { private static final long serialVersionUID = 7249069246863182397L; /** * Version of max for use in retryUpdate */ final long fn(long v, long x) { return v > x ? v : x; } /** * Creates a new instance with initial maximum of {@code * Long.MIN_VALUE}. */ public LongMaxUpdater() { base = Long.MIN_VALUE; } /** * Updates the maximum to be at least the given value. * * @param x the value to update */ public void update(long x) { Cell[] as; long b, v; HashCode hc; Cell a; int n; if ((as = cells) != null || (b = base) < x && !casBase(b, x)) { boolean uncontended = true; int h = (hc = threadHashCode.get()).code; if (as == null || (n = as.length) < 1 || (a = as[(n - 1) & h]) == null || ((v = a.value) < x && !(uncontended = a.cas(v, x)))) retryUpdate(x, hc, uncontended); } } /** * Returns the current maximum. The returned value is * <em>NOT</em> an atomic snapshot; invocation in the absence of * concurrent updates returns an accurate result, but concurrent * updates that occur while the value is being calculated might * not be incorporated. * * @return the maximum */ public long max() { Cell[] as = cells; long max = base; if (as != null) { int n = as.length; long v; for (int i = 0; i < n; ++i) { Cell a = as[i]; if (a != null && (v = a.value) > max) max = v; } } return max; } /** * Resets variables maintaining updates to {@code Long.MIN_VALUE}. * This method may be a useful alternative to creating a new * updater, but is only effective if there are no concurrent * updates. Because this method is intrinsically racy, it should * only be used when it is known that no threads are concurrently * updating. */ public void reset() { internalReset(Long.MIN_VALUE); } /** * Equivalent in effect to {@link #max} followed by {@link * #reset}. This method may apply for example during quiescent * points between multithreaded computations. If there are * updates concurrent with this method, the returned value is * <em>not</em> guaranteed to be the final value occurring before * the reset. * * @return the maximum */ public long maxThenReset() { Cell[] as = cells; long max = base; base = Long.MIN_VALUE; if (as != null) { int n = as.length; for (int i = 0; i < n; ++i) { Cell a = as[i]; if (a != null) { long v = a.value; a.value = Long.MIN_VALUE; if (v > max) max = v; } } } return max; } /** * Returns the String representation of the {@link #max}. * @return the String representation of the {@link #max} */ public String toString() { return Long.toString(max()); } /** * Equivalent to {@link #max}. * * @return the maximum */ public long longValue() { return max(); } /** * Returns the {@link #max} as an {@code int} after a narrowing * primitive conversion. */ public int intValue() { return (int)max(); } /** * Returns the {@link #max} as a {@code float} * after a widening primitive conversion. */ public float floatValue() { return (float)max(); } /** * Returns the {@link #max} as a {@code double} after a widening * primitive conversion. */ public double doubleValue() { return (double)max(); } private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.defaultWriteObject(); s.writeLong(max()); } private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); busy = 0; cells = null; base = s.readLong(); } }
0true
src_main_java_jsr166e_LongMaxUpdater.java
710
static class WriteResult { final Object response; final long preVersion; final Tuple<String, String> mappingToUpdate; final Engine.IndexingOperation op; WriteResult(Object response, long preVersion, Tuple<String, String> mappingToUpdate, Engine.IndexingOperation op) { this.response = response; this.preVersion = preVersion; this.mappingToUpdate = mappingToUpdate; this.op = op; } @SuppressWarnings("unchecked") <T> T response() { return (T) response; } }
0true
src_main_java_org_elasticsearch_action_bulk_TransportShardBulkAction.java
279
public interface ActionFuture<T> extends Future<T> { /** * Similar to {@link #get()}, just catching the {@link InterruptedException} with * restoring the interrupted state on the thread and throwing an {@link org.elasticsearch.ElasticsearchIllegalStateException}, * and throwing the actual cause of the {@link java.util.concurrent.ExecutionException}. * <p/> * <p>Note, the actual cause is unwrapped to the actual failure (for example, unwrapped * from {@link org.elasticsearch.transport.RemoteTransportException}. The root failure is * still accessible using {@link #getRootFailure()}. */ T actionGet() throws ElasticsearchException; /** * Similar to {@link #get(long, java.util.concurrent.TimeUnit)}, just catching the {@link InterruptedException} with * restoring the interrupted state on the thread and throwing an {@link org.elasticsearch.ElasticsearchIllegalStateException}, * and throwing the actual cause of the {@link java.util.concurrent.ExecutionException}. * <p/> * <p>Note, the actual cause is unwrapped to the actual failure (for example, unwrapped * from {@link org.elasticsearch.transport.RemoteTransportException}. The root failure is * still accessible using {@link #getRootFailure()}. */ T actionGet(String timeout) throws ElasticsearchException; /** * Similar to {@link #get(long, java.util.concurrent.TimeUnit)}, just catching the {@link InterruptedException} with * restoring the interrupted state on the thread and throwing an {@link org.elasticsearch.ElasticsearchIllegalStateException}, * and throwing the actual cause of the {@link java.util.concurrent.ExecutionException}. * <p/> * <p>Note, the actual cause is unwrapped to the actual failure (for example, unwrapped * from {@link org.elasticsearch.transport.RemoteTransportException}. The root failure is * still accessible using {@link #getRootFailure()}. * * @param timeoutMillis Timeout in millis */ T actionGet(long timeoutMillis) throws ElasticsearchException; /** * Similar to {@link #get(long, java.util.concurrent.TimeUnit)}, just catching the {@link InterruptedException} with * restoring the interrupted state on the thread and throwing an {@link org.elasticsearch.ElasticsearchIllegalStateException}, * and throwing the actual cause of the {@link java.util.concurrent.ExecutionException}. * <p/> * <p>Note, the actual cause is unwrapped to the actual failure (for example, unwrapped * from {@link org.elasticsearch.transport.RemoteTransportException}. The root failure is * still accessible using {@link #getRootFailure()}. */ T actionGet(long timeout, TimeUnit unit) throws ElasticsearchException; /** * Similar to {@link #get(long, java.util.concurrent.TimeUnit)}, just catching the {@link InterruptedException} with * restoring the interrupted state on the thread and throwing an {@link org.elasticsearch.ElasticsearchIllegalStateException}, * and throwing the actual cause of the {@link java.util.concurrent.ExecutionException}. * <p/> * <p>Note, the actual cause is unwrapped to the actual failure (for example, unwrapped * from {@link org.elasticsearch.transport.RemoteTransportException}. The root failure is * still accessible using {@link #getRootFailure()}. */ T actionGet(TimeValue timeout) throws ElasticsearchException; /** * The root (possibly) wrapped failure. */ @Nullable Throwable getRootFailure(); }
0true
src_main_java_org_elasticsearch_action_ActionFuture.java
12
enum TextCommandType { GET((byte) 0), PARTIAL_GET((byte) 1), GETS((byte) 2), SET((byte) 3), APPEND((byte) 4), PREPEND((byte) 5), ADD((byte) 6), REPLACE((byte) 7), DELETE((byte) 8), QUIT((byte) 9), STATS((byte) 10), GET_END((byte) 11), ERROR_CLIENT((byte) 12), ERROR_SERVER((byte) 13), UNKNOWN((byte) 14), VERSION((byte) 15), TOUCH((byte) 16), INCREMENT((byte) 17), DECREMENT((byte) 18), HTTP_GET((byte) 30), HTTP_POST((byte) 31), HTTP_PUT((byte) 32), HTTP_DELETE((byte) 33), NO_OP((byte) 98), STOP((byte) 99); final byte value; TextCommandType(byte type) { value = type; } public byte getValue() { return value; } }
0true
hazelcast_src_main_java_com_hazelcast_ascii_TextCommandConstants.java
5,400
@SuppressWarnings({"unchecked", "ForLoopReplaceableByForEach"}) public class AggregationContext implements ReaderContextAware, ScorerAware { private final SearchContext searchContext; private ObjectObjectOpenHashMap<String, FieldDataSource>[] perDepthFieldDataSources = new ObjectObjectOpenHashMap[4]; private List<ReaderContextAware> readerAwares = new ArrayList<ReaderContextAware>(); private List<ScorerAware> scorerAwares = new ArrayList<ScorerAware>(); private AtomicReaderContext reader; private Scorer scorer; public AggregationContext(SearchContext searchContext) { this.searchContext = searchContext; } public SearchContext searchContext() { return searchContext; } public CacheRecycler cacheRecycler() { return searchContext.cacheRecycler(); } public PageCacheRecycler pageCacheRecycler() { return searchContext.pageCacheRecycler(); } public AtomicReaderContext currentReader() { return reader; } public Scorer currentScorer() { return scorer; } public void setNextReader(AtomicReaderContext reader) { this.reader = reader; for (ReaderContextAware aware : readerAwares) { aware.setNextReader(reader); } } public void setScorer(Scorer scorer) { this.scorer = scorer; for (ScorerAware scorerAware : scorerAwares) { scorerAware.setScorer(scorer); } } /** Get a value source given its configuration and the depth of the aggregator in the aggregation tree. */ public <VS extends ValuesSource> VS valuesSource(ValuesSourceConfig<VS> config, int depth) { assert config.valid() : "value source config is invalid - must have either a field context or a script or marked as unmapped"; assert !config.unmapped : "value source should not be created for unmapped fields"; if (perDepthFieldDataSources.length <= depth) { perDepthFieldDataSources = Arrays.copyOf(perDepthFieldDataSources, ArrayUtil.oversize(1 + depth, RamUsageEstimator.NUM_BYTES_OBJECT_REF)); } if (perDepthFieldDataSources[depth] == null) { perDepthFieldDataSources[depth] = new ObjectObjectOpenHashMap<String, FieldDataSource>(); } final ObjectObjectOpenHashMap<String, FieldDataSource> fieldDataSources = perDepthFieldDataSources[depth]; if (config.fieldContext == null) { if (NumericValuesSource.class.isAssignableFrom(config.valueSourceType)) { return (VS) numericScript(config); } if (BytesValuesSource.class.isAssignableFrom(config.valueSourceType)) { return (VS) bytesScript(config); } throw new AggregationExecutionException("value source of type [" + config.valueSourceType.getSimpleName() + "] is not supported by scripts"); } if (NumericValuesSource.class.isAssignableFrom(config.valueSourceType)) { return (VS) numericField(fieldDataSources, config); } if (GeoPointValuesSource.class.isAssignableFrom(config.valueSourceType)) { return (VS) geoPointField(fieldDataSources, config); } // falling back to bytes values return (VS) bytesField(fieldDataSources, config); } private NumericValuesSource numericScript(ValuesSourceConfig<?> config) { setScorerIfNeeded(config.script); setReaderIfNeeded(config.script); scorerAwares.add(config.script); readerAwares.add(config.script); FieldDataSource.Numeric source = new FieldDataSource.Numeric.Script(config.script, config.scriptValueType); if (config.ensureUnique || config.ensureSorted) { source = new FieldDataSource.Numeric.SortedAndUnique(source); readerAwares.add((ReaderContextAware) source); } return new NumericValuesSource(source, config.formatter(), config.parser()); } private NumericValuesSource numericField(ObjectObjectOpenHashMap<String, FieldDataSource> fieldDataSources, ValuesSourceConfig<?> config) { FieldDataSource.Numeric dataSource = (FieldDataSource.Numeric) fieldDataSources.get(config.fieldContext.field()); if (dataSource == null) { FieldDataSource.MetaData metaData = FieldDataSource.MetaData.load(config.fieldContext.indexFieldData(), searchContext); dataSource = new FieldDataSource.Numeric.FieldData((IndexNumericFieldData<?>) config.fieldContext.indexFieldData(), metaData); setReaderIfNeeded((ReaderContextAware) dataSource); readerAwares.add((ReaderContextAware) dataSource); fieldDataSources.put(config.fieldContext.field(), dataSource); } if (config.script != null) { setScorerIfNeeded(config.script); setReaderIfNeeded(config.script); scorerAwares.add(config.script); readerAwares.add(config.script); dataSource = new FieldDataSource.Numeric.WithScript(dataSource, config.script); if (config.ensureUnique || config.ensureSorted) { dataSource = new FieldDataSource.Numeric.SortedAndUnique(dataSource); readerAwares.add((ReaderContextAware) dataSource); } } if (config.needsHashes) { dataSource.setNeedsHashes(true); } return new NumericValuesSource(dataSource, config.formatter(), config.parser()); } private ValuesSource bytesField(ObjectObjectOpenHashMap<String, FieldDataSource> fieldDataSources, ValuesSourceConfig<?> config) { FieldDataSource dataSource = fieldDataSources.get(config.fieldContext.field()); if (dataSource == null) { final IndexFieldData<?> indexFieldData = config.fieldContext.indexFieldData(); FieldDataSource.MetaData metaData = FieldDataSource.MetaData.load(config.fieldContext.indexFieldData(), searchContext); if (indexFieldData instanceof IndexFieldData.WithOrdinals) { dataSource = new FieldDataSource.Bytes.WithOrdinals.FieldData((IndexFieldData.WithOrdinals) indexFieldData, metaData); } else { dataSource = new FieldDataSource.Bytes.FieldData(indexFieldData, metaData); } setReaderIfNeeded((ReaderContextAware) dataSource); readerAwares.add((ReaderContextAware) dataSource); fieldDataSources.put(config.fieldContext.field(), dataSource); } if (config.script != null) { setScorerIfNeeded(config.script); setReaderIfNeeded(config.script); scorerAwares.add(config.script); readerAwares.add(config.script); dataSource = new FieldDataSource.WithScript(dataSource, config.script); } // Even in case we wrap field data, we might still need to wrap for sorting, because the wrapped field data might be // eg. a numeric field data that doesn't sort according to the byte order. However field data values are unique so no // need to wrap for uniqueness if ((config.ensureUnique && !dataSource.metaData().uniqueness().unique()) || config.ensureSorted) { dataSource = new FieldDataSource.Bytes.SortedAndUnique(dataSource); readerAwares.add((ReaderContextAware) dataSource); } if (config.needsHashes) { // the data source needs hash if at least one consumer needs hashes dataSource.setNeedsHashes(true); } if (dataSource instanceof FieldDataSource.Bytes.WithOrdinals) { return new BytesValuesSource.WithOrdinals((FieldDataSource.Bytes.WithOrdinals) dataSource); } else { return new BytesValuesSource(dataSource); } } private BytesValuesSource bytesScript(ValuesSourceConfig<?> config) { setScorerIfNeeded(config.script); setReaderIfNeeded(config.script); scorerAwares.add(config.script); readerAwares.add(config.script); FieldDataSource.Bytes source = new FieldDataSource.Bytes.Script(config.script); if (config.ensureUnique || config.ensureSorted) { source = new FieldDataSource.Bytes.SortedAndUnique(source); readerAwares.add((ReaderContextAware) source); } return new BytesValuesSource(source); } private GeoPointValuesSource geoPointField(ObjectObjectOpenHashMap<String, FieldDataSource> fieldDataSources, ValuesSourceConfig<?> config) { FieldDataSource.GeoPoint dataSource = (FieldDataSource.GeoPoint) fieldDataSources.get(config.fieldContext.field()); if (dataSource == null) { FieldDataSource.MetaData metaData = FieldDataSource.MetaData.load(config.fieldContext.indexFieldData(), searchContext); dataSource = new FieldDataSource.GeoPoint((IndexGeoPointFieldData<?>) config.fieldContext.indexFieldData(), metaData); setReaderIfNeeded(dataSource); readerAwares.add(dataSource); fieldDataSources.put(config.fieldContext.field(), dataSource); } if (config.needsHashes) { dataSource.setNeedsHashes(true); } return new GeoPointValuesSource(dataSource); } public void registerReaderContextAware(ReaderContextAware readerContextAware) { setReaderIfNeeded(readerContextAware); readerAwares.add(readerContextAware); } public void registerScorerAware(ScorerAware scorerAware) { setScorerIfNeeded(scorerAware); scorerAwares.add(scorerAware); } private void setReaderIfNeeded(ReaderContextAware readerAware) { if (reader != null) { readerAware.setNextReader(reader); } } private void setScorerIfNeeded(ScorerAware scorerAware) { if (scorer != null) { scorerAware.setScorer(scorer); } } }
1no label
src_main_java_org_elasticsearch_search_aggregations_support_AggregationContext.java
198
public static class Tab { public static class Name { public static final String Audit = "Auditable_Tab"; } public static class Order { public static final int Audit = 99000; } }
0true
common_src_main_java_org_broadleafcommerce_common_audit_Auditable.java
2,064
@Component("blSessionFixationProtectionFilter") public class SessionFixationProtectionFilter extends GenericFilterBean { private static final Log LOG = LogFactory.getLog(SessionFixationProtectionFilter.class); protected static final String SESSION_ATTR = "SFP-ActiveID"; @Resource(name = "blSessionFixationEncryptionModule") protected EncryptionModule encryptionModule; @Resource(name = "blCookieUtils") protected CookieUtils cookieUtils; @Override public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) sRequest; HttpServletResponse response = (HttpServletResponse) sResponse; HttpSession session = request.getSession(false); if (SecurityContextHolder.getContext() == null) { chain.doFilter(request, response); } String activeIdSessionValue = (String) session.getAttribute(SESSION_ATTR); if (StringUtils.isNotBlank(activeIdSessionValue) && request.isSecure()) { // The request is secure and and we've set a session fixation protection cookie String activeIdCookieValue = cookieUtils.getCookieValue(request, SessionFixationProtectionCookie.COOKIE_NAME); String decryptedActiveIdValue = encryptionModule.decrypt(activeIdCookieValue); if (!activeIdSessionValue.equals(decryptedActiveIdValue)) { abortUser(request, response); LOG.info("Session has been terminated. ActiveID did not match expected value."); return; } } else if (request.isSecure()) { // The request is secure, but we haven't set a session fixation protection cookie yet String token; try { token = RandomGenerator.generateRandomId("SHA1PRNG", 32); } catch (NoSuchAlgorithmException e) { throw new ServletException(e); } String encryptedActiveIdValue = encryptionModule.encrypt(token); session.setAttribute(SESSION_ATTR, token); cookieUtils.setCookieValue(response, SessionFixationProtectionCookie.COOKIE_NAME, encryptedActiveIdValue, "/", -1, true); } chain.doFilter(request, response); } protected void abortUser(HttpServletRequest request, HttpServletResponse response) throws IOException { SecurityContextHolder.clearContext(); cookieUtils.invalidateCookie(response, SessionFixationProtectionCookie.COOKIE_NAME); cookieUtils.setCookieValue(response, "JSESSIONID", "-1", "/", 0, false); response.sendRedirect("/"); } }
1no label
core_broadleaf-profile-web_src_main_java_org_broadleafcommerce_profile_web_core_security_SessionFixationProtectionFilter.java
236
@Service("blModuleConfigurationService") public class ModuleConfigurationServiceImpl implements ModuleConfigurationService { @Resource(name = "blModuleConfigurationDao") protected ModuleConfigurationDao moduleConfigDao; @Override public ModuleConfiguration findById(Long id) { return moduleConfigDao.readById(id); } @Override @Transactional(TransactionUtils.DEFAULT_TRANSACTION_MANAGER) public ModuleConfiguration save(ModuleConfiguration config) { return moduleConfigDao.save(config); } @Override @Transactional(TransactionUtils.DEFAULT_TRANSACTION_MANAGER) public void delete(ModuleConfiguration config) { moduleConfigDao.delete(config); } @Override public List<ModuleConfiguration> findActiveConfigurationsByType(ModuleConfigurationType type) { return moduleConfigDao.readActiveByType(type); } @Override public List<ModuleConfiguration> findAllConfigurationByType(ModuleConfigurationType type) { return moduleConfigDao.readAllByType(type); } @Override public List<ModuleConfiguration> findByType(Class<? extends ModuleConfiguration> type) { return moduleConfigDao.readByType(type); } }
0true
common_src_main_java_org_broadleafcommerce_common_config_service_ModuleConfigurationServiceImpl.java
101
public class TestManualAcquireLock extends AbstractNeo4jTestCase { private Worker worker; @Before public void doBefore() throws Exception { worker = new Worker(); } @After public void doAfter() throws Exception { worker.close(); } @Test public void releaseReleaseManually() throws Exception { String key = "name"; Node node = getGraphDb().createNode(); Transaction tx = newTransaction(); Worker worker = new Worker(); Lock nodeLock = tx.acquireWriteLock( node ); worker.beginTx(); try { worker.setProperty( node, key, "ksjd" ); fail( "Shouldn't be able to grab it" ); } catch ( Exception e ) { } nodeLock.release(); worker.setProperty( node, key, "yo" ); worker.finishTx(); } @Test public void canOnlyReleaseOnce() throws Exception { Node node = getGraphDb().createNode(); Transaction tx = newTransaction(); Lock nodeLock = tx.acquireWriteLock( node ); nodeLock.release(); try { nodeLock.release(); fail( "Shouldn't be able to release more than once" ); } catch ( IllegalStateException e ) { // Good } } @Test public void makeSureNodeStaysLockedEvenAfterManualRelease() throws Exception { String key = "name"; Node node = getGraphDb().createNode(); Transaction tx = newTransaction(); Lock nodeLock = tx.acquireWriteLock( node ); node.setProperty( key, "value" ); nodeLock.release(); Worker worker = new Worker(); worker.beginTx(); try { worker.setProperty( node, key, "ksjd" ); fail( "Shouldn't be able to grab it" ); } catch ( Exception e ) { } commit(); tx.success(); tx.finish(); worker.finishTx(); } private class State { private final GraphDatabaseService graphDb; private Transaction tx; public State( GraphDatabaseService graphDb ) { this.graphDb = graphDb; } } private class Worker extends OtherThreadExecutor<State> { public Worker() { super( "other thread", new State( getGraphDb() ) ); } void beginTx() throws Exception { execute( new WorkerCommand<State, Void>() { @Override public Void doWork( State state ) { state.tx = state.graphDb.beginTx(); return null; } } ); } void finishTx() throws Exception { execute( new WorkerCommand<State, Void>() { @Override public Void doWork( State state ) { state.tx.success(); state.tx.finish(); return null; } } ); } void setProperty( final Node node, final String key, final Object value ) throws Exception { execute( new WorkerCommand<State, Object>() { @Override public Object doWork( State state ) { node.setProperty( key, value ); return null; } }, 200, MILLISECONDS ); } } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestManualAcquireLock.java
122
static final class AdaptedCallable<T> extends ForkJoinTask<T> implements RunnableFuture<T> { final Callable<? extends T> callable; T result; AdaptedCallable(Callable<? extends T> callable) { if (callable == null) throw new NullPointerException(); this.callable = callable; } public final T getRawResult() { return result; } public final void setRawResult(T v) { result = v; } public final boolean exec() { try { result = callable.call(); return true; } catch (Error err) { throw err; } catch (RuntimeException rex) { throw rex; } catch (Exception ex) { throw new RuntimeException(ex); } } public final void run() { invoke(); } private static final long serialVersionUID = 2838392045355241008L; }
0true
src_main_java_jsr166e_ForkJoinTask.java
1,852
nodeEngine.getExecutionService().submit("hz:map-merge", new Runnable() { public void run() { final SimpleEntryView entryView = createSimpleEntryView(record.getKey(), toData(record.getValue()), record); MergeOperation operation = new MergeOperation(mapContainer.getName(), record.getKey(), entryView, finalMergePolicy); try { int partitionId = nodeEngine.getPartitionService().getPartitionId(record.getKey()); Future f = nodeEngine.getOperationService().invokeOnPartition(SERVICE_NAME, operation, partitionId); f.get(); } catch (Throwable t) { throw ExceptionUtil.rethrow(t); } } });
1no label
hazelcast_src_main_java_com_hazelcast_map_MapService.java
498
public class CloseIndexResponse extends AcknowledgedResponse { CloseIndexResponse() { } CloseIndexResponse(boolean acknowledged) { super(acknowledged); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); readAcknowledged(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); writeAcknowledged(out); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_close_CloseIndexResponse.java
534
@Deprecated public class GatewaySnapshotResponse extends BroadcastOperationResponse { GatewaySnapshotResponse() { } GatewaySnapshotResponse(int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) { super(totalShards, successfulShards, failedShards, shardFailures); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_gateway_snapshot_GatewaySnapshotResponse.java
278
public class EmailPropertyType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, EmailPropertyType> TYPES = new LinkedHashMap<String, EmailPropertyType>(); public static final EmailPropertyType USER = new EmailPropertyType("user", "User"); public static final EmailPropertyType INFO = new EmailPropertyType("info", "Info"); public static final EmailPropertyType SERVERINFO = new EmailPropertyType("serverInfo", "Server Info"); public static EmailPropertyType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public EmailPropertyType() { //do nothing } public EmailPropertyType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } public String getType() { return type; } public String getFriendlyType() { return friendlyType; } private void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EmailPropertyType other = (EmailPropertyType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
common_src_main_java_org_broadleafcommerce_common_email_service_message_EmailPropertyType.java
877
kryos = new ThreadLocal<Kryo>() { public Kryo initialValue() { Kryo k = new Kryo(); k.setRegistrationRequired(registerRequired); k.register(Class.class,new DefaultSerializers.ClassSerializer()); for (int i=0;i<defaultRegistrations.size();i++) { Class clazz = defaultRegistrations.get(i); k.register(clazz, KRYO_ID_OFFSET + i); } return k; } };
1no label
titan-core_src_main_java_com_thinkaurelius_titan_graphdb_database_serialize_kryo_KryoSerializer.java
1,172
public class OQueryOperatorBetween extends OQueryOperatorEqualityNotNulls { public OQueryOperatorBetween() { super("BETWEEN", 5, false, 3); } @Override @SuppressWarnings("unchecked") protected boolean evaluateExpression(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft, final Object iRight, OCommandContext iContext) { validate(iRight); final Iterator<?> valueIterator = OMultiValue.getMultiValueIterator(iRight); final Object right1 = OType.convert(valueIterator.next(), iLeft.getClass()); if (right1 == null) return false; valueIterator.next(); final Object right2 = OType.convert(valueIterator.next(), iLeft.getClass()); if (right2 == null) return false; return ((Comparable<Object>) iLeft).compareTo(right1) >= 0 && ((Comparable<Object>) iLeft).compareTo(right2) <= 0; } private void validate(Object iRight) { if (!OMultiValue.isMultiValue(iRight.getClass())) { throw new IllegalArgumentException("Found '" + iRight + "' while was expected: " + getSyntax()); } if (OMultiValue.getSize(iRight) != 3) throw new IllegalArgumentException("Found '" + OMultiValue.toString(iRight) + "' while was expected: " + getSyntax()); } @Override public String getSyntax() { return "<left> " + keyword + " <minRange> AND <maxRange>"; } @Override public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) { return OIndexReuseType.INDEX_METHOD; } @Override public Object executeIndexQuery(OCommandContext iContext, OIndex<?> index, INDEX_OPERATION_TYPE iOperationType, List<Object> keyParams, IndexResultListener resultListener, int fetchLimit) { final OIndexDefinition indexDefinition = index.getDefinition(); final Object result; final OIndexInternal<?> internalIndex = index.getInternal(); if (!internalIndex.canBeUsedInEqualityOperators() || !internalIndex.hasRangeQuerySupport()) return null; if (indexDefinition.getParamCount() == 1) { final Object[] betweenKeys = (Object[]) keyParams.get(0); final Object keyOne = indexDefinition.createValue(Collections.singletonList(OSQLHelper.getValue(betweenKeys[0]))); final Object keyTwo = indexDefinition.createValue(Collections.singletonList(OSQLHelper.getValue(betweenKeys[2]))); if (keyOne == null || keyTwo == null) return null; if (iOperationType == INDEX_OPERATION_TYPE.COUNT) result = index.count(keyOne, true, keyTwo, true, fetchLimit); else { if (resultListener != null) { index.getValuesBetween(keyOne, true, keyTwo, true, resultListener); result = resultListener.getResult(); } else result = index.getValuesBetween(keyOne, true, keyTwo, true); } } else { final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition; final Object[] betweenKeys = (Object[]) keyParams.get(keyParams.size() - 1); final Object betweenKeyOne = OSQLHelper.getValue(betweenKeys[0]); if (betweenKeyOne == null) return null; final Object betweenKeyTwo = OSQLHelper.getValue(betweenKeys[2]); if (betweenKeyTwo == null) return null; final List<Object> betweenKeyOneParams = new ArrayList<Object>(keyParams.size()); betweenKeyOneParams.addAll(keyParams.subList(0, keyParams.size() - 1)); betweenKeyOneParams.add(betweenKeyOne); final List<Object> betweenKeyTwoParams = new ArrayList<Object>(keyParams.size()); betweenKeyTwoParams.addAll(keyParams.subList(0, keyParams.size() - 1)); betweenKeyTwoParams.add(betweenKeyTwo); final Object keyOne = compositeIndexDefinition.createSingleValue(betweenKeyOneParams); if (keyOne == null) return null; final Object keyTwo = compositeIndexDefinition.createSingleValue(betweenKeyTwoParams); if (keyTwo == null) return null; if (iOperationType == INDEX_OPERATION_TYPE.COUNT) result = index.count(keyOne, true, keyTwo, true, fetchLimit); else { if (resultListener != null) { index.getValuesBetween(keyOne, true, keyTwo, true, resultListener); result = resultListener.getResult(); } else result = index.getValuesBetween(keyOne, true, keyTwo, true); } } updateProfiler(iContext, index, keyParams, indexDefinition); return result; } @Override public ORID getBeginRidRange(final Object iLeft, final Object iRight) { validate(iRight); if (iLeft instanceof OSQLFilterItemField && ODocumentHelper.ATTRIBUTE_RID.equals(((OSQLFilterItemField) iLeft).getRoot())) { final Iterator<?> valueIterator = OMultiValue.getMultiValueIterator(iRight); final Object right1 = valueIterator.next(); if (right1 != null) return (ORID) right1; valueIterator.next(); return (ORID) valueIterator.next(); } return null; } @Override public ORID getEndRidRange(final Object iLeft, final Object iRight) { validate(iRight); validate(iRight); if (iLeft instanceof OSQLFilterItemField && ODocumentHelper.ATTRIBUTE_RID.equals(((OSQLFilterItemField) iLeft).getRoot())) { final Iterator<?> valueIterator = OMultiValue.getMultiValueIterator(iRight); final Object right1 = valueIterator.next(); valueIterator.next(); final Object right2 = valueIterator.next(); if (right2 == null) return (ORID) right1; return (ORID) right2; } return null; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryOperatorBetween.java
828
getDatabase().getStorage().callInLock(new Callable<Object>() { @Override public Object call() throws Exception { final OClass cls = classes.get(key); if (cls == null) throw new OSchemaException("Class " + iClassName + " was not found in current database"); if (cls.getBaseClasses().hasNext()) throw new OSchemaException("Class " + iClassName + " cannot be dropped because it has sub classes. Remove the dependencies before trying to drop it again"); if (cls.getSuperClass() != null) { // REMOVE DEPENDENCY FROM SUPERCLASS ((OClassImpl) cls.getSuperClass()).removeBaseClassInternal(cls); } dropClassIndexes(cls); classes.remove(key); if (cls.getShortName() != null) // REMOVE THE ALIAS TOO classes.remove(cls.getShortName().toLowerCase()); return null; } }, true);
1no label
core_src_main_java_com_orientechnologies_orient_core_metadata_schema_OSchemaShared.java
204
static class State { final char[] data; // the characters in the query string final char[] buffer; // a temporary buffer used to reduce necessary allocations int index; int length; BooleanClause.Occur currentOperation; BooleanClause.Occur previousOperation; int not; Query top; State(char[] data, char[] buffer, int index, int length) { this.data = data; this.buffer = buffer; this.index = index; this.length = length; } }
0true
src_main_java_org_apache_lucene_queryparser_XSimpleQueryParser.java
63
public interface TitanGraphQuery<Q extends TitanGraphQuery<Q>> extends GraphQuery { /* --------------------------------------------------------------- * Query Specification * --------------------------------------------------------------- */ /** * The returned element must have a property for the given key that matches the condition according to the * specified relation * * @param key Key that identifies the property * @param predicate Predicate between property and condition * @param condition * @return This query */ @Override public Q has(String key, Predicate predicate, Object condition); /** * The returned element must have a property for the given key that matches the condition according to the * specified relation * * @param key Key that identifies the property * @param predicate Relation between property and condition * @param condition * @return This query */ public Q has(PropertyKey key, TitanPredicate predicate, Object condition); @Override public Q has(String key); @Override public Q hasNot(String key); @Override public Q has(String key, Object value); @Override public Q hasNot(String key, Object value); @Override @Deprecated public <T extends Comparable<T>> Q has(String key, T value, Compare compare); @Override public <T extends Comparable<?>> Q interval(String key, T startValue, T endValue); /** * Limits the size of the returned result set * * @param max The maximum number of results to return * @return This query */ @Override public Q limit(final int max); /** * Orders the element results of this query according * to their property for the given key in the given order (increasing/decreasing). * * @param key The key of the properties on which to order * @param order the ordering direction * @return */ public Q orderBy(String key, Order order); /** * Orders the element results of this query according * to their property for the given key in the given order (increasing/decreasing). * * @param key The key of the properties on which to order * @param order the ordering direction * @return */ public Q orderBy(PropertyKey key, Order order); /* --------------------------------------------------------------- * Query Execution * --------------------------------------------------------------- */ /** * Returns all vertices that match the conditions. * * @return */ public Iterable<Vertex> vertices(); /** * Returns all edges that match the conditions. * * @return */ public Iterable<Edge> edges(); /** * Returns all properties that match the conditions * * @return */ public Iterable<TitanProperty> properties(); /** * Returns a description of this query for vertices as a {@link QueryDescription} object. * * This can be used to inspect the query plan for this query. Note, that calling this method * does not actually execute the query but only optimizes it and constructs a query plan. * * @return A description of this query for vertices */ public QueryDescription describeForVertices(); /** * Returns a description of this query for edges as a {@link QueryDescription} object. * * This can be used to inspect the query plan for this query. Note, that calling this method * does not actually execute the query but only optimizes it and constructs a query plan. * * @return A description of this query for edges */ public QueryDescription describeForEdges(); /** * Returns a description of this query for properties as a {@link QueryDescription} object. * * This can be used to inspect the query plan for this query. Note, that calling this method * does not actually execute the query but only optimizes it and constructs a query plan. * * @return A description of this query for properties */ public QueryDescription describeForProperties(); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_TitanGraphQuery.java
1,598
public class ServerRun { protected String rootPath; protected final String serverId; protected OServer server; public ServerRun(final String iRootPath, final String serverId) { this.rootPath = iRootPath; this.serverId = serverId; } protected ODatabaseDocumentTx createDatabase(final String iName) { OGlobalConfiguration.STORAGE_KEEP_OPEN.setValue(false); String dbPath = getDatabasePath(iName); new File(dbPath).mkdirs(); final ODatabaseDocumentTx database = new ODatabaseDocumentTx("local:" + dbPath); if (database.exists()) { System.out.println("Dropping previous database '" + iName + "' under: " + dbPath + "..."); OFileUtils.deleteRecursively(new File(dbPath)); } System.out.println("Creating database '" + iName + "' under: " + dbPath + "..."); database.create(); return database; } protected void copyDatabase(final String iDatabaseName, final String iDestinationDirectory) throws IOException { // COPY THE DATABASE TO OTHER DIRECTORIES System.out.println("Dropping any previous database '" + iDatabaseName + "' under: " + iDatabaseName + "..."); OFileUtils.deleteRecursively(new File(iDestinationDirectory)); System.out.println("Copying database folder " + iDatabaseName + " to " + iDestinationDirectory + "..."); OFileUtils.copyDirectory(new File(getDatabasePath(iDatabaseName)), new File(iDestinationDirectory)); } public OServer getServerInstance() { return server; } public String getServerId() { return serverId; } protected OServer startServer(final String iConfigFile) throws Exception, InstantiationException, IllegalAccessException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException, IOException { System.out.println("Starting server " + serverId + " from " + getServerHome() + "..."); System.setProperty("ORIENTDB_HOME", getServerHome()); server = new OServer(); server.startup(getClass().getClassLoader().getResourceAsStream(iConfigFile)); server.activate(); return server; } protected void shutdownServer() { if (server != null) server.shutdown(); } protected String getServerHome() { return getServerHome(serverId); } protected String getDatabasePath(final String iDatabaseName) { return getDatabasePath(serverId, iDatabaseName); } public String getBinaryProtocolAddress() { return server.getListenerByProtocol(ONetworkProtocolBinary.class).getListeningAddress(); } public static String getServerHome(final String iServerId) { return "target/server" + iServerId; } public static String getDatabasePath(final String iServerId, final String iDatabaseName) { return getServerHome(iServerId) + "/databases/" + iDatabaseName; } }
1no label
distributed_src_test_java_com_orientechnologies_orient_server_distributed_ServerRun.java
370
future.andThen(new ExecutionCallback<Map<String, Integer>>() { @Override public void onResponse(Map<String, Integer> response) { try { listenerResults.putAll(response); } finally { semaphore.release(); } } @Override public void onFailure(Throwable t) { semaphore.release(); } });
0true
hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_DistributedMapperClientMapReduceTest.java
238
XPostingsHighlighter highlighter = new XPostingsHighlighter() { Iterator<String> valuesIterator = Arrays.asList(firstValue, secondValue, thirdValue).iterator(); Iterator<Integer> offsetsIterator = Arrays.asList(0, firstValue.length() + 1, secondValue.length() + 1).iterator(); @Override protected String[][] loadFieldValues(IndexSearcher searcher, String[] fields, int[] docids, int maxLength) throws IOException { return new String[][]{new String[]{valuesIterator.next()}}; } @Override protected int getOffsetForCurrentValue(String field, int docId) { return offsetsIterator.next(); } @Override protected BreakIterator getBreakIterator(String field) { return new WholeBreakIterator(); } @Override protected Passage[] getEmptyHighlight(String fieldName, BreakIterator bi, int maxPassages) { return new Passage[0]; } };
0true
src_test_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighterTests.java
0
public interface AbbreviationService { /** * Gets the available abbreviations for a string. If no abbreviations * are found, the returned available abbreviations consist of each * word in the original string, in turn, with one abbreviation, the * word unchanged. * * @param s the string to abbreviate * @return the available abbreviations */ Abbreviations getAbbreviations(String s); }
0true
tableViews_src_main_java_gov_nasa_arc_mct_abbreviation_AbbreviationService.java
3,710
public class IpFieldMapper extends NumberFieldMapper<Long> { public static final String CONTENT_TYPE = "ip"; public static String longToIp(long longIp) { int octet3 = (int) ((longIp >> 24) % 256); int octet2 = (int) ((longIp >> 16) % 256); int octet1 = (int) ((longIp >> 8) % 256); int octet0 = (int) ((longIp) % 256); return octet3 + "." + octet2 + "." + octet1 + "." + octet0; } private static final Pattern pattern = Pattern.compile("\\."); public static long ipToLong(String ip) throws ElasticsearchIllegalArgumentException { try { String[] octets = pattern.split(ip); if (octets.length != 4) { throw new ElasticsearchIllegalArgumentException("failed to parse ip [" + ip + "], not full ip address (4 dots)"); } return (Long.parseLong(octets[0]) << 24) + (Integer.parseInt(octets[1]) << 16) + (Integer.parseInt(octets[2]) << 8) + Integer.parseInt(octets[3]); } catch (Exception e) { if (e instanceof ElasticsearchIllegalArgumentException) { throw (ElasticsearchIllegalArgumentException) e; } throw new ElasticsearchIllegalArgumentException("failed to parse ip [" + ip + "]", e); } } public static class Defaults extends NumberFieldMapper.Defaults { public static final String NULL_VALUE = null; public static final FieldType FIELD_TYPE = new FieldType(NumberFieldMapper.Defaults.FIELD_TYPE); static { FIELD_TYPE.freeze(); } } public static class Builder extends NumberFieldMapper.Builder<Builder, IpFieldMapper> { protected String nullValue = Defaults.NULL_VALUE; public Builder(String name) { super(name, new FieldType(Defaults.FIELD_TYPE)); builder = this; } public Builder nullValue(String nullValue) { this.nullValue = nullValue; return this; } @Override public IpFieldMapper build(BuilderContext context) { fieldType.setOmitNorms(fieldType.omitNorms() && boost == 1.0f); IpFieldMapper fieldMapper = new IpFieldMapper(buildNames(context), precisionStep, boost, fieldType, docValues, nullValue, ignoreMalformed(context), coerce(context), postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo); fieldMapper.includeInAll(includeInAll); return fieldMapper; } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { IpFieldMapper.Builder builder = ipField(name); parseNumberField(builder, name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String propName = Strings.toUnderscoreCase(entry.getKey()); Object propNode = entry.getValue(); if (propName.equals("null_value")) { builder.nullValue(propNode.toString()); } } return builder; } } private String nullValue; protected IpFieldMapper(Names names, int precisionStep, float boost, FieldType fieldType, Boolean docValues, String nullValue, Explicit<Boolean> ignoreMalformed, Explicit<Boolean> coerce, PostingsFormatProvider postingsProvider, DocValuesFormatProvider docValuesProvider, SimilarityProvider similarity, Loading normsLoading, @Nullable Settings fieldDataSettings, Settings indexSettings, MultiFields multiFields, CopyTo copyTo) { super(names, precisionStep, boost, fieldType, docValues, ignoreMalformed, coerce, new NamedAnalyzer("_ip/" + precisionStep, new NumericIpAnalyzer(precisionStep)), new NamedAnalyzer("_ip/max", new NumericIpAnalyzer(Integer.MAX_VALUE)), postingsProvider, docValuesProvider, similarity, normsLoading, fieldDataSettings, indexSettings, multiFields, copyTo); this.nullValue = nullValue; } @Override public FieldType defaultFieldType() { return Defaults.FIELD_TYPE; } @Override public FieldDataType defaultFieldDataType() { return new FieldDataType("long"); } @Override protected int maxPrecisionStep() { return 64; } @Override public Long value(Object value) { if (value == null) { return null; } if (value instanceof Number) { return ((Number) value).longValue(); } if (value instanceof BytesRef) { return Numbers.bytesToLong((BytesRef) value); } return ipToLong(value.toString()); } /** * IPs should return as a string. */ @Override public Object valueForSearch(Object value) { Long val = value(value); if (val == null) { return null; } return longToIp(val); } @Override public BytesRef indexedValueForSearch(Object value) { BytesRef bytesRef = new BytesRef(); NumericUtils.longToPrefixCoded(parseValue(value), 0, bytesRef); // 0 because of exact match return bytesRef; } private long parseValue(Object value) { if (value instanceof Number) { return ((Number) value).longValue(); } if (value instanceof BytesRef) { return ipToLong(((BytesRef) value).utf8ToString()); } return ipToLong(value.toString()); } @Override public Query fuzzyQuery(String value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions) { long iValue = ipToLong(value); long iSim; try { iSim = ipToLong(fuzziness.asString()); } catch (ElasticsearchIllegalArgumentException e) { iSim = fuzziness.asLong(); } return NumericRangeQuery.newLongRange(names.indexName(), precisionStep, iValue - iSim, iValue + iSim, true, true); } @Override public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return NumericRangeQuery.newLongRange(names.indexName(), precisionStep, lowerTerm == null ? null : parseValue(lowerTerm), upperTerm == null ? null : parseValue(upperTerm), includeLower, includeUpper); } @Override public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return NumericRangeFilter.newLongRange(names.indexName(), precisionStep, lowerTerm == null ? null : parseValue(lowerTerm), upperTerm == null ? null : parseValue(upperTerm), includeLower, includeUpper); } @Override public Filter rangeFilter(IndexFieldDataService fieldData, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) { return NumericRangeFieldDataFilter.newLongRange((IndexNumericFieldData) fieldData.getForField(this), lowerTerm == null ? null : parseValue(lowerTerm), upperTerm == null ? null : parseValue(upperTerm), includeLower, includeUpper); } @Override public Filter nullValueFilter() { if (nullValue == null) { return null; } final long value = ipToLong(nullValue); return NumericRangeFilter.newLongRange(names.indexName(), precisionStep, value, value, true, true); } @Override protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException { String ipAsString; if (context.externalValueSet()) { ipAsString = (String) context.externalValue(); if (ipAsString == null) { ipAsString = nullValue; } } else { if (context.parser().currentToken() == XContentParser.Token.VALUE_NULL) { ipAsString = nullValue; } else { ipAsString = context.parser().text(); } } if (ipAsString == null) { return; } if (context.includeInAll(includeInAll, this)) { context.allEntries().addText(names.fullName(), ipAsString, boost); } final long value = ipToLong(ipAsString); if (fieldType.indexed() || fieldType.stored()) { CustomLongNumericField field = new CustomLongNumericField(this, value, fieldType); field.setBoost(boost); fields.add(field); } if (hasDocValues()) { addDocValue(context, value); } } @Override protected String contentType() { return CONTENT_TYPE; } @Override public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException { super.merge(mergeWith, mergeContext); if (!this.getClass().equals(mergeWith.getClass())) { return; } if (!mergeContext.mergeFlags().simulate()) { this.nullValue = ((IpFieldMapper) mergeWith).nullValue; } } @Override protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException { super.doXContentBody(builder, includeDefaults, params); if (includeDefaults || precisionStep != Defaults.PRECISION_STEP) { builder.field("precision_step", precisionStep); } if (includeDefaults || nullValue != null) { builder.field("null_value", nullValue); } if (includeInAll != null) { builder.field("include_in_all", includeInAll); } else if (includeDefaults) { builder.field("include_in_all", false); } } public static class NumericIpAnalyzer extends NumericAnalyzer<NumericIpTokenizer> { private final int precisionStep; public NumericIpAnalyzer() { this(NumericUtils.PRECISION_STEP_DEFAULT); } public NumericIpAnalyzer(int precisionStep) { this.precisionStep = precisionStep; } @Override protected NumericIpTokenizer createNumericTokenizer(Reader reader, char[] buffer) throws IOException { return new NumericIpTokenizer(reader, precisionStep, buffer); } } public static class NumericIpTokenizer extends NumericTokenizer { public NumericIpTokenizer(Reader reader, int precisionStep, char[] buffer) throws IOException { super(reader, new NumericTokenStream(precisionStep), buffer, null); } @Override protected void setValue(NumericTokenStream tokenStream, String value) { tokenStream.setLongValue(ipToLong(value)); } } }
1no label
src_main_java_org_elasticsearch_index_mapper_ip_IpFieldMapper.java
45
public enum Multiplicity { /** * The given edge label specifies a multi-graph, meaning that the multiplicity is not constrained and that * there may be multiple edges of this label between any given pair of vertices. * * @link http://en.wikipedia.org/wiki/Multigraph */ MULTI, /** * The given edge label specifies a simple graph, meaning that the multiplicity is not constrained but that there * can only be at most a single edge of this label between a given pair of vertices. */ SIMPLE, /** * There can only be a single in-edge of this label for a given vertex but multiple out-edges (i.e. in-unique) */ ONE2MANY, /** * There can only be a single out-edge of this label for a given vertex but multiple in-edges (i.e. out-unique) */ MANY2ONE, /** * There can be only a single in and out-edge of this label for a given vertex (i.e. unique in both directions). */ ONE2ONE; /** * Whether this multiplicity imposes any constraint on the number of edges that may exist between a pair of vertices. * * @return */ public boolean isConstrained() { return this!=MULTI; } public boolean isConstrained(Direction direction) { if (direction==Direction.BOTH) return isConstrained(); if (this==MULTI) return false; if (this==SIMPLE) return true; return isUnique(direction); } /** * If this multiplicity implies edge uniqueness in the given direction for any given vertex. * * @param direction * @return */ public boolean isUnique(Direction direction) { switch (direction) { case IN: return this==ONE2MANY || this==ONE2ONE; case OUT: return this==MANY2ONE || this==ONE2ONE; case BOTH: return this==ONE2ONE; default: throw new AssertionError("Unknown direction: " + direction); } } //######### CONVERTING MULTIPLICITY <-> CARDINALITY ######## public static Multiplicity convert(Cardinality cardinality) { Preconditions.checkNotNull(cardinality); switch(cardinality) { case LIST: return MULTI; case SET: return SIMPLE; case SINGLE: return MANY2ONE; default: throw new AssertionError("Unknown cardinality: " + cardinality); } } public Cardinality getCardinality() { switch (this) { case MULTI: return Cardinality.LIST; case SIMPLE: return Cardinality.SET; case MANY2ONE: return Cardinality.SINGLE; default: throw new AssertionError("Invalid multiplicity: " + this); } } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_Multiplicity.java
52
final class NestedCompletionProposal implements ICompletionProposal, ICompletionProposalExtension2 { private final Declaration dec; private final int offset; public NestedCompletionProposal(Declaration dec, int offset) { super(); this.dec = dec; this.offset = offset; } @Override public void apply(IDocument document) { try { int len = 0; while (isJavaIdentifierPart(document.getChar(offset+len))) { len++; } document.replace(offset, len, getText(false)); } catch (BadLocationException e) { e.printStackTrace(); } } @Override public Point getSelection(IDocument document) { return null; } @Override public String getAdditionalProposalInfo() { return null; } @Override public String getDisplayString() { return getText(true); } @Override public Image getImage() { return getImageForDeclaration(dec); } @Override public IContextInformation getContextInformation() { return null; } private String getText(boolean description) { StringBuilder sb = new StringBuilder() .append(dec.getName()); if (dec instanceof Functional) { appendPositionalArgs(dec, getUnit(), sb, false, description); } return sb.toString(); } @Override public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { apply(viewer.getDocument()); } @Override public void selected(ITextViewer viewer, boolean smartToggle) {} @Override public void unselected(ITextViewer viewer) {} @Override public boolean validate(IDocument document, int currentOffset, DocumentEvent event) { if (event==null) { return true; } else { try { String content = document.get(offset, currentOffset-offset); String filter = content.trim().toLowerCase(); if ((dec.getName().toLowerCase()) .startsWith(filter)) { return true; } } catch (BadLocationException e) { // ignore concurrently modified document } return false; } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_complete_RefinementCompletionProposal.java
13
final ScheduledExecutorService exe = new ScheduledThreadPoolExecutor(1,new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { r.run(); } });
0true
titan-test_src_main_java_com_thinkaurelius_titan_TestBed.java
552
public static class FieldMappingMetaData implements ToXContent { public static final FieldMappingMetaData NULL = new FieldMappingMetaData("", BytesArray.EMPTY); private String fullName; private BytesReference source; public FieldMappingMetaData(String fullName, BytesReference source) { this.fullName = fullName; this.source = source; } public String fullName() { return fullName; } /** Returns the mappings as a map. Note that the returned map has a single key which is always the field's {@link Mapper#name}. */ public Map<String, Object> sourceAsMap() { return XContentHelper.convertToMap(source.array(), source.arrayOffset(), source.length(), true).v2(); } public boolean isNull() { return NULL.fullName().equals(fullName) && NULL.source.length() == source.length(); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.field("full_name", fullName); XContentHelper.writeRawField("mapping", source, builder, params); return builder; } }
1no label
src_main_java_org_elasticsearch_action_admin_indices_mapping_get_GetFieldMappingsResponse.java
186
static final class QNode implements ForkJoinPool.ManagedBlocker { final Phaser phaser; final int phase; final boolean interruptible; final boolean timed; boolean wasInterrupted; long nanos; long lastTime; volatile Thread thread; // nulled to cancel wait QNode next; QNode(Phaser phaser, int phase, boolean interruptible, boolean timed, long nanos) { this.phaser = phaser; this.phase = phase; this.interruptible = interruptible; this.nanos = nanos; this.timed = timed; this.lastTime = timed ? System.nanoTime() : 0L; thread = Thread.currentThread(); } public boolean isReleasable() { if (thread == null) return true; if (phaser.getPhase() != phase) { thread = null; return true; } if (Thread.interrupted()) wasInterrupted = true; if (wasInterrupted && interruptible) { thread = null; return true; } if (timed) { if (nanos > 0L) { long now = System.nanoTime(); nanos -= now - lastTime; lastTime = now; } if (nanos <= 0L) { thread = null; return true; } } return false; } public boolean block() { if (isReleasable()) return true; else if (!timed) LockSupport.park(this); else if (nanos > 0) LockSupport.parkNanos(this, nanos); return isReleasable(); } }
0true
src_main_java_jsr166y_Phaser.java
1,337
public class Hadoop2Compiler extends HybridConfigured implements HadoopCompiler { private static final String MAPRED_COMPRESS_MAP_OUTPUT = "mapred.compress.map.output"; private static final String MAPRED_MAP_OUTPUT_COMPRESSION_CODEC = "mapred.map.output.compression.codec"; enum State {MAPPER, REDUCER, NONE} private static final String ARROW = " > "; private static final String MAPREDUCE_MAP_OUTPUT_COMPRESS = "mapreduce.map.output.compress"; private static final String MAPREDUCE_MAP_OUTPUT_COMPRESS_CODEC = "mapreduce.map.output.compress.codec"; public static final Logger logger = Logger.getLogger(Hadoop2Compiler.class); private HadoopGraph graph; protected final List<Job> jobs = new ArrayList<Job>(); private State state = State.NONE; private static final Class<? extends InputFormat> INTERMEDIATE_INPUT_FORMAT = SequenceFileInputFormat.class; private static final Class<? extends OutputFormat> INTERMEDIATE_OUTPUT_FORMAT = SequenceFileOutputFormat.class; static final String JOB_JAR = "titan-hadoop-2-" + TitanConstants.VERSION + "-job.jar"; private static final String MAPRED_JAR = "mapred.jar"; public Hadoop2Compiler(final HadoopGraph graph) { this.graph = graph; this.setConf(new Configuration(this.graph.getConf())); } private String makeClassName(final Class klass) { return klass.getCanonicalName().replace(klass.getPackage().getName() + ".", ""); } @Override public void addMapReduce(final Class<? extends Mapper> mapper, final Class<? extends Reducer> combiner, final Class<? extends Reducer> reducer, final Class<? extends WritableComparable> mapOutputKey, final Class<? extends WritableComparable> mapOutputValue, final Class<? extends WritableComparable> reduceOutputKey, final Class<? extends WritableComparable> reduceOutputValue, final Configuration configuration) { this.addMapReduce(mapper, combiner, reducer, null, mapOutputKey, mapOutputValue, reduceOutputKey, reduceOutputValue, configuration); } @Override public void addMapReduce(final Class<? extends Mapper> mapper, final Class<? extends Reducer> combiner, final Class<? extends Reducer> reducer, final Class<? extends WritableComparator> comparator, final Class<? extends WritableComparable> mapOutputKey, final Class<? extends WritableComparable> mapOutputValue, final Class<? extends WritableComparable> reduceOutputKey, final Class<? extends WritableComparable> reduceOutputValue, final Configuration configuration) { Configuration mergedConf = overlayConfiguration(getConf(), configuration); try { final Job job; if (State.NONE == this.state || State.REDUCER == this.state) { // Create a new job with a reference to mergedConf job = Job.getInstance(mergedConf); job.setJobName(makeClassName(mapper) + ARROW + makeClassName(reducer)); HBaseAuthHelper.setHBaseAuthToken(mergedConf, job); this.jobs.add(job); } else { job = this.jobs.get(this.jobs.size() - 1); job.setJobName(job.getJobName() + ARROW + makeClassName(mapper) + ARROW + makeClassName(reducer)); } job.setNumReduceTasks(this.getConf().getInt("mapreduce.job.reduces", this.getConf().getInt("mapreduce.tasktracker.reduce.tasks.maximum", 1))); ChainMapper.addMapper(job, mapper, NullWritable.class, FaunusVertex.class, mapOutputKey, mapOutputValue, mergedConf); ChainReducer.setReducer(job, reducer, mapOutputKey, mapOutputValue, reduceOutputKey, reduceOutputValue, mergedConf); if (null != comparator) job.setSortComparatorClass(comparator); if (null != combiner) job.setCombinerClass(combiner); if (null == job.getConfiguration().get(MAPREDUCE_MAP_OUTPUT_COMPRESS, null)) job.getConfiguration().setBoolean(MAPREDUCE_MAP_OUTPUT_COMPRESS, true); if (null == job.getConfiguration().get(MAPREDUCE_MAP_OUTPUT_COMPRESS_CODEC, null)) job.getConfiguration().setClass(MAPREDUCE_MAP_OUTPUT_COMPRESS_CODEC, DefaultCodec.class, CompressionCodec.class); this.state = State.REDUCER; } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } @Override public void addMap(final Class<? extends Mapper> mapper, final Class<? extends WritableComparable> mapOutputKey, final Class<? extends WritableComparable> mapOutputValue, Configuration configuration) { Configuration mergedConf = overlayConfiguration(getConf(), configuration); try { final Job job; if (State.NONE == this.state) { // Create a new job with a reference to mergedConf job = Job.getInstance(mergedConf); job.setNumReduceTasks(0); job.setJobName(makeClassName(mapper)); HBaseAuthHelper.setHBaseAuthToken(mergedConf, job); this.jobs.add(job); } else { job = this.jobs.get(this.jobs.size() - 1); job.setJobName(job.getJobName() + ARROW + makeClassName(mapper)); } if (State.MAPPER == this.state || State.NONE == this.state) { ChainMapper.addMapper(job, mapper, NullWritable.class, FaunusVertex.class, mapOutputKey, mapOutputValue, mergedConf); this.state = State.MAPPER; } else { ChainReducer.addMapper(job, mapper, NullWritable.class, FaunusVertex.class, mapOutputKey, mapOutputValue, mergedConf); this.state = State.REDUCER; } } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } @Override public void completeSequence() { // noop } @Override public void composeJobs() throws IOException { if (this.jobs.size() == 0) { return; } if (getTitanConf().get(TitanHadoopConfiguration.PIPELINE_TRACK_PATHS)) logger.warn("Path tracking is enabled for this Titan/Hadoop job (space and time expensive)"); if (getTitanConf().get(TitanHadoopConfiguration.PIPELINE_TRACK_STATE)) logger.warn("State tracking is enabled for this Titan/Hadoop job (full deletes not possible)"); JobClasspathConfigurer cpConf = JobClasspathConfigurers.get(graph.getConf().get(MAPRED_JAR), JOB_JAR); // Create temporary job data directory on the filesystem Path tmpPath = graph.getJobDir(); final FileSystem fs = FileSystem.get(graph.getConf()); fs.mkdirs(tmpPath); logger.debug("Created " + tmpPath + " on filesystem " + fs); final String jobTmp = tmpPath.toString() + "/" + Tokens.JOB; logger.debug("Set jobDir=" + jobTmp); //////// CHAINING JOBS TOGETHER for (int i = 0; i < this.jobs.size(); i++) { final Job job = this.jobs.get(i); for (ConfigOption<Boolean> c : Arrays.asList(TitanHadoopConfiguration.PIPELINE_TRACK_PATHS, TitanHadoopConfiguration.PIPELINE_TRACK_STATE)) { ModifiableHadoopConfiguration jobFaunusConf = ModifiableHadoopConfiguration.of(job.getConfiguration()); jobFaunusConf.set(c, getTitanConf().get(c)); } SequenceFileOutputFormat.setOutputPath(job, new Path(jobTmp + "-" + i)); cpConf.configure(job); // configure job inputs if (i == 0) { job.setInputFormatClass(this.graph.getGraphInputFormat()); if (FileInputFormat.class.isAssignableFrom(this.graph.getGraphInputFormat())) { FileInputFormat.setInputPaths(job, this.graph.getInputLocation()); FileInputFormat.setInputPathFilter(job, NoSideEffectFilter.class); } } else { job.setInputFormatClass(INTERMEDIATE_INPUT_FORMAT); FileInputFormat.setInputPaths(job, new Path(jobTmp + "-" + (i - 1))); FileInputFormat.setInputPathFilter(job, NoSideEffectFilter.class); } // configure job outputs if (i == this.jobs.size() - 1) { LazyOutputFormat.setOutputFormatClass(job, this.graph.getGraphOutputFormat()); MultipleOutputs.addNamedOutput(job, Tokens.SIDEEFFECT, this.graph.getSideEffectOutputFormat(), job.getOutputKeyClass(), job.getOutputKeyClass()); MultipleOutputs.addNamedOutput(job, Tokens.GRAPH, this.graph.getGraphOutputFormat(), NullWritable.class, FaunusVertex.class); } else { LazyOutputFormat.setOutputFormatClass(job, INTERMEDIATE_OUTPUT_FORMAT); MultipleOutputs.addNamedOutput(job, Tokens.SIDEEFFECT, this.graph.getSideEffectOutputFormat(), job.getOutputKeyClass(), job.getOutputKeyClass()); MultipleOutputs.addNamedOutput(job, Tokens.GRAPH, INTERMEDIATE_OUTPUT_FORMAT, NullWritable.class, FaunusVertex.class); } } } @Override public int run(final String[] args) throws Exception { String script = null; boolean showHeader = true; if (args.length == 2) { script = args[0]; showHeader = Boolean.valueOf(args[1]); } final FileSystem hdfs = FileSystem.get(this.getConf()); if (null != graph.getJobDir() && graph.getJobDirOverwrite() && hdfs.exists(graph.getJobDir())) { hdfs.delete(graph.getJobDir(), true); } if (showHeader) { logger.info("Titan/Hadoop: Distributed Graph Processing with Hadoop"); logger.info(" ,"); logger.info(" , |\\ ,__"); logger.info(" |\\ \\/ `\\"); logger.info(" \\ `-.:. `\\"); logger.info(" `-.__ `\\/\\/\\|"); logger.info(" / `'/ () \\"); logger.info(" .' /\\ )"); logger.info(" .-' .'| \\ \\__"); logger.info(" .' __( \\ '`(()"); logger.info("/_.'` `. | )("); logger.info(" \\ |"); logger.info(" |/"); } if (null != script && !script.isEmpty()) logger.info("Generating job chain: " + script); this.composeJobs(); logger.info("Compiled to " + this.jobs.size() + " MapReduce job(s)"); final String jobTmp = graph.getJobDir().toString() + "/" + Tokens.JOB; for (int i = 0; i < this.jobs.size(); i++) { final Job job = this.jobs.get(i); try { ((JobConfigurationFormat) (FormatTools.getBaseOutputFormatClass(job).newInstance())).updateJob(job); } catch (final Exception e) { } logger.info("Executing job " + (i + 1) + " out of " + this.jobs.size() + ": " + job.getJobName()); boolean success = job.waitForCompletion(true); if (i > 0) { Preconditions.checkNotNull(jobTmp); logger.debug("Cleaninng job data location: " + jobTmp + "-" + i); final Path path = new Path(jobTmp + "-" + (i - 1)); // delete previous intermediate graph data for (final FileStatus temp : hdfs.globStatus(new Path(path.toString() + "/" + Tokens.GRAPH + "*"))) { hdfs.delete(temp.getPath(), true); } // delete previous intermediate graph data for (final FileStatus temp : hdfs.globStatus(new Path(path.toString() + "/" + Tokens.PART + "*"))) { hdfs.delete(temp.getPath(), true); } } if (!success) { logger.error("Titan/Hadoop job error -- remaining MapReduce jobs have been canceled"); return -1; } } return 0; } private static Configuration overlayConfiguration(Configuration base, Configuration overrides) { Configuration mergedConf = new Configuration(base); final Iterator<Entry<String,String>> it = overrides.iterator(); while (it.hasNext()) { Entry<String,String> ent = it.next(); mergedConf.set(ent.getKey(), ent.getValue()); } return mergedConf; } }
1no label
titan-hadoop-parent_titan-hadoop-2_src_main_java_com_thinkaurelius_titan_hadoop_compat_h2_Hadoop2Compiler.java
1,507
@Component("blAuthenticationSuccessHandler") public class BroadleafAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { String targetUrl = request.getParameter(getTargetUrlParameter()); if (StringUtils.isNotBlank(targetUrl) && targetUrl.contains(":")) { getRedirectStrategy().sendRedirect(request, response, getDefaultTargetUrl()); } else { super.onAuthenticationSuccess(request, response, authentication); } } }
1no label
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_order_security_BroadleafAuthenticationSuccessHandler.java
129
@Repository("blStructuredContentDao") public class StructuredContentDaoImpl implements StructuredContentDao { private static SandBox DUMMY_SANDBOX = new SandBoxImpl(); { DUMMY_SANDBOX.setId(-1l); } @PersistenceContext(unitName = "blPU") protected EntityManager em; @Resource(name="blEntityConfiguration") protected EntityConfiguration entityConfiguration; @Override public StructuredContent findStructuredContentById(Long contentId) { return em.find(StructuredContentImpl.class, contentId); } @Override public StructuredContentType findStructuredContentTypeById(Long contentTypeId) { return em.find(StructuredContentTypeImpl.class, contentTypeId); } @Override public List<StructuredContentType> retrieveAllStructuredContentTypes() { Query query = em.createNamedQuery("BC_READ_ALL_STRUCTURED_CONTENT_TYPES"); return query.getResultList(); } @Override public List<StructuredContent> findAllContentItems() { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<StructuredContent> criteria = builder.createQuery(StructuredContent.class); Root<StructuredContentImpl> sc = criteria.from(StructuredContentImpl.class); criteria.select(sc); try { return em.createQuery(criteria).getResultList(); } catch (NoResultException e) { return new ArrayList<StructuredContent>(); } } @Override public Map<String, StructuredContentField> readFieldsForStructuredContentItem(StructuredContent sc) { Query query = em.createNamedQuery("BC_READ_CONTENT_FIELDS_BY_CONTENT_ID"); query.setParameter("structuredContent", sc); query.setHint(QueryHints.HINT_CACHEABLE, true); List<StructuredContentField> fields = query.getResultList(); Map<String, StructuredContentField> fieldMap = new HashMap<String, StructuredContentField>(); for (StructuredContentField scField : fields) { fieldMap.put(scField.getFieldKey(), scField); } return fieldMap; } @Override public StructuredContent addOrUpdateContentItem(StructuredContent content) { return em.merge(content); } @Override public void delete(StructuredContent content) { if (! em.contains(content)) { content = findStructuredContentById(content.getId()); } em.remove(content); } @Override public StructuredContentType saveStructuredContentType(StructuredContentType type) { return em.merge(type); } @Override public List<StructuredContent> findActiveStructuredContentByType(SandBox sandBox, StructuredContentType type, Locale locale) { return findActiveStructuredContentByType(sandBox, type, locale, null); } @Override public List<StructuredContent> findActiveStructuredContentByType(SandBox sandBox, StructuredContentType type, Locale fullLocale, Locale languageOnlyLocale) { String queryName = null; if (languageOnlyLocale == null) { languageOnlyLocale = fullLocale; } if (sandBox == null) { queryName = "BC_ACTIVE_STRUCTURED_CONTENT_BY_TYPE"; } else if (SandBoxType.PRODUCTION.equals(sandBox)) { queryName = "BC_ACTIVE_STRUCTURED_CONTENT_BY_TYPE_AND_PRODUCTION_SANDBOX"; } else { queryName = "BC_ACTIVE_STRUCTURED_CONTENT_BY_TYPE_AND_USER_SANDBOX"; } Query query = em.createNamedQuery(queryName); query.setParameter("contentType", type); query.setParameter("fullLocale", fullLocale); query.setParameter("languageOnlyLocale", languageOnlyLocale); if (sandBox != null) { query.setParameter("sandboxId", sandBox.getId()); } query.setHint(QueryHints.HINT_CACHEABLE, true); return query.getResultList(); } @Override public List<StructuredContent> findActiveStructuredContentByNameAndType(SandBox sandBox, StructuredContentType type, String name, Locale locale) { return findActiveStructuredContentByNameAndType(sandBox, type, name, locale, null); } @Override public List<StructuredContent> findActiveStructuredContentByNameAndType(SandBox sandBox, StructuredContentType type, String name, Locale fullLocale, Locale languageOnlyLocale) { String queryName = null; if (languageOnlyLocale == null) { languageOnlyLocale = fullLocale; } final Query query; if (sandBox == null) { query = em.createNamedQuery("BC_ACTIVE_STRUCTURED_CONTENT_BY_TYPE_AND_NAME"); } else if (SandBoxType.PRODUCTION.equals(sandBox)) { query = em.createNamedQuery("BC_ACTIVE_STRUCTURED_CONTENT_BY_TYPE_AND_NAME_AND_PRODUCTION_SANDBOX"); query.setParameter("sandbox", sandBox); } else { query = em.createNamedQuery("BC_ACTIVE_STRUCTURED_CONTENT_BY_TYPE_AND_NAME_AND_USER_SANDBOX"); query.setParameter("sandboxId", sandBox.getId()); } query.setParameter("contentType", type); query.setParameter("contentName", name); query.setParameter("fullLocale", fullLocale); query.setParameter("languageOnlyLocale", languageOnlyLocale); query.setHint(QueryHints.HINT_CACHEABLE, true); return query.getResultList(); } @Override public List<StructuredContent> findActiveStructuredContentByName(SandBox sandBox, String name, Locale locale) { return findActiveStructuredContentByName(sandBox, name, locale, null); } @Override public List<StructuredContent> findActiveStructuredContentByName(SandBox sandBox, String name, Locale fullLocale, Locale languageOnlyLocale) { String queryName = null; if (languageOnlyLocale == null) { languageOnlyLocale = fullLocale; } if (sandBox == null) { queryName = "BC_ACTIVE_STRUCTURED_CONTENT_BY_NAME"; } else if (SandBoxType.PRODUCTION.equals(sandBox)) { queryName = "BC_ACTIVE_STRUCTURED_CONTENT_BY_NAME_AND_PRODUCTION_SANDBOX"; } else { queryName = "BC_ACTIVE_STRUCTURED_CONTENT_BY_NAME_AND_USER_SANDBOX"; } Query query = em.createNamedQuery(queryName); query.setParameter("contentName", name); query.setParameter("fullLocale", fullLocale); query.setParameter("languageOnlyLocale", languageOnlyLocale); if (sandBox != null) { query.setParameter("sandbox", sandBox); } query.setHint(QueryHints.HINT_CACHEABLE, true); return query.getResultList(); } @Override public StructuredContentType findStructuredContentTypeByName(String name) { Query query = em.createNamedQuery("BC_READ_STRUCTURED_CONTENT_TYPE_BY_NAME"); query.setParameter("name",name); query.setHint(QueryHints.HINT_CACHEABLE, true); List<StructuredContentType> results = query.getResultList(); if (results.size() > 0) { return results.get(0); } else { return null; } } @Override public void detach(StructuredContent sc) { em.detach(sc); } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_dao_StructuredContentDaoImpl.java
48
public class VersionCommandProcessor extends MemcacheCommandProcessor<VersionCommand> { public VersionCommandProcessor(TextCommandServiceImpl textCommandService) { super(textCommandService); } public void handle(VersionCommand request) { textCommandService.sendResponse(request); } public void handleRejection(VersionCommand request) { handle(request); } }
0true
hazelcast_src_main_java_com_hazelcast_ascii_memcache_VersionCommandProcessor.java
153
public class ODecimalSerializer implements OBinarySerializer<BigDecimal> { public static final ODecimalSerializer INSTANCE = new ODecimalSerializer(); public static final byte ID = 18; public int getObjectSize(BigDecimal object, Object... hints) { return OIntegerSerializer.INT_SIZE + OBinaryTypeSerializer.INSTANCE.getObjectSize(object.unscaledValue().toByteArray()); } public int getObjectSize(byte[] stream, int startPosition) { final int size = OIntegerSerializer.INT_SIZE + OBinaryTypeSerializer.INSTANCE.getObjectSize(stream, startPosition + OIntegerSerializer.INT_SIZE); return size; } public void serialize(BigDecimal object, byte[] stream, int startPosition, Object... hints) { OIntegerSerializer.INSTANCE.serialize(object.scale(), stream, startPosition); startPosition += OIntegerSerializer.INT_SIZE; OBinaryTypeSerializer.INSTANCE.serialize(object.unscaledValue().toByteArray(), stream, startPosition); } public BigDecimal deserialize(byte[] stream, int startPosition) { final int scale = OIntegerSerializer.INSTANCE.deserialize(stream, startPosition); startPosition += OIntegerSerializer.INT_SIZE; final byte[] unscaledValue = OBinaryTypeSerializer.INSTANCE.deserialize(stream, startPosition); return new BigDecimal(new BigInteger(unscaledValue), scale); } public byte getId() { return ID; } public int getObjectSizeNative(byte[] stream, int startPosition) { final int size = OIntegerSerializer.INT_SIZE + OBinaryTypeSerializer.INSTANCE.getObjectSizeNative(stream, startPosition + OIntegerSerializer.INT_SIZE); return size; } public void serializeNative(BigDecimal object, byte[] stream, int startPosition, Object... hints) { OIntegerSerializer.INSTANCE.serializeNative(object.scale(), stream, startPosition); startPosition += OIntegerSerializer.INT_SIZE; OBinaryTypeSerializer.INSTANCE.serializeNative(object.unscaledValue().toByteArray(), stream, startPosition); } public BigDecimal deserializeNative(byte[] stream, int startPosition) { final int scale = OIntegerSerializer.INSTANCE.deserializeNative(stream, startPosition); startPosition += OIntegerSerializer.INT_SIZE; final byte[] unscaledValue = OBinaryTypeSerializer.INSTANCE.deserializeNative(stream, startPosition); return new BigDecimal(new BigInteger(unscaledValue), scale); } @Override public void serializeInDirectMemory(BigDecimal object, ODirectMemoryPointer pointer, long offset, Object... hints) { OIntegerSerializer.INSTANCE.serializeInDirectMemory(object.scale(), pointer, offset); offset += OIntegerSerializer.INT_SIZE; OBinaryTypeSerializer.INSTANCE.serializeInDirectMemory(object.unscaledValue().toByteArray(), pointer, offset); } @Override public BigDecimal deserializeFromDirectMemory(ODirectMemoryPointer pointer, long offset) { final int scale = pointer.getInt(offset); offset += OIntegerSerializer.INT_SIZE; final byte[] unscaledValue = OBinaryTypeSerializer.INSTANCE.deserializeFromDirectMemory(pointer, offset); return new BigDecimal(new BigInteger(unscaledValue), scale); } @Override public int getObjectSizeInDirectMemory(ODirectMemoryPointer pointer, long offset) { final int size = OIntegerSerializer.INT_SIZE + OBinaryTypeSerializer.INSTANCE.getObjectSizeInDirectMemory(pointer, offset + OIntegerSerializer.INT_SIZE); return size; } public boolean isFixedLength() { return false; } public int getFixedLength() { return 0; } @Override public BigDecimal preprocess(BigDecimal value, Object... hints) { return value; } }
0true
commons_src_main_java_com_orientechnologies_common_serialization_types_ODecimalSerializer.java
1,884
public class DynamicEntityFormInfo { public static final String FIELD_SEPARATOR = "|"; protected String criteriaName; protected String propertyName; protected String propertyValue; protected String ceilingClassName; public DynamicEntityFormInfo withCriteriaName(String criteriaName) { setCriteriaName(criteriaName); return this; } public DynamicEntityFormInfo withPropertyName(String propertyName) { setPropertyName(propertyName); return this; } public DynamicEntityFormInfo withPropertyValue(String propertyValue) { setPropertyValue(propertyValue); return this; } public DynamicEntityFormInfo withCeilingClassName(String ceilingClassName) { setCeilingClassName(ceilingClassName); return this; } public String getCriteriaName() { return criteriaName; } public void setCriteriaName(String criteriaName) { this.criteriaName = criteriaName; } public String getPropertyName() { return propertyName; } public void setPropertyName(String propertyName) { this.propertyName = propertyName; } public String getPropertyValue() { return propertyValue; } public void setPropertyValue(String propertyValue) { this.propertyValue = propertyValue; } public String getCeilingClassName() { return ceilingClassName; } public void setCeilingClassName(String ceilingClassName) { this.ceilingClassName = ceilingClassName; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_web_form_entity_DynamicEntityFormInfo.java
71
public interface TitanVertex extends TitanElement, Vertex { /* --------------------------------------------------------------- * Creation and modification methods * --------------------------------------------------------------- */ /** * Creates a new edge incident on this vertex. * <p/> * Creates and returns a new {@link TitanEdge} of the specified label with this vertex being the outgoing vertex * and the given vertex being the incoming vertex. * * @param label label of the edge to be created * @param vertex incoming vertex of the edge to be created * @return new edge */ public TitanEdge addEdge(EdgeLabel label, TitanVertex vertex); /** * Creates a new edge incident on this vertex. * <p/> * Creates and returns a new {@link TitanEdge} of the specified label with this vertex being the outgoing vertex * and the given vertex being the incoming vertex. * <br /> * Automatically creates the edge label if it does not exist and automatic creation of types is enabled. Otherwise, * this method with throw an {@link IllegalArgumentException}. * * @param label label of the edge to be created * @param vertex incoming vertex of the edge to be created * @return new edge */ public TitanEdge addEdge(String label, TitanVertex vertex); /** * Creates a new property for this vertex and given key with the specified value. * <p/> * Creates and returns a new {@link TitanProperty} for the given key on this vertex with the specified * object being the value. * * @param key key of the property to be created * @param value value of the property to be created * @return New property * @throws IllegalArgumentException if the value does not match the data type of the property key. */ public TitanProperty addProperty(PropertyKey key, Object value); /** * Creates a new property for this vertex and given key with the specified value. * <p/> * Creates and returns a new {@link TitanProperty} for the given key on this vertex with the specified * object being the value. * <br /> * Automatically creates the property key if it does not exist and automatic creation of types is enabled. Otherwise, * this method with throw an {@link IllegalArgumentException}. * * @param key key of the property to be created * @param value value of the property to be created * @return New property * @throws IllegalArgumentException if the value does not match the data type of the property key. */ public TitanProperty addProperty(String key, Object value); /* --------------------------------------------------------------- * Vertex Label * --------------------------------------------------------------- */ /** * Returns the name of the vertex label for this vertex. * * @return */ public String getLabel(); /** * Returns the vertex label of this vertex. * * @return */ public VertexLabel getVertexLabel(); /* --------------------------------------------------------------- * Incident TitanRelation Access methods * --------------------------------------------------------------- */ /** * Starts a new {@link TitanVertexQuery} for this vertex. * <p/> * Initializes and returns a new {@link TitanVertexQuery} based on this vertex. * * @return New TitanQuery for this vertex * @see TitanVertexQuery */ public TitanVertexQuery<? extends TitanVertexQuery> query(); /** * Returns an iterable over all properties incident on this vertex. * <p/> * There is no guarantee concerning the order in which the properties are returned. All properties incident * on this vertex are returned irrespective of their key. * * @return {@link Iterable} over all properties incident on this vertex */ public Iterable<TitanProperty> getProperties(); /** * Returns an iterable over all properties of the specified property key incident on this vertex. * <p/> * There is no guarantee concerning the order in which the properties are returned. All returned properties are * of the specified key. * * @param key {@link PropertyKey} of the returned properties * @return {@link Iterable} over all properties of the specified key incident on this vertex */ public Iterable<TitanProperty> getProperties(PropertyKey key); /** * Returns an iterable over all properties of the specified property key incident on this vertex. * <p/> * There is no guarantee concerning the order in which the properties are returned. All returned properties are * of the specified key. * * @param key key of the returned properties * @return {@link Iterable} over all properties of the specified key incident on this vertex */ public Iterable<TitanProperty> getProperties(String key); /** * Returns an iterable over all edges of the specified edge label in the given direction incident on this vertex. * <p/> * There is no guarantee concerning the order in which the edges are returned. All returned edges have the given * label and the direction of the edge from the perspective of this vertex matches the specified direction. * * @param labels label of the returned edges * @param d Direction of the returned edges with respect to this vertex * @return {@link Iterable} over all edges with the given label and direction incident on this vertex */ public Iterable<TitanEdge> getTitanEdges(Direction d, EdgeLabel... labels); /** * Returns an iterable over all edges of the specified edge label in the given direction incident on this vertex. * <p/> * There is no guarantee concerning the order in which the edges are returned. All returned edges have the given * label and the direction of the edge from the perspective of this vertex matches the specified direction. * * @param labels label of the returned edges * @param d Direction of the returned edges with respect to this vertex * @return {@link Iterable} over all edges with the given label and direction incident on this vertex */ public Iterable<Edge> getEdges(Direction d, String... labels); /** * Returns an iterable over all edges incident on this vertex. * <p/> * There is no guarantee concerning the order in which the edges are returned. * * @return {@link Iterable} over all edges incident on this vertex */ public Iterable<TitanEdge> getEdges(); /** * Returns an iterable over all relations incident on this vertex. * <p/> * There is no guarantee concerning the order in which the relations are returned. Note, that this * method potentially returns both {@link TitanEdge} and {@link TitanProperty}. * * @return {@link Iterable} over all properties and edges incident on this vertex. */ public Iterable<TitanRelation> getRelations(); /** * Returns the number of edges incident on this vertex. * <p/> * Returns the total number of edges irrespective of label and direction. * Note, that loop edges, i.e. edges with identical in- and outgoing vertex, are counted twice. * * @return The number of edges incident on this vertex. */ public long getEdgeCount(); /** * Returns the number of properties incident on this vertex. * <p/> * Returns the total number of properties irrespective of key. * * @return The number of properties incident on this vertex. */ public long getPropertyCount(); /** * Checks whether this vertex has at least one incident edge. * In other words, it returns getEdgeCount()>0, but might be implemented more efficiently. * * @return true, if this vertex has at least one incident edge, else false */ public boolean isConnected(); /** * Checks whether this entity has been loaded into the current transaction and modified. * * @return True, has been loaded and modified, else false. */ public boolean isModified(); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_TitanVertex.java
616
public class IndexStats implements Iterable<IndexShardStats> { private final String index; private final ShardStats shards[]; public IndexStats(String index, ShardStats[] shards) { this.index = index; this.shards = shards; } public String getIndex() { return this.index; } public ShardStats[] getShards() { return this.shards; } private Map<Integer, IndexShardStats> indexShards; public Map<Integer, IndexShardStats> getIndexShards() { if (indexShards != null) { return indexShards; } Map<Integer, List<ShardStats>> tmpIndexShards = Maps.newHashMap(); for (ShardStats shard : shards) { List<ShardStats> lst = tmpIndexShards.get(shard.getShardRouting().id()); if (lst == null) { lst = Lists.newArrayList(); tmpIndexShards.put(shard.getShardRouting().id(), lst); } lst.add(shard); } indexShards = Maps.newHashMap(); for (Map.Entry<Integer, List<ShardStats>> entry : tmpIndexShards.entrySet()) { indexShards.put(entry.getKey(), new IndexShardStats(entry.getValue().get(0).getShardRouting().shardId(), entry.getValue().toArray(new ShardStats[entry.getValue().size()]))); } return indexShards; } @Override public Iterator<IndexShardStats> iterator() { return getIndexShards().values().iterator(); } private CommonStats total = null; public CommonStats getTotal() { if (total != null) { return total; } CommonStats stats = new CommonStats(); for (ShardStats shard : shards) { stats.add(shard.getStats()); } total = stats; return stats; } private CommonStats primary = null; public CommonStats getPrimaries() { if (primary != null) { return primary; } CommonStats stats = new CommonStats(); for (ShardStats shard : shards) { if (shard.getShardRouting().primary()) { stats.add(shard.getStats()); } } primary = stats; return stats; } }
0true
src_main_java_org_elasticsearch_action_admin_indices_stats_IndexStats.java
832
public class SearchResponse extends ActionResponse implements ToXContent { private InternalSearchResponse internalResponse; private String scrollId; private int totalShards; private int successfulShards; private ShardSearchFailure[] shardFailures; private long tookInMillis; public SearchResponse() { } public SearchResponse(InternalSearchResponse internalResponse, String scrollId, int totalShards, int successfulShards, long tookInMillis, ShardSearchFailure[] shardFailures) { this.internalResponse = internalResponse; this.scrollId = scrollId; this.totalShards = totalShards; this.successfulShards = successfulShards; this.tookInMillis = tookInMillis; this.shardFailures = shardFailures; } public RestStatus status() { if (shardFailures.length == 0) { if (successfulShards == 0 && totalShards > 0) { return RestStatus.SERVICE_UNAVAILABLE; } return RestStatus.OK; } // if total failure, bubble up the status code to the response level if (successfulShards == 0 && totalShards > 0) { RestStatus status = RestStatus.OK; for (int i = 0; i < shardFailures.length; i++) { RestStatus shardStatus = shardFailures[i].status(); if (shardStatus.getStatus() >= status.getStatus()) { status = shardFailures[i].status(); } } return status; } return RestStatus.OK; } /** * The search hits. */ public SearchHits getHits() { return internalResponse.hits(); } /** * The search facets. */ public Facets getFacets() { return internalResponse.facets(); } public Aggregations getAggregations() { return internalResponse.aggregations(); } public Suggest getSuggest() { return internalResponse.suggest(); } /** * Has the search operation timed out. */ public boolean isTimedOut() { return internalResponse.timedOut(); } /** * How long the search took. */ public TimeValue getTook() { return new TimeValue(tookInMillis); } /** * How long the search took in milliseconds. */ public long getTookInMillis() { return tookInMillis; } /** * The total number of shards the search was executed on. */ public int getTotalShards() { return totalShards; } /** * The successful number of shards the search was executed on. */ public int getSuccessfulShards() { return successfulShards; } /** * The failed number of shards the search was executed on. */ public int getFailedShards() { // we don't return totalShards - successfulShards, we don't count "no shards available" as a failed shard, just don't // count it in the successful counter return shardFailures.length; } /** * The failures that occurred during the search. */ public ShardSearchFailure[] getShardFailures() { return this.shardFailures; } /** * If scrolling was enabled ({@link SearchRequest#scroll(org.elasticsearch.search.Scroll)}, the * scroll id that can be used to continue scrolling. */ public String getScrollId() { return scrollId; } static final class Fields { static final XContentBuilderString _SCROLL_ID = new XContentBuilderString("_scroll_id"); static final XContentBuilderString _SHARDS = new XContentBuilderString("_shards"); static final XContentBuilderString TOTAL = new XContentBuilderString("total"); static final XContentBuilderString SUCCESSFUL = new XContentBuilderString("successful"); static final XContentBuilderString FAILED = new XContentBuilderString("failed"); static final XContentBuilderString FAILURES = new XContentBuilderString("failures"); static final XContentBuilderString STATUS = new XContentBuilderString("status"); static final XContentBuilderString INDEX = new XContentBuilderString("index"); static final XContentBuilderString SHARD = new XContentBuilderString("shard"); static final XContentBuilderString REASON = new XContentBuilderString("reason"); static final XContentBuilderString TOOK = new XContentBuilderString("took"); static final XContentBuilderString TIMED_OUT = new XContentBuilderString("timed_out"); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { if (scrollId != null) { builder.field(Fields._SCROLL_ID, scrollId); } builder.field(Fields.TOOK, tookInMillis); builder.field(Fields.TIMED_OUT, isTimedOut()); builder.startObject(Fields._SHARDS); builder.field(Fields.TOTAL, getTotalShards()); builder.field(Fields.SUCCESSFUL, getSuccessfulShards()); builder.field(Fields.FAILED, getFailedShards()); if (shardFailures.length > 0) { builder.startArray(Fields.FAILURES); for (ShardSearchFailure shardFailure : shardFailures) { builder.startObject(); if (shardFailure.shard() != null) { builder.field(Fields.INDEX, shardFailure.shard().index()); builder.field(Fields.SHARD, shardFailure.shard().shardId()); } builder.field(Fields.STATUS, shardFailure.status().getStatus()); builder.field(Fields.REASON, shardFailure.reason()); builder.endObject(); } builder.endArray(); } builder.endObject(); internalResponse.toXContent(builder, params); return builder; } public static SearchResponse readSearchResponse(StreamInput in) throws IOException { SearchResponse response = new SearchResponse(); response.readFrom(in); return response; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); internalResponse = readInternalSearchResponse(in); totalShards = in.readVInt(); successfulShards = in.readVInt(); int size = in.readVInt(); if (size == 0) { shardFailures = ShardSearchFailure.EMPTY_ARRAY; } else { shardFailures = new ShardSearchFailure[size]; for (int i = 0; i < shardFailures.length; i++) { shardFailures[i] = readShardSearchFailure(in); } } scrollId = in.readOptionalString(); tookInMillis = in.readVLong(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); internalResponse.writeTo(out); out.writeVInt(totalShards); out.writeVInt(successfulShards); out.writeVInt(shardFailures.length); for (ShardSearchFailure shardSearchFailure : shardFailures) { shardSearchFailure.writeTo(out); } out.writeOptionalString(scrollId); out.writeVLong(tookInMillis); } @Override public String toString() { try { XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint(); builder.startObject(); toXContent(builder, EMPTY_PARAMS); builder.endObject(); return builder.string(); } catch (IOException e) { return "{ \"error\" : \"" + e.getMessage() + "\"}"; } } }
1no label
src_main_java_org_elasticsearch_action_search_SearchResponse.java