Unnamed: 0
int64
0
6.45k
func
stringlengths
29
253k
target
class label
2 classes
project
stringlengths
36
167
178
private static class FailingFunction implements IFunction<Long, Long> { @Override public Long apply(Long input) { throw new WoohaaException(); } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_atomiclong_ClientAtomicLongTest.java
429
public final class ClientQueueProxy<E> extends ClientProxy implements IQueue<E> { private final String name; public ClientQueueProxy(String instanceName, String serviceName, String name) { super(instanceName, serviceName, name); this.name = name; } public String addItemListener(final ItemListener<E> listener, final boolean includeValue) { final AddListenerRequest request = new AddListenerRequest(name, includeValue); EventHandler<PortableItemEvent> eventHandler = new EventHandler<PortableItemEvent>() { public void handle(PortableItemEvent portableItemEvent) { E item = includeValue ? (E) getContext().getSerializationService().toObject(portableItemEvent.getItem()) : null; Member member = getContext().getClusterService().getMember(portableItemEvent.getUuid()); ItemEvent<E> itemEvent = new ItemEvent<E>(name, portableItemEvent.getEventType(), item, member); if (portableItemEvent.getEventType() == ItemEventType.ADDED) { listener.itemAdded(itemEvent); } else { listener.itemRemoved(itemEvent); } } @Override public void onListenerRegister() { } }; return listen(request, getPartitionKey(), eventHandler); } public boolean removeItemListener(String registrationId) { final RemoveListenerRequest request = new RemoveListenerRequest(name, registrationId); return stopListening(request, registrationId); } public LocalQueueStats getLocalQueueStats() { throw new UnsupportedOperationException("Locality is ambiguous for client!!!"); } public boolean add(E e) { if (offer(e)) { return true; } throw new IllegalStateException("Queue is full!"); } /** * It is advised to use this method in a try-catch block to take the offer operation * full lifecycle control, in a "lost node" scenario you can not be sure * offer is succeeded or not so you may want to retry. * * @param e the element to add * @return <tt>true</tt> if the element was added to this queue. * <tt>false</tt> if there is not enough capacity to insert the element. * @throws HazelcastException if client loses the connected node. */ public boolean offer(E e) { try { return offer(e, 0, TimeUnit.SECONDS); } catch (InterruptedException ex) { return false; } } public void put(E e) throws InterruptedException { offer(e, -1, TimeUnit.MILLISECONDS); } public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { Data data = getContext().getSerializationService().toData(e); OfferRequest request = new OfferRequest(name, unit.toMillis(timeout), data); final Boolean result = invokeInterruptibly(request); return result; } public E take() throws InterruptedException { return poll(-1, TimeUnit.MILLISECONDS); } public E poll(long timeout, TimeUnit unit) throws InterruptedException { PollRequest request = new PollRequest(name, unit.toMillis(timeout)); return invokeInterruptibly(request); } public int remainingCapacity() { RemainingCapacityRequest request = new RemainingCapacityRequest(name); Integer result = invoke(request); return result; } public boolean remove(Object o) { Data data = getContext().getSerializationService().toData(o); RemoveRequest request = new RemoveRequest(name, data); Boolean result = invoke(request); return result; } public boolean contains(Object o) { final Collection<Data> list = new ArrayList<Data>(1); list.add(getContext().getSerializationService().toData(o)); ContainsRequest request = new ContainsRequest(name, list); Boolean result = invoke(request); return result; } public int drainTo(Collection<? super E> objects) { return drainTo(objects, -1); } public int drainTo(Collection<? super E> c, int maxElements) { DrainRequest request = new DrainRequest(name, maxElements); PortableCollection result = invoke(request); Collection<Data> coll = result.getCollection(); for (Data data : coll) { E e = (E) getContext().getSerializationService().toObject(data); c.add(e); } return coll.size(); } public E remove() { final E res = poll(); if (res == null) { throw new NoSuchElementException("Queue is empty!"); } return res; } public E poll() { try { return poll(0, TimeUnit.SECONDS); } catch (InterruptedException e) { return null; } } public E element() { final E res = peek(); if (res == null) { throw new NoSuchElementException("Queue is empty!"); } return res; } public E peek() { PeekRequest request = new PeekRequest(name); return invoke(request); } public int size() { SizeRequest request = new SizeRequest(name); Integer result = invoke(request); return result; } public boolean isEmpty() { return size() == 0; } public Iterator<E> iterator() { IteratorRequest request = new IteratorRequest(name); PortableCollection result = invoke(request); Collection<Data> coll = result.getCollection(); return new QueueIterator<E>(coll.iterator(), getContext().getSerializationService(), false); } public Object[] toArray() { IteratorRequest request = new IteratorRequest(name); PortableCollection result = invoke(request); Collection<Data> coll = result.getCollection(); int i = 0; Object[] array = new Object[coll.size()]; for (Data data : coll) { array[i++] = getContext().getSerializationService().toObject(data); } return array; } public <T> T[] toArray(T[] ts) { IteratorRequest request = new IteratorRequest(name); PortableCollection result = invoke(request); Collection<Data> coll = result.getCollection(); int size = coll.size(); if (ts.length < size) { ts = (T[]) java.lang.reflect.Array.newInstance(ts.getClass().getComponentType(), size); } int i = 0; for (Data data : coll) { ts[i++] = (T) getContext().getSerializationService().toObject(data); } return ts; } public boolean containsAll(Collection<?> c) { List<Data> list = getDataList(c); ContainsRequest request = new ContainsRequest(name, list); Boolean result = invoke(request); return result; } public boolean addAll(Collection<? extends E> c) { AddAllRequest request = new AddAllRequest(name, getDataList(c)); Boolean result = invoke(request); return result; } public boolean removeAll(Collection<?> c) { CompareAndRemoveRequest request = new CompareAndRemoveRequest(name, getDataList(c), false); Boolean result = invoke(request); return result; } public boolean retainAll(Collection<?> c) { CompareAndRemoveRequest request = new CompareAndRemoveRequest(name, getDataList(c), true); Boolean result = invoke(request); return result; } public void clear() { ClearRequest request = new ClearRequest(name); invoke(request); } protected void onDestroy() { } protected <T> T invoke(ClientRequest req) { return super.invoke(req, getPartitionKey()); } protected <T> T invokeInterruptibly(ClientRequest req) throws InterruptedException { return super.invokeInterruptibly(req, getPartitionKey()); } private List<Data> getDataList(Collection<?> objects) { List<Data> dataList = new ArrayList<Data>(objects.size()); for (Object o : objects) { dataList.add(getContext().getSerializationService().toData(o)); } return dataList; } @Override public String toString() { return "IQueue{" + "name='" + getName() + '\'' + '}'; } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientQueueProxy.java
2,805
public static class TokenizersBindings { private final Map<String, Class<? extends TokenizerFactory>> tokenizers = Maps.newHashMap(); public TokenizersBindings() { } public void processTokenizer(String name, Class<? extends TokenizerFactory> tokenizerFactory) { tokenizers.put(name, tokenizerFactory); } }
0true
src_main_java_org_elasticsearch_index_analysis_AnalysisModule.java
202
public class ExtendedCommonTermsQuery extends CommonTermsQuery { public ExtendedCommonTermsQuery(Occur highFreqOccur, Occur lowFreqOccur, float maxTermFrequency, boolean disableCoord) { super(highFreqOccur, lowFreqOccur, maxTermFrequency, disableCoord); } public ExtendedCommonTermsQuery(Occur highFreqOccur, Occur lowFreqOccur, float maxTermFrequency) { super(highFreqOccur, lowFreqOccur, maxTermFrequency); } private String lowFreqMinNumShouldMatchSpec; private String highFreqMinNumShouldMatchSpec; @Override protected int calcLowFreqMinimumNumberShouldMatch(int numOptional) { return calcMinimumNumberShouldMatch(lowFreqMinNumShouldMatchSpec, numOptional); } protected int calcMinimumNumberShouldMatch(String spec, int numOptional) { if (spec == null) { return 0; } return Queries.calculateMinShouldMatch(numOptional, spec); } @Override protected int calcHighFreqMinimumNumberShouldMatch(int numOptional) { return calcMinimumNumberShouldMatch(highFreqMinNumShouldMatchSpec, numOptional); } public void setHighFreqMinimumNumberShouldMatch(String spec) { this.highFreqMinNumShouldMatchSpec = spec; } public String getHighFreqMinimumNumberShouldMatchSpec() { return highFreqMinNumShouldMatchSpec; } public void setLowFreqMinimumNumberShouldMatch(String spec) { this.lowFreqMinNumShouldMatchSpec = spec; } public String getLowFreqMinimumNumberShouldMatchSpec() { return lowFreqMinNumShouldMatchSpec; } }
1no label
src_main_java_org_apache_lucene_queries_ExtendedCommonTermsQuery.java
398
add(store1, "restore-doc1", new HashMap<String, Object>() {{ put(NAME, "first"); put(TIME, 1L); put(WEIGHT, 10.2d); }}, true);
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexProviderTest.java
460
public class TransportPendingClusterTasksAction extends TransportMasterNodeReadOperationAction<PendingClusterTasksRequest, PendingClusterTasksResponse> { private final ClusterService clusterService; @Inject public TransportPendingClusterTasksAction(Settings settings, TransportService transportService, ClusterService clusterService, ThreadPool threadPool) { super(settings, transportService, clusterService, threadPool); this.clusterService = clusterService; } @Override protected String transportAction() { return PendingClusterTasksAction.NAME; } @Override protected String executor() { // very lightweight operation in memory, no need to fork to a thread return ThreadPool.Names.SAME; } @Override protected PendingClusterTasksRequest newRequest() { return new PendingClusterTasksRequest(); } @Override protected PendingClusterTasksResponse newResponse() { return new PendingClusterTasksResponse(); } @Override protected void masterOperation(PendingClusterTasksRequest request, ClusterState state, ActionListener<PendingClusterTasksResponse> listener) throws ElasticsearchException { listener.onResponse(new PendingClusterTasksResponse(clusterService.pendingTasks())); } }
1no label
src_main_java_org_elasticsearch_action_admin_cluster_tasks_TransportPendingClusterTasksAction.java
3,125
class ApplySettings implements IndexSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { long gcDeletesInMillis = settings.getAsTime(INDEX_GC_DELETES, TimeValue.timeValueMillis(InternalEngine.this.gcDeletesInMillis)).millis(); if (gcDeletesInMillis != InternalEngine.this.gcDeletesInMillis) { logger.info("updating index.gc_deletes from [{}] to [{}]", TimeValue.timeValueMillis(InternalEngine.this.gcDeletesInMillis), TimeValue.timeValueMillis(gcDeletesInMillis)); InternalEngine.this.gcDeletesInMillis = gcDeletesInMillis; } final boolean compoundOnFlush = settings.getAsBoolean(INDEX_COMPOUND_ON_FLUSH, InternalEngine.this.compoundOnFlush); if (compoundOnFlush != InternalEngine.this.compoundOnFlush) { logger.info("updating {} from [{}] to [{}]", InternalEngine.INDEX_COMPOUND_ON_FLUSH, InternalEngine.this.compoundOnFlush, compoundOnFlush); InternalEngine.this.compoundOnFlush = compoundOnFlush; indexWriter.getConfig().setUseCompoundFile(compoundOnFlush); } int indexConcurrency = settings.getAsInt(INDEX_INDEX_CONCURRENCY, InternalEngine.this.indexConcurrency); boolean failOnMergeFailure = settings.getAsBoolean(INDEX_FAIL_ON_MERGE_FAILURE, InternalEngine.this.failOnMergeFailure); String codecName = settings.get(INDEX_CODEC, InternalEngine.this.codecName); final boolean codecBloomLoad = settings.getAsBoolean(CodecService.INDEX_CODEC_BLOOM_LOAD, codecService.isLoadBloomFilter()); boolean requiresFlushing = false; if (indexConcurrency != InternalEngine.this.indexConcurrency || !codecName.equals(InternalEngine.this.codecName) || failOnMergeFailure != InternalEngine.this.failOnMergeFailure || codecBloomLoad != codecService.isLoadBloomFilter()) { rwl.readLock().lock(); try { if (indexConcurrency != InternalEngine.this.indexConcurrency) { logger.info("updating index.index_concurrency from [{}] to [{}]", InternalEngine.this.indexConcurrency, indexConcurrency); InternalEngine.this.indexConcurrency = indexConcurrency; // we have to flush in this case, since it only applies on a new index writer requiresFlushing = true; } if (!codecName.equals(InternalEngine.this.codecName)) { logger.info("updating index.codec from [{}] to [{}]", InternalEngine.this.codecName, codecName); InternalEngine.this.codecName = codecName; // we want to flush in this case, so the new codec will be reflected right away... requiresFlushing = true; } if (failOnMergeFailure != InternalEngine.this.failOnMergeFailure) { logger.info("updating {} from [{}] to [{}]", InternalEngine.INDEX_FAIL_ON_MERGE_FAILURE, InternalEngine.this.failOnMergeFailure, failOnMergeFailure); InternalEngine.this.failOnMergeFailure = failOnMergeFailure; } if (codecBloomLoad != codecService.isLoadBloomFilter()) { logger.info("updating {} from [{}] to [{}]", CodecService.INDEX_CODEC_BLOOM_LOAD, codecService.isLoadBloomFilter(), codecBloomLoad); codecService.setLoadBloomFilter(codecBloomLoad); // we need to flush in this case, to load/unload the bloom filters requiresFlushing = true; } } finally { rwl.readLock().unlock(); } if (requiresFlushing) { flush(new Flush().type(Flush.Type.NEW_WRITER)); } } } }
1no label
src_main_java_org_elasticsearch_index_engine_internal_InternalEngine.java
217
{ @Override protected void intercept( List<LogEntry> entries ) { for ( LogEntry entry : entries ) { if ( entry instanceof LogEntry.Command ) { LogEntry.Command commandEntry = (LogEntry.Command) entry; if ( commandEntry.getXaCommand() instanceof Command ) { ( (Command) commandEntry.getXaCommand() ).accept( interceptor ); } } else if ( entry instanceof LogEntry.Start ) { interceptor.setStartEntry( (LogEntry.Start) entry ); } else if ( entry instanceof LogEntry.Commit ) { interceptor.setCommitEntry( (LogEntry.Commit) entry ); } } interceptor.complete(); } };
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_InterceptingXaLogicalLog.java
1,630
public static final Validator INTEGER_GTE_2 = new Validator() { @Override public String validate(String setting, String value) { try { if (Integer.parseInt(value) < 2) { return "the value of the setting " + setting + " must be >= 2"; } } catch (NumberFormatException ex) { return "cannot parse value [" + value + "] as an integer"; } return null; } };
0true
src_main_java_org_elasticsearch_cluster_settings_Validator.java
134
@Test public class UnsafeConverterTest extends AbstractConverterTest { @BeforeClass public void beforeClass() { converter = new OUnsafeBinaryConverter(); } @Override public void testPutIntBigEndian() { super.testPutIntBigEndian(); } @Override public void testPutIntLittleEndian() { super.testPutIntLittleEndian(); } @Override public void testPutLongBigEndian() { super.testPutLongBigEndian(); } @Override public void testPutLongLittleEndian() { super.testPutLongLittleEndian(); } @Override public void testPutShortBigEndian() { super.testPutShortBigEndian(); } @Override public void testPutShortLittleEndian() { super.testPutShortLittleEndian(); } @Override public void testPutCharBigEndian() { super.testPutCharBigEndian(); } @Override public void testPutCharLittleEndian() { super.testPutCharLittleEndian(); } }
0true
commons_src_test_java_com_orientechnologies_common_serialization_UnsafeConverterTest.java
1,530
public enum PersistenceXml { TAG_PERSISTENCE("persistence"), TAG_PERSISTENCE_UNIT("persistence-unit"), TAG_PROPERTIES("properties"), TAG_PROPERTY("property"), TAG_NON_JTA_DATA_SOURCE( "non-jta-data-source"), TAG_JTA_DATA_SOURCE("jta-data-source"), TAG_CLASS("class"), TAG_MAPPING_FILE("mapping-file"), TAG_JAR_FILE( "jar-file"), TAG_EXCLUDE_UNLISTED_CLASSES("exclude-unlisted-classes"), TAG_VALIDATION_MODE("validation-mode"), TAG_SHARED_CACHE_MODE( "shared-cache-mode"), TAG_PROVIDER("provider"), TAG_UNKNOWN$("unknown$"), ATTR_UNIT_NAME("name"), ATTR_TRANSACTION_TYPE( "transaction-type"), ATTR_SCHEMA_VERSION("version"); private final String name; PersistenceXml(String name) { this.name = name; } /** * Case ignorance, null safe method * * @param aName * @return true if tag equals to enum item */ public boolean equals(String aName) { return name.equalsIgnoreCase(aName); } /** * Try to parse tag to enum item * * @param aName * @return TAG_UNKNOWN$ if failed to parse */ public static PersistenceXml parse(String aName) { try { return valueOf("TAG_" + aName.replace('-', '_').toUpperCase()); } catch (IllegalArgumentException e) { return TAG_UNKNOWN$; } } @Override public String toString() { return name; } }
0true
object_src_main_java_com_orientechnologies_orient_object_jpa_parsing_PersistenceXml.java
494
public class CloseIndexAction extends IndicesAction<CloseIndexRequest, CloseIndexResponse, CloseIndexRequestBuilder> { public static final CloseIndexAction INSTANCE = new CloseIndexAction(); public static final String NAME = "indices/close"; private CloseIndexAction() { super(NAME); } @Override public CloseIndexResponse newResponse() { return new CloseIndexResponse(); } @Override public CloseIndexRequestBuilder newRequestBuilder(IndicesAdminClient client) { return new CloseIndexRequestBuilder(client); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_close_CloseIndexAction.java
1,515
@Component("blGoogleAnalyticsProcessor") public class GoogleAnalyticsProcessor extends AbstractModelVariableModifierProcessor { @Resource(name = "blOrderService") protected OrderService orderService; @Value("${googleAnalytics.webPropertyId}") protected String webPropertyId; @Value("${googleAnalytics.affiliation}") protected String affiliation = ""; /** * This will force the domain to 127.0.0.1 which is useful to determine if the Google Analytics tag is sending * a request to Google */ protected boolean testLocal = false; /** * Sets the name of this processor to be used in Thymeleaf template */ public GoogleAnalyticsProcessor() { super("googleanalytics"); } @Override public int getPrecedence() { return 100000; } @Override protected void modifyModelAttributes(Arguments arguments, Element element) { String orderNumber = element.getAttributeValue("orderNumber"); Order order = null; if (orderNumber != null) { order = orderService.findOrderByOrderNumber(orderNumber); } addToModel(arguments, "analytics", analytics(webPropertyId, order)); } /** * Documentation for the recommended asynchronous GA tag is at: * http://code.google.com/apis/analytics/docs/tracking/gaTrackingEcommerce.html * * @param webPropertyId * - Google Analytics ID * @param order * - optionally track the order submission. This should be * included on the page after the order has been sucessfully * submitted. If null, this will just track the current page * @return the relevant Javascript to render on the page */ protected String analytics(String webPropertyId, Order order) { StringBuffer sb = new StringBuffer(); sb.append("var _gaq = _gaq || [];\n"); sb.append("_gaq.push(['_setAccount', '" + webPropertyId + "']);"); sb.append("_gaq.push(['_trackPageview']);"); if (testLocal) { sb.append("_gaq.push(['_setDomainName', '127.0.0.1']);"); } if (order != null) { Address paymentAddress = getBillingAddress(order); if (paymentAddress != null) { sb.append("_gaq.push(['_addTrans','" + order.getOrderNumber() + "'"); sb.append(",'" + affiliation + "'"); sb.append(",'" + order.getTotal() + "'"); sb.append(",'" + order.getTotalTax() + "'"); sb.append(",'" + order.getTotalShipping() + "'"); sb.append(",'" + paymentAddress.getCity() + "'"); if (paymentAddress.getState() != null) { sb.append(",'" + paymentAddress.getState().getName() + "'"); } if (paymentAddress.getCountry() != null) { sb.append(",'" + paymentAddress.getCountry().getName() + "'"); } sb.append("]);"); } for (FulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) { for (FulfillmentGroupItem fulfillmentGroupItem : fulfillmentGroup.getFulfillmentGroupItems()) { OrderItem orderItem = fulfillmentGroupItem.getOrderItem(); Sku sku = null; if (orderItem instanceof DiscreteOrderItem) { sku = ((DiscreteOrderItem)orderItem).getSku(); } else if (orderItem instanceof BundleOrderItem) { sku = ((BundleOrderItem)orderItem).getSku(); } sb.append("_gaq.push(['_addItem','" + order.getOrderNumber() + "'"); sb.append(",'" + sku.getId() + "'"); sb.append(",'" + sku.getName() + "'"); sb.append(",'" + getVariation(orderItem) + "'"); sb.append(",'" + orderItem.getPrice() + "'"); sb.append(",'" + orderItem.getQuantity() + "'"); sb.append("]);"); } } sb.append("_gaq.push(['_trackTrans']);"); } sb.append(" (function() {" + "var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;" + "ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';" + "var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);" + "})();"); return sb.toString(); } /** * Returns the product option values separated by a space if they are * relevant for the item, or the product category if no options are available * * @return */ protected String getVariation(OrderItem item) { if (MapUtils.isEmpty(item.getOrderItemAttributes())) { return item.getCategory() == null ? "" : item.getCategory().getName(); } //use product options instead String result = ""; for (Map.Entry<String, OrderItemAttribute> entry : item.getOrderItemAttributes().entrySet()) { result += entry.getValue().getValue() + " "; } //the result has a space at the end, ensure that is stripped out return result.substring(0, result.length() - 1); } protected Address getBillingAddress(Order order) { PaymentInfo paymentInfo = null; if (order.getPaymentInfos().size() > 0) { paymentInfo = order.getPaymentInfos().get(0); } Address address = null; if (paymentInfo == null || paymentInfo.getAddress() == null) { // in this case, no payment info object on the order or no billing // information received due to external payment gateway address = order.getFulfillmentGroups().get(0).getAddress(); } else { // then the address must exist on the payment info address = paymentInfo.getAddress(); } return address; } protected void setTestLocal(boolean testLocal) { this.testLocal = testLocal; } public boolean getTestLocal() { return testLocal; } public String getAffiliation() { return affiliation; } public void setAffiliation(String affiliation) { this.affiliation = affiliation; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_processor_GoogleAnalyticsProcessor.java
175
public class DirectLogBuffer implements LogBuffer { private final StoreChannel fileChannel; private final ByteBuffer buffer; public DirectLogBuffer( StoreChannel fileChannel, ByteBuffer buffer ) { if ( fileChannel == null || buffer == null ) { throw new IllegalArgumentException( "Null argument" ); } if ( buffer.capacity() < 8 ) { throw new IllegalArgumentException( "Capacity less then 8" ); } this.fileChannel = fileChannel; this.buffer = buffer; } public LogBuffer put( byte b ) throws IOException { buffer.clear(); buffer.put( b ); return flipAndWrite(); } public LogBuffer putShort( short s ) throws IOException { buffer.clear(); buffer.putShort( s ); return flipAndWrite(); } public LogBuffer putInt( int i ) throws IOException { buffer.clear(); buffer.putInt( i ); return flipAndWrite(); } public LogBuffer putLong( long l ) throws IOException { buffer.clear(); buffer.putLong( l ); return flipAndWrite(); } public LogBuffer putFloat( float f ) throws IOException { buffer.clear(); buffer.putFloat( f ); return flipAndWrite(); } public LogBuffer putDouble( double d ) throws IOException { buffer.clear(); buffer.putDouble( d ); return flipAndWrite(); } private LogBuffer flipAndWrite() throws IOException { buffer.flip(); fileChannel.write( buffer ); return this; } public LogBuffer put( byte[] bytes ) throws IOException { fileChannel.write( ByteBuffer.wrap( bytes ) ); return this; } public LogBuffer put( char[] chars ) throws IOException { int position = 0; do { buffer.clear(); int leftToWrite = chars.length - position; if ( leftToWrite * 2 < buffer.capacity() ) { buffer.asCharBuffer().put( chars, position, leftToWrite ); buffer.limit( leftToWrite * 2); fileChannel.write( buffer ); position += leftToWrite; } else { int length = buffer.capacity() / 2; buffer.asCharBuffer().put( chars, position, length ); buffer.limit( length * 2 ); fileChannel.write( buffer ); position += length; } } while ( position < chars.length ); return this; } @Override public void writeOut() throws IOException { // Nothing to do, since the data is always written in the put... methods. } public void force() throws IOException { fileChannel.force( false ); } public long getFileChannelPosition() throws IOException { return fileChannel.position(); } public StoreChannel getFileChannel() { return fileChannel; } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_DirectLogBuffer.java
1,663
EntryListener<Object, Object> listener = new EntryListener<Object, Object>() { public void entryAdded(EntryEvent<Object, Object> event) { addedKey[0] = event.getKey(); addedValue[0] = event.getValue(); } public void entryRemoved(EntryEvent<Object, Object> event) { removedKey[0] = event.getKey(); removedValue[0] = event.getOldValue(); } public void entryUpdated(EntryEvent<Object, Object> event) { updatedKey[0] = event.getKey(); oldValue[0] = event.getOldValue(); newValue[0] = event.getValue(); } public void entryEvicted(EntryEvent<Object, Object> event) { } };
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
344
public class NodesShutdownRequestBuilder extends MasterNodeOperationRequestBuilder<NodesShutdownRequest, NodesShutdownResponse, NodesShutdownRequestBuilder> { public NodesShutdownRequestBuilder(ClusterAdminClient clusterClient) { super((InternalClusterAdminClient) clusterClient, new NodesShutdownRequest()); } /** * The nodes ids to restart. */ public NodesShutdownRequestBuilder setNodesIds(String... nodesIds) { request.nodesIds(nodesIds); return this; } /** * The delay for the restart to occur. Defaults to <tt>1s</tt>. */ public NodesShutdownRequestBuilder setDelay(TimeValue delay) { request.delay(delay); return this; } /** * The delay for the restart to occur. Defaults to <tt>1s</tt>. */ public NodesShutdownRequestBuilder setDelay(String delay) { request.delay(delay); return this; } /** * Should the JVM be exited as well or not. Defaults to <tt>true</tt>. */ public NodesShutdownRequestBuilder setExit(boolean exit) { request.exit(exit); return this; } @Override protected void doExecute(ActionListener<NodesShutdownResponse> listener) { ((ClusterAdminClient) client).nodesShutdown(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_shutdown_NodesShutdownRequestBuilder.java
830
public class SearchRequest extends ActionRequest<SearchRequest> { private static final XContentType contentType = Requests.CONTENT_TYPE; private SearchType searchType = SearchType.DEFAULT; private String[] indices; @Nullable private String routing; @Nullable private String preference; private BytesReference source; private boolean sourceUnsafe; private BytesReference extraSource; private boolean extraSourceUnsafe; private Scroll scroll; private String[] types = Strings.EMPTY_ARRAY; private SearchOperationThreading operationThreading = SearchOperationThreading.THREAD_PER_SHARD; private IndicesOptions indicesOptions = IndicesOptions.strict(); public SearchRequest() { } /** * Constructs a new search request against the indices. No indices provided here means that search * will run against all indices. */ public SearchRequest(String... indices) { indices(indices); } /** * Constructs a new search request against the provided indices with the given search source. */ public SearchRequest(String[] indices, byte[] source) { indices(indices); this.source = new BytesArray(source); } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = null; // no need to check, we resolve to match all query // if (source == null && extraSource == null) { // validationException = addValidationError("search source is missing", validationException); // } return validationException; } public void beforeStart() { // we always copy over if needed, the reason is that a request might fail while being search remotely // and then we need to keep the buffer around if (source != null && sourceUnsafe) { source = source.copyBytesArray(); sourceUnsafe = false; } if (extraSource != null && extraSourceUnsafe) { extraSource = extraSource.copyBytesArray(); extraSourceUnsafe = false; } } /** * Internal. */ public void beforeLocalFork() { } /** * Sets the indices the search will be executed on. */ public SearchRequest indices(String... indices) { if (indices == null) { throw new ElasticsearchIllegalArgumentException("indices must not be null"); } else { for (int i = 0; i < indices.length; i++) { if (indices[i] == null) { throw new ElasticsearchIllegalArgumentException("indices[" + i +"] must not be null"); } } } this.indices = indices; return this; } /** * Controls the the search operation threading model. */ public SearchOperationThreading operationThreading() { return this.operationThreading; } /** * Controls the the search operation threading model. */ public SearchRequest operationThreading(SearchOperationThreading operationThreading) { this.operationThreading = operationThreading; return this; } /** * Sets the string representation of the operation threading model. Can be one of * "no_threads", "single_thread" and "thread_per_shard". */ public SearchRequest operationThreading(String operationThreading) { return operationThreading(SearchOperationThreading.fromString(operationThreading, this.operationThreading)); } public IndicesOptions indicesOptions() { return indicesOptions; } public SearchRequest indicesOptions(IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; return this; } /** * The document types to execute the search against. Defaults to be executed against * all types. */ public String[] types() { return types; } /** * The document types to execute the search against. Defaults to be executed against * all types. */ public SearchRequest types(String... types) { this.types = types; return this; } /** * A comma separated list of routing values to control the shards the search will be executed on. */ public String routing() { return this.routing; } /** * A comma separated list of routing values to control the shards the search will be executed on. */ public SearchRequest routing(String routing) { this.routing = routing; return this; } /** * The routing values to control the shards that the search will be executed on. */ public SearchRequest routing(String... routings) { this.routing = Strings.arrayToCommaDelimitedString(routings); return this; } /** * Sets the preference to execute the search. Defaults to randomize across shards. Can be set to * <tt>_local</tt> to prefer local shards, <tt>_primary</tt> to execute only on primary shards, or * a custom value, which guarantees that the same order will be used across different requests. */ public SearchRequest preference(String preference) { this.preference = preference; return this; } public String preference() { return this.preference; } /** * The search type to execute, defaults to {@link SearchType#DEFAULT}. */ public SearchRequest searchType(SearchType searchType) { this.searchType = searchType; return this; } /** * The a string representation search type to execute, defaults to {@link SearchType#DEFAULT}. Can be * one of "dfs_query_then_fetch"/"dfsQueryThenFetch", "dfs_query_and_fetch"/"dfsQueryAndFetch", * "query_then_fetch"/"queryThenFetch", and "query_and_fetch"/"queryAndFetch". */ public SearchRequest searchType(String searchType) throws ElasticsearchIllegalArgumentException { return searchType(SearchType.fromString(searchType)); } /** * The source of the search request. */ public SearchRequest source(SearchSourceBuilder sourceBuilder) { this.source = sourceBuilder.buildAsBytes(contentType); this.sourceUnsafe = false; return this; } /** * The source of the search request. Consider using either {@link #source(byte[])} or * {@link #source(org.elasticsearch.search.builder.SearchSourceBuilder)}. */ public SearchRequest source(String source) { this.source = new BytesArray(source); this.sourceUnsafe = false; return this; } /** * The source of the search request in the form of a map. */ public SearchRequest source(Map source) { try { XContentBuilder builder = XContentFactory.contentBuilder(contentType); builder.map(source); return source(builder); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); } } public SearchRequest source(XContentBuilder builder) { this.source = builder.bytes(); this.sourceUnsafe = false; return this; } /** * The search source to execute. */ public SearchRequest source(byte[] source) { return source(source, 0, source.length, false); } /** * The search source to execute. */ public SearchRequest source(byte[] source, int offset, int length) { return source(source, offset, length, false); } /** * The search source to execute. */ public SearchRequest source(byte[] source, int offset, int length, boolean unsafe) { return source(new BytesArray(source, offset, length), unsafe); } /** * The search source to execute. */ public SearchRequest source(BytesReference source, boolean unsafe) { this.source = source; this.sourceUnsafe = unsafe; return this; } /** * The search source to execute. */ public BytesReference source() { return source; } /** * Allows to provide additional source that will be used as well. */ public SearchRequest extraSource(SearchSourceBuilder sourceBuilder) { if (sourceBuilder == null) { extraSource = null; return this; } this.extraSource = sourceBuilder.buildAsBytes(contentType); this.extraSourceUnsafe = false; return this; } public SearchRequest extraSource(Map extraSource) { try { XContentBuilder builder = XContentFactory.contentBuilder(contentType); builder.map(extraSource); return extraSource(builder); } catch (IOException e) { throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e); } } public SearchRequest extraSource(XContentBuilder builder) { this.extraSource = builder.bytes(); this.extraSourceUnsafe = false; return this; } /** * Allows to provide additional source that will use used as well. */ public SearchRequest extraSource(String source) { this.extraSource = new BytesArray(source); this.extraSourceUnsafe = false; return this; } /** * Allows to provide additional source that will be used as well. */ public SearchRequest extraSource(byte[] source) { return extraSource(source, 0, source.length, false); } /** * Allows to provide additional source that will be used as well. */ public SearchRequest extraSource(byte[] source, int offset, int length) { return extraSource(source, offset, length, false); } /** * Allows to provide additional source that will be used as well. */ public SearchRequest extraSource(byte[] source, int offset, int length, boolean unsafe) { return extraSource(new BytesArray(source, offset, length), unsafe); } /** * Allows to provide additional source that will be used as well. */ public SearchRequest extraSource(BytesReference source, boolean unsafe) { this.extraSource = source; this.extraSourceUnsafe = unsafe; return this; } /** * Additional search source to execute. */ public BytesReference extraSource() { return this.extraSource; } /** * The tye of search to execute. */ public SearchType searchType() { return searchType; } /** * The indices */ public String[] indices() { return indices; } /** * If set, will enable scrolling of the search request. */ public Scroll scroll() { return scroll; } /** * If set, will enable scrolling of the search request. */ public SearchRequest scroll(Scroll scroll) { this.scroll = scroll; return this; } /** * If set, will enable scrolling of the search request for the specified timeout. */ public SearchRequest scroll(TimeValue keepAlive) { return scroll(new Scroll(keepAlive)); } /** * If set, will enable scrolling of the search request for the specified timeout. */ public SearchRequest scroll(String keepAlive) { return scroll(new Scroll(TimeValue.parseTimeValue(keepAlive, null))); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); operationThreading = SearchOperationThreading.fromId(in.readByte()); searchType = SearchType.fromId(in.readByte()); indices = new String[in.readVInt()]; for (int i = 0; i < indices.length; i++) { indices[i] = in.readString(); } routing = in.readOptionalString(); preference = in.readOptionalString(); if (in.readBoolean()) { scroll = readScroll(in); } sourceUnsafe = false; source = in.readBytesReference(); extraSourceUnsafe = false; extraSource = in.readBytesReference(); types = in.readStringArray(); indicesOptions = IndicesOptions.readIndicesOptions(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeByte(operationThreading.id()); out.writeByte(searchType.id()); out.writeVInt(indices.length); for (String index : indices) { out.writeString(index); } out.writeOptionalString(routing); out.writeOptionalString(preference); if (scroll == null) { out.writeBoolean(false); } else { out.writeBoolean(true); scroll.writeTo(out); } out.writeBytesReference(source); out.writeBytesReference(extraSource); out.writeStringArray(types); indicesOptions.writeIndicesOptions(out); } }
1no label
src_main_java_org_elasticsearch_action_search_SearchRequest.java
1,122
public class WanReplicationRefReadOnly extends WanReplicationRef { public WanReplicationRefReadOnly(WanReplicationRef ref) { super(ref); } public WanReplicationRef setName(String name) { throw new UnsupportedOperationException("This config is read-only"); } public WanReplicationRef setMergePolicy(String mergePolicy) { throw new UnsupportedOperationException("This config is read-only"); } }
0true
hazelcast_src_main_java_com_hazelcast_config_WanReplicationRefReadOnly.java
2,829
public interface CharFilterFactoryFactory { CharFilterFactory create(String name, Settings settings); }
0true
src_main_java_org_elasticsearch_index_analysis_CharFilterFactoryFactory.java
1,789
private static final class IntersectionOrder implements Comparator<Edge> { private static final Coordinate SENTINEL = new Coordinate(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); @Override public int compare(Edge o1, Edge o2) { return Double.compare(o1.intersect.y, o2.intersect.y); } }
0true
src_main_java_org_elasticsearch_common_geo_builders_ShapeBuilder.java
920
public interface LockService extends SharedService { String SERVICE_NAME = "hz:impl:lockService"; void registerLockStoreConstructor(String serviceName, ConstructorFunction<ObjectNamespace, LockStoreInfo> constructorFunction); LockStore createLockStore(int partitionId, ObjectNamespace namespace); void clearLockStore(int partitionId, ObjectNamespace namespace); Collection<LockResource> getAllLocks(); }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_lock_LockService.java
682
constructors[COLLECTION_REMOVE] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new CollectionRemoveOperation(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
1,479
@Component("blCustomerAddressValidator") public class CustomerAddressValidator implements Validator { @SuppressWarnings("rawtypes") public boolean supports(Class clazz) { return clazz.equals(CustomerAddressValidator.class); } public void validate(Object obj, Errors errors) { CustomerAddressForm form = (CustomerAddressForm) obj; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.addressLine1", "addressLine1.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.city", "city.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.postalCode", "postalCode.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.firstName", "firstName.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.lastName", "lastName.required"); if (form.getAddress().getCountry() == null) { errors.rejectValue("address.country", "country.required", null, null); } } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_account_validator_CustomerAddressValidator.java
114
static final class DefaultForkJoinWorkerThreadFactory implements ForkJoinWorkerThreadFactory { public final ForkJoinWorkerThread newThread(ForkJoinPool pool) { return new ForkJoinWorkerThread(pool); } }
0true
src_main_java_jsr166e_ForkJoinPool.java
650
constructors[COLLECTION_ADD] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new CollectionAddOperation(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
181
@RunWith(Parameterized.class) public abstract class IDAuthorityTest { private static final Logger log = LoggerFactory.getLogger(IDAuthorityTest.class); public static final int CONCURRENCY = 8; public static final int MAX_NUM_PARTITIONS = 4; public static final String DB_NAME = "test"; public static final Duration GET_ID_BLOCK_TIMEOUT = new StandardDuration(300000L, TimeUnit.MILLISECONDS); @Parameterized.Parameters public static Collection<Object[]> configs() { List<Object[]> configurations = new ArrayList<Object[]>(); ModifiableConfiguration c = getBasicConfig(); configurations.add(new Object[]{c.getConfiguration()}); c = getBasicConfig(); c.set(IDAUTHORITY_CAV_BITS,9); c.set(IDAUTHORITY_CAV_TAG,511); configurations.add(new Object[]{c.getConfiguration()}); c = getBasicConfig(); c.set(IDAUTHORITY_CAV_RETRIES,10); c.set(IDAUTHORITY_WAIT, new StandardDuration(10L, TimeUnit.MILLISECONDS)); c.set(IDAUTHORITY_CAV_BITS,7); //c.set(IDAUTHORITY_RANDOMIZE_UNIQUEID,true); c.set(IDAUTHORITY_CONFLICT_AVOIDANCE, ConflictAvoidanceMode.GLOBAL_AUTO); configurations.add(new Object[]{c.getConfiguration()}); return configurations; } public static ModifiableConfiguration getBasicConfig() { ModifiableConfiguration c = GraphDatabaseConfiguration.buildConfiguration(); c.set(IDAUTHORITY_WAIT, new StandardDuration(100L, TimeUnit.MILLISECONDS)); c.set(IDS_BLOCK_SIZE,400); return c; } public KeyColumnValueStoreManager[] manager; public IDAuthority[] idAuthorities; public WriteConfiguration baseStoreConfiguration; public final int uidBitWidth; public final boolean hasFixedUid; public final boolean hasEmptyUid; public final long blockSize; public final long idUpperBoundBitWidth; public final long idUpperBound; public IDAuthorityTest(WriteConfiguration baseConfig) { Preconditions.checkNotNull(baseConfig); TestGraphConfigs.applyOverrides(baseConfig); this.baseStoreConfiguration = baseConfig; Configuration config = StorageSetup.getConfig(baseConfig); uidBitWidth = config.get(IDAUTHORITY_CAV_BITS); //hasFixedUid = !config.get(IDAUTHORITY_RANDOMIZE_UNIQUEID); hasFixedUid = !ConflictAvoidanceMode.GLOBAL_AUTO.equals(config.get(IDAUTHORITY_CONFLICT_AVOIDANCE)); hasEmptyUid = uidBitWidth==0; blockSize = config.get(IDS_BLOCK_SIZE); idUpperBoundBitWidth = 30; idUpperBound = 1l<<idUpperBoundBitWidth; } @Before public void setUp() throws Exception { StoreManager m = openStorageManager(); m.clearStorage(); m.close(); open(); } public abstract KeyColumnValueStoreManager openStorageManager() throws BackendException; public void open() throws BackendException { manager = new KeyColumnValueStoreManager[CONCURRENCY]; idAuthorities = new IDAuthority[CONCURRENCY]; for (int i = 0; i < CONCURRENCY; i++) { ModifiableConfiguration sc = StorageSetup.getConfig(baseStoreConfiguration.copy()); //sc.set(GraphDatabaseConfiguration.INSTANCE_RID_SHORT,(short)i); sc.set(GraphDatabaseConfiguration.UNIQUE_INSTANCE_ID_SUFFIX, (short)i); if (!sc.has(UNIQUE_INSTANCE_ID)) { String uniqueGraphId = getOrGenerateUniqueInstanceId(sc); log.debug("Setting unique instance id: {}", uniqueGraphId); sc.set(UNIQUE_INSTANCE_ID, uniqueGraphId); } sc.set(GraphDatabaseConfiguration.CLUSTER_PARTITION,true); sc.set(GraphDatabaseConfiguration.CLUSTER_MAX_PARTITIONS,MAX_NUM_PARTITIONS); manager[i] = openStorageManager(); StoreFeatures storeFeatures = manager[i].getFeatures(); KeyColumnValueStore idStore = manager[i].openDatabase("ids"); if (storeFeatures.isKeyConsistent()) idAuthorities[i] = new ConsistentKeyIDAuthority(idStore, manager[i], sc); else throw new IllegalArgumentException("Cannot open id store"); } } @After public void tearDown() throws Exception { close(); } public void close() throws BackendException { for (int i = 0; i < CONCURRENCY; i++) { idAuthorities[i].close(); manager[i].close(); } } private class InnerIDBlockSizer implements IDBlockSizer { @Override public long getBlockSize(int idNamespace) { return blockSize; } @Override public long getIdUpperBound(int idNamespace) { return idUpperBound; } } private void checkBlock(IDBlock block) { assertTrue(blockSize<10000); LongSet ids = new LongOpenHashSet((int)blockSize); checkBlock(block,ids); } private void checkBlock(IDBlock block, LongSet ids) { assertEquals(blockSize,block.numIds()); for (int i=0;i<blockSize;i++) { long id = block.getId(i); assertEquals(id,block.getId(i)); assertFalse(ids.contains(id)); assertTrue(id<idUpperBound); assertTrue(id>0); ids.add(id); } if (hasEmptyUid) { assertEquals(blockSize-1,block.getId(block.numIds()-1)-block.getId(0)); } try { block.getId(blockSize); fail(); } catch (ArrayIndexOutOfBoundsException e) {} } // private void checkIdList(List<Long> ids) { // Collections.sort(ids); // for (int i=1;i<ids.size();i++) { // long current = ids.get(i); // long previous = ids.get(i-1); // Assert.assertTrue(current>0); // Assert.assertTrue(previous>0); // Assert.assertTrue("ID block allocated twice: blockstart=" + current + ", indices=(" + i + ", " + (i-1) + ")", current!=previous); // Assert.assertTrue("ID blocks allocated in non-increasing order: " + previous + " then " + current, current>previous); // Assert.assertTrue(previous+blockSize<=current); // // if (hasFixedUid) { // Assert.assertTrue(current + " vs " + previous, 0 == (current - previous) % blockSize); // final long skipped = (current - previous) / blockSize; // Assert.assertTrue(0 <= skipped); // } // } // } @Test public void testAuthorityUniqueIDsAreDistinct() { /* Check that each IDAuthority was created with a unique id. Duplicate * values reflect a problem in either this test or the * implementation-under-test. */ Set<String> uids = new HashSet<String>(); String uidErrorMessage = "Uniqueness failure detected for config option " + UNIQUE_INSTANCE_ID.getName(); for (int i = 0; i < CONCURRENCY; i++) { String uid = idAuthorities[i].getUniqueID(); Assert.assertTrue(uidErrorMessage, !uids.contains(uid)); uids.add(uid); } assertEquals(uidErrorMessage, CONCURRENCY, uids.size()); } @Test public void testSimpleIDAcquisition() throws BackendException { final IDBlockSizer blockSizer = new InnerIDBlockSizer(); idAuthorities[0].setIDBlockSizer(blockSizer); int numTrials = 100; LongSet ids = new LongOpenHashSet((int)blockSize*numTrials); long previous = 0; for (int i=0;i<numTrials;i++) { IDBlock block = idAuthorities[0].getIDBlock(0, 0, GET_ID_BLOCK_TIMEOUT); checkBlock(block,ids); if (hasEmptyUid) { if (previous!=0) assertEquals(previous+1, block.getId(0)); previous=block.getId(block.numIds()-1); } } } @Test public void testIDExhaustion() throws BackendException { final int chunks = 30; final IDBlockSizer blockSizer = new IDBlockSizer() { @Override public long getBlockSize(int idNamespace) { return ((1l<<(idUpperBoundBitWidth-uidBitWidth))-1)/chunks; } @Override public long getIdUpperBound(int idNamespace) { return idUpperBound; } }; idAuthorities[0].setIDBlockSizer(blockSizer); if (hasFixedUid) { for (int i=0;i<chunks;i++) { idAuthorities[0].getIDBlock(0,0,GET_ID_BLOCK_TIMEOUT); } try { idAuthorities[0].getIDBlock(0,0,GET_ID_BLOCK_TIMEOUT); Assert.fail(); } catch (IDPoolExhaustedException e) {} } else { for (int i=0;i<(chunks*Math.max(1,(1<<uidBitWidth)/10));i++) { idAuthorities[0].getIDBlock(0,0,GET_ID_BLOCK_TIMEOUT); } try { for (int i=0;i<(chunks*Math.max(1,(1<<uidBitWidth)*9/10));i++) { idAuthorities[0].getIDBlock(0,0,GET_ID_BLOCK_TIMEOUT); } Assert.fail(); } catch (IDPoolExhaustedException e) {} } } @Test public void testLocalPartitionAcquisition() throws BackendException { for (int c = 0; c < CONCURRENCY; c++) { if (manager[c].getFeatures().hasLocalKeyPartition()) { try { List<KeyRange> partitions = idAuthorities[c].getLocalIDPartition(); for (KeyRange range : partitions) { assertEquals(range.getStart().length(), range.getEnd().length()); for (int i = 0; i < 2; i++) { Assert.assertTrue(range.getAt(i).length() >= 4); } } } catch (UnsupportedOperationException e) { Assert.fail(); } } } } @Test public void testManyThreadsOneIDAuthority() throws BackendException, InterruptedException, ExecutionException { ExecutorService es = Executors.newFixedThreadPool(CONCURRENCY); final IDAuthority targetAuthority = idAuthorities[0]; targetAuthority.setIDBlockSizer(new InnerIDBlockSizer()); final int targetPartition = 0; final int targetNamespace = 2; final ConcurrentLinkedQueue<IDBlock> blocks = new ConcurrentLinkedQueue<IDBlock>(); final int blocksPerThread = 40; Assert.assertTrue(0 < blocksPerThread); List <Future<Void>> futures = new ArrayList<Future<Void>>(CONCURRENCY); // Start some concurrent threads getting blocks the same ID authority and same partition in that authority for (int c = 0; c < CONCURRENCY; c++) { futures.add(es.submit(new Callable<Void>() { @Override public Void call() { try { getBlock(); } catch (BackendException e) { throw new RuntimeException(e); } return null; } private void getBlock() throws BackendException { for (int i = 0; i < blocksPerThread; i++) { IDBlock block = targetAuthority.getIDBlock(targetPartition,targetNamespace, GET_ID_BLOCK_TIMEOUT); Assert.assertNotNull(block); blocks.add(block); } } })); } for (Future<Void> f : futures) { try { f.get(); } catch (ExecutionException e) { throw e; } } es.shutdownNow(); assertEquals(blocksPerThread * CONCURRENCY, blocks.size()); LongSet ids = new LongOpenHashSet((int)blockSize*blocksPerThread*CONCURRENCY); for (IDBlock block : blocks) checkBlock(block,ids); } @Test public void testMultiIDAcquisition() throws Throwable { final int numPartitions = MAX_NUM_PARTITIONS; final int numAcquisitionsPerThreadPartition = 100; final IDBlockSizer blockSizer = new InnerIDBlockSizer(); for (int i = 0; i < CONCURRENCY; i++) idAuthorities[i].setIDBlockSizer(blockSizer); final List<ConcurrentLinkedQueue<IDBlock>> ids = new ArrayList<ConcurrentLinkedQueue<IDBlock>>(numPartitions); for (int i = 0; i < numPartitions; i++) { ids.add(new ConcurrentLinkedQueue<IDBlock>()); } final int maxIterations = numAcquisitionsPerThreadPartition * numPartitions * 2; final Collection<Future<?>> futures = new ArrayList<Future<?>>(CONCURRENCY); ExecutorService es = Executors.newFixedThreadPool(CONCURRENCY); Set<String> uids = new HashSet<String>(CONCURRENCY); for (int i = 0; i < CONCURRENCY; i++) { final IDAuthority idAuthority = idAuthorities[i]; final IDStressor stressRunnable = new IDStressor( numAcquisitionsPerThreadPartition, numPartitions, maxIterations, idAuthority, ids); uids.add(idAuthority.getUniqueID()); futures.add(es.submit(stressRunnable)); } // If this fails, it's likely to be a bug in the test rather than the // IDAuthority (the latter is technically possible, just less likely) assertEquals(CONCURRENCY, uids.size()); for (Future<?> f : futures) { try { f.get(); } catch (ExecutionException e) { throw e.getCause(); } } for (int i = 0; i < numPartitions; i++) { ConcurrentLinkedQueue<IDBlock> list = ids.get(i); assertEquals(numAcquisitionsPerThreadPartition * CONCURRENCY, list.size()); LongSet idset = new LongOpenHashSet((int)blockSize*list.size()); for (IDBlock block : list) checkBlock(block,idset); } es.shutdownNow(); } private class IDStressor implements Runnable { private final int numRounds; private final int numPartitions; private final int maxIterations; private final IDAuthority authority; private final List<ConcurrentLinkedQueue<IDBlock>> allocatedBlocks; private static final long sleepMS = 250L; private IDStressor(int numRounds, int numPartitions, int maxIterations, IDAuthority authority, List<ConcurrentLinkedQueue<IDBlock>> ids) { this.numRounds = numRounds; this.numPartitions = numPartitions; this.maxIterations = maxIterations; this.authority = authority; this.allocatedBlocks = ids; } @Override public void run() { try { runInterruptible(); } catch (InterruptedException e) { throw new RuntimeException(e); } } private void runInterruptible() throws InterruptedException { int iterations = 0; long lastStart[] = new long[numPartitions]; for (int i = 0; i < numPartitions; i++) lastStart[i] = Long.MIN_VALUE; for (int j = 0; j < numRounds; j++) { for (int p = 0; p < numPartitions; p++) { if (maxIterations < ++iterations) { throwIterationsExceededException(); } final IDBlock block = allocate(p); if (null == block) { Thread.sleep(sleepMS); p--; } else { allocatedBlocks.get(p).add(block); if (hasEmptyUid) { long start = block.getId(0); Assert.assertTrue("Previous block start " + lastStart[p] + " exceeds next block start " + start, lastStart[p] <= start); lastStart[p] = start; } } } } } private IDBlock allocate(int partitionIndex) { IDBlock block; try { block = authority.getIDBlock(partitionIndex,partitionIndex,GET_ID_BLOCK_TIMEOUT); } catch (BackendException e) { log.error("Unexpected exception while getting ID block", e); return null; } /* * This is not guaranteed in the consistentkey implementation. * Writers of ID block claims in that implementation delete their * writes if they take too long. A peek can see this short-lived * block claim even though a subsequent getblock does not. */ // Assert.assertTrue(nextId <= block[0]); if (hasEmptyUid) assertEquals(block.getId(0)+ blockSize-1, block.getId(blockSize-1)); log.trace("Obtained ID block {}", block); return block; } private boolean throwIterationsExceededException() { throw new RuntimeException( "Exceeded maximum ID allocation iteration count (" + maxIterations + "); too many timeouts?"); } } }
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_IDAuthorityTest.java
1,673
map.addEntryListener(new EntryListener<String, String>() { public void entryAdded(EntryEvent event) { assertEquals("world", event.getValue()); assertEquals("hello", event.getKey()); latchAdded.countDown(); } public void entryRemoved(EntryEvent event) { assertEquals("hello", event.getKey()); assertEquals("new world", event.getValue()); latchRemoved.countDown(); } public void entryUpdated(EntryEvent event) { assertEquals("world", event.getOldValue()); assertEquals("new world", event.getValue()); assertEquals("hello", event.getKey()); latchUpdated.countDown(); } public void entryEvicted(EntryEvent event) { entryRemoved(event); } }, true);
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
447
public interface KeyIterator extends RecordIterator<StaticBuffer> { /** * Returns an iterator over all entries associated with the current * key that match the column range specified in the query. * </p> * Closing the returned sub-iterator has no effect on this iterator. * * Calling {@link #next()} might close previously returned RecordIterators * depending on the implementation, hence it is important to iterate over * (and close) the RecordIterator before calling {@link #next()} or {@link #hasNext()}. * * @return */ public RecordIterator<Entry> getEntries(); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_KeyIterator.java
813
public class AddAndGetOperation extends AtomicLongBackupAwareOperation { private long delta; private long returnValue; public AddAndGetOperation() { } public AddAndGetOperation(String name, long delta) { super(name); this.delta = delta; } @Override public void run() throws Exception { LongWrapper number = getNumber(); returnValue = number.addAndGet(delta); } @Override public Object getResponse() { return returnValue; } @Override public int getId() { return AtomicLongDataSerializerHook.ADD_AND_GET; } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeLong(delta); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); delta = in.readLong(); } @Override public Operation getBackupOperation() { return new AddBackupOperation(name, delta); } }
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_operations_AddAndGetOperation.java
162
public final class OperationFactoryWrapper implements OperationFactory { private OperationFactory opFactory; private String uuid; public OperationFactoryWrapper() { } public OperationFactoryWrapper(OperationFactory opFactory, String uuid) { this.opFactory = opFactory; this.uuid = uuid; } @Override public Operation createOperation() { Operation op = opFactory.createOperation(); op.setCallerUuid(uuid); return op; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(uuid); out.writeObject(opFactory); } @Override public void readData(ObjectDataInput in) throws IOException { uuid = in.readUTF(); opFactory = in.readObject(); } }
0true
hazelcast_src_main_java_com_hazelcast_client_OperationFactoryWrapper.java
994
transportService.sendRequest(node, transportReplicaAction, shardRequest, transportOptions, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleResponse(TransportResponse.Empty vResponse) { finishIfPossible(); } @Override public void handleException(TransportException exp) { if (!ignoreReplicaException(exp.unwrapCause())) { logger.warn("Failed to perform " + transportAction + " on replica " + shardIt.shardId(), exp); shardStateAction.shardFailed(shard, indexMetaData.getUUID(), "Failed to perform [" + transportAction + "] on replica, message [" + detailedMessage(exp) + "]"); } finishIfPossible(); } private void finishIfPossible() { if (counter.decrementAndGet() == 0) { listener.onResponse(response.response()); } } });
0true
src_main_java_org_elasticsearch_action_support_replication_TransportShardReplicationOperationAction.java
1,394
@XmlRootElement(name = "fulfillmentGroupItem") @XmlAccessorType(value = XmlAccessType.FIELD) public class FulfillmentGroupItemWrapper extends BaseWrapper implements APIWrapper<FulfillmentGroupItem>, APIUnwrapper<FulfillmentGroupItemRequest> { @XmlElement protected Long id; @XmlElement protected Long fulfillmentGroupId; @XmlElement protected Long orderItemId; @XmlElement protected Money totalTax; @XmlElement protected Integer quantity; @XmlElement protected Money totalItemAmount; @XmlElement(name = "taxDetail") @XmlElementWrapper(name = "taxDetails") protected List<TaxDetailWrapper> taxDetails; @Override public void wrapDetails(FulfillmentGroupItem model, HttpServletRequest request) { this.id = model.getId(); if (model.getFulfillmentGroup() != null) { this.fulfillmentGroupId = model.getFulfillmentGroup().getId(); } if (model.getOrderItem() != null) { this.orderItemId = model.getOrderItem().getId(); } this.totalTax = model.getTotalTax(); this.quantity = model.getQuantity(); this.totalItemAmount = model.getTotalItemAmount(); List<TaxDetail> taxes = model.getTaxes(); if (taxes != null && !taxes.isEmpty()) { this.taxDetails = new ArrayList<TaxDetailWrapper>(); for (TaxDetail detail : taxes) { TaxDetailWrapper taxDetailWrapper = (TaxDetailWrapper) context.getBean(TaxDetailWrapper.class.getName()); taxDetailWrapper.wrapSummary(detail, request); this.taxDetails.add(taxDetailWrapper); } } } @Override public void wrapSummary(FulfillmentGroupItem model, HttpServletRequest request) { wrapDetails(model, request); } @Override public FulfillmentGroupItemRequest unwrap(HttpServletRequest request, ApplicationContext appContext) { OrderItemService orderItemService = (OrderItemService) appContext.getBean("blOrderItemService"); OrderItem orderItem = orderItemService.readOrderItemById(this.orderItemId); if (orderItem != null) { FulfillmentGroupItemRequest fulfillmentGroupItemRequest = new FulfillmentGroupItemRequest(); fulfillmentGroupItemRequest.setOrderItem(orderItem); fulfillmentGroupItemRequest.setQuantity(this.quantity); return fulfillmentGroupItemRequest; } return null; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_wrapper_FulfillmentGroupItemWrapper.java
1,109
final OSQLFunctionDifference differenceFunction = new OSQLFunctionDifference() { @Override protected boolean returnDistributedResult() { return false; } };
0true
core_src_test_java_com_orientechnologies_orient_core_sql_functions_coll_SQLFunctionDifferenceTest.java
350
Thread t = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(request.delay.millis()); } catch (InterruptedException e) { // ignore } final CountDownLatch latch = new CountDownLatch(nodesIds.length); for (String nodeId : nodesIds) { final DiscoveryNode node = state.nodes().get(nodeId); if (node == null) { logger.warn("[partial_cluster_shutdown]: no node to shutdown for node_id [{}]", nodeId); latch.countDown(); continue; } logger.trace("[partial_cluster_shutdown]: sending shutdown request to [{}]", node); 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(); } }); } try { latch.await(); } catch (InterruptedException e) { // ignore } logger.info("[partial_cluster_shutdown]: done shutting down [{}]", ((Object) nodesIds)); } });
0true
src_main_java_org_elasticsearch_action_admin_cluster_node_shutdown_TransportNodesShutdownAction.java
229
XPostingsHighlighter highlighter = new XPostingsHighlighter(10000) { @Override protected BreakIterator getBreakIterator(String field) { return new WholeBreakIterator(); } };
0true
src_test_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighterTests.java
1,443
public class OGremlinConsole extends OConsoleDatabaseApp { public OGremlinConsole(final String[] args) { super(args); } public static void main(final String[] args) { try { boolean tty = false; try { if (setTerminalToCBreak()) tty = true; } catch (Exception e) { } final OConsoleDatabaseApp console = new OGremlinConsole(args); if (tty) console.setReader(new TTYConsoleReader()); console.run(); } finally { try { stty("echo"); } catch (Exception e) { } } } @Override protected void onBefore() { super.onBefore(); out.println("\nInstalling extensions for GREMLIN language v." + OGremlinHelper.getEngineVersion()); OGremlinHelper.global().create(); } @Override protected boolean isCollectingCommands(final String iLine) { return super.isCollectingCommands(iLine) || iLine.startsWith("gremlin"); } @ConsoleCommand(splitInWords = false, description = "Execute a GREMLIN script") public void gremlin(@ConsoleParameter(name = "script-text", description = "The script text to execute") final String iScriptText) { checkForDatabase(); if (iScriptText == null || iScriptText.length() == 0) return; currentResultSet.clear(); long start = System.currentTimeMillis(); try { final Object result = currentDatabase.command(new OCommandGremlin(iScriptText)).execute(); float elapsedSeconds = (System.currentTimeMillis() - start) / 1000; out.println("\n" + result); out.printf("\nScript executed in %f sec(s).", elapsedSeconds); } catch (OStorageException e) { final Throwable cause = e.getCause(); if (cause instanceof OCommandExecutorNotFoundException) out.printf("\nError: the GREMLIN command executor is not installed, check your configuration"); } } }
0true
graphdb_src_main_java_com_orientechnologies_orient_graph_console_OGremlinConsole.java
276
public class ProblemMarkerManager implements IResourceChangeListener, IAnnotationModelListener, IAnnotationModelListenerExtension { private ListenerList fListeners; public ProblemMarkerManager() { fListeners= new ListenerList(); } /** * Visitor used to determine whether the resource delta contains a marker change. */ private static class ProjectErrorVisitor implements IResourceDeltaVisitor { private Set<IResource> fChangedElements; public ProjectErrorVisitor(Set<IResource> changedElements) { fChangedElements= changedElements; } public boolean visit(IResourceDelta delta) throws CoreException { IResource res= delta.getResource(); if (res instanceof IProject && delta.getKind()==IResourceDelta.CHANGED) { IProject project= (IProject) res; if (!project.isAccessible()) { // only track open Java projects return false; } } checkInvalidate(delta, res); return true; } private void checkInvalidate(IResourceDelta delta, IResource resource) { int kind= delta.getKind(); if (kind==IResourceDelta.REMOVED || kind==IResourceDelta.ADDED || (kind==IResourceDelta.CHANGED && isErrorDelta(delta))) { // invalidate the resource and all parents while (resource.getType()!=IResource.ROOT && fChangedElements.add(resource)) { resource= resource.getParent(); } } } private boolean isErrorDelta(IResourceDelta delta) { if ((delta.getFlags() & IResourceDelta.MARKERS)!=0) { IMarkerDelta[] markerDeltas= delta.getMarkerDeltas(); for(int i= 0; i < markerDeltas.length; i++) { IMarkerDelta markerDelta= markerDeltas[i]; if (markerDelta.isSubtypeOf(IMarker.PROBLEM)) { int kind= markerDelta.getKind(); if (kind==IResourceDelta.ADDED || kind==IResourceDelta.REMOVED) return true; int severity= markerDelta.getAttribute(IMarker.SEVERITY, -1); int newSeverity= markerDelta.getMarker().getAttribute(IMarker.SEVERITY, -1); if (newSeverity!=severity) return true; } } } return false; } } public void resourceChanged(IResourceChangeEvent event) { Set<IResource> changedElements= new HashSet<IResource>(); try { IResourceDelta delta= event.getDelta(); if (delta != null) delta.accept(new ProjectErrorVisitor(changedElements)); } catch (CoreException e) { e.printStackTrace(); } if (!changedElements.isEmpty()) { IResource[] changes= (IResource[]) changedElements.toArray(new IResource[changedElements.size()]); fireChanges(changes, true); } } public void modelChanged(IAnnotationModel model) {} public void modelChanged(AnnotationModelEvent event) {} /** * Adds a listener for problem marker changes. */ public void addListener(IProblemChangedListener listener) { if (fListeners.isEmpty()) { ResourcesPlugin.getWorkspace().addResourceChangeListener(this); } fListeners.add(listener); } /** * Removes a <code>IProblemChangedListener</code>. */ public void removeListener(IProblemChangedListener listener) { fListeners.remove(listener); if (fListeners.isEmpty()) { ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); } } private void fireChanges(final IResource[] changes, final boolean isMarkerChange) { Display display = Display.getCurrent(); if (display==null) display= Display.getDefault(); if (display!=null && !display.isDisposed()) { display.asyncExec(new Runnable() { public void run() { Object[] listeners= fListeners.getListeners(); for(int i= 0; i < listeners.length; i++) { IProblemChangedListener curr= (IProblemChangedListener) listeners[i]; curr.problemsChanged(changes, isMarkerChange); } } }); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_ProblemMarkerManager.java
341
private abstract static class AcquireLockCommand implements WorkerCommand<LockWorkerState, Void> { @Override public Void doWork( LockWorkerState state ) { try { acquireLock( state ); state.deadlockOnLastWait = false; } catch ( DeadlockDetectedException e ) { state.deadlockOnLastWait = true; } return null; } protected abstract void acquireLock( LockWorkerState state ); }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_LockWorker.java
2,896
public class NumericDateAnalyzer extends NumericAnalyzer<NumericDateTokenizer> { private final int precisionStep; private final DateTimeFormatter dateTimeFormatter; public NumericDateAnalyzer(DateTimeFormatter dateTimeFormatter) { this(NumericUtils.PRECISION_STEP_DEFAULT, dateTimeFormatter); } public NumericDateAnalyzer(int precisionStep, DateTimeFormatter dateTimeFormatter) { this.precisionStep = precisionStep; this.dateTimeFormatter = dateTimeFormatter; } @Override protected NumericDateTokenizer createNumericTokenizer(Reader reader, char[] buffer) throws IOException { return new NumericDateTokenizer(reader, precisionStep, buffer, dateTimeFormatter); } }
0true
src_main_java_org_elasticsearch_index_analysis_NumericDateAnalyzer.java
1,146
public class OSQLMethodIndexOf extends OAbstractSQLMethod { public static final String NAME = "indexof"; public OSQLMethodIndexOf() { super(NAME, 1, 2); } @Override public Object execute(OIdentifiable iCurrentRecord, OCommandContext iContext, Object ioResult, Object[] iMethodParams) { final String param0 = iMethodParams[0].toString(); if (param0.length() > 2) { String toFind = param0.substring(1, param0.length() - 1); int startIndex = iMethodParams.length > 1 ? Integer.parseInt(iMethodParams[1].toString()) : 0; ioResult = ioResult != null ? ioResult.toString().indexOf(toFind, startIndex) : null; } return ioResult; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_method_misc_OSQLMethodIndexOf.java
555
public class GetMappingsRequestBuilder extends ClusterInfoRequestBuilder<GetMappingsRequest, GetMappingsResponse, GetMappingsRequestBuilder> { public GetMappingsRequestBuilder(InternalGenericClient client, String... indices) { super(client, new GetMappingsRequest().indices(indices)); } @Override protected void doExecute(ActionListener<GetMappingsResponse> listener) { ((IndicesAdminClient) client).getMappings(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_mapping_get_GetMappingsRequestBuilder.java
1,556
public class AllocationCommands { private static Map<String, AllocationCommand.Factory> factories = new HashMap<String, AllocationCommand.Factory>(); /** * Register a custom index meta data factory. Make sure to call it from a static block. */ public static void registerFactory(String type, AllocationCommand.Factory factory) { factories.put(type, factory); } @SuppressWarnings("unchecked") @Nullable public static <T extends AllocationCommand> AllocationCommand.Factory<T> lookupFactory(String name) { return factories.get(name); } @SuppressWarnings("unchecked") public static <T extends AllocationCommand> AllocationCommand.Factory<T> lookupFactorySafe(String name) throws ElasticsearchIllegalArgumentException { AllocationCommand.Factory<T> factory = factories.get(name); if (factory == null) { throw new ElasticsearchIllegalArgumentException("No allocation command factory registered for name [" + name + "]"); } return factory; } static { registerFactory(AllocateAllocationCommand.NAME, new AllocateAllocationCommand.Factory()); registerFactory(CancelAllocationCommand.NAME, new CancelAllocationCommand.Factory()); registerFactory(MoveAllocationCommand.NAME, new MoveAllocationCommand.Factory()); } private final List<AllocationCommand> commands = Lists.newArrayList(); /** * Creates a new set of {@link AllocationCommands} * * @param commands {@link AllocationCommand}s that are wrapped by this instance */ public AllocationCommands(AllocationCommand... commands) { if (commands != null) { this.commands.addAll(Arrays.asList(commands)); } } /** * Adds a set of commands to this collection * @param commands Array of commands to add to this instance * @return {@link AllocationCommands} with the given commands added */ public AllocationCommands add(AllocationCommand... commands) { if (commands != null) { this.commands.addAll(Arrays.asList(commands)); } return this; } /** * Get the commands wrapped by this instance * @return {@link List} of commands */ public List<AllocationCommand> commands() { return this.commands; } /** * Executes all wrapped commands on a given {@link RoutingAllocation} * @param allocation {@link RoutingAllocation} to apply this command to * @throws org.elasticsearch.ElasticsearchException if something happens during execution */ public void execute(RoutingAllocation allocation) throws ElasticsearchException { for (AllocationCommand command : commands) { command.execute(allocation); } } /** * Reads a {@link AllocationCommands} from a {@link StreamInput} * @param in {@link StreamInput} to read from * @return {@link AllocationCommands} read * * @throws IOException if something happens during read */ public static AllocationCommands readFrom(StreamInput in) throws IOException { AllocationCommands commands = new AllocationCommands(); int size = in.readVInt(); for (int i = 0; i < size; i++) { String name = in.readString(); commands.add(lookupFactorySafe(name).readFrom(in)); } return commands; } /** * Writes {@link AllocationCommands} to a {@link StreamOutput} * * @param commands Commands to write * @param out {@link StreamOutput} to write the commands to * @throws IOException if something happens during write */ public static void writeTo(AllocationCommands commands, StreamOutput out) throws IOException { out.writeVInt(commands.commands.size()); for (AllocationCommand command : commands.commands) { out.writeString(command.name()); lookupFactorySafe(command.name()).writeTo(command, out); } } /** * Reads {@link AllocationCommands} from a {@link XContentParser} * <pre> * { * "commands" : [ * {"allocate" : {"index" : "test", "shard" : 0, "node" : "test"}} * ] * } * </pre> * @param parser {@link XContentParser} to read the commands from * @return {@link AllocationCommands} read * @throws IOException if something bad happens while reading the stream */ public static AllocationCommands fromXContent(XContentParser parser) throws IOException { AllocationCommands commands = new AllocationCommands(); XContentParser.Token token = parser.currentToken(); if (token == null) { throw new ElasticsearchParseException("No commands"); } if (token == XContentParser.Token.FIELD_NAME) { if (!parser.currentName().equals("commands")) { throw new ElasticsearchParseException("expected field name to be named `commands`, got " + parser.currentName()); } if (!parser.currentName().equals("commands")) { throw new ElasticsearchParseException("expected field name to be named `commands`, got " + parser.currentName()); } token = parser.nextToken(); if (token != XContentParser.Token.START_ARRAY) { throw new ElasticsearchParseException("commands should follow with an array element"); } } else if (token == XContentParser.Token.START_ARRAY) { // ok... } else { throw new ElasticsearchParseException("expected either field name commands, or start array, got " + token); } while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { if (token == XContentParser.Token.START_OBJECT) { // move to the command name token = parser.nextToken(); String commandName = parser.currentName(); token = parser.nextToken(); commands.add(AllocationCommands.lookupFactorySafe(commandName).fromXContent(parser)); // move to the end object one if (parser.nextToken() != XContentParser.Token.END_OBJECT) { throw new ElasticsearchParseException("allocation command is malformed, done parsing a command, but didn't get END_OBJECT, got " + token); } } else { throw new ElasticsearchParseException("allocation command is malformed, got token " + token); } } return commands; } /** * Writes {@link AllocationCommands} to a {@link XContentBuilder} * * @param commands {@link AllocationCommands} to write * @param builder {@link XContentBuilder} to use * @param params Parameters to use for building * @throws IOException if something bad happens while building the content */ public static void toXContent(AllocationCommands commands, XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startArray("commands"); for (AllocationCommand command : commands.commands) { builder.startObject(); builder.field(command.name()); AllocationCommands.lookupFactorySafe(command.name()).toXContent(command, builder, params); builder.endObject(); } builder.endArray(); } }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_command_AllocationCommands.java
461
public abstract class IndicesAction<Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> extends GenericAction<Request, Response> { protected IndicesAction(String name) { super(name); } public abstract RequestBuilder newRequestBuilder(IndicesAdminClient client); }
0true
src_main_java_org_elasticsearch_action_admin_indices_IndicesAction.java
2,151
public class TransactionalMapProxy extends TransactionalMapProxySupport implements TransactionalMap { private final Map<Object, TxnValueWrapper> txMap = new HashMap<Object, TxnValueWrapper>(); public TransactionalMapProxy(String name, MapService mapService, NodeEngine nodeEngine, TransactionSupport transaction) { super(name, mapService, nodeEngine, transaction); } public boolean containsKey(Object key) { checkTransactionState(); return txMap.containsKey(key) || containsKeyInternal(getService().toData(key, partitionStrategy)); } public int size() { checkTransactionState(); int currentSize = sizeInternal(); for (TxnValueWrapper wrapper : txMap.values()) { if (wrapper.type == TxnValueWrapper.Type.NEW) { currentSize++; } else if (wrapper.type == TxnValueWrapper.Type.REMOVED) { currentSize--; } } return currentSize; } public boolean isEmpty() { checkTransactionState(); return size() == 0; } public Object get(Object key) { checkTransactionState(); TxnValueWrapper currentValue = txMap.get(key); if (currentValue != null) { return checkIfRemoved(currentValue); } return getService().toObject(getInternal(getService().toData(key, partitionStrategy))); } public Object getForUpdate(Object key) { checkTransactionState(); TxnValueWrapper currentValue = txMap.get(key); if (currentValue != null) { return checkIfRemoved(currentValue); } Data dataKey = getService().toData(key, partitionStrategy); return getService().toObject(getForUpdateInternal(dataKey)); } private Object checkIfRemoved(TxnValueWrapper wrapper) { checkTransactionState(); return wrapper == null || wrapper.type == TxnValueWrapper.Type.REMOVED ? null : wrapper.value; } public Object put(Object key, Object value) { checkTransactionState(); MapService service = getService(); final Object valueBeforeTxn = service.toObject(putInternal(service.toData(key, partitionStrategy), service.toData(value))); TxnValueWrapper currentValue = txMap.get(key); if (value != null) { TxnValueWrapper wrapper = valueBeforeTxn == null ? new TxnValueWrapper(value, TxnValueWrapper.Type.NEW) : new TxnValueWrapper(value, TxnValueWrapper.Type.UPDATED); txMap.put(key, wrapper); } return currentValue == null ? valueBeforeTxn : checkIfRemoved(currentValue); } public Object put(Object key, Object value, long ttl, TimeUnit timeUnit) { checkTransactionState(); MapService service = getService(); final Object valueBeforeTxn = service.toObject(putInternal(service.toData(key, partitionStrategy), service.toData(value), ttl, timeUnit)); TxnValueWrapper currentValue = txMap.get(key); if (value != null) { TxnValueWrapper wrapper = valueBeforeTxn == null ? new TxnValueWrapper(value, TxnValueWrapper.Type.NEW) : new TxnValueWrapper(value, TxnValueWrapper.Type.UPDATED); txMap.put(key, wrapper); } return currentValue == null ? valueBeforeTxn : checkIfRemoved(currentValue); } public void set(Object key, Object value) { checkTransactionState(); MapService service = getService(); final Data dataBeforeTxn = putInternal(service.toData(key, partitionStrategy), service.toData(value)); if (value != null) { TxnValueWrapper wrapper = dataBeforeTxn == null ? new TxnValueWrapper(value, TxnValueWrapper.Type.NEW) : new TxnValueWrapper(value, TxnValueWrapper.Type.UPDATED); txMap.put(key, wrapper); } } public Object putIfAbsent(Object key, Object value) { checkTransactionState(); TxnValueWrapper wrapper = txMap.get(key); boolean haveTxnPast = wrapper != null; MapService service = getService(); if (haveTxnPast) { if (wrapper.type != TxnValueWrapper.Type.REMOVED) { return wrapper.value; } putInternal(service.toData(key, partitionStrategy), service.toData(value)); txMap.put(key, new TxnValueWrapper(value, TxnValueWrapper.Type.NEW)); return null; } else { Data oldValue = putIfAbsentInternal(service.toData(key, partitionStrategy), service.toData(value)); if (oldValue == null) { txMap.put(key, new TxnValueWrapper(value, TxnValueWrapper.Type.NEW)); } return service.toObject(oldValue); } } public Object replace(Object key, Object value) { checkTransactionState(); TxnValueWrapper wrapper = txMap.get(key); boolean haveTxnPast = wrapper != null; MapService service = getService(); if (haveTxnPast) { if (wrapper.type == TxnValueWrapper.Type.REMOVED) { return null; } putInternal(service.toData(key, partitionStrategy), service.toData(value)); txMap.put(key, new TxnValueWrapper(value, TxnValueWrapper.Type.UPDATED)); return wrapper.value; } else { Data oldValue = replaceInternal(service.toData(key, partitionStrategy), service.toData(value)); if (oldValue != null) { txMap.put(key, new TxnValueWrapper(value, TxnValueWrapper.Type.UPDATED)); } return service.toObject(oldValue); } } public boolean replace(Object key, Object oldValue, Object newValue) { checkTransactionState(); TxnValueWrapper wrapper = txMap.get(key); boolean haveTxnPast = wrapper != null; MapService service = getService(); if (haveTxnPast) { if (!wrapper.value.equals(oldValue)) { return false; } putInternal(service.toData(key, partitionStrategy), service.toData(newValue)); txMap.put(key, new TxnValueWrapper(wrapper.value, TxnValueWrapper.Type.UPDATED)); return true; } else { boolean success = replaceIfSameInternal(service.toData(key), service.toData(oldValue), service.toData(newValue)); if (success) { txMap.put(key, new TxnValueWrapper(newValue, TxnValueWrapper.Type.UPDATED)); } return success; } } public boolean remove(Object key, Object value) { checkTransactionState(); TxnValueWrapper wrapper = txMap.get(key); MapService service = getService(); if (wrapper != null && !service.compare(name, wrapper.value, value)) { return false; } boolean removed = removeIfSameInternal(service.toData(key, partitionStrategy), value); if (removed) { txMap.put(key, new TxnValueWrapper(value, TxnValueWrapper.Type.REMOVED)); } return removed; } public Object remove(Object key) { checkTransactionState(); MapService service = getService(); final Object valueBeforeTxn = service.toObject(removeInternal(service.toData(key, partitionStrategy))); TxnValueWrapper wrapper = null; if (valueBeforeTxn != null || txMap.containsKey(key)) { wrapper = txMap.put(key, new TxnValueWrapper(valueBeforeTxn, TxnValueWrapper.Type.REMOVED)); } return wrapper == null ? valueBeforeTxn : checkIfRemoved(wrapper); } public void delete(Object key) { checkTransactionState(); MapService service = getService(); Data data = removeInternal(service.toData(key, partitionStrategy)); if (data != null || txMap.containsKey(key)) { txMap.put(key, new TxnValueWrapper(service.toObject(data), TxnValueWrapper.Type.REMOVED)); } } public Set<Object> keySet() { checkTransactionState(); final Set<Data> keySet = keySetInternal(); final Set<Object> keys = new HashSet<Object>(keySet.size()); final MapService service = getService(); // convert Data to Object for (final Data data : keySet) { keys.add(service.toObject(data)); } for (final Map.Entry<Object, TxnValueWrapper> entry : txMap.entrySet()) { if (TxnValueWrapper.Type.NEW.equals(entry.getValue().type)) { keys.add(entry.getKey()); } else if (TxnValueWrapper.Type.REMOVED.equals(entry.getValue().type)) { keys.remove(entry.getKey()); } } return keys; } public Set keySet(Predicate predicate) { checkTransactionState(); if (predicate == null) { throw new NullPointerException("Predicate should not be null!"); } if (predicate instanceof PagingPredicate) { throw new NullPointerException("Paging is not supported for Transactional queries!"); } final MapService service = getService(); final QueryResultSet queryResultSet = (QueryResultSet) queryInternal(predicate, IterationType.KEY, false); final Set<Object> keySet = new HashSet<Object>(queryResultSet); //todo: Can't we just use the original set? for (final Map.Entry<Object, TxnValueWrapper> entry : txMap.entrySet()) { if (!TxnValueWrapper.Type.REMOVED.equals(entry.getValue().type)) { final Object value = entry.getValue().value instanceof Data ? service.toObject(entry.getValue().value) : entry.getValue().value; final QueryEntry queryEntry = new QueryEntry(null, service.toData(entry.getKey()), entry.getKey(), value); // apply predicate on txMap. if (predicate.apply(queryEntry)) { keySet.add(entry.getKey()); } } else { // meanwhile remove keys which are not in txMap. keySet.remove(entry.getKey()); } } return keySet; } public Collection<Object> values() { checkTransactionState(); final Collection<Data> dataSet = valuesInternal(); final Collection<Object> values = new ArrayList<Object>(dataSet.size()); for (final Data data : dataSet) { values.add(getService().toObject(data)); } for (TxnValueWrapper wrapper : txMap.values()) { if (TxnValueWrapper.Type.NEW.equals(wrapper.type)) { values.add(wrapper.value); } else if (TxnValueWrapper.Type.REMOVED.equals(wrapper.type)) { values.remove(wrapper.value); } } return values; } public Collection values(Predicate predicate) { checkTransactionState(); if (predicate == null) { throw new NullPointerException("Predicate can not be null!"); } if (predicate instanceof PagingPredicate) { throw new IllegalArgumentException("Paging is not supported for Transactional queries"); } final MapService service = getService(); final QueryResultSet queryResultSet = (QueryResultSet) queryInternal(predicate, IterationType.ENTRY, false); final Set<Object> valueSet = new HashSet<Object>(); //todo: Can't we just use the original set? final Set<Object> keyWontBeIncluded = new HashSet<Object>(); // delete updated or removed elements from the result set for (final Map.Entry<Object, TxnValueWrapper> entry : txMap.entrySet()) { final boolean isRemoved = TxnValueWrapper.Type.REMOVED.equals(entry.getValue().type); final boolean isUpdated = TxnValueWrapper.Type.UPDATED.equals(entry.getValue().type); if (isRemoved) { keyWontBeIncluded.add(entry.getKey()); } else { if (isUpdated){ keyWontBeIncluded.add(entry.getKey()); } final Object entryValue = entry.getValue().value; final Object objectValue = entryValue instanceof Data ? service.toObject(entryValue) : entryValue; final QueryEntry queryEntry = new QueryEntry(null, service.toData(entry.getKey()), entry.getKey(), objectValue); // apply predicate on txMap. if (predicate.apply(queryEntry)) { valueSet.add(entryValue); } } } final Iterator<Map.Entry> iterator = queryResultSet.rawIterator(); while (iterator.hasNext()){ final Map.Entry entry = iterator.next(); if (keyWontBeIncluded.contains(entry.getKey())){ continue; } valueSet.add(entry.getValue()); } return valueSet; } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("TransactionalMap"); sb.append("{name='").append(name).append('\''); sb.append('}'); return sb.toString(); } }
1no label
hazelcast_src_main_java_com_hazelcast_map_tx_TransactionalMapProxy.java
1,325
config.setManagedContext(new ManagedContext() { @Override public Object initialize(Object obj) { if (obj instanceof RunnableWithManagedContext) { RunnableWithManagedContext task = (RunnableWithManagedContext) obj; task.initializeCalled = true; } return obj; } });
0true
hazelcast_src_test_java_com_hazelcast_executor_ExecutorServiceTest.java
3,464
public abstract class IndexingOperationListener { /** * Called before the indexing occurs. */ public Engine.Create preCreate(Engine.Create create) { return create; } /** * Called after the indexing occurs, under a locking scheme to maintain * concurrent updates to the same doc. * <p/> * Note, long operations should not occur under this callback. */ public void postCreateUnderLock(Engine.Create create) { } /** * Called after the indexing operation occurred. */ public void postCreate(Engine.Create create) { } /** * Called before the indexing occurs. */ public Engine.Index preIndex(Engine.Index index) { return index; } /** * Called after the indexing occurs, under a locking scheme to maintain * concurrent updates to the same doc. * <p/> * Note, long operations should not occur under this callback. */ public void postIndexUnderLock(Engine.Index index) { } /** * Called after the indexing operation occurred. */ public void postIndex(Engine.Index index) { } /** * Called before the delete occurs. */ public Engine.Delete preDelete(Engine.Delete delete) { return delete; } /** * Called after the delete occurs, under a locking scheme to maintain * concurrent updates to the same doc. * <p/> * Note, long operations should not occur under this callback. */ public void postDeleteUnderLock(Engine.Delete delete) { } /** * Called after the delete operation occurred. */ public void postDelete(Engine.Delete delete) { } public Engine.DeleteByQuery preDeleteByQuery(Engine.DeleteByQuery deleteByQuery) { return deleteByQuery; } public void postDeleteByQuery(Engine.DeleteByQuery deleteByQuery) { } }
0true
src_main_java_org_elasticsearch_index_indexing_IndexingOperationListener.java
1,545
public class OClientConnection { public final int id; public final ONetworkProtocol protocol; public final long since; public volatile ODatabaseDocumentTx database; public volatile ODatabaseRaw rawDatabase; public volatile OServerUserConfiguration serverUser; public ONetworkProtocolData data = new ONetworkProtocolData(); public OClientConnection(final int iId, final ONetworkProtocol iProtocol) throws IOException { this.id = iId; this.protocol = iProtocol; this.since = System.currentTimeMillis(); } public void close() { if (database != null) { database.close(); database = null; } } @Override public String toString() { return "OClientConnection [id=" + id + ", source=" + (protocol != null && protocol.getChannel() != null ? protocol.getChannel().socket.getRemoteSocketAddress() : "?") + ", since=" + since + "]"; } /** * Returns the remote network address in the format <ip>:<port>. */ public String getRemoteAddress() { final InetSocketAddress remoteAddress = (InetSocketAddress) protocol.getChannel().socket.getRemoteSocketAddress(); return remoteAddress.getAddress().getHostAddress() + ":" + remoteAddress.getPort(); } @Override public int hashCode() { return id; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final OClientConnection other = (OClientConnection) obj; if (id != other.id) return false; return true; } public OChannelBinary getChannel() { return (OChannelBinary) protocol.getChannel(); } public ONetworkProtocol getProtocol() { return protocol; } }
0true
server_src_main_java_com_orientechnologies_orient_server_OClientConnection.java
1,355
final MultiExecutionCallback callback = new MultiExecutionCallback() { public void onResponse(Member member, Object value) { if (value == null) count.incrementAndGet(); latch.countDown(); } public void onComplete(Map<Member, Object> values) { } };
0true
hazelcast_src_test_java_com_hazelcast_executor_ExecutorServiceTest.java
1,477
public class UpdateAccountForm implements Serializable { private static final long serialVersionUID = 1L; private String emailAddress; private String firstName; private String lastName; public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_account_UpdateAccountForm.java
672
constructors[LIST_ADD] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new ListAddOperation(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
464
new Thread(){ public void run() { try { if(semaphore.tryAcquire(1, 5, TimeUnit.SECONDS)){ latch.countDown(); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_semaphore_ClientSemaphoreTest.java
1,355
@Service("blStoreService") public class StoreServiceImpl implements StoreService { // private final static int MAXIMUM_DISTANCE = Integer.valueOf(25); @Resource(name = "blStoreDao") private StoreDao storeDao; @Resource(name = "blZipCodeService") private ZipCodeService zipCodeService; public Store readStoreByStoreCode(String storeCode) { return storeDao.readStoreByStoreCode(storeCode); } public List<Store> readAllStores() { return storeDao.readAllStores(); } public Map<Store, Double> findStoresByAddress(Address searchAddress, double distance) { Map<Store, Double> matchingStores = new HashMap<Store, Double>(); for (Store store : readAllStores()) { Double storeDistance = findStoreDistance(store, Integer.parseInt(searchAddress.getPostalCode())); if (storeDistance != null && storeDistance <= distance) { matchingStores.put(store, storeDistance); } } return matchingStores; } private Double findStoreDistance(Store store, Integer zip) { ZipCode zipCode = zipCodeService.findZipCodeByZipCode(zip); if (zipCode == null) { return null; } // A constant used to convert from degrees to radians. double degreesToRadians = 57.3; double storeDistance = 3959 * Math.acos((Math.sin(zipCode.getZipLatitude() / degreesToRadians) * Math.sin(store.getLatitude() / degreesToRadians)) + (Math.cos(zipCode.getZipLatitude() / degreesToRadians) * Math.cos(store.getLatitude() / degreesToRadians) * Math.cos((store.getLongitude() / degreesToRadians) - (zipCode.getZipLongitude() / degreesToRadians)))); return storeDistance; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_store_service_StoreServiceImpl.java
943
Thread t = new Thread(new Runnable() { public void run() { lock.lock(); } });
0true
hazelcast_src_test_java_com_hazelcast_concurrent_lock_LockTest.java
348
public class EntityClassNotFoundException extends RuntimeException { private static final long serialVersionUID = 1L; public EntityClassNotFoundException() { super(); } public EntityClassNotFoundException(String arg0, Throwable arg1) { super(arg0, arg1); } public EntityClassNotFoundException(String arg0) { super(arg0); } public EntityClassNotFoundException(Throwable arg0) { super(arg0); } }
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_jpa_EntityClassNotFoundException.java
1,302
public class FieldEntity implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, FieldEntity> TYPES = new LinkedHashMap<String, FieldEntity>(); public static final FieldEntity PRODUCT = new FieldEntity("PRODUCT", "product"); public static final FieldEntity CUSTOMER = new FieldEntity("CUSTOMER", "customer"); public static final FieldEntity ORDER = new FieldEntity("ORDER", "order"); public static final FieldEntity ORDERITEM = new FieldEntity("ORDERITEM", "orderItem"); public static final FieldEntity OFFER = new FieldEntity("OFFER", "offer"); public static FieldEntity getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public FieldEntity() { //do nothing } public FieldEntity(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; FieldEntity other = (FieldEntity) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_search_domain_FieldEntity.java
3,021
.add(new AbstractModule() { @Override protected void configure() { bind(CircuitBreakerService.class).to(DummyCircuitBreakerService.class); } })
0true
src_test_java_org_elasticsearch_index_codec_CodecTests.java
11
@SuppressWarnings({ "unchecked", "serial" }) public abstract class OMVRBTree<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, Cloneable, java.io.Serializable { private static final OAlwaysLessKey ALWAYS_LESS_KEY = new OAlwaysLessKey(); private static final OAlwaysGreaterKey ALWAYS_GREATER_KEY = new OAlwaysGreaterKey(); protected boolean pageItemFound = false; protected int pageItemComparator = 0; protected int pageIndex = -1; protected float pageLoadFactor = 0.7f; /** * The comparator used to maintain order in this tree map, or null if it uses the natural ordering of its keys. * * @serial */ protected final Comparator<? super K> comparator; protected transient OMVRBTreeEntry<K, V> root = null; /** * The number of structural modifications to the tree. */ transient int modCount = 0; protected transient boolean runtimeCheckEnabled = false; protected transient boolean debug = false; protected Object lastSearchKey; protected OMVRBTreeEntry<K, V> lastSearchNode; protected boolean lastSearchFound = false; protected int lastSearchIndex = -1; protected int keySize = 1; /** * Indicates search behavior in case of {@link OCompositeKey} keys that have less amount of internal keys are used, whether lowest * or highest partially matched key should be used. Such keys is allowed to use only in * * @link OMVRBTree#subMap(K, boolean, K, boolean)}, {@link OMVRBTree#tailMap(Object, boolean)} and * {@link OMVRBTree#headMap(Object, boolean)} . */ public static enum PartialSearchMode { /** * Any partially matched key will be used as search result. */ NONE, /** * The biggest partially matched key will be used as search result. */ HIGHEST_BOUNDARY, /** * The smallest partially matched key will be used as search result. */ LOWEST_BOUNDARY } /** * Constructs a new, empty tree map, using the natural ordering of its keys. All keys inserted into the map must implement the * {@link Comparable} interface. Furthermore, all such keys must be <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not * throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> in the map. If the user attempts to put a key into * the map that violates this constraint (for example, the user attempts to put a string key into a map whose keys are integers), * the <tt>put(Object key, Object value)</tt> call will throw a <tt>ClassCastException</tt>. */ public OMVRBTree() { this(1); } public OMVRBTree(int keySize) { comparator = ODefaultComparator.INSTANCE; init(); this.keySize = keySize; } /** * Constructs a new, empty tree map, ordered according to the given comparator. All keys inserted into the map must be <i>mutually * comparable</i> by the given comparator: <tt>comparator.compare(k1, * k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> in the map. If the user attempts * to put a key into the map that violates this constraint, the <tt>put(Object * key, Object value)</tt> call will throw a <tt>ClassCastException</tt>. * * @param iComparator * the comparator that will be used to order this map. If <tt>null</tt>, the {@linkplain Comparable natural ordering} of * the keys will be used. */ public OMVRBTree(final Comparator<? super K> iComparator) { init(); this.comparator = iComparator; } /** * Constructs a new tree map containing the same mappings as the given map, ordered according to the <i>natural ordering</i> of * its keys. All keys inserted into the new map must implement the {@link Comparable} interface. Furthermore, all such keys must * be <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> * and <tt>k2</tt> in the map. This method runs in n*log(n) time. * * @param m * the map whose mappings are to be placed in this map * @throws ClassCastException * if the keys in m are not {@link Comparable}, or are not mutually comparable * @throws NullPointerException * if the specified map is null */ public OMVRBTree(final Map<? extends K, ? extends V> m) { comparator = ODefaultComparator.INSTANCE; init(); putAll(m); } /** * Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map. This method * runs in linear time. * * @param m * the sorted map whose mappings are to be placed in this map, and whose comparator is to be used to sort this map * @throws NullPointerException * if the specified map is null */ public OMVRBTree(final SortedMap<K, ? extends V> m) { init(); comparator = m.comparator(); try { buildFromSorted(m.size(), m.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } } /** * Create a new entry with the first key/value to handle. */ protected abstract OMVRBTreeEntry<K, V> createEntry(final K key, final V value); /** * Create a new node with the same parent of the node is splitting. */ protected abstract OMVRBTreeEntry<K, V> createEntry(final OMVRBTreeEntry<K, V> parent); protected abstract int getTreeSize(); public int getNodes() { int counter = -1; OMVRBTreeEntry<K, V> entry = getFirstEntry(); while (entry != null) { entry = successor(entry); counter++; } return counter; } protected abstract void setSize(int iSize); public abstract int getDefaultPageSize(); /** * Returns <tt>true</tt> if this map contains a mapping for the specified key. * * @param key * key whose presence in this map is to be tested * @return <tt>true</tt> if this map contains a mapping for the specified key * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ @Override public boolean containsKey(final Object key) { return getEntry(key, PartialSearchMode.NONE) != null; } /** * Returns <tt>true</tt> if this map maps one or more keys to the specified value. More formally, returns <tt>true</tt> if and * only if this map contains at least one mapping to a value <tt>v</tt> such that * <tt>(value==null ? v==null : value.equals(v))</tt>. This operation will probably require time linear in the map size for most * implementations. * * @param value * value whose presence in this map is to be tested * @return <tt>true</tt> if a mapping to <tt>value</tt> exists; <tt>false</tt> otherwise * @since 1.2 */ @Override public boolean containsValue(final Object value) { for (OMVRBTreeEntry<K, V> e = getFirstEntry(); e != null; e = next(e)) if (valEquals(value, e.getValue())) return true; return false; } @Override public int size() { return getTreeSize(); } /** * Returns the value to which the specified key is mapped, or {@code null} if this map contains no mapping for the key. * * <p> * More formally, if this map contains a mapping from a key {@code k} to a value {@code v} such that {@code key} compares equal to * {@code k} according to the map's ordering, then this method returns {@code v}; otherwise it returns {@code null}. (There can be * at most one such mapping.) * * <p> * A return value of {@code null} does not <i>necessarily</i> indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ @Override public V get(final Object key) { if (getTreeSize() == 0) return null; OMVRBTreeEntry<K, V> entry = null; // TRY TO GET LATEST SEARCH final OMVRBTreeEntry<K, V> node = getLastSearchNodeForSameKey(key); if (node != null) { // SAME SEARCH OF PREVIOUS ONE: REUSE LAST RESULT? if (lastSearchFound) // REUSE LAST RESULT, OTHERWISE THE KEY NOT EXISTS return node.getValue(lastSearchIndex); } else // SEARCH THE ITEM entry = getEntry(key, PartialSearchMode.NONE); return entry == null ? null : entry.getValue(); } public Comparator<? super K> comparator() { return comparator; } /** * @throws NoSuchElementException * {@inheritDoc} */ public K firstKey() { return key(getFirstEntry()); } /** * @throws NoSuchElementException * {@inheritDoc} */ public K lastKey() { return key(getLastEntry()); } /** * Copies all of the mappings from the specified map to this map. These mappings replace any mappings that this map had for any of * the keys currently in the specified map. * * @param map * mappings to be stored in this map * @throws ClassCastException * if the class of a key or value in the specified map prevents it from being stored in this map * @throws NullPointerException * if the specified map is null or the specified map contains a null key and this map does not permit null keys */ @Override public void putAll(final Map<? extends K, ? extends V> map) { int mapSize = map.size(); if (getTreeSize() == 0 && mapSize != 0 && map instanceof SortedMap) { Comparator<?> c = ((SortedMap<? extends K, ? extends V>) map).comparator(); if (c == comparator || (c != null && c.equals(comparator))) { ++modCount; try { buildFromSorted(mapSize, map.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } return; } } super.putAll(map); } /** * Returns this map's entry for the given key, or <tt>null</tt> if the map does not contain an entry for the key. * * In case of {@link OCompositeKey} keys you can specify which key can be used: lowest, highest, any. * * @param key * Key to search. * @param partialSearchMode * Which key can be used in case of {@link OCompositeKey} key is passed in. * * @return this map's entry for the given key, or <tt>null</tt> if the map does not contain an entry for the key * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ public final OMVRBTreeEntry<K, V> getEntry(final Object key, final PartialSearchMode partialSearchMode) { return getEntry(key, false, partialSearchMode); } final OMVRBTreeEntry<K, V> getEntry(final Object key, final boolean iGetContainer, final PartialSearchMode partialSearchMode) { if (key == null) return setLastSearchNode(null, null); pageItemFound = false; if (getTreeSize() == 0) { pageIndex = 0; return iGetContainer ? root : null; } final K k; if (keySize == 1) k = (K) key; else if (((OCompositeKey) key).getKeys().size() == keySize) k = (K) key; else if (partialSearchMode.equals(PartialSearchMode.NONE)) k = (K) key; else { final OCompositeKey fullKey = new OCompositeKey((Comparable<? super K>) key); int itemsToAdd = keySize - fullKey.getKeys().size(); final Comparable<?> keyItem; if (partialSearchMode.equals(PartialSearchMode.HIGHEST_BOUNDARY)) keyItem = ALWAYS_GREATER_KEY; else keyItem = ALWAYS_LESS_KEY; for (int i = 0; i < itemsToAdd; i++) fullKey.addKey(keyItem); k = (K) fullKey; } OMVRBTreeEntry<K, V> p = getBestEntryPoint(k); checkTreeStructure(p); if (p == null) return setLastSearchNode(key, null); OMVRBTreeEntry<K, V> lastNode = p; OMVRBTreeEntry<K, V> prevNode = null; OMVRBTreeEntry<K, V> tmpNode; int beginKey = -1; try { while (p != null && p.getSize() > 0) { searchNodeCallback(); lastNode = p; beginKey = compare(k, p.getFirstKey()); if (beginKey == 0) { // EXACT MATCH, YOU'RE VERY LUCKY: RETURN THE FIRST KEY WITHOUT SEARCH INSIDE THE NODE pageIndex = 0; pageItemFound = true; pageItemComparator = 0; return setLastSearchNode(key, p); } pageItemComparator = compare(k, p.getLastKey()); if (beginKey < 0) { if (pageItemComparator < 0) { tmpNode = predecessor(p); if (tmpNode != null && tmpNode != prevNode) { // MINOR THAN THE CURRENT: GET THE LEFT NODE prevNode = p; p = tmpNode; continue; } } } else if (beginKey > 0) { if (pageItemComparator > 0) { tmpNode = successor(p); if (tmpNode != null && tmpNode != prevNode) { // MAJOR THAN THE CURRENT: GET THE RIGHT NODE prevNode = p; p = tmpNode; continue; } } } // SEARCH INSIDE THE NODE final V value = lastNode.search(k); // PROBABLY PARTIAL KEY IS FOUND USE SEARCH MODE TO FIND PREFERRED ONE if (key instanceof OCompositeKey) { final OCompositeKey compositeKey = (OCompositeKey) key; if (value != null && compositeKey.getKeys().size() == keySize) { return setLastSearchNode(key, lastNode); } if (partialSearchMode.equals(PartialSearchMode.NONE)) { if (value != null || iGetContainer) return lastNode; else return null; } if (partialSearchMode.equals(PartialSearchMode.HIGHEST_BOUNDARY)) { // FOUNDED ENTRY EITHER GREATER THAN EXISTING ITEM OR ITEM DOES NOT EXIST return adjustHighestPartialSearchResult(iGetContainer, lastNode, compositeKey); } if (partialSearchMode.equals(PartialSearchMode.LOWEST_BOUNDARY)) { return adjustLowestPartialSearchResult(iGetContainer, lastNode, compositeKey); } } if (value != null) { setLastSearchNode(key, lastNode); } if (value != null || iGetContainer) // FOUND: RETURN CURRENT NODE OR AT LEAST THE CONTAINER NODE return lastNode; // NOT FOUND return null; } } finally { checkTreeStructure(p); } return setLastSearchNode(key, null); } private OMVRBTreeEntry<K, V> adjustHighestPartialSearchResult(final boolean iGetContainer, final OMVRBTreeEntry<K, V> lastNode, final OCompositeKey compositeKey) { final int oldPageIndex = pageIndex; final OMVRBTreeEntry<K, V> prevNd = previous(lastNode); if (prevNd == null) { pageIndex = oldPageIndex; pageItemFound = false; if (iGetContainer) return lastNode; return null; } pageItemComparator = compare(prevNd.getKey(), compositeKey); if (pageItemComparator == 0) { pageItemFound = true; return prevNd; } else if (pageItemComparator > 1) { pageItemFound = false; if (iGetContainer) return prevNd; return null; } else { pageIndex = oldPageIndex; pageItemFound = false; if (iGetContainer) return lastNode; return null; } } private OMVRBTreeEntry<K, V> adjustLowestPartialSearchResult(final boolean iGetContainer, OMVRBTreeEntry<K, V> lastNode, final OCompositeKey compositeKey) { // RARE CASE WHEN NODE ITSELF DOES CONTAIN KEY, BUT ALL KEYS LESS THAN GIVEN ONE final int oldPageIndex = pageIndex; final OMVRBTreeEntry<K, V> oldNode = lastNode; if (pageIndex >= lastNode.getSize()) { lastNode = next(lastNode); if (lastNode == null) { lastNode = oldNode; pageIndex = oldPageIndex; pageItemFound = false; if (iGetContainer) return lastNode; return null; } } pageItemComparator = compare(lastNode.getKey(), compositeKey); if (pageItemComparator == 0) { pageItemFound = true; return lastNode; } else { pageItemFound = false; if (iGetContainer) return lastNode; return null; } } /** * Basic implementation that returns the root node. */ protected OMVRBTreeEntry<K, V> getBestEntryPoint(final K key) { return root; } /** * Gets the entry corresponding to the specified key; if no such entry exists, returns the entry for the least key greater than * the specified key; if no such entry exists (i.e., the greatest key in the Tree is less than the specified key), returns * <tt>null</tt>. * * @param key * Key to search. * @param partialSearchMode * In case of {@link OCompositeKey} key is passed in this parameter will be used to find preferred one. */ public OMVRBTreeEntry<K, V> getCeilingEntry(final K key, final PartialSearchMode partialSearchMode) { OMVRBTreeEntry<K, V> p = getEntry(key, true, partialSearchMode); if (p == null) return null; if (pageItemFound) return p; // NOT MATCHED, POSITION IS ALREADY TO THE NEXT ONE else if (pageIndex < p.getSize()) { if (key instanceof OCompositeKey) return adjustSearchResult((OCompositeKey) key, partialSearchMode, p); else return p; } return null; } /** * Gets the entry corresponding to the specified key; if no such entry exists, returns the entry for the greatest key less than * the specified key; if no such entry exists, returns <tt>null</tt>. * * @param key * Key to search. * @param partialSearchMode * In case of {@link OCompositeKey} composite key is passed in this parameter will be used to find preferred one. */ public OMVRBTreeEntry<K, V> getFloorEntry(final K key, final PartialSearchMode partialSearchMode) { OMVRBTreeEntry<K, V> p = getEntry(key, true, partialSearchMode); if (p == null) return null; if (pageItemFound) return p; final OMVRBTreeEntry<K, V> adjacentEntry = previous(p); if (adjacentEntry == null) return null; if (key instanceof OCompositeKey) { return adjustSearchResult((OCompositeKey) key, partialSearchMode, adjacentEntry); } return adjacentEntry; } private OMVRBTreeEntry<K, V> adjustSearchResult(final OCompositeKey key, final PartialSearchMode partialSearchMode, final OMVRBTreeEntry<K, V> foundEntry) { if (partialSearchMode.equals(PartialSearchMode.NONE)) return foundEntry; final OCompositeKey keyToSearch = key; final OCompositeKey foundKey = (OCompositeKey) foundEntry.getKey(); if (keyToSearch.getKeys().size() < keySize) { final OCompositeKey borderKey = new OCompositeKey(); final OCompositeKey keyToCompare = new OCompositeKey(); final List<Object> keyItems = foundKey.getKeys(); for (int i = 0; i < keySize - 1; i++) { final Object keyItem = keyItems.get(i); borderKey.addKey(keyItem); if (i < keyToSearch.getKeys().size()) keyToCompare.addKey(keyItem); } if (partialSearchMode.equals(PartialSearchMode.HIGHEST_BOUNDARY)) borderKey.addKey(ALWAYS_GREATER_KEY); else borderKey.addKey(ALWAYS_LESS_KEY); final OMVRBTreeEntry<K, V> adjustedNode = getEntry(borderKey, true, PartialSearchMode.NONE); if (partialSearchMode.equals(PartialSearchMode.HIGHEST_BOUNDARY)) return adjustHighestPartialSearchResult(false, adjustedNode, keyToCompare); else return adjustLowestPartialSearchResult(false, adjustedNode, keyToCompare); } return foundEntry; } /** * Gets the entry for the least key greater than the specified key; if no such entry exists, returns the entry for the least key * greater than the specified key; if no such entry exists returns <tt>null</tt>. */ public OMVRBTreeEntry<K, V> getHigherEntry(final K key) { final OMVRBTreeEntry<K, V> p = getEntry(key, true, PartialSearchMode.HIGHEST_BOUNDARY); if (p == null) return null; if (pageItemFound) // MATCH, RETURN THE NEXT ONE return next(p); else if (pageIndex < p.getSize()) // NOT MATCHED, POSITION IS ALREADY TO THE NEXT ONE return p; return null; } /** * Returns the entry for the greatest key less than the specified key; if no such entry exists (i.e., the least key in the Tree is * greater than the specified key), returns <tt>null</tt>. */ public OMVRBTreeEntry<K, V> getLowerEntry(final K key) { final OMVRBTreeEntry<K, V> p = getEntry(key, true, PartialSearchMode.LOWEST_BOUNDARY); if (p == null) return null; return previous(p); } /** * Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the * old value is replaced. * * @param key * key with which the specified value is to be associated * @param value * value to be associated with the specified key * * @return the previous value associated with <tt>key</tt>, or <tt>null</tt> if there was no mapping for <tt>key</tt>. (A * <tt>null</tt> return can also indicate that the map previously associated <tt>null</tt> with <tt>key</tt>.) * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ @Override public V put(final K key, final V value) { OMVRBTreeEntry<K, V> parentNode = null; try { if (root == null) { root = createEntry(key, value); root.setColor(BLACK); setSize(1); modCount++; return null; } // TRY TO GET LATEST SEARCH parentNode = getLastSearchNodeForSameKey(key); if (parentNode != null) { if (lastSearchFound) { // EXACT MATCH: UPDATE THE VALUE pageIndex = lastSearchIndex; modCount++; return parentNode.setValue(value); } } // SEARCH THE ITEM parentNode = getEntry(key, true, PartialSearchMode.NONE); if (pageItemFound) { modCount++; // EXACT MATCH: UPDATE THE VALUE return parentNode.setValue(value); } setLastSearchNode(null, null); if (parentNode == null) { parentNode = root; pageIndex = 0; } if (parentNode.getFreeSpace() > 0) { // INSERT INTO THE PAGE parentNode.insert(pageIndex, key, value); } else { // CREATE NEW NODE AND COPY HALF OF VALUES FROM THE ORIGIN TO THE NEW ONE IN ORDER TO GET VALUES BALANCED final OMVRBTreeEntry<K, V> newNode = createEntry(parentNode); if (pageIndex < parentNode.getPageSplitItems()) // INSERT IN THE ORIGINAL NODE parentNode.insert(pageIndex, key, value); else // INSERT IN THE NEW NODE newNode.insert(pageIndex - parentNode.getPageSplitItems(), key, value); OMVRBTreeEntry<K, V> node = parentNode.getRight(); OMVRBTreeEntry<K, V> prevNode = parentNode; int cmp = 0; final K fk = newNode.getFirstKey(); if (comparator != null) while (node != null) { cmp = comparator.compare(fk, node.getFirstKey()); if (cmp < 0) { prevNode = node; node = node.getLeft(); } else if (cmp > 0) { prevNode = node; node = node.getRight(); } else { throw new IllegalStateException("Duplicated keys were found in OMVRBTree."); } } else while (node != null) { cmp = compare(fk, node.getFirstKey()); if (cmp < 0) { prevNode = node; node = node.getLeft(); } else if (cmp > 0) { prevNode = node; node = node.getRight(); } else { throw new IllegalStateException("Duplicated keys were found in OMVRBTree."); } } if (prevNode == parentNode) parentNode.setRight(newNode); else if (cmp < 0) prevNode.setLeft(newNode); else if (cmp > 0) prevNode.setRight(newNode); else throw new IllegalStateException("Duplicated keys were found in OMVRBTree."); fixAfterInsertion(newNode); } modCount++; setSizeDelta(+1); } finally { checkTreeStructure(parentNode); } return null; } /** * Removes the mapping for this key from this OMVRBTree if present. * * @param key * key for which mapping should be removed * @return the previous value associated with <tt>key</tt>, or <tt>null</tt> if there was no mapping for <tt>key</tt>. (A * <tt>null</tt> return can also indicate that the map previously associated <tt>null</tt> with <tt>key</tt>.) * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ @Override public V remove(final Object key) { OMVRBTreeEntry<K, V> p = getEntry(key, PartialSearchMode.NONE); setLastSearchNode(null, null); if (p == null) return null; V oldValue = p.getValue(); deleteEntry(p); return oldValue; } /** * Removes all of the mappings from this map. The map will be empty after this call returns. */ @Override public void clear() { modCount++; setSize(0); setLastSearchNode(null, null); setRoot(null); } /** * Returns a shallow copy of this <tt>OMVRBTree</tt> instance. (The keys and values themselves are not cloned.) * * @return a shallow copy of this map */ @Override public Object clone() { OMVRBTree<K, V> clone = null; try { clone = (OMVRBTree<K, V>) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } // Put clone into "virgin" state (except for comparator) clone.pageIndex = pageIndex; clone.pageItemFound = pageItemFound; clone.pageLoadFactor = pageLoadFactor; clone.root = null; clone.setSize(0); clone.modCount = 0; clone.entrySet = null; clone.navigableKeySet = null; clone.descendingMap = null; // Initialize clone with our mappings try { clone.buildFromSorted(getTreeSize(), entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } return clone; } // ONavigableMap API methods /** * @since 1.6 */ public Map.Entry<K, V> firstEntry() { return exportEntry(getFirstEntry()); } /** * @since 1.6 */ public Map.Entry<K, V> lastEntry() { return exportEntry(getLastEntry()); } /** * @since 1.6 */ public Entry<K, V> pollFirstEntry() { OMVRBTreeEntry<K, V> p = getFirstEntry(); Map.Entry<K, V> result = exportEntry(p); if (p != null) deleteEntry(p); return result; } /** * @since 1.6 */ public Entry<K, V> pollLastEntry() { OMVRBTreeEntry<K, V> p = getLastEntry(); Map.Entry<K, V> result = exportEntry(p); if (p != null) deleteEntry(p); return result; } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public Map.Entry<K, V> lowerEntry(final K key) { return exportEntry(getLowerEntry(key)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public K lowerKey(final K key) { return keyOrNull(getLowerEntry(key)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public Map.Entry<K, V> floorEntry(final K key) { return exportEntry(getFloorEntry(key, PartialSearchMode.NONE)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public K floorKey(final K key) { return keyOrNull(getFloorEntry(key, PartialSearchMode.NONE)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public Map.Entry<K, V> ceilingEntry(final K key) { return exportEntry(getCeilingEntry(key, PartialSearchMode.NONE)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public K ceilingKey(final K key) { return keyOrNull(getCeilingEntry(key, PartialSearchMode.NONE)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public Map.Entry<K, V> higherEntry(final K key) { return exportEntry(getHigherEntry(key)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public K higherKey(final K key) { return keyOrNull(getHigherEntry(key)); } // Views /** * Fields initialized to contain an instance of the entry set view the first time this view is requested. Views are stateless, so * there's no reason to create more than one. */ private transient EntrySet entrySet = null; private transient KeySet<K> navigableKeySet = null; private transient ONavigableMap<K, V> descendingMap = null; /** * Returns a {@link Set} view of the keys contained in this map. The set's iterator returns the keys in ascending order. The set * is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration * over the set is in progress (except through the iterator's own <tt>remove</tt> operation), the results of the iteration are * undefined. The set supports element removal, which removes the corresponding mapping from the map, via the * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations. It does * not support the <tt>add</tt> or <tt>addAll</tt> operations. */ @Override public Set<K> keySet() { return navigableKeySet(); } /** * @since 1.6 */ public ONavigableSet<K> navigableKeySet() { final KeySet<K> nks = navigableKeySet; return (nks != null) ? nks : (navigableKeySet = (KeySet<K>) new KeySet<Object>((ONavigableMap<Object, Object>) this)); } /** * @since 1.6 */ public ONavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } /** * Returns a {@link Collection} view of the values contained in this map. The collection's iterator returns the values in * ascending order of the corresponding keys. The collection is backed by the map, so changes to the map are reflected in the * collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the * iterator's own <tt>remove</tt> operation), the results of the iteration are undefined. The collection supports element removal, * which removes the corresponding mapping from the map, via the <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> operations. It does not support the <tt>add</tt> or <tt>addAll</tt> * operations. */ @Override public Collection<V> values() { final Collection<V> vs = new Values(); return (vs != null) ? vs : null; } /** * Returns a {@link Set} view of the mappings contained in this map. The set's iterator returns the entries in ascending key * order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified * while an iteration over the set is in progress (except through the iterator's own <tt>remove</tt> operation, or through the * <tt>setValue</tt> operation on a map entry returned by the iterator) the results of the iteration are undefined. The set * supports element removal, which removes the corresponding mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> operations. It does not support the <tt>add</tt> * or <tt>addAll</tt> operations. */ @Override public Set<Map.Entry<K, V>> entrySet() { final EntrySet es = entrySet; return (es != null) ? es : (entrySet = new EntrySet()); } /** * @since 1.6 */ public ONavigableMap<K, V> descendingMap() { final ONavigableMap<K, V> km = descendingMap; return (km != null) ? km : (descendingMap = new DescendingSubMap<K, V>(this, true, null, true, true, null, true)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if <tt>fromKey</tt> or <tt>toKey</tt> is null and this map uses natural ordering, or its comparator does not permit * null keys * @throws IllegalArgumentException * {@inheritDoc} * @since 1.6 */ public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) { return new AscendingSubMap<K, V>(this, false, fromKey, fromInclusive, false, toKey, toInclusive); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if <tt>toKey</tt> is null and this map uses natural ordering, or its comparator does not permit null keys * @throws IllegalArgumentException * {@inheritDoc} * @since 1.6 */ public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) { return new AscendingSubMap<K, V>(this, true, null, true, false, toKey, inclusive); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if <tt>fromKey</tt> is null and this map uses natural ordering, or its comparator does not permit null keys * @throws IllegalArgumentException * {@inheritDoc} * @since 1.6 */ public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) { return new AscendingSubMap<K, V>(this, false, fromKey, inclusive, true, null, true); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if <tt>fromKey</tt> or <tt>toKey</tt> is null and this map uses natural ordering, or its comparator does not permit * null keys * @throws IllegalArgumentException * {@inheritDoc} */ public SortedMap<K, V> subMap(final K fromKey, final K toKey) { return subMap(fromKey, true, toKey, false); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if <tt>toKey</tt> is null and this map uses natural ordering, or its comparator does not permit null keys * @throws IllegalArgumentException * {@inheritDoc} */ public SortedMap<K, V> headMap(final K toKey) { return headMap(toKey, false); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if <tt>fromKey</tt> is null and this map uses natural ordering, or its comparator does not permit null keys * @throws IllegalArgumentException * {@inheritDoc} */ public SortedMap<K, V> tailMap(final K fromKey) { return tailMap(fromKey, true); } // View class support public class Values extends AbstractCollection<V> { @Override public Iterator<V> iterator() { return new ValueIterator(getFirstEntry()); } public Iterator<V> inverseIterator() { return new ValueInverseIterator(getLastEntry()); } @Override public int size() { return OMVRBTree.this.size(); } @Override public boolean contains(final Object o) { return OMVRBTree.this.containsValue(o); } @Override public boolean remove(final Object o) { for (OMVRBTreeEntry<K, V> e = getFirstEntry(); e != null; e = next(e)) { if (valEquals(e.getValue(), o)) { deleteEntry(e); return true; } } return false; } @Override public void clear() { OMVRBTree.this.clear(); } } public class EntrySet extends AbstractSet<Map.Entry<K, V>> { @Override public Iterator<Map.Entry<K, V>> iterator() { return new EntryIterator(getFirstEntry()); } public Iterator<Map.Entry<K, V>> inverseIterator() { return new InverseEntryIterator(getLastEntry()); } @Override public boolean contains(final Object o) { if (!(o instanceof Map.Entry)) return false; OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final V value = entry.getValue(); final V p = get(entry.getKey()); return p != null && valEquals(p, value); } @Override public boolean remove(final Object o) { if (!(o instanceof Map.Entry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final V value = entry.getValue(); OMVRBTreeEntry<K, V> p = getEntry(entry.getKey(), PartialSearchMode.NONE); if (p != null && valEquals(p.getValue(), value)) { deleteEntry(p); return true; } return false; } @Override public int size() { return OMVRBTree.this.size(); } @Override public void clear() { OMVRBTree.this.clear(); } } /* * Unlike Values and EntrySet, the KeySet class is static, delegating to a ONavigableMap to allow use by SubMaps, which outweighs * the ugliness of needing type-tests for the following Iterator methods that are defined appropriately in main versus submap * classes. */ OLazyIterator<K> keyIterator() { return new KeyIterator(getFirstEntry()); } OLazyIterator<K> descendingKeyIterator() { return new DescendingKeyIterator(getLastEntry()); } @SuppressWarnings("rawtypes") static final class KeySet<E> extends AbstractSet<E> implements ONavigableSet<E> { private final ONavigableMap<E, Object> m; KeySet(ONavigableMap<E, Object> map) { m = map; } @Override public OLazyIterator<E> iterator() { if (m instanceof OMVRBTree) return ((OMVRBTree<E, Object>) m).keyIterator(); else return (((OMVRBTree.NavigableSubMap) m).keyIterator()); } public OLazyIterator<E> descendingIterator() { if (m instanceof OMVRBTree) return ((OMVRBTree<E, Object>) m).descendingKeyIterator(); else return (((OMVRBTree.NavigableSubMap) m).descendingKeyIterator()); } @Override public int size() { return m.size(); } @Override public boolean isEmpty() { return m.isEmpty(); } @Override public boolean contains(final Object o) { return m.containsKey(o); } @Override public void clear() { m.clear(); } public E lower(final E e) { return m.lowerKey(e); } public E floor(final E e) { return m.floorKey(e); } public E ceiling(final E e) { return m.ceilingKey(e); } public E higher(final E e) { return m.higherKey(e); } public E first() { return m.firstKey(); } public E last() { return m.lastKey(); } public Comparator<? super E> comparator() { return m.comparator(); } public E pollFirst() { final Map.Entry<E, Object> e = m.pollFirstEntry(); return e == null ? null : e.getKey(); } public E pollLast() { final Map.Entry<E, Object> e = m.pollLastEntry(); return e == null ? null : e.getKey(); } @Override public boolean remove(final Object o) { final int oldSize = size(); m.remove(o); return size() != oldSize; } public ONavigableSet<E> subSet(final E fromElement, final boolean fromInclusive, final E toElement, final boolean toInclusive) { return new OMVRBTreeSet<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive)); } public ONavigableSet<E> headSet(final E toElement, final boolean inclusive) { return new OMVRBTreeSet<E>(m.headMap(toElement, inclusive)); } public ONavigableSet<E> tailSet(final E fromElement, final boolean inclusive) { return new OMVRBTreeSet<E>(m.tailMap(fromElement, inclusive)); } public SortedSet<E> subSet(final E fromElement, final E toElement) { return subSet(fromElement, true, toElement, false); } public SortedSet<E> headSet(final E toElement) { return headSet(toElement, false); } public SortedSet<E> tailSet(final E fromElement) { return tailSet(fromElement, true); } public ONavigableSet<E> descendingSet() { return new OMVRBTreeSet<E>(m.descendingMap()); } } final class EntryIterator extends AbstractEntryIterator<K, V, Map.Entry<K, V>> { EntryIterator(final OMVRBTreeEntry<K, V> first) { super(first); } public Map.Entry<K, V> next() { return nextEntry(); } } final class InverseEntryIterator extends AbstractEntryIterator<K, V, Map.Entry<K, V>> { InverseEntryIterator(final OMVRBTreeEntry<K, V> last) { super(last); // we have to set ourselves after current index to make iterator work if (last != null) { pageIndex = last.getTree().getPageIndex() + 1; } } public Map.Entry<K, V> next() { return prevEntry(); } } final class ValueIterator extends AbstractEntryIterator<K, V, V> { ValueIterator(final OMVRBTreeEntry<K, V> first) { super(first); } @Override public V next() { return nextValue(); } } final class ValueInverseIterator extends AbstractEntryIterator<K, V, V> { ValueInverseIterator(final OMVRBTreeEntry<K, V> last) { super(last); // we have to set ourselves after current index to make iterator work if (last != null) { pageIndex = last.getTree().getPageIndex() + 1; } } @Override public boolean hasNext() { return hasPrevious(); } @Override public V next() { return prevValue(); } } final class KeyIterator extends AbstractEntryIterator<K, V, K> { KeyIterator(final OMVRBTreeEntry<K, V> first) { super(first); } @Override public K next() { return nextKey(); } } final class DescendingKeyIterator extends AbstractEntryIterator<K, V, K> { DescendingKeyIterator(final OMVRBTreeEntry<K, V> first) { super(first); } public K next() { return prevEntry().getKey(); } } // Little utilities /** * Compares two keys using the correct comparison method for this OMVRBTree. */ final int compare(final Object k1, final Object k2) { return comparator == null ? ((Comparable<? super K>) k1).compareTo((K) k2) : comparator.compare((K) k1, (K) k2); } /** * Test two values for equality. Differs from o1.equals(o2) only in that it copes with <tt>null</tt> o1 properly. */ final static boolean valEquals(final Object o1, final Object o2) { return (o1 == null ? o2 == null : o1.equals(o2)); } /** * Return SimpleImmutableEntry for entry, or null if null */ static <K, V> Map.Entry<K, V> exportEntry(final OMVRBTreeEntry<K, V> omvrbTreeEntryPosition) { return omvrbTreeEntryPosition == null ? null : new OSimpleImmutableEntry<K, V>(omvrbTreeEntryPosition); } /** * Return SimpleImmutableEntry for entry, or null if null */ static <K, V> Map.Entry<K, V> exportEntry(final OMVRBTreeEntryPosition<K, V> omvrbTreeEntryPosition) { return omvrbTreeEntryPosition == null ? null : new OSimpleImmutableEntry<K, V>(omvrbTreeEntryPosition.entry); } /** * Return key for entry, or null if null */ static <K, V> K keyOrNull(final OMVRBTreeEntry<K, V> e) { return e == null ? null : e.getKey(); } /** * Return key for entry, or null if null */ static <K, V> K keyOrNull(OMVRBTreeEntryPosition<K, V> e) { return e == null ? null : e.getKey(); } /** * Returns the key corresponding to the specified Entry. * * @throws NoSuchElementException * if the Entry is null */ static <K> K key(OMVRBTreeEntry<K, ?> e) { if (e == null) throw new NoSuchElementException(); return e.getKey(); } // SubMaps /** * @serial include */ static abstract class NavigableSubMap<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, java.io.Serializable { /** * The backing map. */ final OMVRBTree<K, V> m; /** * Endpoints are represented as triples (fromStart, lo, loInclusive) and (toEnd, hi, hiInclusive). If fromStart is true, then * the low (absolute) bound is the start of the backing map, and the other values are ignored. Otherwise, if loInclusive is * true, lo is the inclusive bound, else lo is the exclusive bound. Similarly for the upper bound. */ final K lo, hi; final boolean fromStart, toEnd; final boolean loInclusive, hiInclusive; NavigableSubMap(final OMVRBTree<K, V> m, final boolean fromStart, K lo, final boolean loInclusive, final boolean toEnd, K hi, final boolean hiInclusive) { if (!fromStart && !toEnd) { if (m.compare(lo, hi) > 0) throw new IllegalArgumentException("fromKey > toKey"); } else { if (!fromStart) // type check m.compare(lo, lo); if (!toEnd) m.compare(hi, hi); } this.m = m; this.fromStart = fromStart; this.lo = lo; this.loInclusive = loInclusive; this.toEnd = toEnd; this.hi = hi; this.hiInclusive = hiInclusive; } // internal utilities final boolean tooLow(final Object key) { if (!fromStart) { int c = m.compare(key, lo); if (c < 0 || (c == 0 && !loInclusive)) return true; } return false; } final boolean tooHigh(final Object key) { if (!toEnd) { int c = m.compare(key, hi); if (c > 0 || (c == 0 && !hiInclusive)) return true; } return false; } final boolean inRange(final Object key) { return !tooLow(key) && !tooHigh(key); } final boolean inClosedRange(final Object key) { return (fromStart || m.compare(key, lo) >= 0) && (toEnd || m.compare(hi, key) >= 0); } final boolean inRange(final Object key, final boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } /* * Absolute versions of relation operations. Subclasses map to these using like-named "sub" versions that invert senses for * descending maps */ final OMVRBTreeEntryPosition<K, V> absLowest() { OMVRBTreeEntry<K, V> e = (fromStart ? m.getFirstEntry() : (loInclusive ? m.getCeilingEntry(lo, PartialSearchMode.LOWEST_BOUNDARY) : m.getHigherEntry(lo))); return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absHighest() { OMVRBTreeEntry<K, V> e = (toEnd ? m.getLastEntry() : (hiInclusive ? m.getFloorEntry(hi, PartialSearchMode.HIGHEST_BOUNDARY) : m.getLowerEntry(hi))); return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absCeiling(K key) { if (tooLow(key)) return absLowest(); OMVRBTreeEntry<K, V> e = m.getCeilingEntry(key, PartialSearchMode.NONE); return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absHigher(K key) { if (tooLow(key)) return absLowest(); OMVRBTreeEntry<K, V> e = m.getHigherEntry(key); return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absFloor(K key) { if (tooHigh(key)) return absHighest(); OMVRBTreeEntry<K, V> e = m.getFloorEntry(key, PartialSearchMode.NONE); return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absLower(K key) { if (tooHigh(key)) return absHighest(); OMVRBTreeEntry<K, V> e = m.getLowerEntry(key); return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } /** Returns the absolute high fence for ascending traversal */ final OMVRBTreeEntryPosition<K, V> absHighFence() { return (toEnd ? null : new OMVRBTreeEntryPosition<K, V>(hiInclusive ? m.getHigherEntry(hi) : m.getCeilingEntry(hi, PartialSearchMode.LOWEST_BOUNDARY))); } /** Return the absolute low fence for descending traversal */ final OMVRBTreeEntryPosition<K, V> absLowFence() { return (fromStart ? null : new OMVRBTreeEntryPosition<K, V>(loInclusive ? m.getLowerEntry(lo) : m.getFloorEntry(lo, PartialSearchMode.HIGHEST_BOUNDARY))); } // Abstract methods defined in ascending vs descending classes // These relay to the appropriate absolute versions abstract OMVRBTreeEntry<K, V> subLowest(); abstract OMVRBTreeEntry<K, V> subHighest(); abstract OMVRBTreeEntry<K, V> subCeiling(K key); abstract OMVRBTreeEntry<K, V> subHigher(K key); abstract OMVRBTreeEntry<K, V> subFloor(K key); abstract OMVRBTreeEntry<K, V> subLower(K key); /** Returns ascending iterator from the perspective of this submap */ abstract OLazyIterator<K> keyIterator(); /** Returns descending iterator from the perspective of this submap */ abstract OLazyIterator<K> descendingKeyIterator(); // public methods @Override public boolean isEmpty() { return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty(); } @Override public int size() { return (fromStart && toEnd) ? m.size() : entrySet().size(); } @Override public final boolean containsKey(Object key) { return inRange(key) && m.containsKey(key); } @Override public final V put(K key, V value) { if (!inRange(key)) throw new IllegalArgumentException("key out of range"); return m.put(key, value); } @Override public final V get(Object key) { return !inRange(key) ? null : m.get(key); } @Override public final V remove(Object key) { return !inRange(key) ? null : m.remove(key); } public final Map.Entry<K, V> ceilingEntry(K key) { return exportEntry(subCeiling(key)); } public final K ceilingKey(K key) { return keyOrNull(subCeiling(key)); } public final Map.Entry<K, V> higherEntry(K key) { return exportEntry(subHigher(key)); } public final K higherKey(K key) { return keyOrNull(subHigher(key)); } public final Map.Entry<K, V> floorEntry(K key) { return exportEntry(subFloor(key)); } public final K floorKey(K key) { return keyOrNull(subFloor(key)); } public final Map.Entry<K, V> lowerEntry(K key) { return exportEntry(subLower(key)); } public final K lowerKey(K key) { return keyOrNull(subLower(key)); } public final K firstKey() { return key(subLowest()); } public final K lastKey() { return key(subHighest()); } public final Map.Entry<K, V> firstEntry() { return exportEntry(subLowest()); } public final Map.Entry<K, V> lastEntry() { return exportEntry(subHighest()); } public final Map.Entry<K, V> pollFirstEntry() { OMVRBTreeEntry<K, V> e = subLowest(); Map.Entry<K, V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } public final Map.Entry<K, V> pollLastEntry() { OMVRBTreeEntry<K, V> e = subHighest(); Map.Entry<K, V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } // Views transient ONavigableMap<K, V> descendingMapView = null; transient EntrySetView entrySetView = null; transient KeySet<K> navigableKeySetView = null; @SuppressWarnings("rawtypes") public final ONavigableSet<K> navigableKeySet() { KeySet<K> nksv = navigableKeySetView; return (nksv != null) ? nksv : (navigableKeySetView = new OMVRBTree.KeySet(this)); } @Override public final Set<K> keySet() { return navigableKeySet(); } public ONavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } public final SortedMap<K, V> subMap(final K fromKey, final K toKey) { return subMap(fromKey, true, toKey, false); } public final SortedMap<K, V> headMap(final K toKey) { return headMap(toKey, false); } public final SortedMap<K, V> tailMap(final K fromKey) { return tailMap(fromKey, true); } // View classes abstract class EntrySetView extends AbstractSet<Map.Entry<K, V>> { private transient int size = -1, sizeModCount; @Override public int size() { if (fromStart && toEnd) return m.size(); if (size == -1 || sizeModCount != m.modCount) { sizeModCount = m.modCount; size = 0; Iterator<?> i = iterator(); while (i.hasNext()) { size++; i.next(); } } return size; } @Override public boolean isEmpty() { OMVRBTreeEntryPosition<K, V> n = absLowest(); return n == null || tooHigh(n.getKey()); } @Override public boolean contains(final Object o) { if (!(o instanceof OMVRBTreeEntry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final K key = entry.getKey(); if (!inRange(key)) return false; V nodeValue = m.get(key); return nodeValue != null && valEquals(nodeValue, entry.getValue()); } @Override public boolean remove(final Object o) { if (!(o instanceof OMVRBTreeEntry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final K key = entry.getKey(); if (!inRange(key)) return false; final OMVRBTreeEntry<K, V> node = m.getEntry(key, PartialSearchMode.NONE); if (node != null && valEquals(node.getValue(), entry.getValue())) { m.deleteEntry(node); return true; } return false; } } /** * Iterators for SubMaps */ abstract class SubMapIterator<T> implements OLazyIterator<T> { OMVRBTreeEntryPosition<K, V> lastReturned; OMVRBTreeEntryPosition<K, V> next; final K fenceKey; int expectedModCount; SubMapIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { expectedModCount = m.modCount; lastReturned = null; next = first; fenceKey = fence == null ? null : fence.getKey(); } public final boolean hasNext() { if (next != null) { final K k = next.getKey(); return k != fenceKey && !k.equals(fenceKey); } return false; } final OMVRBTreeEntryPosition<K, V> nextEntry() { final OMVRBTreeEntryPosition<K, V> e; if (next != null) e = new OMVRBTreeEntryPosition<K, V>(next); else e = null; if (e == null || e.entry == null) throw new NoSuchElementException(); final K k = e.getKey(); if (k == fenceKey || k.equals(fenceKey)) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next.assign(OMVRBTree.next(e)); lastReturned = e; return e; } final OMVRBTreeEntryPosition<K, V> prevEntry() { final OMVRBTreeEntryPosition<K, V> e; if (next != null) e = new OMVRBTreeEntryPosition<K, V>(next); else e = null; if (e == null || e.entry == null) throw new NoSuchElementException(); final K k = e.getKey(); if (k == fenceKey || k.equals(fenceKey)) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next.assign(OMVRBTree.previous(e)); lastReturned = e; return e; } final public T update(final T iValue) { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); return (T) lastReturned.entry.setValue((V) iValue); } final void removeAscending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); // deleted entries are replaced by their successors if (lastReturned.entry.getLeft() != null && lastReturned.entry.getRight() != null) next = lastReturned; m.deleteEntry(lastReturned.entry); lastReturned = null; expectedModCount = m.modCount; } final void removeDescending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); m.deleteEntry(lastReturned.entry); lastReturned = null; expectedModCount = m.modCount; } } final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> { SubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { super(first, fence); } public Map.Entry<K, V> next() { final Map.Entry<K, V> e = OMVRBTree.exportEntry(next); nextEntry(); return e; } public void remove() { removeAscending(); } } final class SubMapKeyIterator extends SubMapIterator<K> { SubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { super(first, fence); } public K next() { return nextEntry().getKey(); } public void remove() { removeAscending(); } } final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> { DescendingSubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) { super(last, fence); } public Map.Entry<K, V> next() { final Map.Entry<K, V> e = OMVRBTree.exportEntry(next); prevEntry(); return e; } public void remove() { removeDescending(); } } final class DescendingSubMapKeyIterator extends SubMapIterator<K> { DescendingSubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) { super(last, fence); } public K next() { return prevEntry().getKey(); } public void remove() { removeDescending(); } } } /** * @serial include */ static final class AscendingSubMap<K, V> extends NavigableSubMap<K, V> { private static final long serialVersionUID = 912986545866124060L; AscendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd, K hi, final boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } public Comparator<? super K> comparator() { return m.comparator(); } public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new AscendingSubMap<K, V>(m, false, fromKey, fromInclusive, false, toKey, toInclusive); } public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, toKey, inclusive); } public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) { if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new AscendingSubMap<K, V>(m, false, fromKey, inclusive, toEnd, hi, hiInclusive); } public ONavigableMap<K, V> descendingMap() { ONavigableMap<K, V> mv = descendingMapView; return (mv != null) ? mv : (descendingMapView = new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive)); } @Override OLazyIterator<K> keyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } @Override OLazyIterator<K> descendingKeyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } final class AscendingEntrySetView extends EntrySetView { @Override public Iterator<Map.Entry<K, V>> iterator() { return new SubMapEntryIterator(absLowest(), absHighFence()); } } @Override public Set<Map.Entry<K, V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : new AscendingEntrySetView(); } @Override OMVRBTreeEntry<K, V> subLowest() { return absLowest().entry; } @Override OMVRBTreeEntry<K, V> subHighest() { return absHighest().entry; } @Override OMVRBTreeEntry<K, V> subCeiling(final K key) { return absCeiling(key).entry; } @Override OMVRBTreeEntry<K, V> subHigher(final K key) { return absHigher(key).entry; } @Override OMVRBTreeEntry<K, V> subFloor(final K key) { return absFloor(key).entry; } @Override OMVRBTreeEntry<K, V> subLower(final K key) { return absLower(key).entry; } } /** * @serial include */ static final class DescendingSubMap<K, V> extends NavigableSubMap<K, V> { private static final long serialVersionUID = 912986545866120460L; private final Comparator<? super K> reverseComparator = Collections.reverseOrder(m.comparator); DescendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd, final K hi, final boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } public Comparator<? super K> comparator() { return reverseComparator; } public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap<K, V>(m, false, toKey, toInclusive, false, fromKey, fromInclusive); } public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap<K, V>(m, false, toKey, inclusive, toEnd, hi, hiInclusive); } public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) { if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, fromKey, inclusive); } public ONavigableMap<K, V> descendingMap() { ONavigableMap<K, V> mv = descendingMapView; return (mv != null) ? mv : (descendingMapView = new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive)); } @Override OLazyIterator<K> keyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } @Override OLazyIterator<K> descendingKeyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } final class DescendingEntrySetView extends EntrySetView { @Override public Iterator<Map.Entry<K, V>> iterator() { return new DescendingSubMapEntryIterator(absHighest(), absLowFence()); } } @Override public Set<Map.Entry<K, V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : new DescendingEntrySetView(); } @Override OMVRBTreeEntry<K, V> subLowest() { return absHighest().entry; } @Override OMVRBTreeEntry<K, V> subHighest() { return absLowest().entry; } @Override OMVRBTreeEntry<K, V> subCeiling(final K key) { return absFloor(key).entry; } @Override OMVRBTreeEntry<K, V> subHigher(final K key) { return absLower(key).entry; } @Override OMVRBTreeEntry<K, V> subFloor(final K key) { return absCeiling(key).entry; } @Override OMVRBTreeEntry<K, V> subLower(final K key) { return absHigher(key).entry; } } // Red-black mechanics public static final boolean RED = false; public static final boolean BLACK = true; /** * Node in the Tree. Doubles as a means to pass key-value pairs back to user (see Map.Entry). */ /** * Returns the first Entry in the OMVRBTree (according to the OMVRBTree's key-sort function). Returns null if the OMVRBTree is * empty. */ public OMVRBTreeEntry<K, V> getFirstEntry() { OMVRBTreeEntry<K, V> p = root; if (p != null) { if (p.getSize() > 0) pageIndex = 0; while (p.getLeft() != null) p = p.getLeft(); } return p; } /** * Returns the last Entry in the OMVRBTree (according to the OMVRBTree's key-sort function). Returns null if the OMVRBTree is * empty. */ protected OMVRBTreeEntry<K, V> getLastEntry() { OMVRBTreeEntry<K, V> p = root; if (p != null) while (p.getRight() != null) p = p.getRight(); if (p != null) pageIndex = p.getSize() - 1; return p; } public static <K, V> OMVRBTreeEntry<K, V> successor(final OMVRBTreeEntryPosition<K, V> t) { t.entry.getTree().setPageIndex(t.position); return successor(t.entry); } /** * Returns the successor of the specified Entry, or null if no such. */ public static <K, V> OMVRBTreeEntry<K, V> successor(final OMVRBTreeEntry<K, V> t) { if (t == null) return null; OMVRBTreeEntry<K, V> p = null; if (t.getRight() != null) { p = t.getRight(); while (p.getLeft() != null) p = p.getLeft(); } else { p = t.getParent(); OMVRBTreeEntry<K, V> ch = t; while (p != null && ch == p.getRight()) { ch = p; p = p.getParent(); } } return p; } public static <K, V> OMVRBTreeEntry<K, V> next(final OMVRBTreeEntryPosition<K, V> t) { t.entry.getTree().setPageIndex(t.position); return next(t.entry); } /** * Returns the next item of the tree. */ public static <K, V> OMVRBTreeEntry<K, V> next(final OMVRBTreeEntry<K, V> t) { if (t == null) return null; final OMVRBTreeEntry<K, V> succ; if (t.tree.pageIndex < t.getSize() - 1) { // ITERATE INSIDE THE NODE succ = t; t.tree.pageIndex++; } else { // GET THE NEXT NODE succ = OMVRBTree.successor(t); t.tree.pageIndex = 0; } return succ; } public static <K, V> OMVRBTreeEntry<K, V> predecessor(final OMVRBTreeEntryPosition<K, V> t) { t.entry.getTree().setPageIndex(t.position); return predecessor(t.entry); } /** * Returns the predecessor of the specified Entry, or null if no such. */ public static <K, V> OMVRBTreeEntry<K, V> predecessor(final OMVRBTreeEntry<K, V> t) { if (t == null) return null; else if (t.getLeft() != null) { OMVRBTreeEntry<K, V> p = t.getLeft(); while (p.getRight() != null) p = p.getRight(); return p; } else { OMVRBTreeEntry<K, V> p = t.getParent(); Entry<K, V> ch = t; while (p != null && ch == p.getLeft()) { ch = p; p = p.getParent(); } return p; } } public static <K, V> OMVRBTreeEntry<K, V> previous(final OMVRBTreeEntryPosition<K, V> t) { t.entry.getTree().setPageIndex(t.position); return previous(t.entry); } /** * Returns the previous item of the tree. */ public static <K, V> OMVRBTreeEntry<K, V> previous(final OMVRBTreeEntry<K, V> t) { if (t == null) return null; final int index = t.getTree().getPageIndex(); final OMVRBTreeEntry<K, V> prev; if (index <= 0) { prev = predecessor(t); if (prev != null) t.tree.pageIndex = prev.getSize() - 1; else t.tree.pageIndex = 0; } else { prev = t; t.tree.pageIndex = index - 1; } return prev; } /** * Balancing operations. * * Implementations of rebalancings during insertion and deletion are slightly different than the CLR version. Rather than using * dummy nilnodes, we use a set of accessors that deal properly with null. They are used to avoid messiness surrounding nullness * checks in the main algorithms. */ private static <K, V> boolean colorOf(final OMVRBTreeEntry<K, V> p) { return (p == null ? BLACK : p.getColor()); } private static <K, V> OMVRBTreeEntry<K, V> parentOf(final OMVRBTreeEntry<K, V> p) { return (p == null ? null : p.getParent()); } private static <K, V> void setColor(final OMVRBTreeEntry<K, V> p, final boolean c) { if (p != null) p.setColor(c); } private static <K, V> OMVRBTreeEntry<K, V> leftOf(final OMVRBTreeEntry<K, V> p) { return (p == null) ? null : p.getLeft(); } private static <K, V> OMVRBTreeEntry<K, V> rightOf(final OMVRBTreeEntry<K, V> p) { return (p == null) ? null : p.getRight(); } /** From CLR */ protected void rotateLeft(final OMVRBTreeEntry<K, V> p) { if (p != null) { OMVRBTreeEntry<K, V> r = p.getRight(); p.setRight(r.getLeft()); if (r.getLeft() != null) r.getLeft().setParent(p); r.setParent(p.getParent()); if (p.getParent() == null) setRoot(r); else if (p.getParent().getLeft() == p) p.getParent().setLeft(r); else p.getParent().setRight(r); p.setParent(r); r.setLeft(p); } } protected void setRoot(final OMVRBTreeEntry<K, V> iRoot) { root = iRoot; } /** From CLR */ protected void rotateRight(final OMVRBTreeEntry<K, V> p) { if (p != null) { OMVRBTreeEntry<K, V> l = p.getLeft(); p.setLeft(l.getRight()); if (l.getRight() != null) l.getRight().setParent(p); l.setParent(p.getParent()); if (p.getParent() == null) setRoot(l); else if (p.getParent().getRight() == p) p.getParent().setRight(l); else p.getParent().setLeft(l); l.setRight(p); p.setParent(l); } } private OMVRBTreeEntry<K, V> grandparent(final OMVRBTreeEntry<K, V> n) { return parentOf(parentOf(n)); } private OMVRBTreeEntry<K, V> uncle(final OMVRBTreeEntry<K, V> n) { if (parentOf(n) == leftOf(grandparent(n))) return rightOf(grandparent(n)); else return leftOf(grandparent(n)); } private void fixAfterInsertion(final OMVRBTreeEntry<K, V> n) { if (parentOf(n) == null) setColor(n, BLACK); else insert_case2(n); } private void insert_case2(final OMVRBTreeEntry<K, V> n) { if (colorOf(parentOf(n)) == BLACK) return; /* Tree is still valid */ else insert_case3(n); } private void insert_case3(final OMVRBTreeEntry<K, V> n) { if (uncle(n) != null && colorOf(uncle(n)) == RED) { setColor(parentOf(n), BLACK); setColor(uncle(n), BLACK); setColor(grandparent(n), RED); fixAfterInsertion(grandparent(n)); } else insert_case4(n); } private void insert_case4(OMVRBTreeEntry<K, V> n) { if (n == rightOf(parentOf(n)) && parentOf(n) == leftOf(grandparent(n))) { rotateLeft(parentOf(n)); n = leftOf(n); } else if (n == leftOf(parentOf(n)) && parentOf(n) == rightOf(grandparent(n))) { rotateRight(parentOf(n)); n = rightOf(n); } insert_case5(n); } private void insert_case5(final OMVRBTreeEntry<K, V> n) { setColor(parentOf(n), BLACK); setColor(grandparent(n), RED); if (n == leftOf(parentOf(n)) && parentOf(n) == leftOf(grandparent(n))) { rotateRight(grandparent(n)); } else { rotateLeft(grandparent(n)); } } /** * Delete node p, and then re-balance the tree. * * @param p * node to delete * @return */ OMVRBTreeEntry<K, V> deleteEntry(OMVRBTreeEntry<K, V> p) { setSizeDelta(-1); modCount++; if (pageIndex > -1) { // DELETE INSIDE THE NODE p.remove(); if (p.getSize() > 0) return p; } final OMVRBTreeEntry<K, V> next = successor(p); // DELETE THE ENTIRE NODE, RE-BUILDING THE STRUCTURE removeNode(p); // RETURN NEXT NODE return next; } /** * Remove a node from the tree. * * @param p * Node to remove * * @return Node that was removed. Passed and removed nodes may be different in case node to remove contains two children. In this * case node successor will be found and removed but it's content will be copied to the node that was passed in method. */ protected OMVRBTreeEntry<K, V> removeNode(OMVRBTreeEntry<K, V> p) { modCount++; // If strictly internal, copy successor's element to p and then make p // point to successor. if (p.getLeft() != null && p.getRight() != null) { OMVRBTreeEntry<K, V> s = next(p); p.copyFrom(s); p = s; } // p has 2 children // Start fixup at replacement node, if it exists. final OMVRBTreeEntry<K, V> replacement = (p.getLeft() != null ? p.getLeft() : p.getRight()); if (replacement != null) { // Link replacement to parent replacement.setParent(p.getParent()); if (p.getParent() == null) setRoot(replacement); else if (p == p.getParent().getLeft()) p.getParent().setLeft(replacement); else p.getParent().setRight(replacement); // Null out links so they are OK to use by fixAfterDeletion. p.setLeft(null); p.setRight(null); p.setParent(null); // Fix replacement if (p.getColor() == BLACK) fixAfterDeletion(replacement); } else if (p.getParent() == null && size() == 0) { // return if we are the only node. Check the size to be sure the map is empty clear(); } else { // No children. Use self as phantom replacement and unlink. if (p.getColor() == BLACK) fixAfterDeletion(p); if (p.getParent() != null) { if (p == p.getParent().getLeft()) p.getParent().setLeft(null); else if (p == p.getParent().getRight()) p.getParent().setRight(null); p.setParent(null); } } return p; } /** From CLR */ private void fixAfterDeletion(OMVRBTreeEntry<K, V> x) { while (x != root && colorOf(x) == BLACK) { if (x == leftOf(parentOf(x))) { OMVRBTreeEntry<K, V> sib = rightOf(parentOf(x)); if (colorOf(sib) == RED) { setColor(sib, BLACK); setColor(parentOf(x), RED); rotateLeft(parentOf(x)); sib = rightOf(parentOf(x)); } if (colorOf(leftOf(sib)) == BLACK && colorOf(rightOf(sib)) == BLACK) { setColor(sib, RED); x = parentOf(x); } else { if (colorOf(rightOf(sib)) == BLACK) { setColor(leftOf(sib), BLACK); setColor(sib, RED); rotateRight(sib); sib = rightOf(parentOf(x)); } setColor(sib, colorOf(parentOf(x))); setColor(parentOf(x), BLACK); setColor(rightOf(sib), BLACK); rotateLeft(parentOf(x)); x = root; } } else { // symmetric OMVRBTreeEntry<K, V> sib = leftOf(parentOf(x)); if (colorOf(sib) == RED) { setColor(sib, BLACK); setColor(parentOf(x), RED); rotateRight(parentOf(x)); sib = leftOf(parentOf(x)); } if (x != null && colorOf(rightOf(sib)) == BLACK && colorOf(leftOf(sib)) == BLACK) { setColor(sib, RED); x = parentOf(x); } else { if (colorOf(leftOf(sib)) == BLACK) { setColor(rightOf(sib), BLACK); setColor(sib, RED); rotateLeft(sib); sib = leftOf(parentOf(x)); } setColor(sib, colorOf(parentOf(x))); setColor(parentOf(x), BLACK); setColor(leftOf(sib), BLACK); rotateRight(parentOf(x)); x = root; } } } setColor(x, BLACK); } /** * Save the state of the <tt>OMVRBTree</tt> instance to a stream (i.e., serialize it). * * @serialData The <i>size</i> of the OMVRBTree (the number of key-value mappings) is emitted (int), followed by the key (Object) * and value (Object) for each key-value mapping represented by the OMVRBTree. The key-value mappings are emitted in * key-order (as determined by the OMVRBTree's Comparator, or by the keys' natural ordering if the OMVRBTree has no * Comparator). */ private void writeObject(final ObjectOutputStream s) throws java.io.IOException { // Write out the Comparator and any hidden stuff s.defaultWriteObject(); // Write out size (number of Mappings) s.writeInt(size()); // Write out keys and values (alternating) for (Iterator<Map.Entry<K, V>> i = entrySet().iterator(); i.hasNext();) { Entry<K, V> e = i.next(); s.writeObject(e.getKey()); s.writeObject(e.getValue()); } } /** * Reconstitute the <tt>OMVRBTree</tt> instance from a stream (i.e., deserialize it). */ private void readObject(final java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { // Read in the Comparator and any hidden stuff s.defaultReadObject(); // Read in size setSize(s.readInt()); buildFromSorted(size(), null, s, null); } /** Intended to be called only from OTreeSet.readObject */ void readOTreeSet(int iSize, ObjectInputStream s, V defaultVal) throws java.io.IOException, ClassNotFoundException { buildFromSorted(iSize, null, s, defaultVal); } /** Intended to be called only from OTreeSet.addAll */ void addAllForOTreeSet(SortedSet<? extends K> set, V defaultVal) { try { buildFromSorted(set.size(), set.iterator(), null, defaultVal); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } } /** * Linear time tree building algorithm from sorted data. Can accept keys and/or values from iterator or stream. This leads to too * many parameters, but seems better than alternatives. The four formats that this method accepts are: * * 1) An iterator of Map.Entries. (it != null, defaultVal == null). 2) An iterator of keys. (it != null, defaultVal != null). 3) A * stream of alternating serialized keys and values. (it == null, defaultVal == null). 4) A stream of serialized keys. (it == * null, defaultVal != null). * * It is assumed that the comparator of the OMVRBTree is already set prior to calling this method. * * @param size * the number of keys (or key-value pairs) to be read from the iterator or stream * @param it * If non-null, new entries are created from entries or keys read from this iterator. * @param str * If non-null, new entries are created from keys and possibly values read from this stream in serialized form. Exactly * one of it and str should be non-null. * @param defaultVal * if non-null, this default value is used for each value in the map. If null, each value is read from iterator or * stream, as described above. * @throws IOException * propagated from stream reads. This cannot occur if str is null. * @throws ClassNotFoundException * propagated from readObject. This cannot occur if str is null. */ private void buildFromSorted(final int size, final Iterator<?> it, final java.io.ObjectInputStream str, final V defaultVal) throws java.io.IOException, ClassNotFoundException { setSize(size); root = buildFromSorted(0, 0, size - 1, computeRedLevel(size), it, str, defaultVal); } /** * Recursive "helper method" that does the real work of the previous method. Identically named parameters have identical * definitions. Additional parameters are documented below. It is assumed that the comparator and size fields of the OMVRBTree are * already set prior to calling this method. (It ignores both fields.) * * @param level * the current level of tree. Initial call should be 0. * @param lo * the first element index of this subtree. Initial should be 0. * @param hi * the last element index of this subtree. Initial should be size-1. * @param redLevel * the level at which nodes should be red. Must be equal to computeRedLevel for tree of this size. */ private final OMVRBTreeEntry<K, V> buildFromSorted(final int level, final int lo, final int hi, final int redLevel, final Iterator<?> it, final java.io.ObjectInputStream str, final V defaultVal) throws java.io.IOException, ClassNotFoundException { /* * Strategy: The root is the middlemost element. To get to it, we have to first recursively construct the entire left subtree, * so as to grab all of its elements. We can then proceed with right subtree. * * The lo and hi arguments are the minimum and maximum indices to pull out of the iterator or stream for current subtree. They * are not actually indexed, we just proceed sequentially, ensuring that items are extracted in corresponding order. */ if (hi < lo) return null; final int mid = (lo + hi) / 2; OMVRBTreeEntry<K, V> left = null; if (lo < mid) left = buildFromSorted(level + 1, lo, mid - 1, redLevel, it, str, defaultVal); // extract key and/or value from iterator or stream K key; V value; if (it != null) { if (defaultVal == null) { OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) it.next(); key = entry.getKey(); value = entry.getValue(); } else { key = (K) it.next(); value = defaultVal; } } else { // use stream key = (K) str.readObject(); value = (defaultVal != null ? defaultVal : (V) str.readObject()); } final OMVRBTreeEntry<K, V> middle = createEntry(key, value); // color nodes in non-full bottom most level red if (level == redLevel) middle.setColor(RED); if (left != null) { middle.setLeft(left); left.setParent(middle); } if (mid < hi) { OMVRBTreeEntry<K, V> right = buildFromSorted(level + 1, mid + 1, hi, redLevel, it, str, defaultVal); middle.setRight(right); right.setParent(middle); } return middle; } /** * Find the level down to which to assign all nodes BLACK. This is the last `full' level of the complete binary tree produced by * buildTree. The remaining nodes are colored RED. (This makes a `nice' set of color assignments wrt future insertions.) This * level number is computed by finding the number of splits needed to reach the zeroeth node. (The answer is ~lg(N), but in any * case must be computed by same quick O(lg(N)) loop.) */ private static int computeRedLevel(final int sz) { int level = 0; for (int m = sz - 1; m >= 0; m = m / 2 - 1) level++; return level; } public int getPageIndex() { return pageIndex; } public void setPageIndex(final int iPageIndex) { pageIndex = iPageIndex; } private void init() { } public OMVRBTreeEntry<K, V> getRoot() { return root; } protected void printInMemoryStructure(final OMVRBTreeEntry<K, V> iRootNode) { printInMemoryNode("root", iRootNode, 0); } private void printInMemoryNode(final String iLabel, OMVRBTreeEntry<K, V> iNode, int iLevel) { if (iNode == null) return; for (int i = 0; i < iLevel; ++i) System.out.print(' '); System.out.println(iLabel + ": " + iNode.toString() + " (" + (iNode.getColor() ? "B" : "R") + ")"); ++iLevel; printInMemoryNode(iLevel + ".left", iNode.getLeftInMemory(), iLevel); printInMemoryNode(iLevel + ".right", iNode.getRightInMemory(), iLevel); } public void checkTreeStructure(final OMVRBTreeEntry<K, V> iRootNode) { if (!runtimeCheckEnabled || iRootNode == null) return; int currPageIndex = pageIndex; OMVRBTreeEntry<K, V> prevNode = null; int i = 0; for (OMVRBTreeEntry<K, V> e = iRootNode.getFirstInMemory(); e != null; e = e.getNextInMemory()) { if (e.getSize() == 0) OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has 0 items\n", e); if (prevNode != null) { if (prevNode.getTree() == null) OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Freed record %d found in memory\n", i); if (compare(e.getFirstKey(), e.getLastKey()) > 0) { OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] begin key is > than last key\n", e.getFirstKey(), e.getLastKey()); printInMemoryStructure(iRootNode); } if (compare(e.getFirstKey(), prevNode.getLastKey()) < 0) { OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s starts with a key minor than the last key of the previous node %s\n", e, prevNode); printInMemoryStructure(e.getParentInMemory() != null ? e.getParentInMemory() : e); } } if (e.getLeftInMemory() != null && e.getLeftInMemory() == e) { OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has left that points to itself!\n", e); printInMemoryStructure(iRootNode); } if (e.getRightInMemory() != null && e.getRightInMemory() == e) { OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has right that points to itself!\n", e); printInMemoryStructure(iRootNode); } if (e.getLeftInMemory() != null && e.getLeftInMemory() == e.getRightInMemory()) { OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has left and right equals!\n", e); printInMemoryStructure(iRootNode); } if (e.getParentInMemory() != null && e.getParentInMemory().getRightInMemory() != e && e.getParentInMemory().getLeftInMemory() != e) { OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s is the children of node %s but the cross-reference is missed!\n", e, e.getParentInMemory()); printInMemoryStructure(iRootNode); } prevNode = e; ++i; } pageIndex = currPageIndex; } public boolean isRuntimeCheckEnabled() { return runtimeCheckEnabled; } public void setChecks(boolean checks) { this.runtimeCheckEnabled = checks; } public void setRuntimeCheckEnabled(boolean runtimeCheckEnabled) { this.runtimeCheckEnabled = runtimeCheckEnabled; } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } protected OMVRBTreeEntry<K, V> getLastSearchNodeForSameKey(final Object key) { if (key != null && lastSearchKey != null) { if (key instanceof OCompositeKey) return key.equals(lastSearchKey) ? lastSearchNode : null; if (comparator != null) return comparator.compare((K) key, (K) lastSearchKey) == 0 ? lastSearchNode : null; else try { return ((Comparable<? super K>) key).compareTo((K) lastSearchKey) == 0 ? lastSearchNode : null; } catch (Exception e) { // IGNORE IT } } return null; } protected OMVRBTreeEntry<K, V> setLastSearchNode(final Object iKey, final OMVRBTreeEntry<K, V> iNode) { lastSearchKey = iKey; lastSearchNode = iNode; lastSearchFound = iNode != null ? iNode.tree.pageItemFound : false; lastSearchIndex = iNode != null ? iNode.tree.pageIndex : -1; return iNode; } protected void searchNodeCallback() { } protected void setSizeDelta(final int iDelta) { setSize(size() + iDelta); } }
0true
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
558
public enum Mode { OR, AND }
0true
common_src_main_java_org_broadleafcommerce_common_util_dao_TQRestriction.java
2,003
static class NoDuplicateMapStore extends TestMapStore { boolean failed = false; @Override public void store(Object key, Object value) { if (store.containsKey(key)) { failed = true; throw new RuntimeException("duplicate is not allowed"); } super.store(key, value); } @Override public void storeAll(Map map) { for (Object key : map.keySet()) { if (store.containsKey(key)) { failed = true; throw new RuntimeException("duplicate is not allowed"); } } super.storeAll(map); } }
0true
hazelcast_src_test_java_com_hazelcast_map_mapstore_MapStoreTest.java
1,081
class MyService implements ConfigurableService<MyServiceConfig> { MyServiceConfig config; @Override public void configure(MyServiceConfig configObject) { config = configObject; } }
0true
hazelcast_src_test_java_com_hazelcast_config_MyService.java
134
public class NullLogBuffer implements LogBuffer { public static final LogBuffer INSTANCE = new NullLogBuffer(); private NullLogBuffer() {} @Override public LogBuffer put( byte b ) throws IOException { return this; } @Override public LogBuffer putShort( short b ) throws IOException { return this; } @Override public LogBuffer putInt( int i ) throws IOException { return this; } @Override public LogBuffer putLong( long l ) throws IOException { return this; } @Override public LogBuffer putFloat( float f ) throws IOException { return this; } @Override public LogBuffer putDouble( double d ) throws IOException { return this; } @Override public LogBuffer put( byte[] bytes ) throws IOException { return this; } @Override public LogBuffer put( char[] chars ) throws IOException { return this; } @Override public void writeOut() throws IOException {} @Override public void force() throws IOException {} @Override public long getFileChannelPosition() throws IOException { throw new UnsupportedOperationException(); } @Override public StoreChannel getFileChannel() { throw new UnsupportedOperationException(); } }
0true
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_NullLogBuffer.java
3
static final class AcceptEither<T> extends Completion { final CompletableFuture<? extends T> src; final CompletableFuture<? extends T> snd; final Action<? super T> fn; final CompletableFuture<Void> dst; final Executor executor; AcceptEither(CompletableFuture<? extends T> src, CompletableFuture<? extends T> snd, Action<? super T> fn, CompletableFuture<Void> dst, Executor executor) { this.src = src; this.snd = snd; this.fn = fn; this.dst = dst; this.executor = executor; } public final void run() { final CompletableFuture<? extends T> a; final CompletableFuture<? extends T> b; final Action<? super T> fn; final CompletableFuture<Void> dst; Object r; T t; Throwable ex; if ((dst = this.dst) != null && (fn = this.fn) != null && (((a = this.src) != null && (r = a.result) != null) || ((b = this.snd) != null && (r = b.result) != null)) && compareAndSet(0, 1)) { if (r instanceof AltResult) { ex = ((AltResult)r).ex; t = null; } else { ex = null; @SuppressWarnings("unchecked") T tr = (T) r; t = tr; } Executor e = executor; if (ex == null) { try { if (e != null) e.execute(new AsyncAccept<T>(t, fn, dst)); else fn.accept(t); } catch (Throwable rex) { ex = rex; } } if (e == null || ex != null) dst.internalComplete(null, ex); } } private static final long serialVersionUID = 5232453952276885070L; }
0true
src_main_java_jsr166e_CompletableFuture.java
1,098
public class OSQLFunctionDistinct extends OSQLFunctionAbstract { public static final String NAME = "distinct"; private Set<Object> context = new LinkedHashSet<Object>(); public OSQLFunctionDistinct() { super(NAME, 1, 1); } public Object execute(final OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParameters, OCommandContext iContext) { final Object value = iParameters[0]; if (value != null && !context.contains(value)) { context.add(value); return value; } return null; } @Override public boolean filterResult() { return true; } public String getSyntax() { return "Syntax error: distinct(<field>)"; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_functions_coll_OSQLFunctionDistinct.java
233
public abstract class OAbstractMapCache<T extends Map<ORID, ORecordInternal<?>>> implements OCache { protected final OSharedResourceAdaptiveExternal lock = new OSharedResourceAdaptiveExternal( OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean(), 0, true); protected final T cache; private final AtomicBoolean enabled = new AtomicBoolean(false); public OAbstractMapCache(T cache) { this.cache = cache; } @Override public void startup() { enable(); } @Override public void shutdown() { disable(); } @Override public boolean isEnabled() { return enabled.get(); } @Override public boolean enable() { return enabled.compareAndSet(false, true); } @Override public boolean disable() { clear(); return enabled.compareAndSet(true, false); } @Override public ORecordInternal<?> get(final ORID id) { if (!isEnabled()) return null; lock.acquireExclusiveLock(); try { return cache.get(id); } finally { lock.releaseExclusiveLock(); } } @Override public ORecordInternal<?> put(final ORecordInternal<?> record) { if (!isEnabled()) return null; lock.acquireExclusiveLock(); try { return cache.put(record.getIdentity(), record); } finally { lock.releaseExclusiveLock(); } } @Override public ORecordInternal<?> remove(final ORID id) { if (!isEnabled()) return null; lock.acquireExclusiveLock(); try { return cache.remove(id); } finally { lock.releaseExclusiveLock(); } } @Override public void clear() { if (!isEnabled()) return; lock.acquireExclusiveLock(); try { cache.clear(); } finally { lock.releaseExclusiveLock(); } } @Override public int size() { lock.acquireSharedLock(); try { return cache.size(); } finally { lock.releaseSharedLock(); } } @Override public Collection<ORID> keys() { lock.acquireExclusiveLock(); try { return new ArrayList<ORID>(cache.keySet()); } finally { lock.releaseExclusiveLock(); } } @Override public void lock(final ORID id) { lock.acquireExclusiveLock(); } @Override public void unlock(final ORID id) { lock.releaseExclusiveLock(); } }
1no label
core_src_main_java_com_orientechnologies_orient_core_cache_OAbstractMapCache.java
404
add(store, "expiring-doc3", new HashMap<String, Object>() {{ put(NAME, "third"); put(TIME, 3L); put(WEIGHT, 5.2d); }}, true, 2);
0true
titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexProviderTest.java
2,068
return new AbstractModule() { @Override public void configure() { final List<Element> elements = Elements.getElements(baseModules); final List<Element> overrideElements = Elements.getElements(overrides); final Set<Key> overriddenKeys = Sets.newHashSet(); final Set<Class<? extends Annotation>> overridesScopeAnnotations = Sets.newHashSet(); // execute the overrides module, keeping track of which keys and scopes are bound new ModuleWriter(binder()) { @Override public <T> Void visit(Binding<T> binding) { overriddenKeys.add(binding.getKey()); return super.visit(binding); } @Override public Void visit(ScopeBinding scopeBinding) { overridesScopeAnnotations.add(scopeBinding.getAnnotationType()); return super.visit(scopeBinding); } @Override public Void visit(PrivateElements privateElements) { overriddenKeys.addAll(privateElements.getExposedKeys()); return super.visit(privateElements); } }.writeAll(overrideElements); // execute the original module, skipping all scopes and overridden keys. We only skip each // overridden binding once so things still blow up if the module binds the same thing // multiple times. final Map<Scope, Object> scopeInstancesInUse = Maps.newHashMap(); final List<ScopeBinding> scopeBindings = Lists.newArrayList(); new ModuleWriter(binder()) { @Override public <T> Void visit(Binding<T> binding) { if (!overriddenKeys.remove(binding.getKey())) { super.visit(binding); // Record when a scope instance is used in a binding Scope scope = getScopeInstanceOrNull(binding); if (scope != null) { scopeInstancesInUse.put(scope, binding.getSource()); } } return null; } @Override public Void visit(PrivateElements privateElements) { PrivateBinder privateBinder = binder.withSource(privateElements.getSource()) .newPrivateBinder(); Set<Key<?>> skippedExposes = Sets.newHashSet(); for (Key<?> key : privateElements.getExposedKeys()) { if (overriddenKeys.remove(key)) { skippedExposes.add(key); } else { privateBinder.withSource(privateElements.getExposedSource(key)).expose(key); } } // we're not skipping deep exposes, but that should be okay. If we ever need to, we // have to search through this set of elements for PrivateElements, recursively for (Element element : privateElements.getElements()) { if (element instanceof Binding && skippedExposes.contains(((Binding) element).getKey())) { continue; } element.applyTo(privateBinder); } return null; } @Override public Void visit(ScopeBinding scopeBinding) { scopeBindings.add(scopeBinding); return null; } }.writeAll(elements); // execute the scope bindings, skipping scopes that have been overridden. Any scope that // is overridden and in active use will prompt an error new ModuleWriter(binder()) { @Override public Void visit(ScopeBinding scopeBinding) { if (!overridesScopeAnnotations.remove(scopeBinding.getAnnotationType())) { super.visit(scopeBinding); } else { Object source = scopeInstancesInUse.get(scopeBinding.getScope()); if (source != null) { binder().withSource(source).addError( "The scope for @%s is bound directly and cannot be overridden.", scopeBinding.getAnnotationType().getSimpleName()); } } return null; } }.writeAll(scopeBindings); // TODO: bind the overridden keys using multibinder } private Scope getScopeInstanceOrNull(Binding<?> binding) { return binding.acceptScopingVisitor(new DefaultBindingScopingVisitor<Scope>() { public Scope visitScope(Scope scope) { return scope; } }); } };
0true
src_main_java_org_elasticsearch_common_inject_util_Modules.java
298
public class OTraverseMultiValueBreadthFirstProcess extends OTraverseAbstractProcess<Iterator<Object>> { protected Object value; protected int index = -1; protected List<Object> sub = new ArrayList<Object>(); protected boolean shallow = true; public OTraverseMultiValueBreadthFirstProcess(final OTraverse iCommand, final Iterator<Object> iTarget) { super(iCommand, iTarget); command.getContext().incrementDepth(); } public OIdentifiable process() { if (shallow) { // RETURNS THE SHALLOW LEVEL FIRST while (target.hasNext()) { value = target.next(); index++; if (value instanceof OIdentifiable) { final ORecord<?> rec = ((OIdentifiable) value).getRecord(); if (rec instanceof ODocument) { if (command.getPredicate() != null) { final Object conditionResult = command.getPredicate().evaluate(rec, null, command.getContext()); if (conditionResult != Boolean.TRUE) continue; } sub.add(rec); return rec; } } } target = sub.iterator(); index = -1; shallow = false; } // SHALLOW DONE, GO IN DEEP while (target.hasNext()) { value = target.next(); index++; final OTraverseRecordProcess subProcess = new OTraverseRecordProcess(command, (ODocument) value, true); final OIdentifiable subValue = subProcess.process(); if (subValue != null) return subValue; } sub = null; return drop(); } @Override public OIdentifiable drop() { command.getContext().decrementDepth(); return super.drop(); } @Override public String getStatus() { return toString(); } @Override public String toString() { return "[" + index + "]"; } }
0true
core_src_main_java_com_orientechnologies_orient_core_command_traverse_OTraverseMultiValueBreadthFirstProcess.java
1,526
@Component("blRatingsProcessor") public class RatingsProcessor extends AbstractModelVariableModifierProcessor { @Resource(name = "blRatingService") protected RatingService ratingService; /** * Sets the name of this processor to be used in Thymeleaf template * * NOTE: Thymeleaf normalizes the attribute names by converting all to lower-case * we will use the underscore instead of camel case to avoid confusion * */ public RatingsProcessor() { super("ratings"); } @Override public int getPrecedence() { return 10000; } @Override protected void modifyModelAttributes(Arguments arguments, Element element) { String itemId = String.valueOf(StandardExpressionProcessor.processExpression(arguments, element.getAttributeValue("itemId"))); RatingSummary ratingSummary = ratingService.readRatingSummary(itemId, RatingType.PRODUCT); if (ratingSummary != null) { addToModel(arguments, getRatingsVar(element), ratingSummary); } Customer customer = CustomerState.getCustomer(); ReviewDetail reviewDetail = null; if (!customer.isAnonymous()) { reviewDetail = ratingService.readReviewByCustomerAndItem(customer, itemId); } if (reviewDetail != null) { addToModel(arguments, "currentCustomerReview", reviewDetail); } } private String getRatingsVar(Element element) { String ratingsVar = element.getAttributeValue("ratingsVar"); if (StringUtils.isNotEmpty(ratingsVar)) { return ratingsVar; } return "ratingSummary"; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_processor_RatingsProcessor.java
1,353
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_ZIP_CODE") public class ZipCodeImpl implements Serializable, ZipCode { private static final long serialVersionUID = 1L; @Id @Column(name = "ZIP_CODE_ID", nullable = false) private String id; @Column(name = "ZIPCODE", insertable = false, updatable = false) @Index(name="ZIPCODE_ZIP_INDEX", columnNames={"ZIPCODE"}) private Integer zipcode; @Column(name = "ZIP_STATE", insertable = false, updatable = false) @Index(name="ZIPCODE_STATE_INDEX", columnNames={"ZIP_STATE"}) private String zipState; @Column(name = "ZIP_CITY") @Index(name="ZIPCODE_CITY_INDEX", columnNames={"ZIP_CITY"}) private String zipCity; @Column(name = "ZIP_LONGITUDE") @Index(name="ZIPCODE_LONGITUDE_INDEX", columnNames={"ZIP_LONGITUDE"}) private double zipLongitude; @Column(name = "ZIP_LATITUDE") @Index(name="ZIPCODE_LATITUDE_INDEX", columnNames={"ZIP_LATITUDE"}) private double zipLatitude; public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getZipcode() { return zipcode; } public void setZipcode(Integer zipcode) { this.zipcode = zipcode; } public String getZipState() { return zipState; } public void setZipState(String zipState) { this.zipState = zipState; } public String getZipCity() { return zipCity; } public void setZipCity(String zipCity) { this.zipCity = zipCity; } public double getZipLongitude() { return zipLongitude; } public void setZipLongitude(double zipLongitude) { this.zipLongitude = zipLongitude; } public double getZipLatitude() { return zipLatitude; } public void setZipLatitude(double zipLatitude) { this.zipLatitude = zipLatitude; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_store_domain_ZipCodeImpl.java
1,693
public class MemoryCircuitBreakerTests extends ElasticsearchTestCase { @Test public void testThreadedUpdatesToBreaker() throws Exception { final int NUM_THREADS = 5; final int BYTES_PER_THREAD = 1000; final Thread[] threads = new Thread[NUM_THREADS]; final AtomicBoolean tripped = new AtomicBoolean(false); final AtomicReference<Throwable> lastException = new AtomicReference<Throwable>(null); final MemoryCircuitBreaker breaker = new MemoryCircuitBreaker(new ByteSizeValue((BYTES_PER_THREAD * NUM_THREADS) - 1), 1.0, logger); for (int i = 0; i < NUM_THREADS; i++) { threads[i] = new Thread(new Runnable() { @Override public void run() { for (int j = 0; j < BYTES_PER_THREAD; j++) { try { breaker.addEstimateBytesAndMaybeBreak(1L); } catch (CircuitBreakingException e) { if (tripped.get()) { assertThat("tripped too many times", true, equalTo(false)); } else { assertThat(tripped.compareAndSet(false, true), equalTo(true)); } } catch (Throwable e2) { lastException.set(e2); } } } }); threads[i].start(); } for (Thread t : threads) { t.join(); } assertThat("no other exceptions were thrown", lastException.get(), equalTo(null)); assertThat("breaker was tripped exactly once", tripped.get(), equalTo(true)); } @Test public void testConstantFactor() throws Exception { final MemoryCircuitBreaker breaker = new MemoryCircuitBreaker(new ByteSizeValue(15), 1.6, logger); // add only 7 bytes breaker.addWithoutBreaking(7); try { // this won't actually add it because it trips the breaker breaker.addEstimateBytesAndMaybeBreak(3); fail("should never reach this"); } catch (CircuitBreakingException cbe) { } // shouldn't throw an exception breaker.addEstimateBytesAndMaybeBreak(2); assertThat(breaker.getUsed(), equalTo(9L)); // adding 3 more bytes (now at 12) breaker.addWithoutBreaking(3); try { // Adding no bytes still breaks breaker.addEstimateBytesAndMaybeBreak(0); fail("should never reach this"); } catch (CircuitBreakingException cbe) { } } }
0true
src_test_java_org_elasticsearch_common_breaker_MemoryCircuitBreakerTests.java
1,094
public class StructuredContentCartRuleProcessor extends AbstractStructuredContentRuleProcessor { private OrderDao orderDao; /** * Expects to find a valid "Customer" in the valueMap. * Uses the customer to locate the cart and then loops through the items in the current * cart and checks to see if the cart items rules are met. * * @param sc * @return */ @Override public boolean checkForMatch(StructuredContentDTO sc, Map<String, Object> valueMap) { List<ItemCriteriaDTO> itemCriterias = sc.getItemCriteriaDTOList(); if (itemCriterias != null && itemCriterias.size() > 0) { Order order = lookupOrderForCustomer((Customer) valueMap.get("customer")); if (order == null || order.getOrderItems() == null || order.getOrderItems().size() < 1) { return false; } for(ItemCriteriaDTO itemCriteria : itemCriterias) { if (! checkItemCriteria(itemCriteria, order.getOrderItems())) { // Item criteria check failed. return false; } } } return true; } private Order lookupOrderForCustomer(Customer c) { Order o = null; if (c != null) { o = orderDao.readCartForCustomer(c); } return o; } private boolean checkItemCriteria(ItemCriteriaDTO itemCriteria, List<OrderItem> orderItems) { Map<String,Object> vars = new HashMap<String, Object>(); int foundCount = 0; Iterator<OrderItem> items = orderItems.iterator(); while (foundCount < itemCriteria.getQty() && items.hasNext()) { OrderItem currentItem = items.next(); vars.put("discreteOrderItem", currentItem); vars.put("orderItem", currentItem); boolean match = executeExpression(itemCriteria.getMatchRule(), vars); if (match) { foundCount = foundCount + currentItem.getQuantity(); } } return (foundCount >= itemCriteria.getQty().intValue()); } public void setOrderDao(OrderDao orderDao) { this.orderDao = orderDao; } public OrderDao getOrderDao() { return orderDao; } }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_StructuredContentCartRuleProcessor.java
1,482
public class BroadleafCartController extends AbstractCartController { protected static String cartView = "cart/cart"; protected static String cartPageRedirect = "redirect:/cart"; /** * Renders the cart page. * * If the method was invoked via an AJAX call, it will render the "ajax/cart" template. * Otherwise, it will render the "cart" template. * * Will reprice the order if the currency has been changed. * * @param request * @param response * @param model * @throws PricingException */ public String cart(HttpServletRequest request, HttpServletResponse response, Model model) throws PricingException { return getCartView(); } /** * Takes in an item request, adds the item to the customer's current cart, and returns. * * If the method was invoked via an AJAX call, it will render the "ajax/cart" template. * Otherwise, it will perform a 302 redirect to "/cart" * * @param request * @param response * @param model * @param itemRequest * @throws IOException * @throws AddToCartException * @throws PricingException */ public String add(HttpServletRequest request, HttpServletResponse response, Model model, AddToCartItem itemRequest) throws IOException, AddToCartException, PricingException { Order cart = CartState.getCart(); // If the cart is currently empty, it will be the shared, "null" cart. We must detect this // and provision a fresh cart for the current customer upon the first cart add if (cart == null || cart instanceof NullOrderImpl) { cart = orderService.createNewCartForCustomer(CustomerState.getCustomer(request)); } updateCartService.validateCart(cart); cart = orderService.addItem(cart.getId(), itemRequest, false); cart = orderService.save(cart, true); return isAjaxRequest(request) ? getCartView() : getCartPageRedirect(); } /** * Takes in an item request, adds the item to the customer's current cart, and returns. * * Calls the addWithOverrides method on the orderService which will honor the override * prices on the AddToCartItem request object. * * Implementors must secure this method to avoid accidentally exposing the ability for * malicious clients to override prices by hacking the post parameters. * * @param request * @param response * @param model * @param itemRequest * @throws IOException * @throws AddToCartException * @throws PricingException */ public String addWithPriceOverride(HttpServletRequest request, HttpServletResponse response, Model model, AddToCartItem itemRequest) throws IOException, AddToCartException, PricingException { Order cart = CartState.getCart(); // If the cart is currently empty, it will be the shared, "null" cart. We must detect this // and provision a fresh cart for the current customer upon the first cart add if (cart == null || cart instanceof NullOrderImpl) { cart = orderService.createNewCartForCustomer(CustomerState.getCustomer(request)); } updateCartService.validateCart(cart); cart = orderService.addItemWithPriceOverrides(cart.getId(), itemRequest, false); cart = orderService.save(cart, true); return isAjaxRequest(request) ? getCartView() : getCartPageRedirect(); } /** * Takes in an item request and updates the quantity of that item in the cart. If the quantity * was passed in as 0, it will remove the item. * * If the method was invoked via an AJAX call, it will render the "ajax/cart" template. * Otherwise, it will perform a 302 redirect to "/cart" * * @param request * @param response * @param model * @param itemRequest * @throws IOException * @throws PricingException * @throws UpdateCartException * @throws RemoveFromCartException */ public String updateQuantity(HttpServletRequest request, HttpServletResponse response, Model model, AddToCartItem itemRequest) throws IOException, UpdateCartException, PricingException, RemoveFromCartException { Order cart = CartState.getCart(); cart = orderService.updateItemQuantity(cart.getId(), itemRequest, true); cart = orderService.save(cart, false); if (isAjaxRequest(request)) { Map<String, Object> extraData = new HashMap<String, Object>(); extraData.put("productId", itemRequest.getProductId()); extraData.put("cartItemCount", cart.getItemCount()); model.addAttribute("blcextradata", new ObjectMapper().writeValueAsString(extraData)); return getCartView(); } else { return getCartPageRedirect(); } } /** * Takes in an item request, updates the quantity of that item in the cart, and returns * * If the method was invoked via an AJAX call, it will render the "ajax/cart" template. * Otherwise, it will perform a 302 redirect to "/cart" * * @param request * @param response * @param model * @param itemRequest * @throws IOException * @throws PricingException * @throws RemoveFromCartException */ public String remove(HttpServletRequest request, HttpServletResponse response, Model model, AddToCartItem itemRequest) throws IOException, PricingException, RemoveFromCartException { Order cart = CartState.getCart(); cart = orderService.removeItem(cart.getId(), itemRequest.getOrderItemId(), false); cart = orderService.save(cart, true); if (isAjaxRequest(request)) { Map<String, Object> extraData = new HashMap<String, Object>(); extraData.put("cartItemCount", cart.getItemCount()); extraData.put("productId", itemRequest.getProductId()); model.addAttribute("blcextradata", new ObjectMapper().writeValueAsString(extraData)); return getCartView(); } else { return getCartPageRedirect(); } } /** * Cancels the current cart and redirects to the homepage * * @param request * @param response * @param model * @throws PricingException */ public String empty(HttpServletRequest request, HttpServletResponse response, Model model) throws PricingException { Order cart = CartState.getCart(); orderService.cancelOrder(cart); CartState.setCart(null); return "redirect:/"; } /** Attempts to add provided Offer to Cart * * @param request * @param response * @param model * @param customerOffer * @return the return view * @throws IOException * @throws PricingException * @throws ItemNotFoundException * @throws OfferMaxUseExceededException */ public String addPromo(HttpServletRequest request, HttpServletResponse response, Model model, String customerOffer) throws IOException, PricingException { Order cart = CartState.getCart(); Boolean promoAdded = false; String exception = ""; if (cart != null && !(cart instanceof NullOrderImpl)) { OfferCode offerCode = offerService.lookupOfferCodeByCode(customerOffer); if (offerCode != null) { try { orderService.addOfferCode(cart, offerCode, false); promoAdded = true; cart = orderService.save(cart, true); } catch(OfferMaxUseExceededException e) { exception = "Use Limit Exceeded"; } } else { exception = "Invalid Code"; } } else { exception = "Invalid cart"; } if (isAjaxRequest(request)) { Map<String, Object> extraData = new HashMap<String, Object>(); extraData.put("promoAdded", promoAdded); extraData.put("exception" , exception); model.addAttribute("blcextradata", new ObjectMapper().writeValueAsString(extraData)); return getCartView(); } else { model.addAttribute("exception", exception); return getCartView(); } } /** Removes offer from cart * * @param request * @param response * @param model * @return the return view * @throws IOException * @throws PricingException * @throws ItemNotFoundException * @throws OfferMaxUseExceededException */ public String removePromo(HttpServletRequest request, HttpServletResponse response, Model model, Long offerCodeId) throws IOException, PricingException { Order cart = CartState.getCart(); OfferCode offerCode = offerService.findOfferCodeById(offerCodeId); orderService.removeOfferCode(cart, offerCode, false); cart = orderService.save(cart, true); return isAjaxRequest(request) ? getCartView() : getCartPageRedirect(); } public String getCartView() { return cartView; } public String getCartPageRedirect() { return cartPageRedirect; } }
0true
core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_cart_BroadleafCartController.java
445
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface AdminPresentationMergeOverride { /** * The name of the property whose admin presentation annotation should be overwritten * * @return the name of the property that should be overwritten */ String name(); /** * The array of override configuration values. Each entry correlates to a property on * {@link org.broadleafcommerce.common.presentation.AdminPresentation}, * {@link org.broadleafcommerce.common.presentation.AdminPresentationToOneLookup}, * {@link org.broadleafcommerce.common.presentation.AdminPresentationDataDrivenEnumeration}, * {@link org.broadleafcommerce.common.presentation.AdminPresentationAdornedTargetCollection}, * {@link org.broadleafcommerce.common.presentation.AdminPresentationCollection} or * {@link org.broadleafcommerce.common.presentation.AdminPresentationMap} * * @return The array of override configuration values. */ AdminPresentationMergeEntry[] mergeEntries(); }
0true
common_src_main_java_org_broadleafcommerce_common_presentation_override_AdminPresentationMergeOverride.java
2,060
public class MapFlushOperationFactory implements OperationFactory { String name; public MapFlushOperationFactory() { } public MapFlushOperationFactory(String name) { this.name = name; } @Override public Operation createOperation() { return new MapFlushOperation(name); } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeUTF(name); } @Override public void readData(ObjectDataInput in) throws IOException { name = in.readUTF(); } }
0true
hazelcast_src_main_java_com_hazelcast_map_operation_MapFlushOperationFactory.java
440
trackedMap.addChangeListener(new OMultiValueChangeListener<Object, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) { if (!firedEvents.remove(event)) Assert.fail(); changed.value = true; } });
0true
core_src_test_java_com_orientechnologies_orient_core_db_record_TrackedMapTest.java
49
@edu.umd.cs.findbugs.annotations.SuppressWarnings({ "EI_EXPOSE_REP", "MS_MUTABLE_ARRAY", "MS_PKGPROTECT" }) public abstract class HttpCommand extends AbstractTextCommand { public static final String HEADER_CONTENT_TYPE = "content-type: "; public static final String HEADER_CONTENT_LENGTH = "content-length: "; public static final String HEADER_CHUNKED = "transfer-encoding: chunked"; public static final String HEADER_EXPECT_100 = "expect: 100"; public static final byte[] RES_200 = stringToBytes("HTTP/1.1 200 OK\r\n"); public static final byte[] RES_400 = stringToBytes("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n"); public static final byte[] RES_403 = stringToBytes("HTTP/1.1 403 Forbidden\r\n\r\n"); public static final byte[] RES_404 = stringToBytes("HTTP/1.1 404 Not Found\r\n\r\n"); public static final byte[] RES_100 = stringToBytes("HTTP/1.1 100 Continue\r\n\r\n"); public static final byte[] RES_204 = stringToBytes("HTTP/1.1 204 No Content\r\nContent-Length: 0\r\n\r\n"); public static final byte[] RES_503 = stringToBytes("HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n"); public static final byte[] RES_500 = stringToBytes("HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n"); public static final byte[] CONTENT_TYPE = stringToBytes("Content-Type: "); public static final byte[] CONTENT_LENGTH = stringToBytes("Content-Length: "); public static final byte[] CONTENT_TYPE_PLAIN_TEXT = stringToBytes("text/plain"); public static final byte[] CONTENT_TYPE_BINARY = stringToBytes("application/binary"); protected final String uri; protected ByteBuffer response; public HttpCommand(TextCommandType type, String uri) { super(type); this.uri = uri; } public boolean shouldReply() { return true; } public String getURI() { return uri; } public void send204() { this.response = ByteBuffer.wrap(RES_204); } public void send400() { this.response = ByteBuffer.wrap(RES_400); } public void setResponse(byte[] value) { this.response = ByteBuffer.wrap(value); } public void send200() { setResponse(null, null); } /** * HTTP/1.0 200 OK * Date: Fri, 31 Dec 1999 23:59:59 GMT * Content-TextCommandType: text/html * Content-Length: 1354 * * @param contentType * @param value */ public void setResponse(byte[] contentType, byte[] value) { int valueSize = (value == null) ? 0 : value.length; byte[] len = stringToBytes(String.valueOf(valueSize)); int size = RES_200.length; if (contentType != null) { size += CONTENT_TYPE.length; size += contentType.length; size += RETURN.length; } size += CONTENT_LENGTH.length; size += len.length; size += RETURN.length; size += RETURN.length; size += valueSize; size += RETURN.length; this.response = ByteBuffer.allocate(size); response.put(RES_200); if (contentType != null) { response.put(CONTENT_TYPE); response.put(contentType); response.put(RETURN); } response.put(CONTENT_LENGTH); response.put(len); response.put(RETURN); response.put(RETURN); if (value != null) { response.put(value); } response.put(RETURN); response.flip(); } public boolean writeTo(ByteBuffer bb) { IOUtil.copyToHeapBuffer(response, bb); return !response.hasRemaining(); } @Override public String toString() { return "HttpCommand [" + type + "]{" + "uri='" + uri + '\'' + '}' + super.toString(); } }
0true
hazelcast_src_main_java_com_hazelcast_ascii_rest_HttpCommand.java
2,880
public class LatvianAnalyzerProvider extends AbstractIndexAnalyzerProvider<LatvianAnalyzer> { private final LatvianAnalyzer analyzer; @Inject public LatvianAnalyzerProvider(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); analyzer = new LatvianAnalyzer(version, Analysis.parseStopWords(env, settings, LatvianAnalyzer.getDefaultStopSet(), version), Analysis.parseStemExclusion(settings, CharArraySet.EMPTY_SET, version)); } @Override public LatvianAnalyzer get() { return this.analyzer; } }
0true
src_main_java_org_elasticsearch_index_analysis_LatvianAnalyzerProvider.java
181
private static class AppendFunction implements IFunction<String,String> { private String add; private AppendFunction(String add) { this.add = add; } @Override public String apply(String input) { return input+add; } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_atomicreference_ClientAtomicReferenceTest.java
2,542
public class DeleteByQueryTests extends ElasticsearchIntegrationTest { @Test public void testDeleteAllNoIndices() { client().admin().indices().prepareRefresh().execute().actionGet(); DeleteByQueryRequestBuilder deleteByQueryRequestBuilder = client().prepareDeleteByQuery(); deleteByQueryRequestBuilder.setQuery(QueryBuilders.matchAllQuery()); deleteByQueryRequestBuilder.setIndicesOptions(IndicesOptions.fromOptions(false, true, true, false)); DeleteByQueryResponse actionGet = deleteByQueryRequestBuilder.execute().actionGet(); assertThat(actionGet.getIndices().size(), equalTo(0)); } @Test public void testDeleteAllOneIndex() { String json = "{" + "\"user\":\"kimchy\"," + "\"postDate\":\"2013-01-30\"," + "\"message\":\"trying out Elastic Search\"" + "}"; client().prepareIndex("twitter", "tweet").setSource(json).setRefresh(true).execute().actionGet(); SearchResponse search = client().prepareSearch().setQuery(QueryBuilders.matchAllQuery()).execute().actionGet(); assertThat(search.getHits().totalHits(), equalTo(1l)); DeleteByQueryRequestBuilder deleteByQueryRequestBuilder = client().prepareDeleteByQuery(); deleteByQueryRequestBuilder.setQuery(QueryBuilders.matchAllQuery()); DeleteByQueryResponse actionGet = deleteByQueryRequestBuilder.execute().actionGet(); assertThat(actionGet.status(), equalTo(RestStatus.OK)); assertThat(actionGet.getIndex("twitter"), notNullValue()); assertThat(actionGet.getIndex("twitter").getFailedShards(), equalTo(0)); client().admin().indices().prepareRefresh().execute().actionGet(); search = client().prepareSearch().setQuery(QueryBuilders.matchAllQuery()).execute().actionGet(); assertThat(search.getHits().totalHits(), equalTo(0l)); } @Test public void testMissing() { String json = "{" + "\"user\":\"kimchy\"," + "\"postDate\":\"2013-01-30\"," + "\"message\":\"trying out Elastic Search\"" + "}"; client().prepareIndex("twitter", "tweet").setSource(json).setRefresh(true).execute().actionGet(); SearchResponse search = client().prepareSearch().setQuery(QueryBuilders.matchAllQuery()).execute().actionGet(); assertThat(search.getHits().totalHits(), equalTo(1l)); DeleteByQueryRequestBuilder deleteByQueryRequestBuilder = client().prepareDeleteByQuery(); deleteByQueryRequestBuilder.setIndices("twitter", "missing"); deleteByQueryRequestBuilder.setQuery(QueryBuilders.matchAllQuery()); try { DeleteByQueryResponse actionGet = deleteByQueryRequestBuilder.execute().actionGet(); Assert.fail("Exception should have been thrown."); } catch (IndexMissingException e) { } deleteByQueryRequestBuilder.setIndicesOptions(IndicesOptions.lenient()); DeleteByQueryResponse actionGet = deleteByQueryRequestBuilder.execute().actionGet(); assertThat(actionGet.status(), equalTo(RestStatus.OK)); assertThat(actionGet.getIndex("twitter").getFailedShards(), equalTo(0)); assertThat(actionGet.getIndex("twitter"), notNullValue()); client().admin().indices().prepareRefresh().execute().actionGet(); search = client().prepareSearch().setQuery(QueryBuilders.matchAllQuery()).execute().actionGet(); assertThat(search.getHits().totalHits(), equalTo(0l)); } @Test public void testFailure() throws Exception { client().admin().indices().prepareCreate("twitter").execute().actionGet(); DeleteByQueryResponse response = client().prepareDeleteByQuery("twitter") .setQuery(QueryBuilders.hasChildQuery("type", QueryBuilders.matchAllQuery())) .execute().actionGet(); assertThat(response.status(), equalTo(RestStatus.BAD_REQUEST)); assertThat(response.getIndex("twitter").getSuccessfulShards(), equalTo(0)); assertThat(response.getIndex("twitter").getFailedShards(), equalTo(5)); } @Test public void testDeleteByFieldQuery() throws Exception { client().admin().indices().prepareCreate("test").execute().actionGet(); int numDocs = atLeast(10); for (int i = 0; i < numDocs; i++) { client().prepareIndex("test", "test", Integer.toString(i)) .setRouting(randomAsciiOfLengthBetween(1, 5)) .setSource("foo", "bar").get(); } refresh(); assertHitCount(client().prepareCount("test").setQuery(QueryBuilders.matchQuery("_id", Integer.toString(between(0, numDocs - 1)))).get(), 1); assertHitCount(client().prepareCount("test").setQuery(QueryBuilders.matchAllQuery()).get(), numDocs); client().prepareDeleteByQuery("test") .setQuery(QueryBuilders.matchQuery("_id", Integer.toString(between(0, numDocs - 1)))) .execute().actionGet(); refresh(); assertHitCount(client().prepareCount("test").setQuery(QueryBuilders.matchAllQuery()).get(), numDocs - 1); } }
0true
src_test_java_org_elasticsearch_deleteByQuery_DeleteByQueryTests.java
905
return new Iterator<Entry<String, Object>>() { private Entry<String, Object> current; public boolean hasNext() { return iterator.hasNext(); } public Entry<String, Object> next() { current = iterator.next(); return current; } public void remove() { iterator.remove(); if (_trackingChanges) { // SAVE THE OLD VALUE IN A SEPARATE MAP if (_fieldOriginalValues == null) _fieldOriginalValues = new HashMap<String, Object>(); // INSERT IT ONLY IF NOT EXISTS TO AVOID LOOSE OF THE ORIGINAL VALUE (FUNDAMENTAL FOR INDEX HOOK) if (!_fieldOriginalValues.containsKey(current.getKey())) { _fieldOriginalValues.put(current.getKey(), current.getValue()); } } removeCollectionChangeListener(current.getKey()); removeCollectionTimeLine(current.getKey()); } };
1no label
core_src_main_java_com_orientechnologies_orient_core_record_impl_ODocument.java
208
public interface Factory<T> { public T get(byte[] array, int offset, int limit); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_StaticBuffer.java
1,162
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "BLC_CREDIT_CARD_PAYMENT") public class CreditCardPaymentInfoImpl implements CreditCardPaymentInfo { private static final long serialVersionUID = 1L; protected CreditCardPaymentInfoImpl() { //do not allow direct instantiation -- must at least be package private for bytecode instrumentation //this complies with JPA specification requirements for entity construction } @Transient protected EncryptionModule encryptionModule; @Id @GeneratedValue(generator = "CreditCardPaymentId") @GenericGenerator( name="CreditCardPaymentId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="CreditCardPaymentInfoImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.payment.domain.CreditCardPaymentInfoImpl") } ) @Column(name = "PAYMENT_ID") protected Long id; @Column(name = "REFERENCE_NUMBER", nullable=false) @Index(name="CREDITCARD_INDEX", columnNames={"REFERENCE_NUMBER"}) protected String referenceNumber; @Column(name = "PAN", nullable=false) protected String pan; @Column(name = "EXPIRATION_MONTH", nullable=false) protected Integer expirationMonth; @Column(name = "EXPIRATION_YEAR", nullable=false) protected Integer expirationYear; @Column(name = "NAME_ON_CARD", nullable=false) protected String nameOnCard; @Transient protected String cvvCode; /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#getId() */ @Override public Long getId() { return id; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#setId(long) */ @Override public void setId(Long id) { this.id = id; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#getReferenceNumber() */ @Override public String getReferenceNumber() { return referenceNumber; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#setReferenceNumber(java.lang.String) */ @Override public void setReferenceNumber(String referenceNumber) { this.referenceNumber = referenceNumber; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#getPan() */ @Override public String getPan() { return encryptionModule.decrypt(pan); } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#setPan(java.lang.Long) */ @Override public void setPan(String pan) { this.pan = encryptionModule.encrypt(pan); } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#getExpirationMonth() */ @Override public Integer getExpirationMonth() { return expirationMonth; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#setExpirationMonth(java.lang.Integer) */ @Override public void setExpirationMonth(Integer expirationMonth) { this.expirationMonth = expirationMonth; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#getExpirationYear() */ @Override public Integer getExpirationYear() { return expirationYear; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#setExpirationYear(java.lang.Integer) */ @Override public void setExpirationYear(Integer expirationYear) { this.expirationYear = expirationYear; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#getNameOnCard() */ @Override public String getNameOnCard() { return nameOnCard; } /* (non-Javadoc) * @see org.broadleafcommerce.profile.payment.secure.domain.CreditCardPaymentInfo#setNameOnCard(java.lang.String) */ @Override public void setNameOnCard(String nameOnCard) { this.nameOnCard = nameOnCard; } @Override public String getCvvCode() { return cvvCode; } @Override public void setCvvCode(String cvvCode) { this.cvvCode = cvvCode; } @Override public EncryptionModule getEncryptionModule() { return encryptionModule; } @Override public void setEncryptionModule(EncryptionModule encryptionModule) { this.encryptionModule = encryptionModule; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((expirationMonth == null) ? 0 : expirationMonth.hashCode()); result = prime * result + ((expirationYear == null) ? 0 : expirationYear.hashCode()); result = prime * result + ((pan == null) ? 0 : pan.hashCode()); result = prime * result + ((referenceNumber == null) ? 0 : referenceNumber.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; CreditCardPaymentInfoImpl other = (CreditCardPaymentInfoImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (expirationMonth == null) { if (other.expirationMonth != null) return false; } else if (!expirationMonth.equals(other.expirationMonth)) return false; if (expirationYear == null) { if (other.expirationYear != null) return false; } else if (!expirationYear.equals(other.expirationYear)) return false; if (pan == null) { if (other.pan != null) return false; } else if (!pan.equals(other.pan)) return false; if (referenceNumber == null) { if (other.referenceNumber != null) return false; } else if (!referenceNumber.equals(other.referenceNumber)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_payment_domain_CreditCardPaymentInfoImpl.java
1,544
public static enum Operation { /** * Provided during balance operations. */ BALANCE, /** * Provided during initial allocation operation for unassigned shards. */ ALLOCATE, /** * Provided during move operation. */ MOVE, /** * Provided when the weight delta is checked against the configured threshold. * This can be used to ignore tie-breaking weight factors that should not * solely trigger a relocation unless the delta is above the threshold. */ THRESHOLD_CHECK }
0true
src_main_java_org_elasticsearch_cluster_routing_allocation_allocator_BalancedShardsAllocator.java
903
final class ShardSuggestRequest extends BroadcastShardOperationRequest { private BytesReference suggestSource; ShardSuggestRequest() { } public ShardSuggestRequest(String index, int shardId, SuggestRequest request) { super(index, shardId, request); this.suggestSource = request.suggest(); } public BytesReference suggest() { return suggestSource; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); suggestSource = in.readBytesReference(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeBytesReference(suggestSource); } }
0true
src_main_java_org_elasticsearch_action_suggest_ShardSuggestRequest.java
2,716
transportService.sendRequest(masterNode, AllocateDangledRequestHandler.ACTION, request, new TransportResponseHandler<AllocateDangledResponse>() { @Override public AllocateDangledResponse newInstance() { return new AllocateDangledResponse(); } @Override public void handleResponse(AllocateDangledResponse response) { listener.onResponse(response); } @Override public void handleException(TransportException exp) { listener.onFailure(exp); } @Override public String executor() { return ThreadPool.Names.SAME; } });
0true
src_main_java_org_elasticsearch_gateway_local_state_meta_LocalAllocateDangledIndices.java
150
public interface Action<A> { void apply(A a); }
0true
src_main_java_jsr166e_extra_ReadMostlyVector.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
1,717
Thread thread = new Thread(new Runnable() { public void run() { try { b1.set(map.isLocked("key1")); b2.set(map.isLocked("key2")); latch.countDown(); } catch (Exception e) { fail(e.getMessage()); } } });
0true
hazelcast_src_test_java_com_hazelcast_map_BasicMapTest.java
1,228
@Deprecated public interface ShippingRate extends Serializable { public Long getId(); public void setId(Long id); public String getFeeType(); public void setFeeType(String feeType); public String getFeeSubType(); public void setFeeSubType(String feeSubType); public Integer getFeeBand(); public void setFeeBand(Integer feeBand); public BigDecimal getBandUnitQuantity(); public void setBandUnitQuantity(BigDecimal bandUnitQuantity); public BigDecimal getBandResultQuantity(); public void setBandResultQuantity(BigDecimal bandResultQuantity); public Integer getBandResultPercent(); public void setBandResultPercent(Integer bandResultPersent); }
0true
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_domain_ShippingRate.java
449
public class KeyRangeQuery extends SliceQuery { private final StaticBuffer keyStart; private final StaticBuffer keyEnd; public KeyRangeQuery(StaticBuffer keyStart, StaticBuffer keyEnd, StaticBuffer sliceStart, StaticBuffer sliceEnd) { super(sliceStart, sliceEnd); Preconditions.checkNotNull(keyStart); Preconditions.checkNotNull(keyEnd); this.keyStart=keyStart; this.keyEnd = keyEnd; } public KeyRangeQuery(StaticBuffer keyStart, StaticBuffer keyEnd, SliceQuery query) { super(query); Preconditions.checkNotNull(keyStart); Preconditions.checkNotNull(keyEnd); this.keyStart=keyStart; this.keyEnd = keyEnd; } public StaticBuffer getKeyStart() { return keyStart; } public StaticBuffer getKeyEnd() { return keyEnd; } @Override public KeyRangeQuery setLimit(int limit) { super.setLimit(limit); return this; } @Override public KeyRangeQuery updateLimit(int newLimit) { return new KeyRangeQuery(keyStart,keyEnd,this).setLimit(newLimit); } @Override public int hashCode() { return new HashCodeBuilder().append(keyStart).append(keyEnd).appendSuper(super.hashCode()).toHashCode(); } @Override public boolean equals(Object other) { if (this==other) return true; else if (other==null) return false; else if (!getClass().isInstance(other)) return false; KeyRangeQuery oth = (KeyRangeQuery)other; return keyStart.equals(oth.keyStart) && keyEnd.equals(oth.keyEnd) && super.equals(oth); } public boolean subsumes(KeyRangeQuery oth) { return super.subsumes(oth) && keyStart.compareTo(oth.keyStart)<=0 && keyEnd.compareTo(oth.keyEnd)>=0; } @Override public String toString() { return String.format("KeyRangeQuery(start: %s, end: %s, columns:[start: %s, end: %s], limit=%d)", keyStart, keyEnd, getSliceStart(), getSliceEnd(), getLimit()); } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_keycolumnvalue_KeyRangeQuery.java
84
@SuppressWarnings("serial") static final class MapReduceValuesToLongTask<K,V> extends BulkTask<K,V,Long> { final ObjectToLong<? super V> transformer; final LongByLongToLong reducer; final long basis; long result; MapReduceValuesToLongTask<K,V> rights, nextRight; MapReduceValuesToLongTask (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t, MapReduceValuesToLongTask<K,V> nextRight, ObjectToLong<? super V> transformer, long basis, LongByLongToLong reducer) { super(p, b, i, f, t); this.nextRight = nextRight; this.transformer = transformer; this.basis = basis; this.reducer = reducer; } public final Long getRawResult() { return result; } public final void compute() { final ObjectToLong<? super V> transformer; final LongByLongToLong reducer; if ((transformer = this.transformer) != null && (reducer = this.reducer) != null) { long r = this.basis; for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { addToPendingCount(1); (rights = new MapReduceValuesToLongTask<K,V> (this, batch >>>= 1, baseLimit = h, f, tab, rights, transformer, r, reducer)).fork(); } for (Node<K,V> p; (p = advance()) != null; ) r = reducer.apply(r, transformer.apply(p.val)); result = r; CountedCompleter<?> c; for (c = firstComplete(); c != null; c = c.nextComplete()) { @SuppressWarnings("unchecked") MapReduceValuesToLongTask<K,V> t = (MapReduceValuesToLongTask<K,V>)c, s = t.rights; while (s != null) { t.result = reducer.apply(t.result, s.result); s = t.rights = s.nextRight; } } } } }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
88
public class Decimal extends AbstractDecimal { public static final int DECIMALS = 3; public static final Decimal MIN_VALUE = new Decimal(minDoubleValue(DECIMALS)); public static final Decimal MAX_VALUE = new Decimal(maxDoubleValue(DECIMALS)); private Decimal() {} public Decimal(double value) { super(value, DECIMALS); } private Decimal(long format) { super(format, DECIMALS); } public static class DecimalSerializer extends AbstractDecimalSerializer<Decimal> { public DecimalSerializer() { super(DECIMALS, Decimal.class); } @Override protected Decimal construct(long format, int decimals) { assert decimals==DECIMALS; return new Decimal(format); } } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Decimal.java
592
public class CompositeStatusHandler implements StatusHandler { protected List<StatusHandler> handlers = new ArrayList<StatusHandler>(); public void handleStatus(String serviceName, ServiceStatusType status) { for (StatusHandler statusHandler : handlers) { statusHandler.handleStatus(serviceName, status); } } public List<StatusHandler> getHandlers() { return handlers; } public void setHandlers(List<StatusHandler> handlers) { this.handlers = handlers; } }
0true
common_src_main_java_org_broadleafcommerce_common_vendor_service_monitor_handler_CompositeStatusHandler.java
220
new Thread(){ public void run() { for (int i=0; i<20; i++){ l.countDown(); try { Thread.sleep(60); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start();
0true
hazelcast-client_src_test_java_com_hazelcast_client_countdownlatch_ClientCountDownLatchTest.java
3,680
public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { RoutingFieldMapper.Builder builder = routing(); parseField(builder, builder.name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("required")) { builder.required(nodeBooleanValue(fieldNode)); } else if (fieldName.equals("path")) { builder.path(fieldNode.toString()); } } return builder; } }
0true
src_main_java_org_elasticsearch_index_mapper_internal_RoutingFieldMapper.java
365
public class OGraphDatabasePool extends ODatabasePoolBase<OGraphDatabase> { private static OGraphDatabasePool globalInstance = new OGraphDatabasePool(); public OGraphDatabasePool() { super(); } public OGraphDatabasePool(final String iURL, final String iUserName, final String iUserPassword) { super(iURL, iUserName, iUserPassword); } public static OGraphDatabasePool global() { globalInstance.setup(); return globalInstance; } @Override protected OGraphDatabase createResource(Object owner, String iDatabaseName, Object... iAdditionalArgs) { return new OGraphDatabasePooled((OGraphDatabasePool) owner, iDatabaseName, (String) iAdditionalArgs[0], (String) iAdditionalArgs[1]); } }
0true
core_src_main_java_com_orientechnologies_orient_core_db_graph_OGraphDatabasePool.java
840
private class Async { final DiscoveryNodes nodes; final CountDown expectedOps; final ClearScrollRequest request; final List<Tuple<String, Long>[]> contexts = new ArrayList<Tuple<String, Long>[]>(); final AtomicReference<Throwable> expHolder; final ActionListener<ClearScrollResponse> listener; private Async(ClearScrollRequest request, ActionListener<ClearScrollResponse> listener, ClusterState clusterState) { int expectedOps = 0; this.nodes = clusterState.nodes(); if (request.getScrollIds().size() == 1 && "_all".equals(request.getScrollIds().get(0))) { expectedOps = nodes.size(); } else { for (String parsedScrollId : request.getScrollIds()) { Tuple<String, Long>[] context = parseScrollId(parsedScrollId).getContext(); expectedOps += context.length; this.contexts.add(context); } } this.request = request; this.listener = listener; this.expHolder = new AtomicReference<Throwable>(); this.expectedOps = new CountDown(expectedOps); } public void run() { if (expectedOps.isCountedDown()) { listener.onResponse(new ClearScrollResponse(true)); return; } if (contexts.isEmpty()) { for (final DiscoveryNode node : nodes) { searchServiceTransportAction.sendClearAllScrollContexts(node, request, new ActionListener<Boolean>() { @Override public void onResponse(Boolean success) { onFreedContext(); } @Override public void onFailure(Throwable e) { onFailedFreedContext(e, node); } }); } } else { for (Tuple<String, Long>[] context : contexts) { for (Tuple<String, Long> target : context) { final DiscoveryNode node = nodes.get(target.v1()); if (node == null) { onFreedContext(); continue; } searchServiceTransportAction.sendFreeContext(node, target.v2(), request, new ActionListener<Boolean>() { @Override public void onResponse(Boolean success) { onFreedContext(); } @Override public void onFailure(Throwable e) { onFailedFreedContext(e, node); } }); } } } } void onFreedContext() { if (expectedOps.countDown()) { boolean succeeded = expHolder.get() == null; listener.onResponse(new ClearScrollResponse(succeeded)); } } void onFailedFreedContext(Throwable e, DiscoveryNode node) { logger.warn("Clear SC failed on node[{}]", e, node); if (expectedOps.countDown()) { listener.onResponse(new ClearScrollResponse(false)); } else { expHolder.set(e); } } }
1no label
src_main_java_org_elasticsearch_action_search_TransportClearScrollAction.java
772
public class OIterationException extends OException { private static final long serialVersionUID = 2347493191705052402L; public OIterationException(String message, Throwable cause) { super(message, cause); } public OIterationException(String message) { super(message); } }
0true
core_src_main_java_com_orientechnologies_orient_core_iterator_OIterationException.java
94
@SuppressWarnings("serial") static final class ReduceValuesTask<K,V> extends BulkTask<K,V,V> { final BiFun<? super V, ? super V, ? extends V> reducer; V result; ReduceValuesTask<K,V> rights, nextRight; ReduceValuesTask (BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t, ReduceValuesTask<K,V> nextRight, BiFun<? super V, ? super V, ? extends V> reducer) { super(p, b, i, f, t); this.nextRight = nextRight; this.reducer = reducer; } public final V getRawResult() { return result; } public final void compute() { final BiFun<? super V, ? super V, ? extends V> reducer; if ((reducer = this.reducer) != null) { for (int i = baseIndex, f, h; batch > 0 && (h = ((f = baseLimit) + i) >>> 1) > i;) { addToPendingCount(1); (rights = new ReduceValuesTask<K,V> (this, batch >>>= 1, baseLimit = h, f, tab, rights, reducer)).fork(); } V r = null; for (Node<K,V> p; (p = advance()) != null; ) { V v = p.val; r = (r == null) ? v : reducer.apply(r, v); } result = r; CountedCompleter<?> c; for (c = firstComplete(); c != null; c = c.nextComplete()) { @SuppressWarnings("unchecked") ReduceValuesTask<K,V> t = (ReduceValuesTask<K,V>)c, s = t.rights; while (s != null) { V tr, sr; if ((sr = s.result) != null) t.result = (((tr = t.result) == null) ? sr : reducer.apply(tr, sr)); s = t.rights = s.nextRight; } } } } }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
4,518
public class IndicesTTLService extends AbstractLifecycleComponent<IndicesTTLService> { public static final String INDICES_TTL_INTERVAL = "indices.ttl.interval"; public static final String INDEX_TTL_DISABLE_PURGE = "index.ttl.disable_purge"; private final ClusterService clusterService; private final IndicesService indicesService; private final Client client; private volatile TimeValue interval; private final int bulkSize; private PurgerThread purgerThread; @Inject public IndicesTTLService(Settings settings, ClusterService clusterService, IndicesService indicesService, NodeSettingsService nodeSettingsService, Client client) { super(settings); this.clusterService = clusterService; this.indicesService = indicesService; this.client = client; this.interval = componentSettings.getAsTime("interval", TimeValue.timeValueSeconds(60)); this.bulkSize = componentSettings.getAsInt("bulk_size", 10000); nodeSettingsService.addListener(new ApplySettings()); } @Override protected void doStart() throws ElasticsearchException { this.purgerThread = new PurgerThread(EsExecutors.threadName(settings, "[ttl_expire]")); this.purgerThread.start(); } @Override protected void doStop() throws ElasticsearchException { this.purgerThread.doStop(); this.purgerThread.interrupt(); } @Override protected void doClose() throws ElasticsearchException { } private class PurgerThread extends Thread { volatile boolean running = true; public PurgerThread(String name) { super(name); setDaemon(true); } public void doStop() { running = false; } public void run() { while (running) { try { List<IndexShard> shardsToPurge = getShardsToPurge(); purgeShards(shardsToPurge); } catch (Throwable e) { if (running) { logger.warn("failed to execute ttl purge", e); } } try { Thread.sleep(interval.millis()); } catch (InterruptedException e) { // ignore, if we are interrupted because we are shutting down, running will be false } } } /** * Returns the shards to purge, i.e. the local started primary shards that have ttl enabled and disable_purge to false */ private List<IndexShard> getShardsToPurge() { List<IndexShard> shardsToPurge = new ArrayList<IndexShard>(); MetaData metaData = clusterService.state().metaData(); for (IndexService indexService : indicesService) { // check the value of disable_purge for this index IndexMetaData indexMetaData = metaData.index(indexService.index().name()); if (indexMetaData == null) { continue; } boolean disablePurge = indexMetaData.settings().getAsBoolean(INDEX_TTL_DISABLE_PURGE, false); if (disablePurge) { continue; } // should be optimized with the hasTTL flag FieldMappers ttlFieldMappers = indexService.mapperService().name(TTLFieldMapper.NAME); if (ttlFieldMappers == null) { continue; } // check if ttl is enabled for at least one type of this index boolean hasTTLEnabled = false; for (FieldMapper ttlFieldMapper : ttlFieldMappers) { if (((TTLFieldMapper) ttlFieldMapper).enabled()) { hasTTLEnabled = true; break; } } if (hasTTLEnabled) { for (IndexShard indexShard : indexService) { if (indexShard.state() == IndexShardState.STARTED && indexShard.routingEntry().primary() && indexShard.routingEntry().started()) { shardsToPurge.add(indexShard); } } } } return shardsToPurge; } } private void purgeShards(List<IndexShard> shardsToPurge) { for (IndexShard shardToPurge : shardsToPurge) { Query query = NumericRangeQuery.newLongRange(TTLFieldMapper.NAME, null, System.currentTimeMillis(), false, true); Engine.Searcher searcher = shardToPurge.acquireSearcher("indices_ttl"); try { logger.debug("[{}][{}] purging shard", shardToPurge.routingEntry().index(), shardToPurge.routingEntry().id()); ExpiredDocsCollector expiredDocsCollector = new ExpiredDocsCollector(shardToPurge.routingEntry().index()); searcher.searcher().search(query, expiredDocsCollector); List<DocToPurge> docsToPurge = expiredDocsCollector.getDocsToPurge(); BulkRequestBuilder bulkRequest = client.prepareBulk(); for (DocToPurge docToPurge : docsToPurge) { bulkRequest.add(new DeleteRequest().index(shardToPurge.routingEntry().index()).type(docToPurge.type).id(docToPurge.id).version(docToPurge.version).routing(docToPurge.routing)); bulkRequest = processBulkIfNeeded(bulkRequest, false); } processBulkIfNeeded(bulkRequest, true); } catch (Exception e) { logger.warn("failed to purge", e); } finally { searcher.release(); } } } private static class DocToPurge { public final String type; public final String id; public final long version; public final String routing; public DocToPurge(String type, String id, long version, String routing) { this.type = type; this.id = id; this.version = version; this.routing = routing; } } private class ExpiredDocsCollector extends Collector { private final MapperService mapperService; private AtomicReaderContext context; private List<DocToPurge> docsToPurge = new ArrayList<DocToPurge>(); public ExpiredDocsCollector(String index) { mapperService = indicesService.indexService(index).mapperService(); } public void setScorer(Scorer scorer) { } public boolean acceptsDocsOutOfOrder() { return true; } public void collect(int doc) { try { UidAndRoutingFieldsVisitor fieldsVisitor = new UidAndRoutingFieldsVisitor(); context.reader().document(doc, fieldsVisitor); Uid uid = fieldsVisitor.uid(); final long version = Versions.loadVersion(context.reader(), new Term(UidFieldMapper.NAME, uid.toBytesRef())); docsToPurge.add(new DocToPurge(uid.type(), uid.id(), version, fieldsVisitor.routing())); } catch (Exception e) { logger.trace("failed to collect doc", e); } } public void setNextReader(AtomicReaderContext context) throws IOException { this.context = context; } public List<DocToPurge> getDocsToPurge() { return this.docsToPurge; } } private BulkRequestBuilder processBulkIfNeeded(BulkRequestBuilder bulkRequest, boolean force) { if ((force && bulkRequest.numberOfActions() > 0) || bulkRequest.numberOfActions() >= bulkSize) { try { bulkRequest.execute(new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse bulkResponse) { logger.trace("bulk took " + bulkResponse.getTookInMillis() + "ms"); } @Override public void onFailure(Throwable e) { logger.warn("failed to execute bulk"); } }); } catch (Exception e) { logger.warn("failed to process bulk", e); } bulkRequest = client.prepareBulk(); } return bulkRequest; } class ApplySettings implements NodeSettingsService.Listener { @Override public void onRefreshSettings(Settings settings) { TimeValue interval = settings.getAsTime(INDICES_TTL_INTERVAL, IndicesTTLService.this.interval); if (!interval.equals(IndicesTTLService.this.interval)) { logger.info("updating indices.ttl.interval from [{}] to [{}]", IndicesTTLService.this.interval, interval); IndicesTTLService.this.interval = interval; } } } }
1no label
src_main_java_org_elasticsearch_indices_ttl_IndicesTTLService.java