Unnamed: 0
int64 0
6.45k
| func
stringlengths 29
253k
| target
class label 2
classes | project
stringlengths 36
167
|
---|---|---|---|
27 | 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;
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java |
1,970 | @Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.FIELD})
public @interface Nullable {
} | 0true
| src_main_java_org_elasticsearch_common_inject_internal_Nullable.java |
1,562 | @XmlRootElement(name = "listener")
@XmlType(propOrder = { "commands", "parameters", "protocol", "portRange", "ipAddress" })
public class OServerNetworkListenerConfiguration {
@XmlAttribute(name = "ip-address", required = true)
public String ipAddress = "127.0.0.1";
@XmlAttribute(name = "port-range")
public String portRange = "2424-2430";
@XmlAttribute
public String protocol = "binary";
@XmlElementWrapper
@XmlElementRef(type = OServerParameterConfiguration.class)
public OServerParameterConfiguration[] parameters;
@XmlElementWrapper(required = false)
@XmlAnyElement
@XmlElementRef(type = OServerCommandConfiguration.class)
public OServerCommandConfiguration[] commands;
} | 0true
| server_src_main_java_com_orientechnologies_orient_server_config_OServerNetworkListenerConfiguration.java |
3,010 | public class SimpleIdCache extends AbstractIndexComponent implements IdCache, SegmentReader.CoreClosedListener, DocumentTypeListener {
private final boolean reuse;
private final ConcurrentMap<Object, SimpleIdReaderCache> idReaders;
private final NavigableSet<HashedBytesArray> parentTypes;
IndexService indexService;
@Inject
public SimpleIdCache(Index index, @IndexSettings Settings indexSettings) {
super(index, indexSettings);
reuse = componentSettings.getAsBoolean("reuse", false);
idReaders = ConcurrentCollections.newConcurrentMap();
parentTypes = new TreeSet<HashedBytesArray>(UTF8SortedAsUnicodeComparator.utf8SortedAsUnicodeSortOrder);
}
@Override
public void setIndexService(IndexService indexService) {
this.indexService = indexService;
indexService.mapperService().addTypeListener(this);
}
@Override
public void close() throws ElasticsearchException {
indexService.mapperService().removeTypeListener(this);
clear();
}
@Override
public void clear() {
// Make a copy of the live id readers...
Map<Object, SimpleIdReaderCache> copy = new HashMap<Object, SimpleIdReaderCache>(idReaders);
for (Map.Entry<Object, SimpleIdReaderCache> entry : copy.entrySet()) {
SimpleIdReaderCache removed = idReaders.remove(entry.getKey());
// ... and only if the id reader still exists in live readers we decrement stats,
// this will prevent double onRemoval calls
if (removed != null) {
onRemoval(removed);
}
}
}
@Override
public void onClose(Object coreCacheKey) {
clear(coreCacheKey);
}
@Override
public void clear(Object coreCacheKey) {
SimpleIdReaderCache removed = idReaders.remove(coreCacheKey);
if (removed != null) onRemoval(removed);
}
@Override
public IdReaderCache reader(AtomicReader reader) {
return idReaders.get(reader.getCoreCacheKey());
}
@SuppressWarnings({"StringEquality"})
@Override
public void refresh(List<AtomicReaderContext> atomicReaderContexts) throws IOException {
// do a quick check for the common case, that all are there
if (refreshNeeded(atomicReaderContexts)) {
synchronized (idReaders) {
if (!refreshNeeded(atomicReaderContexts)) {
return;
}
// do the refresh
Map<Object, Map<String, TypeBuilder>> builders = new HashMap<Object, Map<String, TypeBuilder>>();
Map<Object, AtomicReader> cacheToReader = new HashMap<Object, AtomicReader>();
// first, go over and load all the id->doc map for all types
for (AtomicReaderContext context : atomicReaderContexts) {
AtomicReader reader = context.reader();
if (!refreshNeeded(context)) {
// no need, continue
continue;
}
if (reader instanceof SegmentReader) {
((SegmentReader) reader).addCoreClosedListener(this);
}
Map<String, TypeBuilder> readerBuilder = new HashMap<String, TypeBuilder>();
builders.put(reader.getCoreCacheKey(), readerBuilder);
cacheToReader.put(reader.getCoreCacheKey(), context.reader());
Terms terms = reader.terms(UidFieldMapper.NAME);
if (terms != null) {
TermsEnum termsEnum = terms.iterator(null);
DocsEnum docsEnum = null;
uid: for (BytesRef term = termsEnum.next(); term != null; term = termsEnum.next()) {
HashedBytesArray[] typeAndId = Uid.splitUidIntoTypeAndId(term);
// We don't want to load uid of child documents, this allows us to not load uids of child types.
if (!parentTypes.contains(typeAndId[0])) {
do {
HashedBytesArray nextParent = parentTypes.ceiling(typeAndId[0]);
if (nextParent == null) {
break uid;
}
TermsEnum.SeekStatus status = termsEnum.seekCeil(nextParent.toBytesRef());
if (status == TermsEnum.SeekStatus.END) {
break uid;
} else if (status == TermsEnum.SeekStatus.NOT_FOUND) {
term = termsEnum.term();
typeAndId = Uid.splitUidIntoTypeAndId(term);
} else if (status == TermsEnum.SeekStatus.FOUND) {
assert false : "Seek status should never be FOUND, because we seek only the type part";
term = termsEnum.term();
typeAndId = Uid.splitUidIntoTypeAndId(term);
}
} while (!parentTypes.contains(typeAndId[0]));
}
String type = typeAndId[0].toUtf8();
TypeBuilder typeBuilder = readerBuilder.get(type);
if (typeBuilder == null) {
typeBuilder = new TypeBuilder(reader);
readerBuilder.put(type, typeBuilder);
}
HashedBytesArray idAsBytes = checkIfCanReuse(builders, typeAndId[1]);
docsEnum = termsEnum.docs(null, docsEnum, 0);
for (int docId = docsEnum.nextDoc(); docId != DocsEnum.NO_MORE_DOCS; docId = docsEnum.nextDoc()) {
typeBuilder.idToDoc.put(idAsBytes, docId);
typeBuilder.docToId[docId] = idAsBytes;
}
}
}
}
// now, go and load the docId->parentId map
for (AtomicReaderContext context : atomicReaderContexts) {
AtomicReader reader = context.reader();
if (!refreshNeeded(context)) {
// no need, continue
continue;
}
Map<String, TypeBuilder> readerBuilder = builders.get(reader.getCoreCacheKey());
Terms terms = reader.terms(ParentFieldMapper.NAME);
if (terms != null) {
TermsEnum termsEnum = terms.iterator(null);
DocsEnum docsEnum = null;
for (BytesRef term = termsEnum.next(); term != null; term = termsEnum.next()) {
HashedBytesArray[] typeAndId = Uid.splitUidIntoTypeAndId(term);
TypeBuilder typeBuilder = readerBuilder.get(typeAndId[0].toUtf8());
if (typeBuilder == null) {
typeBuilder = new TypeBuilder(reader);
readerBuilder.put(typeAndId[0].toUtf8(), typeBuilder);
}
HashedBytesArray idAsBytes = checkIfCanReuse(builders, typeAndId[1]);
boolean added = false; // optimize for when all the docs are deleted for this id
docsEnum = termsEnum.docs(null, docsEnum, 0);
for (int docId = docsEnum.nextDoc(); docId != DocsEnum.NO_MORE_DOCS; docId = docsEnum.nextDoc()) {
if (!added) {
typeBuilder.parentIdsValues.add(idAsBytes);
added = true;
}
typeBuilder.parentIdsOrdinals[docId] = typeBuilder.t;
}
if (added) {
typeBuilder.t++;
}
}
}
}
// now, build it back
for (Map.Entry<Object, Map<String, TypeBuilder>> entry : builders.entrySet()) {
Object readerKey = entry.getKey();
MapBuilder<String, SimpleIdReaderTypeCache> types = MapBuilder.newMapBuilder();
for (Map.Entry<String, TypeBuilder> typeBuilderEntry : entry.getValue().entrySet()) {
types.put(typeBuilderEntry.getKey(), new SimpleIdReaderTypeCache(typeBuilderEntry.getKey(),
typeBuilderEntry.getValue().idToDoc,
typeBuilderEntry.getValue().docToId,
typeBuilderEntry.getValue().parentIdsValues.toArray(new HashedBytesArray[typeBuilderEntry.getValue().parentIdsValues.size()]),
typeBuilderEntry.getValue().parentIdsOrdinals));
}
AtomicReader indexReader = cacheToReader.get(readerKey);
SimpleIdReaderCache readerCache = new SimpleIdReaderCache(types.immutableMap(), ShardUtils.extractShardId(indexReader));
idReaders.put(readerKey, readerCache);
onCached(readerCache);
}
}
}
}
void onCached(SimpleIdReaderCache readerCache) {
if (readerCache.shardId != null) {
IndexShard shard = indexService.shard(readerCache.shardId.id());
if (shard != null) {
shard.idCache().onCached(readerCache.sizeInBytes());
}
}
}
void onRemoval(SimpleIdReaderCache readerCache) {
if (readerCache.shardId != null) {
IndexShard shard = indexService.shard(readerCache.shardId.id());
if (shard != null) {
shard.idCache().onRemoval(readerCache.sizeInBytes());
}
}
}
private HashedBytesArray checkIfCanReuse(Map<Object, Map<String, TypeBuilder>> builders, HashedBytesArray idAsBytes) {
HashedBytesArray finalIdAsBytes;
// go over and see if we can reuse this id
if (reuse) {
for (SimpleIdReaderCache idReaderCache : idReaders.values()) {
finalIdAsBytes = idReaderCache.canReuse(idAsBytes);
if (finalIdAsBytes != null) {
return finalIdAsBytes;
}
}
}
// even if we don't enable reuse, at least check on the current "live" builders that we are handling
for (Map<String, TypeBuilder> map : builders.values()) {
for (TypeBuilder typeBuilder : map.values()) {
finalIdAsBytes = typeBuilder.canReuse(idAsBytes);
if (finalIdAsBytes != null) {
return finalIdAsBytes;
}
}
}
return idAsBytes;
}
private boolean refreshNeeded(List<AtomicReaderContext> atomicReaderContexts) {
for (AtomicReaderContext atomicReaderContext : atomicReaderContexts) {
if (refreshNeeded(atomicReaderContext)) {
return true;
}
}
return false;
}
private boolean refreshNeeded(AtomicReaderContext atomicReaderContext) {
return !idReaders.containsKey(atomicReaderContext.reader().getCoreCacheKey());
}
@Override
public void beforeCreate(DocumentMapper mapper) {
synchronized (idReaders) {
ParentFieldMapper parentFieldMapper = mapper.parentFieldMapper();
if (parentFieldMapper.active()) {
// A _parent field can never be added to an existing mapping, so a _parent field either exists on
// a new created or doesn't exists. This is why we can update the known parent types via DocumentTypeListener
if (parentTypes.add(new HashedBytesArray(Strings.toUTF8Bytes(parentFieldMapper.type(), new BytesRef())))) {
clear();
}
}
}
}
@Override
public void afterRemove(DocumentMapper mapper) {
synchronized (idReaders) {
ParentFieldMapper parentFieldMapper = mapper.parentFieldMapper();
if (parentFieldMapper.active()) {
parentTypes.remove(new HashedBytesArray(Strings.toUTF8Bytes(parentFieldMapper.type(), new BytesRef())));
}
}
}
static class TypeBuilder {
final ObjectIntOpenHashMap<HashedBytesArray> idToDoc = new ObjectIntOpenHashMap<HashedBytesArray>();
final HashedBytesArray[] docToId;
final ArrayList<HashedBytesArray> parentIdsValues = new ArrayList<HashedBytesArray>();
final int[] parentIdsOrdinals;
int t = 1; // current term number (0 indicated null value)
TypeBuilder(IndexReader reader) {
parentIdsOrdinals = new int[reader.maxDoc()];
// the first one indicates null value
parentIdsValues.add(null);
docToId = new HashedBytesArray[reader.maxDoc()];
}
/**
* Returns an already stored instance if exists, if not, returns null;
*/
public HashedBytesArray canReuse(HashedBytesArray id) {
if (idToDoc.containsKey(id)) {
// we can use #lkey() since this is called from a synchronized block
return idToDoc.lkey();
} else {
return id;
}
}
}
} | 0true
| src_main_java_org_elasticsearch_index_cache_id_simple_SimpleIdCache.java |
178 | static final class ExceptionNode extends WeakReference<ForkJoinTask<?>> {
final Throwable ex;
ExceptionNode next;
final long thrower; // use id not ref to avoid weak cycles
final int hashCode; // store task hashCode before weak ref disappears
ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
super(task, exceptionTableRefQueue);
this.ex = ex;
this.next = next;
this.thrower = Thread.currentThread().getId();
this.hashCode = System.identityHashCode(task);
}
} | 0true
| src_main_java_jsr166y_ForkJoinTask.java |
51 | public class InstanceId implements Externalizable, Comparable<InstanceId>
{
private int serverId;
public InstanceId()
{}
public InstanceId( int serverId )
{
this.serverId = serverId;
}
@Override
public int compareTo( InstanceId o )
{
return serverId - o.serverId;
}
@Override
public int hashCode()
{
return serverId;
}
@Override
public String toString()
{
return Integer.toString( serverId );
}
@Override
public boolean equals( Object o )
{
if ( this == o )
{
return true;
}
if ( o == null || getClass() != o.getClass() )
{
return false;
}
InstanceId instanceId1 = (InstanceId) o;
if ( serverId != instanceId1.serverId )
{
return false;
}
return true;
}
@Override
public void writeExternal( ObjectOutput out ) throws IOException
{
out.writeInt( serverId );
}
@Override
public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException
{
serverId = in.readInt();
}
public int toIntegerIndex()
{
return serverId;
}
} | 1no label
| enterprise_cluster_src_main_java_org_neo4j_cluster_InstanceId.java |
133 | public abstract class RecursiveTask<V> extends ForkJoinTask<V> {
private static final long serialVersionUID = 5232453952276485270L;
/**
* The result of the computation.
*/
V result;
/**
* The main computation performed by this task.
* @return the result of the computation
*/
protected abstract V compute();
public final V getRawResult() {
return result;
}
protected final void setRawResult(V value) {
result = value;
}
/**
* Implements execution conventions for RecursiveTask.
*/
protected final boolean exec() {
result = compute();
return true;
}
} | 0true
| src_main_java_jsr166e_RecursiveTask.java |
1,253 | public class TransportClient extends AbstractClient {
private final Injector injector;
private final Settings settings;
private final Environment environment;
private final PluginsService pluginsService;
private final TransportClientNodesService nodesService;
private final InternalTransportClient internalClient;
/**
* Constructs a new transport client with settings loaded either from the classpath or the file system (the
* <tt>elasticsearch.(yml|json)</tt> files optionally prefixed with <tt>config/</tt>).
*/
public TransportClient() throws ElasticsearchException {
this(ImmutableSettings.Builder.EMPTY_SETTINGS, true);
}
/**
* Constructs a new transport client with explicit settings and settings loaded either from the classpath or the file
* system (the <tt>elasticsearch.(yml|json)</tt> files optionally prefixed with <tt>config/</tt>).
*/
public TransportClient(Settings settings) {
this(settings, true);
}
/**
* Constructs a new transport client with explicit settings and settings loaded either from the classpath or the file
* system (the <tt>elasticsearch.(yml|json)</tt> files optionally prefixed with <tt>config/</tt>).
*/
public TransportClient(Settings.Builder settings) {
this(settings.build(), true);
}
/**
* Constructs a new transport client with the provided settings and the ability to control if settings will
* be loaded from the classpath / file system (the <tt>elasticsearch.(yml|json)</tt> files optionally prefixed with
* <tt>config/</tt>).
*
* @param settings The explicit settings.
* @param loadConfigSettings <tt>true</tt> if settings should be loaded from the classpath/file system.
* @throws org.elasticsearch.ElasticsearchException
*/
public TransportClient(Settings.Builder settings, boolean loadConfigSettings) throws ElasticsearchException {
this(settings.build(), loadConfigSettings);
}
/**
* Constructs a new transport client with the provided settings and the ability to control if settings will
* be loaded from the classpath / file system (the <tt>elasticsearch.(yml|json)</tt> files optionally prefixed with
* <tt>config/</tt>).
*
* @param pSettings The explicit settings.
* @param loadConfigSettings <tt>true</tt> if settings should be loaded from the classpath/file system.
* @throws org.elasticsearch.ElasticsearchException
*/
public TransportClient(Settings pSettings, boolean loadConfigSettings) throws ElasticsearchException {
Tuple<Settings, Environment> tuple = InternalSettingsPreparer.prepareSettings(pSettings, loadConfigSettings);
Settings settings = settingsBuilder().put(tuple.v1())
.put("network.server", false)
.put("node.client", true)
.build();
this.environment = tuple.v2();
this.pluginsService = new PluginsService(settings, tuple.v2());
this.settings = pluginsService.updatedSettings();
Version version = Version.CURRENT;
CompressorFactory.configure(this.settings);
ModulesBuilder modules = new ModulesBuilder();
modules.add(new Version.Module(version));
modules.add(new CacheRecyclerModule(settings));
modules.add(new PluginsModule(this.settings, pluginsService));
modules.add(new EnvironmentModule(environment));
modules.add(new SettingsModule(this.settings));
modules.add(new NetworkModule());
modules.add(new ClusterNameModule(this.settings));
modules.add(new ThreadPoolModule(this.settings));
modules.add(new TransportSearchModule());
modules.add(new TransportModule(this.settings));
modules.add(new ActionModule(true));
modules.add(new ClientTransportModule());
injector = modules.createInjector();
injector.getInstance(TransportService.class).start();
nodesService = injector.getInstance(TransportClientNodesService.class);
internalClient = injector.getInstance(InternalTransportClient.class);
}
/**
* Returns the current registered transport addresses to use (added using
* {@link #addTransportAddress(org.elasticsearch.common.transport.TransportAddress)}.
*/
public ImmutableList<TransportAddress> transportAddresses() {
return nodesService.transportAddresses();
}
/**
* Returns the current connected transport nodes that this client will use.
* <p/>
* <p>The nodes include all the nodes that are currently alive based on the transport
* addresses provided.
*/
public ImmutableList<DiscoveryNode> connectedNodes() {
return nodesService.connectedNodes();
}
/**
* The list of filtered nodes that were not connected to, for example, due to
* mismatch in cluster name.
*/
public ImmutableList<DiscoveryNode> filteredNodes() {
return nodesService.filteredNodes();
}
/**
* Returns the listed nodes in the transport client (ones added to it).
*/
public ImmutableList<DiscoveryNode> listedNodes() {
return nodesService.listedNodes();
}
/**
* Adds a transport address that will be used to connect to.
* <p/>
* <p>The Node this transport address represents will be used if its possible to connect to it.
* If it is unavailable, it will be automatically connected to once it is up.
* <p/>
* <p>In order to get the list of all the current connected nodes, please see {@link #connectedNodes()}.
*/
public TransportClient addTransportAddress(TransportAddress transportAddress) {
nodesService.addTransportAddresses(transportAddress);
return this;
}
/**
* Adds a list of transport addresses that will be used to connect to.
* <p/>
* <p>The Node this transport address represents will be used if its possible to connect to it.
* If it is unavailable, it will be automatically connected to once it is up.
* <p/>
* <p>In order to get the list of all the current connected nodes, please see {@link #connectedNodes()}.
*/
public TransportClient addTransportAddresses(TransportAddress... transportAddress) {
nodesService.addTransportAddresses(transportAddress);
return this;
}
/**
* Removes a transport address from the list of transport addresses that are used to connect to.
*/
public TransportClient removeTransportAddress(TransportAddress transportAddress) {
nodesService.removeTransportAddress(transportAddress);
return this;
}
/**
* Closes the client.
*/
@Override
public void close() {
injector.getInstance(TransportClientNodesService.class).close();
injector.getInstance(TransportService.class).close();
try {
injector.getInstance(MonitorService.class).close();
} catch (Exception e) {
// ignore, might not be bounded
}
for (Class<? extends LifecycleComponent> plugin : pluginsService.services()) {
injector.getInstance(plugin).close();
}
injector.getInstance(ThreadPool.class).shutdown();
try {
injector.getInstance(ThreadPool.class).awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// ignore
Thread.currentThread().interrupt();
}
try {
injector.getInstance(ThreadPool.class).shutdownNow();
} catch (Exception e) {
// ignore
}
injector.getInstance(CacheRecycler.class).close();
injector.getInstance(PageCacheRecycler.class).close();
CachedStreams.clear();
}
@Override
public Settings settings() {
return this.settings;
}
@Override
public ThreadPool threadPool() {
return internalClient.threadPool();
}
@Override
public AdminClient admin() {
return internalClient.admin();
}
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> ActionFuture<Response> execute(Action<Request, Response, RequestBuilder> action, Request request) {
return internalClient.execute(action, request);
}
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void execute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
internalClient.execute(action, request, listener);
}
@Override
public ActionFuture<IndexResponse> index(IndexRequest request) {
return internalClient.index(request);
}
@Override
public void index(IndexRequest request, ActionListener<IndexResponse> listener) {
internalClient.index(request, listener);
}
@Override
public ActionFuture<UpdateResponse> update(UpdateRequest request) {
return internalClient.update(request);
}
@Override
public void update(UpdateRequest request, ActionListener<UpdateResponse> listener) {
internalClient.update(request, listener);
}
@Override
public ActionFuture<DeleteResponse> delete(DeleteRequest request) {
return internalClient.delete(request);
}
@Override
public void delete(DeleteRequest request, ActionListener<DeleteResponse> listener) {
internalClient.delete(request, listener);
}
@Override
public ActionFuture<BulkResponse> bulk(BulkRequest request) {
return internalClient.bulk(request);
}
@Override
public void bulk(BulkRequest request, ActionListener<BulkResponse> listener) {
internalClient.bulk(request, listener);
}
@Override
public ActionFuture<DeleteByQueryResponse> deleteByQuery(DeleteByQueryRequest request) {
return internalClient.deleteByQuery(request);
}
@Override
public void deleteByQuery(DeleteByQueryRequest request, ActionListener<DeleteByQueryResponse> listener) {
internalClient.deleteByQuery(request, listener);
}
@Override
public ActionFuture<GetResponse> get(GetRequest request) {
return internalClient.get(request);
}
@Override
public void get(GetRequest request, ActionListener<GetResponse> listener) {
internalClient.get(request, listener);
}
@Override
public ActionFuture<MultiGetResponse> multiGet(MultiGetRequest request) {
return internalClient.multiGet(request);
}
@Override
public void multiGet(MultiGetRequest request, ActionListener<MultiGetResponse> listener) {
internalClient.multiGet(request, listener);
}
@Override
public ActionFuture<CountResponse> count(CountRequest request) {
return internalClient.count(request);
}
@Override
public void count(CountRequest request, ActionListener<CountResponse> listener) {
internalClient.count(request, listener);
}
@Override
public ActionFuture<SuggestResponse> suggest(SuggestRequest request) {
return internalClient.suggest(request);
}
@Override
public void suggest(SuggestRequest request, ActionListener<SuggestResponse> listener) {
internalClient.suggest(request, listener);
}
@Override
public ActionFuture<SearchResponse> search(SearchRequest request) {
return internalClient.search(request);
}
@Override
public void search(SearchRequest request, ActionListener<SearchResponse> listener) {
internalClient.search(request, listener);
}
@Override
public ActionFuture<SearchResponse> searchScroll(SearchScrollRequest request) {
return internalClient.searchScroll(request);
}
@Override
public void searchScroll(SearchScrollRequest request, ActionListener<SearchResponse> listener) {
internalClient.searchScroll(request, listener);
}
@Override
public ActionFuture<MultiSearchResponse> multiSearch(MultiSearchRequest request) {
return internalClient.multiSearch(request);
}
@Override
public void multiSearch(MultiSearchRequest request, ActionListener<MultiSearchResponse> listener) {
internalClient.multiSearch(request, listener);
}
@Override
public ActionFuture<SearchResponse> moreLikeThis(MoreLikeThisRequest request) {
return internalClient.moreLikeThis(request);
}
@Override
public void moreLikeThis(MoreLikeThisRequest request, ActionListener<SearchResponse> listener) {
internalClient.moreLikeThis(request, listener);
}
@Override
public ActionFuture<TermVectorResponse> termVector(TermVectorRequest request) {
return internalClient.termVector(request);
}
@Override
public void termVector(TermVectorRequest request, ActionListener<TermVectorResponse> listener) {
internalClient.termVector(request, listener);
}
@Override
public ActionFuture<MultiTermVectorsResponse> multiTermVectors(final MultiTermVectorsRequest request) {
return internalClient.multiTermVectors(request);
}
@Override
public void multiTermVectors(final MultiTermVectorsRequest request, final ActionListener<MultiTermVectorsResponse> listener) {
internalClient.multiTermVectors(request, listener);
}
@Override
public ActionFuture<PercolateResponse> percolate(PercolateRequest request) {
return internalClient.percolate(request);
}
@Override
public void percolate(PercolateRequest request, ActionListener<PercolateResponse> listener) {
internalClient.percolate(request, listener);
}
@Override
public ActionFuture<ExplainResponse> explain(ExplainRequest request) {
return internalClient.explain(request);
}
@Override
public void explain(ExplainRequest request, ActionListener<ExplainResponse> listener) {
internalClient.explain(request, listener);
}
} | 1no label
| src_main_java_org_elasticsearch_client_transport_TransportClient.java |
760 | public class ListRemoveOperation extends CollectionBackupAwareOperation {
private int index;
private long itemId;
public ListRemoveOperation() {
}
public ListRemoveOperation(String name, int index) {
super(name);
this.index = index;
}
@Override
public boolean shouldBackup() {
return true;
}
@Override
public Operation getBackupOperation() {
return new CollectionRemoveBackupOperation(name, itemId);
}
@Override
public int getId() {
return CollectionDataSerializerHook.LIST_REMOVE;
}
@Override
public void beforeRun() throws Exception {
publishEvent(ItemEventType.ADDED, (Data) response);
}
@Override
public void run() throws Exception {
final CollectionItem item = getOrCreateListContainer().remove(index);
itemId = item.getItemId();
response = item.getValue();
}
@Override
public void afterRun() throws Exception {
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeInt(index);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
index = in.readInt();
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_collection_list_ListRemoveOperation.java |
1,093 | @Service("blProductOptionValidationService")
public class ProductOptionValidationServiceImpl implements ProductOptionValidationService {
private static final Log LOG = LogFactory.getLog(ProductOptionValidationServiceImpl.class);
/* (non-Javadoc)
* @see org.broadleafcommerce.core.order.service.ProductOptionValidationService#validate(org.broadleafcommerce.core.catalog.domain.ProductOption, java.lang.String)
*/
@Override
public Boolean validate(ProductOption productOption, String value) {
if (productOption.getProductOptionValidationType() == ProductOptionValidationType.REGEX) {
if (!validateRegex(productOption.getValidationString(), value))
{
LOG.error(productOption.getErrorMessage() + ". Value [" + value + "] does not match regex string [" + productOption.getValidationString() + "]");
throw new ProductOptionValidationException(productOption.getErrorMessage(), productOption.getErrorCode());
}
}
return true;
}
protected Boolean validateRegex(String regex, String value) {
return Pattern.matches(regex, value);
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_service_ProductOptionValidationServiceImpl.java |
225 | public class RuntimeEnvironmentPropertiesManagerTest extends BaseTest {
@Resource(name = "blConfigurationManager")
RuntimeEnvironmentPropertiesManager configurationManager;
@Test
public void testPropertyOnly() throws Exception {
String s = configurationManager.getProperty("detect.sequence.generator.inconsistencies");
if(s.indexOf("$")>=0) {
Assert.fail("RuntimeEnvironmentPropertiesManager bean not defined");
}
}
@Test(dependsOnMethods={"testPropertyOnly"})
public void testPrefix() throws Exception {
configurationManager.setPrefix("detect");
String s = configurationManager.getProperty("sequence.generator.inconsistencies");
if(s.indexOf("$")>=0) {
Assert.fail("RuntimeEnvironmentPropertiesManager bean not defined");
}
}
@Test(dependsOnMethods={"testPrefix"})
public void testSuffix() throws Exception {
String s = configurationManager.getProperty("sequence.generator","inconsistencies");
if(s.indexOf("$")>=0) {
Assert.fail("RuntimeEnvironmentPropertiesManager bean not defined");
}
}
@Test(dependsOnMethods={"testSuffix"})
public void testNullSuffix() throws Exception {
configurationManager.setPrefix("detect");
String s = configurationManager.getProperty("sequence.generator.inconsistencies", "SOMETHING");
Assert.assertNotNull(s);
}
@Test
public void testNULL() throws Exception {
String s = configurationManager.getProperty(null, "SOMETHING");
Assert.assertEquals(s, null);
}
} | 0true
| integration_src_test_java_org_broadleafcommerce_common_config_RuntimeEnvironmentPropertiesManagerTest.java |
192 | public class KeyValueStoreUtil {
private static final Logger log = LoggerFactory.getLogger(KeyValueStoreUtil.class);
public static final Serializer serial = new StandardSerializer();
public static final long idOffset = 1000;
public static final StaticBuffer MIN_KEY = BufferUtil.getLongBuffer(0);
public static final StaticBuffer MAX_KEY = BufferUtil.getLongBuffer(-1);
public static String[] generateData(int numKeys) {
String[] ret = new String[numKeys];
for (int i = 0; i < numKeys; i++) {
ret[i] = RandomGenerator.randomString();
}
return ret;
}
public static String[][] generateData(int numKeys, int numColumns) {
String[][] ret = new String[numKeys][numColumns];
for (int i = 0; i < numKeys; i++) {
for (int j = 0; j < numColumns; j++) {
ret[i][j] = RandomGenerator.randomString();
}
}
return ret;
}
public static void print(String[] data) {
log.debug(Arrays.toString(data));
}
public static void print(String[][] data) {
for (int i = 0; i < data.length; i++) print(data[i]);
}
public static StaticBuffer getBuffer(int no) {
return BufferUtil.getLongBuffer(no + idOffset);
}
public static int getID(StaticBuffer b) {
long res = b.getLong(0) - idOffset;
Assert.assertTrue(res >= 0 && res < Integer.MAX_VALUE);
return (int) res;
}
public static StaticBuffer getBuffer(String s) {
DataOutput out = serial.getDataOutput(50);
out.writeObjectNotNull(s);
return out.getStaticBuffer();
}
public static String getString(ReadBuffer b) {
return serial.readObjectNotNull(b, String.class);
}
public static String getString(StaticBuffer b) {
return serial.readObjectNotNull(b.asReadBuffer(), String.class);
}
public static int count(RecordIterator<?> iterator) throws BackendException {
int count = 0;
while (iterator.hasNext()) {
iterator.next();
count++;
}
return count;
}
} | 0true
| titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_KeyValueStoreUtil.java |
1,977 | public static final Scoping SINGLETON_ANNOTATION = new Scoping() {
public <V> V acceptVisitor(BindingScopingVisitor<V> visitor) {
return visitor.visitScopeAnnotation(Singleton.class);
}
@Override
public Class<? extends Annotation> getScopeAnnotation() {
return Singleton.class;
}
@Override
public String toString() {
return Singleton.class.getName();
}
public void applyTo(ScopedBindingBuilder scopedBindingBuilder) {
scopedBindingBuilder.in(Singleton.class);
}
}; | 0true
| src_main_java_org_elasticsearch_common_inject_internal_Scoping.java |
482 | public interface ResponseHandler {
void handle(ResponseStream stream) throws Exception;
} | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_spi_ResponseHandler.java |
297 | public class OTraverseFieldProcess extends OTraverseAbstractProcess<Iterator<Object>> {
protected Object field;
public OTraverseFieldProcess(final OTraverse iCommand, final Iterator<Object> iTarget) {
super(iCommand, iTarget);
}
public OIdentifiable process() {
while (target.hasNext()) {
field = target.next();
final Object fieldValue;
if (field instanceof OSQLFilterItem)
fieldValue = ((OSQLFilterItem) field).getValue(((OTraverseRecordProcess) command.getContext().peek(-2)).getTarget(), null);
else
fieldValue = ((OTraverseRecordProcess) command.getContext().peek(-2)).getTarget().rawField(field.toString());
if (fieldValue != null) {
final OTraverseAbstractProcess<?> subProcess;
if (fieldValue instanceof Iterator<?> || OMultiValue.isMultiValue(fieldValue)) {
final Iterator<Object> coll = OMultiValue.getMultiValueIterator(fieldValue);
switch (command.getStrategy()) {
case BREADTH_FIRST:
subProcess = new OTraverseMultiValueBreadthFirstProcess(command, coll);
break;
case DEPTH_FIRST:
subProcess = new OTraverseMultiValueDepthFirstProcess(command, coll);
break;
default:
throw new IllegalArgumentException("Traverse strategy not supported: " + command.getStrategy());
}
} else if (fieldValue instanceof OIdentifiable && ((OIdentifiable) fieldValue).getRecord() instanceof ODocument)
subProcess = new OTraverseRecordProcess(command, (ODocument) ((OIdentifiable) fieldValue).getRecord());
else
continue;
final OIdentifiable subValue = subProcess.process();
if (subValue != null)
return subValue;
}
}
return drop();
}
@Override
public String getStatus() {
return field != null ? field.toString() : null;
}
@Override
public String toString() {
return field != null ? "[field:" + field.toString() + "]" : null;
}
} | 1no label
| core_src_main_java_com_orientechnologies_orient_core_command_traverse_OTraverseFieldProcess.java |
3,742 | node.nodeEngine.getExecutionService().execute("hz:wan", new Runnable() {
@Override
public void run() {
final Data data = packet.getData();
try {
WanReplicationEvent replicationEvent = (WanReplicationEvent) node.nodeEngine.toObject(data);
String serviceName = replicationEvent.getServiceName();
ReplicationSupportingService service = node.nodeEngine.getService(serviceName);
service.onReplicationEvent(replicationEvent);
} catch (Exception e) {
logger.severe(e);
}
}
}); | 1no label
| hazelcast_src_main_java_com_hazelcast_wan_impl_WanReplicationServiceImpl.java |
1,699 | public class ChannelBufferBytesReference implements BytesReference {
private final ChannelBuffer buffer;
public ChannelBufferBytesReference(ChannelBuffer buffer) {
this.buffer = buffer;
}
@Override
public byte get(int index) {
return buffer.getByte(buffer.readerIndex() + index);
}
@Override
public int length() {
return buffer.readableBytes();
}
@Override
public BytesReference slice(int from, int length) {
return new ChannelBufferBytesReference(buffer.slice(from, length));
}
@Override
public StreamInput streamInput() {
return ChannelBufferStreamInputFactory.create(buffer.duplicate());
}
@Override
public void writeTo(OutputStream os) throws IOException {
buffer.getBytes(buffer.readerIndex(), os, length());
}
@Override
public byte[] toBytes() {
return copyBytesArray().toBytes();
}
@Override
public BytesArray toBytesArray() {
if (buffer.hasArray()) {
return new BytesArray(buffer.array(), buffer.arrayOffset() + buffer.readerIndex(), buffer.readableBytes());
}
return copyBytesArray();
}
@Override
public BytesArray copyBytesArray() {
byte[] copy = new byte[buffer.readableBytes()];
buffer.getBytes(buffer.readerIndex(), copy);
return new BytesArray(copy);
}
@Override
public ChannelBuffer toChannelBuffer() {
return buffer.duplicate();
}
@Override
public boolean hasArray() {
return buffer.hasArray();
}
@Override
public byte[] array() {
return buffer.array();
}
@Override
public int arrayOffset() {
return buffer.arrayOffset() + buffer.readerIndex();
}
@Override
public String toUtf8() {
return buffer.toString(Charsets.UTF_8);
}
@Override
public BytesRef toBytesRef() {
if (buffer.hasArray()) {
return new BytesRef(buffer.array(), buffer.arrayOffset() + buffer.readerIndex(), buffer.readableBytes());
}
byte[] copy = new byte[buffer.readableBytes()];
buffer.getBytes(buffer.readerIndex(), copy);
return new BytesRef(copy);
}
@Override
public BytesRef copyBytesRef() {
byte[] copy = new byte[buffer.readableBytes()];
buffer.getBytes(buffer.readerIndex(), copy);
return new BytesRef(copy);
}
@Override
public int hashCode() {
return Helper.bytesHashCode(this);
}
@Override
public boolean equals(Object obj) {
return Helper.bytesEqual(this, (BytesReference) obj);
}
} | 1no label
| src_main_java_org_elasticsearch_common_bytes_ChannelBufferBytesReference.java |
427 | public class IndexTransaction implements BaseTransaction, LoggableTransaction {
private static final int DEFAULT_OUTER_MAP_SIZE = 3;
private static final int DEFAULT_INNER_MAP_SIZE = 5;
private final IndexProvider index;
private final BaseTransaction indexTx;
private final KeyInformation.IndexRetriever keyInformations;
private final Duration maxWriteTime;
private Map<String,Map<String,IndexMutation>> mutations;
public IndexTransaction(final IndexProvider index, final KeyInformation.IndexRetriever keyInformations,
BaseTransactionConfig config,
Duration maxWriteTime) throws BackendException {
Preconditions.checkNotNull(index);
Preconditions.checkNotNull(keyInformations);
this.index=index;
this.keyInformations = keyInformations;
this.indexTx=index.beginTransaction(config);
Preconditions.checkNotNull(indexTx);
this.maxWriteTime = maxWriteTime;
this.mutations = new HashMap<String,Map<String,IndexMutation>>(DEFAULT_OUTER_MAP_SIZE);
}
public void add(String store, String docid, IndexEntry entry, boolean isNew) {
getIndexMutation(store,docid, isNew, false).addition(new IndexEntry(entry.field, entry.value, entry.getMetaData()));
}
public void add(String store, String docid, String key, Object value, boolean isNew) {
getIndexMutation(store,docid,isNew,false).addition(new IndexEntry(key,value));
}
public void delete(String store, String docid, String key, Object value, boolean deleteAll) {
getIndexMutation(store,docid,false,deleteAll).deletion(new IndexEntry(key,value));
}
private IndexMutation getIndexMutation(String store, String docid, boolean isNew, boolean isDeleted) {
Map<String,IndexMutation> storeMutations = mutations.get(store);
if (storeMutations==null) {
storeMutations = new HashMap<String,IndexMutation>(DEFAULT_INNER_MAP_SIZE);
mutations.put(store,storeMutations);
}
IndexMutation m = storeMutations.get(docid);
if (m==null) {
m = new IndexMutation(isNew,isDeleted);
storeMutations.put(docid, m);
} else {
//IndexMutation already exists => if we deleted and re-created it we need to remove the deleted flag
if (isNew && m.isDeleted()) {
m.resetDelete();
assert !m.isNew() && !m.isDeleted();
}
}
return m;
}
public void register(String store, String key, KeyInformation information) throws BackendException {
index.register(store,key,information,indexTx);
}
public List<String> query(IndexQuery query) throws BackendException {
return index.query(query,keyInformations,indexTx);
}
public Iterable<RawQuery.Result<String>> query(RawQuery query) throws BackendException {
return index.query(query,keyInformations,indexTx);
}
public void restore(Map<String, Map<String,List<IndexEntry>>> documents) throws BackendException {
index.restore(documents,keyInformations,indexTx);
}
@Override
public void commit() throws BackendException {
flushInternal();
indexTx.commit();
}
@Override
public void rollback() throws BackendException {
mutations=null;
indexTx.rollback();
}
private void flushInternal() throws BackendException {
if (mutations!=null && !mutations.isEmpty()) {
//Consolidate all mutations prior to persistence to ensure that no addition accidentally gets swallowed by a delete
for (Map<String, IndexMutation> store : mutations.values()) {
for (IndexMutation mut : store.values()) mut.consolidate();
}
BackendOperation.execute(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
index.mutate(mutations, keyInformations, indexTx);
return true;
}
@Override
public String toString() {
return "IndexMutation";
}
}, maxWriteTime);
mutations=null;
}
}
@Override
public void logMutations(DataOutput out) {
VariableLong.writePositive(out,mutations.size());
for (Map.Entry<String,Map<String,IndexMutation>> store : mutations.entrySet()) {
out.writeObjectNotNull(store.getKey());
VariableLong.writePositive(out,store.getValue().size());
for (Map.Entry<String,IndexMutation> doc : store.getValue().entrySet()) {
out.writeObjectNotNull(doc.getKey());
IndexMutation mut = doc.getValue();
out.putByte((byte)(mut.isNew()?1:(mut.isDeleted()?2:0)));
List<IndexEntry> adds = mut.getAdditions();
VariableLong.writePositive(out,adds.size());
for (IndexEntry add : adds) writeIndexEntry(out,add);
List<IndexEntry> dels = mut.getDeletions();
VariableLong.writePositive(out,dels.size());
for (IndexEntry del: dels) writeIndexEntry(out,del);
}
}
}
private void writeIndexEntry(DataOutput out, IndexEntry entry) {
out.writeObjectNotNull(entry.field);
out.writeClassAndObject(entry.value);
}
} | 0true
| titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexTransaction.java |
1,485 | public class BroadleafProductController extends BroadleafAbstractController implements Controller {
protected String defaultProductView = "catalog/product";
protected static String MODEL_ATTRIBUTE_NAME = "product";
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView();
Product product = (Product) request.getAttribute(ProductHandlerMapping.CURRENT_PRODUCT_ATTRIBUTE_NAME);
assert(product != null);
model.addObject(MODEL_ATTRIBUTE_NAME, product);
if (StringUtils.isNotEmpty(product.getDisplayTemplate())) {
model.setViewName(product.getDisplayTemplate());
} else {
model.setViewName(getDefaultProductView());
}
return model;
}
public String getDefaultProductView() {
return defaultProductView;
}
public void setDefaultProductView(String defaultProductView) {
this.defaultProductView = defaultProductView;
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_controller_catalog_BroadleafProductController.java |
57 | public class HighAvailabilityConsoleLogger
implements ClusterMemberListener, ClusterListener, AvailabilityGuard.AvailabilityListener
{
private ConsoleLogger console;
private InstanceId myId;
private URI myUri;
public HighAvailabilityConsoleLogger( ConsoleLogger console, InstanceId myId )
{
this.console = console;
this.myId = myId;
}
// Cluster events
/**
* Logged when the instance itself joins or rejoins a cluster
*
* @param clusterConfiguration
*/
@Override
public void enteredCluster( ClusterConfiguration clusterConfiguration )
{
myUri = clusterConfiguration.getUriForId( myId );
console.log( String.format( "Instance %s joined the cluster", printId( myId, myUri )) );
}
/**
* Logged when the instance itself leaves the cluster
*/
@Override
public void leftCluster()
{
console.log( String.format( "Instance %s left the cluster", printId( myId, myUri ) ) );
}
/**
* Logged when another instance joins the cluster
*
* @param instanceId
* @param member
*/
@Override
public void joinedCluster( InstanceId instanceId, URI member )
{
console.log( "Instance " + printId(instanceId, member) + " joined the cluster" );
}
/**
* Logged when another instance leaves the cluster
*
* @param instanceId
*/
@Override
public void leftCluster( InstanceId instanceId )
{
console.log( "Instance " + instanceId + " has left the cluster" );
}
/**
* Logged when an instance is elected for a role, such as coordinator of a cluster.
*
* @param role
* @param instanceId
* @param electedMember
*/
@Override
public void elected( String role, InstanceId instanceId, URI electedMember )
{
console.log( "Instance " + printId( instanceId, electedMember ) + "was elected as " + role );
}
/**
* Logged when an instance is demoted from a role.
*
* @param role
* @param instanceId
* @param electedMember
*/
@Override
public void unelected( String role, InstanceId instanceId, URI electedMember )
{
console.log( "Instance " + printId( instanceId, electedMember ) + "was demoted as " + role );
}
// HA events
@Override
public void coordinatorIsElected( InstanceId coordinatorId )
{
}
/**
* Logged when a member becomes available as a role, such as MASTER or SLAVE.
*
* @param role
* @param availableId the role connection information for the new role holder
* @param atUri the URI at which the instance is available at
*/
@Override
public void memberIsAvailable( String role, InstanceId availableId, URI atUri )
{
console.log( "Instance " + printId( availableId, atUri ) + "is available as " + role + " at " + atUri.toASCIIString() );
}
/**
* Logged when a member becomes unavailable as a role, such as MASTER or SLAVE.
*
* @param role The role for which the member is unavailable
* @param unavailableId The id of the member which became unavailable for that role
*/
@Override
public void memberIsUnavailable( String role, InstanceId unavailableId )
{
console.log( "Instance " + printId( unavailableId, null ) + "is unavailable as " + role );
}
/**
* Logged when another instance is detected as being failed.
*
* @param instanceId
*/
@Override
public void memberIsFailed( InstanceId instanceId )
{
console.log( "Instance " + printId( instanceId, null ) + "has failed" );
}
/**
* Logged when another instance is detected as being alive again.
*
* @param instanceId
*/
@Override
public void memberIsAlive( InstanceId instanceId )
{
console.log( "Instance " + printId( instanceId, null ) + "is alive" );
}
// InstanceAccessGuard events
/**
* Logged when users are allowed to access the database for transactions.
*/
@Override
public void available()
{
console.log( "Database available for write transactions" );
}
/**
* Logged when users are not allowed to access the database for transactions.
*/
@Override
public void unavailable()
{
console.log( "Write transactions to database disabled" );
}
private String printId( InstanceId id, URI member )
{
String memberName = member == null ? null : parameter( "memberName" ).apply( member );
String memberNameOrId = memberName == null ? id.toString() : memberName;
return memberNameOrId + (id.equals( myId ) ? " (this server) " : " ");
}
} | 1no label
| enterprise_ha_src_main_java_org_neo4j_kernel_ha_HighAvailabilityConsoleLogger.java |
991 | public interface FulfillmentGroup extends Serializable {
public Long getId();
public void setId(Long id);
public Order getOrder();
public void setOrder(Order order);
public void setSequence(Integer sequence);
public Integer getSequence();
public FulfillmentOption getFulfillmentOption();
public void setFulfillmentOption(FulfillmentOption fulfillmentOption);
public Address getAddress();
public void setAddress(Address address);
public Phone getPhone();
public void setPhone(Phone phone);
public List<FulfillmentGroupItem> getFulfillmentGroupItems();
public void setFulfillmentGroupItems(List<FulfillmentGroupItem> fulfillmentGroupItems);
public void addFulfillmentGroupItem(FulfillmentGroupItem fulfillmentGroupItem);
/**
* @deprecated Should use {@link #getFulfillmentOption()} instead
* @see {@link FulfillmentOption}
*/
@Deprecated
public String getMethod();
/**
* @deprecated Should use {@link #setFulfillmentOption()} instead
* @see {@link FulfillmentOption}
*/
@Deprecated
public void setMethod(String fulfillmentMethod);
/**
* Returns the retail price for this fulfillmentGroup. The retail and sale concepts used
* for item pricing are not generally used with fulfillmentPricing but supported
* nonetheless. Typically only a retail price would be set on a fulfillment group.
* @return
*/
public Money getRetailFulfillmentPrice();
/**
* Sets the retail price for this fulfillmentGroup.
* @param fulfillmentPrice
*/
public void setRetailFulfillmentPrice(Money fulfillmentPrice);
/**
* Returns the sale price for this fulfillmentGroup.
* Typically this will be null or equal to the retailFulfillmentPrice
* @return
*/
public Money getSaleFulfillmentPrice();
/**
* Sets the sale price for this fulfillmentGroup. Typically not used.
* @see #setRetailFulfillmentPrice(Money)
* @param fulfillmentPrice
*/
public void setSaleFulfillmentPrice(Money fulfillmentPrice);
/**
* Gets the price to charge for this fulfillmentGroup. Includes the effects of any adjustments such as those that
* might have been applied by the promotion engine (e.g. free shipping)
* @return
*/
public Money getFulfillmentPrice();
/**
* Sets the price to charge for this fulfillmentGroup. Typically set internally by the Broadleaf pricing and
* promotion engines.
* @return
*/
public void setFulfillmentPrice(Money fulfillmentPrice);
/**
* @deprecated - use {@link #getRetailFulfillmentPrice()} instead. Deprecated as the price might be for other
* fulfillment types such as PickUpAtStore fees or download fees.
* @return
*/
public Money getRetailShippingPrice();
/**
* @deprecated - use {@link #setRetailFulfillmentPrice(Money)} instead.
* @return
*/
public void setRetailShippingPrice(Money retailShippingPrice);
/**
* @deprecated - use {@link #getSaleFulfillmentPrice()} instead.
* @return
*/
public Money getSaleShippingPrice();
/**
* @deprecated - use {@link #setSaleFulfillmentPrice(Money)} instead.
* @param saleShippingPrice
*/
public void setSaleShippingPrice(Money saleShippingPrice);
/**
* @deprecated - use {@link #getFulfillmentPrice()} instead.
* @return
*/
public Money getShippingPrice();
/**
* @deprecated - use {@link #setRetailFulfillmentPrice(Money)} instead.
* @param shippingPrice
*/
public void setShippingPrice(Money shippingPrice);
public String getReferenceNumber();
public void setReferenceNumber(String referenceNumber);
public FulfillmentType getType();
void setType(FulfillmentType type);
public List<CandidateFulfillmentGroupOffer> getCandidateFulfillmentGroupOffers();
public void setCandidateFulfillmentGroupOffer(List<CandidateFulfillmentGroupOffer> candidateOffers);
public void addCandidateFulfillmentGroupOffer(CandidateFulfillmentGroupOffer candidateOffer);
public void removeAllCandidateOffers();
public List<FulfillmentGroupAdjustment> getFulfillmentGroupAdjustments();
public void setFulfillmentGroupAdjustments(List<FulfillmentGroupAdjustment> fulfillmentGroupAdjustments);
public void removeAllAdjustments();
/**
* Gets a list of TaxDetail objects, which are taxes that apply directly to this fulfillment group.
* An example of a such a tax would be a shipping tax.
*
* @return a list of taxes that apply to this fulfillment group
*/
public List<TaxDetail> getTaxes();
/**
* Gets the list of TaxDetail objects, which are taxes that apply directly to this fulfillment group.
* An example of a such a tax would be a shipping tax.
*
* @param taxes the list of taxes on this fulfillment group
*/
public void setTaxes(List<TaxDetail> taxes);
/**
* Gets the total tax for this fulfillment group, which is the sum of the taxes on all fulfillment
* group items, fees, and taxes on this fulfillment group itself (such as a shipping tax).
* This total is calculated in the TotalActivity stage of the pricing workflow.
*
* @return the total tax for the fulfillment group
*/
public Money getTotalTax();
/**
* Sets the total tax for this fulfillment group, which is the sum of the taxes on all fulfillment
* group items, fees, and taxes on this fulfillment group itself (such as a shipping tax).
* This total should only be set during the TotalActivity stage of the pricing workflow.
*
* @param the total tax for this fulfillment group
*/
public void setTotalTax(Money totalTax);
/**
* Gets the total item tax for this fulfillment group, which is the sum of the taxes on all fulfillment
* group items. This total is calculated in the TotalActivity stage of the pricing workflow.
*
* @return the total tax for this fulfillment group
*/
public Money getTotalItemTax();
/**
* Sets the total item tax for this fulfillment group, which is the sum of the taxes on all fulfillment
* group items. This total should only be set during the TotalActivity stage of the pricing workflow.
*
* @param the total tax for this fulfillment group
*/
public void setTotalItemTax(Money totalItemTax);
/**
* Gets the total fee tax for this fulfillment group, which is the sum of the taxes on all fulfillment
* group fees. This total is calculated in the TotalActivity stage of the pricing workflow.
*
* @return the total tax for this fulfillment group
*/
public Money getTotalFeeTax();
/**
* Sets the total fee tax for this fulfillment group, which is the sum of the taxes on all fulfillment
* group fees. This total should only be set during the TotalActivity stage of the pricing workflow.
*
* @param the total tax for this fulfillment group
*/
public void setTotalFeeTax(Money totalFeeTax);
/**
* Gets the total fulfillment group tax for this fulfillment group, which is the sum of the taxes
* on this fulfillment group itself (such as a shipping tax) only. It does not include the taxes on
* items or fees in this fulfillment group. This total is calculated in the TotalActivity stage of the pricing workflow.
*
* @return the total tax for this fulfillment group
*/
public Money getTotalFulfillmentGroupTax();
/**
* Sets the total fulfillment group tax for this fulfillment group, which is the sum of the taxes
* on this fulfillment group itself (such as a shipping tax) only. It does not include the taxes on
* items or fees in this fulfillment group. This total should only be set during the TotalActivity stage of the pricing workflow.
*
* @param the total tax for this fulfillment group
*/
public void setTotalFulfillmentGroupTax(Money totalFulfillmentGroupTax);
public String getDeliveryInstruction();
public void setDeliveryInstruction(String deliveryInstruction);
public PersonalMessage getPersonalMessage();
public void setPersonalMessage(PersonalMessage personalMessage);
public boolean isPrimary();
public void setPrimary(boolean primary);
public Money getMerchandiseTotal();
public void setMerchandiseTotal(Money merchandiseTotal);
public Money getTotal();
public void setTotal(Money orderTotal);
public FulfillmentGroupStatusType getStatus();
public void setStatus(FulfillmentGroupStatusType status);
public List<FulfillmentGroupFee> getFulfillmentGroupFees();
public void setFulfillmentGroupFees(List<FulfillmentGroupFee> fulfillmentGroupFees);
public void addFulfillmentGroupFee(FulfillmentGroupFee fulfillmentGroupFee);
public void removeAllFulfillmentGroupFees();
public Boolean isShippingPriceTaxable();
public void setIsShippingPriceTaxable(Boolean isShippingPriceTaxable);
/**
* @deprecated Should use {@link #getFulfillmentOption()} instead
* @see {@link FulfillmentOption}
*/
@Deprecated
public String getService();
/**
* @deprecated Should use {@link #setFulfillmentOption()} instead
* @see {@link FulfillmentOption}
*/
@Deprecated
public void setService(String service);
public List<DiscreteOrderItem> getDiscreteOrderItems();
public Money getFulfillmentGroupAdjustmentsValue();
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_order_domain_FulfillmentGroup.java |
152 | static final class ReadMostlyVectorSublist<E>
implements List<E>, RandomAccess, java.io.Serializable {
private static final long serialVersionUID = 3041673470172026059L;
final ReadMostlyVector<E> list;
final int offset;
volatile int size;
ReadMostlyVectorSublist(ReadMostlyVector<E> list,
int offset, int size) {
this.list = list;
this.offset = offset;
this.size = size;
}
private void rangeCheck(int index) {
if (index < 0 || index >= size)
throw new ArrayIndexOutOfBoundsException(index);
}
public boolean add(E element) {
final StampedLock lock = list.lock;
long stamp = lock.writeLock();
try {
int c = size;
list.rawAddAt(c + offset, element);
size = c + 1;
} finally {
lock.unlockWrite(stamp);
}
return true;
}
public void add(int index, E element) {
final StampedLock lock = list.lock;
long stamp = lock.writeLock();
try {
if (index < 0 || index > size)
throw new ArrayIndexOutOfBoundsException(index);
list.rawAddAt(index + offset, element);
++size;
} finally {
lock.unlockWrite(stamp);
}
}
public boolean addAll(Collection<? extends E> c) {
Object[] elements = c.toArray();
final StampedLock lock = list.lock;
long stamp = lock.writeLock();
try {
int s = size;
int pc = list.count;
list.rawAddAllAt(offset + s, elements);
int added = list.count - pc;
size = s + added;
return added != 0;
} finally {
lock.unlockWrite(stamp);
}
}
public boolean addAll(int index, Collection<? extends E> c) {
Object[] elements = c.toArray();
final StampedLock lock = list.lock;
long stamp = lock.writeLock();
try {
int s = size;
if (index < 0 || index > s)
throw new ArrayIndexOutOfBoundsException(index);
int pc = list.count;
list.rawAddAllAt(index + offset, elements);
int added = list.count - pc;
size = s + added;
return added != 0;
} finally {
lock.unlockWrite(stamp);
}
}
public void clear() {
final StampedLock lock = list.lock;
long stamp = lock.writeLock();
try {
list.internalClear(offset, offset + size);
size = 0;
} finally {
lock.unlockWrite(stamp);
}
}
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public boolean containsAll(Collection<?> c) {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
return list.internalContainsAll(c, offset, offset + size);
} finally {
lock.unlockRead(stamp);
}
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
return list.internalEquals((List<?>)(o), offset, offset + size);
} finally {
lock.unlockRead(stamp);
}
}
public E get(int index) {
if (index < 0 || index >= size)
throw new ArrayIndexOutOfBoundsException(index);
return list.get(index + offset);
}
public int hashCode() {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
return list.internalHashCode(offset, offset + size);
} finally {
lock.unlockRead(stamp);
}
}
public int indexOf(Object o) {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
int idx = findFirstIndex(list.array, o, offset, offset + size);
return idx < 0 ? -1 : idx - offset;
} finally {
lock.unlockRead(stamp);
}
}
public boolean isEmpty() {
return size() == 0;
}
public Iterator<E> iterator() {
return new SubItr<E>(this, offset);
}
public int lastIndexOf(Object o) {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
int idx = findLastIndex(list.array, o, offset + size - 1, offset);
return idx < 0 ? -1 : idx - offset;
} finally {
lock.unlockRead(stamp);
}
}
public ListIterator<E> listIterator() {
return new SubItr<E>(this, offset);
}
public ListIterator<E> listIterator(int index) {
return new SubItr<E>(this, index + offset);
}
public E remove(int index) {
final StampedLock lock = list.lock;
long stamp = lock.writeLock();
try {
Object[] items = list.array;
int i = index + offset;
if (items == null || index < 0 || index >= size || i >= items.length)
throw new ArrayIndexOutOfBoundsException(index);
@SuppressWarnings("unchecked") E result = (E)items[i];
list.rawRemoveAt(i);
size--;
return result;
} finally {
lock.unlockWrite(stamp);
}
}
public boolean remove(Object o) {
final StampedLock lock = list.lock;
long stamp = lock.writeLock();
try {
if (list.rawRemoveAt(findFirstIndex(list.array, o, offset,
offset + size))) {
--size;
return true;
}
else
return false;
} finally {
lock.unlockWrite(stamp);
}
}
public boolean removeAll(Collection<?> c) {
return list.lockedRemoveAll(c, offset, offset + size);
}
public boolean retainAll(Collection<?> c) {
return list.lockedRetainAll(c, offset, offset + size);
}
public E set(int index, E element) {
if (index < 0 || index >= size)
throw new ArrayIndexOutOfBoundsException(index);
return list.set(index+offset, element);
}
public int size() {
return size;
}
public List<E> subList(int fromIndex, int toIndex) {
int c = size;
int ssize = toIndex - fromIndex;
if (fromIndex < 0)
throw new ArrayIndexOutOfBoundsException(fromIndex);
if (toIndex > c || ssize < 0)
throw new ArrayIndexOutOfBoundsException(toIndex);
return new ReadMostlyVectorSublist<E>(list, offset+fromIndex, ssize);
}
public Object[] toArray() {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
return list.internalToArray(offset, offset + size);
} finally {
lock.unlockRead(stamp);
}
}
public <T> T[] toArray(T[] a) {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
return list.internalToArray(a, offset, offset + size);
} finally {
lock.unlockRead(stamp);
}
}
public String toString() {
final StampedLock lock = list.lock;
long stamp = lock.readLock();
try {
return list.internalToString(offset, offset + size);
} finally {
lock.unlockRead(stamp);
}
}
} | 0true
| src_main_java_jsr166e_extra_ReadMostlyVector.java |
1,296 | es.execute(new Runnable() {
public void run() {
map.put(key, new byte[valueSize]);
}
}); | 0true
| hazelcast_src_main_java_com_hazelcast_examples_SimpleMultiMapTest.java |
899 | public class PromotableOrderItemImpl implements PromotableOrderItem {
private static final Log LOG = LogFactory.getLog(PromotableOrderItem.class);
private static final long serialVersionUID = 1L;
protected PromotableOrder promotableOrder;
protected OrderItem orderItem;
protected PromotableItemFactory itemFactory;
protected List<PromotableOrderItemPriceDetail> itemPriceDetails = new ArrayList<PromotableOrderItemPriceDetail>();
protected boolean includeAdjustments;
public PromotableOrderItemImpl(OrderItem orderItem, PromotableOrder promotableOrder, PromotableItemFactory itemFactory,
boolean includeAdjustments) {
this.orderItem = orderItem;
this.promotableOrder = promotableOrder;
this.itemFactory = itemFactory;
this.includeAdjustments = includeAdjustments;
initializePriceDetails();
}
@Override
public void resetPriceDetails() {
itemPriceDetails.clear();
initializePriceDetails();
}
private void initializePriceDetails() {
if (includeAdjustments) {
for (OrderItemPriceDetail detail : orderItem.getOrderItemPriceDetails()) {
PromotableOrderItemPriceDetail poid =
itemFactory.createPromotableOrderItemPriceDetail(this, detail.getQuantity());
itemPriceDetails.add(poid);
poid.chooseSaleOrRetailAdjustments();
for (OrderItemPriceDetailAdjustment adjustment : detail.getOrderItemPriceDetailAdjustments()) {
PromotableOrderItemPriceDetailAdjustment poidAdj =
new PromotableOrderItemPriceDetailAdjustmentImpl(adjustment, poid);
poid.addCandidateItemPriceDetailAdjustment(poidAdj);
}
}
} else {
PromotableOrderItemPriceDetail poid =
itemFactory.createPromotableOrderItemPriceDetail(this, orderItem.getQuantity());
itemPriceDetails.add(poid);
}
}
/**
* Adds the item to the rule variables map.
* @param ruleVars
*/
public void updateRuleVariables(Map<String, Object> ruleVars) {
ruleVars.put("orderItem", orderItem);
ruleVars.put("discreteOrderItem", orderItem);
ruleVars.put("bundleOrderItem", orderItem);
}
@Override
public boolean isDiscountingAllowed() {
return orderItem.isDiscountingAllowed();
}
@Override
public boolean isOrderItemContainer() {
return orderItem instanceof OrderItemContainer;
}
@Override
public OrderItemContainer getOrderItemContainer() {
if (orderItem instanceof OrderItemContainer) {
return (OrderItemContainer) orderItem;
}
return null;
}
public List<PromotableOrderItemPriceDetail> getPromotableOrderItemPriceDetails() {
return itemPriceDetails;
}
public Money getSalePriceBeforeAdjustments() {
return orderItem.getSalePrice();
}
public Money getRetailPriceBeforeAdjustments() {
return orderItem.getRetailPrice();
}
public Money getPriceBeforeAdjustments(boolean applyToSalePrice) {
if (applyToSalePrice && getSalePriceBeforeAdjustments() != null) {
return getSalePriceBeforeAdjustments();
}
return getRetailPriceBeforeAdjustments();
}
public Money getCurrentBasePrice() {
if (orderItem.getIsOnSale()) {
return orderItem.getSalePrice();
} else {
return orderItem.getRetailPrice();
}
}
public int getQuantity() {
return orderItem.getQuantity();
}
@Override
public boolean isOnSale() {
return orderItem.getIsOnSale();
}
@Override
public BroadleafCurrency getCurrency() {
return orderItem.getOrder().getCurrency();
}
@Override
public void removeAllItemAdjustments() {
Iterator<PromotableOrderItemPriceDetail> detailIterator = itemPriceDetails.iterator();
boolean first = true;
while (detailIterator.hasNext()) {
PromotableOrderItemPriceDetail detail = detailIterator.next();
if (first) {
detail.setQuantity(getQuantity());
detail.getPromotionDiscounts().clear();
detail.getPromotionQualifiers().clear();
detail.removeAllAdjustments();
first = false;
} else {
// Get rid of all other details
detailIterator.remove();
}
}
}
protected void mergeDetails(PromotableOrderItemPriceDetail firstDetail, PromotableOrderItemPriceDetail secondDetail) {
int firstQty = firstDetail.getQuantity();
int secondQty = secondDetail.getQuantity();
if (LOG.isDebugEnabled()) {
LOG.trace("Merging priceDetails with quantities " + firstQty + " and " + secondQty);
}
firstDetail.setQuantity(firstQty + secondQty);
}
@Override
public void mergeLikeDetails() {
if (itemPriceDetails.size() > 1) {
Iterator<PromotableOrderItemPriceDetail> detailIterator = itemPriceDetails.iterator();
Map<String, PromotableOrderItemPriceDetail> detailMap = new HashMap<String, PromotableOrderItemPriceDetail>();
while (detailIterator.hasNext()) {
PromotableOrderItemPriceDetail currentDetail = detailIterator.next();
String detailKey = currentDetail.buildDetailKey();
if (detailMap.containsKey(detailKey)) {
PromotableOrderItemPriceDetail firstDetail = detailMap.get(detailKey);
mergeDetails(firstDetail, currentDetail);
detailIterator.remove();
} else {
detailMap.put(detailKey, currentDetail);
}
}
}
}
@Override
public Long getOrderItemId() {
return orderItem.getId();
}
@Override
public Money calculateTotalWithAdjustments() {
Money returnTotal = new Money(getCurrency());
for (PromotableOrderItemPriceDetail detail : itemPriceDetails) {
returnTotal = returnTotal.add(detail.getFinalizedTotalWithAdjustments());
}
return returnTotal;
}
@Override
public Money calculateTotalWithoutAdjustments() {
return getCurrentBasePrice().multiply(orderItem.getQuantity());
}
@Override
public Money calculateTotalAdjustmentValue() {
Money returnTotal = new Money(getCurrency());
for (PromotableOrderItemPriceDetail detail : itemPriceDetails) {
returnTotal = returnTotal.add(detail.calculateTotalAdjustmentValue());
}
return returnTotal;
}
public PromotableOrderItemPriceDetail createNewDetail(int quantity) {
if (includeAdjustments) {
throw new RuntimeException("Trying to createNewDetail when adjustments have already been included.");
}
return itemFactory.createPromotableOrderItemPriceDetail(this, quantity);
}
public OrderItem getOrderItem() {
return orderItem;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_service_discount_domain_PromotableOrderItemImpl.java |
35 | public class TitanEdgeTestSuite extends EdgeTestSuite {
public TitanEdgeTestSuite(final GraphTest graphTest) {
super(graphTest);
}
} | 0true
| titan-test_src_main_java_com_thinkaurelius_titan_blueprints_TitanEdgeTestSuite.java |
1,914 | final class WeakKeySet {
/**
* We store strings rather than keys so we don't hold strong references.
* <p/>
* <p>One potential problem with this approach is that parent and child injectors cannot define
* keys whose class names are equal but class loaders are different. This shouldn't be an issue
* in practice.
*/
private Set<String> backingSet = Sets.newHashSet();
public boolean add(Key<?> key) {
return backingSet.add(key.toString());
}
public boolean contains(Object o) {
return o instanceof Key && backingSet.contains(o.toString());
}
} | 0true
| src_main_java_org_elasticsearch_common_inject_WeakKeySet.java |
549 | public abstract class OClusterPositionFactory {
public static final OClusterPositionFactory INSTANCE;
static {
if (OGlobalConfiguration.USE_NODE_ID_CLUSTER_POSITION.getValueAsBoolean())
INSTANCE = new OClusterPositionFactoryNodeId();
else
INSTANCE = new OClusterPositionFactoryLong();
}
public abstract OClusterPosition generateUniqueClusterPosition();
public abstract OClusterPosition valueOf(long value);
public abstract OClusterPosition valueOf(String value);
public abstract OClusterPosition fromStream(byte[] content, int start);
/**
* @return Size of {@link OClusterPosition} instance in serialized form.
* @see com.orientechnologies.orient.core.id.OClusterPosition#toStream()
*/
public abstract int getSerializedSize();
public OClusterPosition fromStream(byte[] content) {
return fromStream(content, 0);
}
public OClusterPosition fromStream(InputStream in) throws IOException {
int bytesToRead;
int contentLength = 0;
final int clusterSize = OClusterPositionFactory.INSTANCE.getSerializedSize();
final byte[] clusterContent = new byte[clusterSize];
do {
bytesToRead = in.read(clusterContent, contentLength, clusterSize - contentLength);
if (bytesToRead < 0)
break;
contentLength += bytesToRead;
} while (contentLength < clusterSize);
return fromStream(clusterContent);
}
public OClusterPosition fromStream(ObjectInput in) throws IOException {
int bytesToRead;
int contentLength = 0;
final int clusterSize = OClusterPositionFactory.INSTANCE.getSerializedSize();
final byte[] clusterContent = new byte[clusterSize];
do {
bytesToRead = in.read(clusterContent, contentLength, clusterSize - contentLength);
if (bytesToRead < 0)
break;
contentLength += bytesToRead;
} while (contentLength < clusterSize);
return fromStream(clusterContent);
}
public OClusterPosition fromStream(DataInput in) throws IOException {
final int clusterSize = OClusterPositionFactory.INSTANCE.getSerializedSize();
final byte[] clusterContent = new byte[clusterSize];
in.readFully(clusterContent);
return fromStream(clusterContent);
}
public abstract OClusterPosition getMaxValue();
public static final class OClusterPositionFactoryLong extends OClusterPositionFactory {
@Override
public OClusterPosition generateUniqueClusterPosition() {
throw new UnsupportedOperationException();
}
@Override
public OClusterPosition valueOf(long value) {
return new OClusterPositionLong(value);
}
@Override
public OClusterPosition valueOf(String value) {
return new OClusterPositionLong(Long.valueOf(value));
}
@Override
public OClusterPosition fromStream(byte[] content, int start) {
return new OClusterPositionLong(OLongSerializer.INSTANCE.deserialize(content, start));
}
@Override
public int getSerializedSize() {
return OLongSerializer.LONG_SIZE;
}
@Override
public OClusterPosition getMaxValue() {
return new OClusterPositionLong(Long.MAX_VALUE);
}
}
public static final class OClusterPositionFactoryNodeId extends OClusterPositionFactory {
@Override
public OClusterPosition generateUniqueClusterPosition() {
return new OClusterPositionNodeId(ONodeId.generateUniqueId());
}
@Override
public OClusterPosition valueOf(long value) {
return new OClusterPositionNodeId(ONodeId.valueOf(value));
}
@Override
public OClusterPosition valueOf(String value) {
return new OClusterPositionNodeId(ONodeId.parseString(value));
}
@Override
public OClusterPosition fromStream(byte[] content, int start) {
return new OClusterPositionNodeId(ONodeId.fromStream(content, start));
}
@Override
public int getSerializedSize() {
return ONodeId.SERIALIZED_SIZE;
}
@Override
public OClusterPosition getMaxValue() {
return new OClusterPositionNodeId(ONodeId.MAX_VALUE);
}
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_id_OClusterPositionFactory.java |
751 | public class OSBTreeBonsai<K, V> extends ODurableComponent implements OTreeInternal<K, V> {
private static final OAlwaysLessKey ALWAYS_LESS_KEY = new OAlwaysLessKey();
private static final OAlwaysGreaterKey ALWAYS_GREATER_KEY = new OAlwaysGreaterKey();
private static final int PAGE_SIZE = OGlobalConfiguration.DISK_CACHE_PAGE_SIZE.getValueAsInteger() * 1024;
private static final OBonsaiBucketPointer SYS_BUCKET = new OBonsaiBucketPointer(0, 0);
private OBonsaiBucketPointer rootBucketPointer;
private final Comparator<? super K> comparator = ODefaultComparator.INSTANCE;
private OStorageLocalAbstract storage;
private String name;
private final String dataFileExtension;
private ODiskCache diskCache;
private long fileId;
private int keySize;
private OBinarySerializer<K> keySerializer;
private OBinarySerializer<V> valueSerializer;
private final boolean durableInNonTxMode;
public OSBTreeBonsai(String dataFileExtension, int keySize, boolean durableInNonTxMode) {
super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean());
this.dataFileExtension = dataFileExtension;
this.keySize = keySize;
this.durableInNonTxMode = durableInNonTxMode;
}
public void create(String name, OBinarySerializer<K> keySerializer, OBinarySerializer<V> valueSerializer,
OStorageLocalAbstract storageLocal) {
try {
this.storage = storageLocal;
this.diskCache = storage.getDiskCache();
this.keySerializer = keySerializer;
this.valueSerializer = valueSerializer;
this.fileId = diskCache.openFile(name + dataFileExtension);
this.name = name;
initAfterCreate();
} catch (IOException e) {
throw new OSBTreeException("Error creation of sbtree with name" + name, e);
}
create(fileId, keySerializer, valueSerializer, storageLocal);
}
public void create(long fileId, OBinarySerializer<K> keySerializer, OBinarySerializer<V> valueSerializer,
OStorageLocalAbstract storageLocal) {
acquireExclusiveLock();
try {
this.storage = storageLocal;
this.diskCache = storage.getDiskCache();
this.keySerializer = keySerializer;
this.valueSerializer = valueSerializer;
diskCache.openFile(fileId);
this.fileId = fileId;
this.name = resolveTreeName(fileId);
initAfterCreate();
} catch (IOException e) {
throw new OSBTreeException("Error creation of sbtree with name" + name, e);
} finally {
releaseExclusiveLock();
}
}
private void initAfterCreate() {
initDurableComponent(storage);
try {
initSysBucket();
super.startDurableOperation(null);
final AllocationResult allocationResult = allocateBucket();
OCacheEntry rootCacheEntry = allocationResult.getCacheEntry();
this.rootBucketPointer = allocationResult.getPointer();
OCachePointer rootPointer = rootCacheEntry.getCachePointer();
rootPointer.acquireExclusiveLock();
try {
OSBTreeBonsaiBucket<K, V> rootBucket = new OSBTreeBonsaiBucket<K, V>(rootPointer.getDataPointer(),
this.rootBucketPointer.getPageOffset(), true, keySerializer, valueSerializer, getTrackMode());
rootBucket.setKeySerializerId(keySerializer.getId());
rootBucket.setValueSerializerId(valueSerializer.getId());
rootBucket.setTreeSize(0);
super.logPageChanges(rootBucket, fileId, this.rootBucketPointer.getPageIndex(), true);
rootCacheEntry.markDirty();
} finally {
rootPointer.releaseExclusiveLock();
diskCache.release(rootCacheEntry);
}
super.endDurableOperation(null, false);
} catch (IOException e) {
try {
super.endDurableOperation(null, true);
} catch (IOException e1) {
OLogManager.instance().error(this, "Error during sbtree data rollback", e1);
}
throw new OSBTreeException("Error creation of sbtree with name" + name, e);
}
}
private void initDurableComponent(OStorageLocalAbstract storageLocal) {
OWriteAheadLog writeAheadLog = storageLocal.getWALInstance();
init(writeAheadLog);
}
public String getName() {
acquireSharedLock();
try {
return name;
} finally {
releaseSharedLock();
}
}
public long getFileId() {
acquireSharedLock();
try {
return fileId;
} finally {
releaseSharedLock();
}
}
public OBonsaiBucketPointer getRootBucketPointer() {
acquireSharedLock();
try {
return rootBucketPointer;
} finally {
releaseSharedLock();
}
}
public V get(K key) {
acquireSharedLock();
try {
BucketSearchResult bucketSearchResult = findBucket(key, PartialSearchMode.NONE);
if (bucketSearchResult.itemIndex < 0)
return null;
OBonsaiBucketPointer bucketPointer = bucketSearchResult.getLastPathItem();
OCacheEntry keyBucketCacheEntry = diskCache.load(fileId, bucketPointer.getPageIndex(), false);
OCachePointer keyBucketPointer = keyBucketCacheEntry.getCachePointer();
try {
OSBTreeBonsaiBucket<K, V> keyBucket = new OSBTreeBonsaiBucket<K, V>(keyBucketPointer.getDataPointer(),
bucketPointer.getPageOffset(), keySerializer, valueSerializer, ODurablePage.TrackMode.NONE);
return keyBucket.getEntry(bucketSearchResult.itemIndex).value;
} finally {
diskCache.release(keyBucketCacheEntry);
}
} catch (IOException e) {
throw new OSBTreeException("Error during retrieving of sbtree with name " + name, e);
} finally {
releaseSharedLock();
}
}
public boolean put(K key, V value) {
acquireExclusiveLock();
final OStorageTransaction transaction = storage.getStorageTransaction();
try {
startDurableOperation(transaction);
BucketSearchResult bucketSearchResult = findBucket(key, PartialSearchMode.NONE);
OBonsaiBucketPointer bucketPointer = bucketSearchResult.getLastPathItem();
OCacheEntry keyBucketCacheEntry = diskCache.load(fileId, bucketPointer.getPageIndex(), false);
OCachePointer keyBucketPointer = keyBucketCacheEntry.getCachePointer();
keyBucketPointer.acquireExclusiveLock();
OSBTreeBonsaiBucket<K, V> keyBucket = new OSBTreeBonsaiBucket<K, V>(keyBucketPointer.getDataPointer(),
bucketPointer.getPageOffset(), keySerializer, valueSerializer, getTrackMode());
final boolean itemFound = bucketSearchResult.itemIndex >= 0;
boolean result = true;
if (itemFound) {
final int updateResult = keyBucket.updateValue(bucketSearchResult.itemIndex, value);
if (updateResult == 1) {
logPageChanges(keyBucket, fileId, bucketSearchResult.getLastPathItem().getPageIndex(), false);
keyBucketCacheEntry.markDirty();
}
assert updateResult == 0 || updateResult == 1;
result = updateResult != 0;
} else {
int insertionIndex = -bucketSearchResult.itemIndex - 1;
while (!keyBucket.addEntry(insertionIndex, new OSBTreeBonsaiBucket.SBTreeEntry<K, V>(OBonsaiBucketPointer.NULL,
OBonsaiBucketPointer.NULL, key, value), true)) {
keyBucketPointer.releaseExclusiveLock();
diskCache.release(keyBucketCacheEntry);
bucketSearchResult = splitBucket(bucketSearchResult.path, insertionIndex, key);
bucketPointer = bucketSearchResult.getLastPathItem();
insertionIndex = bucketSearchResult.itemIndex;
keyBucketCacheEntry = diskCache.load(fileId, bucketSearchResult.getLastPathItem().getPageIndex(), false);
keyBucketPointer = keyBucketCacheEntry.getCachePointer();
keyBucketPointer.acquireExclusiveLock();
keyBucket = new OSBTreeBonsaiBucket<K, V>(keyBucketPointer.getDataPointer(), bucketPointer.getPageOffset(),
keySerializer, valueSerializer, getTrackMode());
}
logPageChanges(keyBucket, fileId, bucketPointer.getPageIndex(), false);
keyBucketCacheEntry.markDirty();
}
keyBucketPointer.releaseExclusiveLock();
diskCache.release(keyBucketCacheEntry);
if (!itemFound)
setSize(size() + 1);
endDurableOperation(transaction, false);
return result;
} catch (IOException e) {
rollback(transaction);
throw new OSBTreeException("Error during index update with key " + key + " and value " + value, e);
} finally {
releaseExclusiveLock();
}
}
private void rollback(OStorageTransaction transaction) {
try {
endDurableOperation(transaction, true);
} catch (IOException e1) {
OLogManager.instance().error(this, "Error during sbtree operation rollback", e1);
}
}
public void close(boolean flush) {
acquireExclusiveLock();
try {
diskCache.closeFile(fileId, flush);
} catch (IOException e) {
throw new OSBTreeException("Error during close of index " + name, e);
} finally {
releaseExclusiveLock();
}
}
public void close() {
close(true);
}
public void clear() {
acquireExclusiveLock();
OStorageTransaction transaction = storage.getStorageTransaction();
try {
startDurableOperation(transaction);
final Queue<OBonsaiBucketPointer> subTreesToDelete = new LinkedList<OBonsaiBucketPointer>();
OCacheEntry cacheEntry = diskCache.load(fileId, rootBucketPointer.getPageIndex(), false);
OCachePointer rootPointer = cacheEntry.getCachePointer();
rootPointer.acquireExclusiveLock();
try {
OSBTreeBonsaiBucket<K, V> rootBucket = new OSBTreeBonsaiBucket<K, V>(rootPointer.getDataPointer(),
rootBucketPointer.getPageOffset(), keySerializer, valueSerializer, getTrackMode());
addChildrenToQueue(subTreesToDelete, rootBucket);
rootBucket.shrink(0);
rootBucket = new OSBTreeBonsaiBucket<K, V>(rootPointer.getDataPointer(), rootBucketPointer.getPageOffset(), true,
keySerializer, valueSerializer, getTrackMode());
rootBucket.setTreeSize(0);
logPageChanges(rootBucket, fileId, rootBucketPointer.getPageIndex(), true);
cacheEntry.markDirty();
} finally {
rootPointer.releaseExclusiveLock();
diskCache.release(cacheEntry);
}
recycleSubTrees(subTreesToDelete);
endDurableOperation(transaction, false);
} catch (IOException e) {
rollback(transaction);
throw new OSBTreeException("Error during clear of sbtree with name " + name, e);
} finally {
releaseExclusiveLock();
}
}
private void addChildrenToQueue(Queue<OBonsaiBucketPointer> subTreesToDelete, OSBTreeBonsaiBucket<K, V> rootBucket) {
if (!rootBucket.isLeaf()) {
final int size = rootBucket.size();
if (size > 0)
subTreesToDelete.add(rootBucket.getEntry(0).leftChild);
for (int i = 0; i < size; i++) {
final OSBTreeBonsaiBucket.SBTreeEntry<K, V> entry = rootBucket.getEntry(i);
subTreesToDelete.add(entry.rightChild);
}
}
}
private void recycleSubTrees(Queue<OBonsaiBucketPointer> subTreesToDelete) throws IOException {
OBonsaiBucketPointer head = OBonsaiBucketPointer.NULL;
OBonsaiBucketPointer tail = subTreesToDelete.peek();
int bucketCount = 0;
while (!subTreesToDelete.isEmpty()) {
final OBonsaiBucketPointer bucketPointer = subTreesToDelete.poll();
OCacheEntry cacheEntry = diskCache.load(fileId, bucketPointer.getPageIndex(), false);
OCachePointer pointer = cacheEntry.getCachePointer();
pointer.acquireExclusiveLock();
try {
final OSBTreeBonsaiBucket<K, V> bucket = new OSBTreeBonsaiBucket<K, V>(pointer.getDataPointer(),
bucketPointer.getPageOffset(), keySerializer, valueSerializer, getTrackMode());
addChildrenToQueue(subTreesToDelete, bucket);
bucket.setFreeListPointer(head);
head = bucketPointer;
logPageChanges(bucket, fileId, bucketPointer.getPageIndex(), false);
cacheEntry.markDirty();
} finally {
pointer.releaseExclusiveLock();
diskCache.release(cacheEntry);
}
bucketCount++;
}
if (head.isValid()) {
final OCacheEntry sysCacheEntry = diskCache.load(fileId, SYS_BUCKET.getPageIndex(), false);
final OCachePointer sysCachePointer = sysCacheEntry.getCachePointer();
sysCachePointer.acquireExclusiveLock();
try {
final OSysBucket sysBucket = new OSysBucket(sysCachePointer.getDataPointer(), getTrackMode());
attachFreeListHead(tail, sysBucket.getFreeListHead());
sysBucket.setFreeListHead(head);
sysBucket.setFreeListLength(sysBucket.freeListLength() + bucketCount);
logPageChanges(sysBucket, fileId, SYS_BUCKET.getPageIndex(), false);
sysCacheEntry.markDirty();
} finally {
sysCachePointer.releaseExclusiveLock();
diskCache.release(sysCacheEntry);
}
}
}
private void attachFreeListHead(OBonsaiBucketPointer bucketPointer, OBonsaiBucketPointer freeListHead) throws IOException {
OCacheEntry cacheEntry = diskCache.load(fileId, bucketPointer.getPageIndex(), false);
OCachePointer pointer = cacheEntry.getCachePointer();
pointer.acquireExclusiveLock();
try {
final OSBTreeBonsaiBucket<K, V> bucket = new OSBTreeBonsaiBucket<K, V>(pointer.getDataPointer(),
bucketPointer.getPageOffset(), keySerializer, valueSerializer, getTrackMode());
bucket.setFreeListPointer(freeListHead);
super.logPageChanges(bucket, fileId, bucketPointer.getPageIndex(), false);
cacheEntry.markDirty();
} finally {
pointer.releaseExclusiveLock();
diskCache.release(cacheEntry);
}
}
public void delete() {
acquireExclusiveLock();
OStorageTransaction transaction = storage.getStorageTransaction();
try {
startDurableOperation(transaction);
final Queue<OBonsaiBucketPointer> subTreesToDelete = new LinkedList<OBonsaiBucketPointer>();
subTreesToDelete.add(rootBucketPointer);
recycleSubTrees(subTreesToDelete);
endDurableOperation(transaction, false);
} catch (IOException e) {
rollback(transaction);
throw new OSBTreeException("Error during delete of sbtree with name " + name, e);
} finally {
releaseExclusiveLock();
}
}
public void load(long fileId, OBonsaiBucketPointer rootBucketPointer, OStorageLocalAbstract storageLocal) {
acquireExclusiveLock();
try {
this.storage = storageLocal;
this.rootBucketPointer = rootBucketPointer;
diskCache = storage.getDiskCache();
diskCache.openFile(fileId);
this.fileId = fileId;
this.name = resolveTreeName(fileId);
OCacheEntry rootCacheEntry = diskCache.load(this.fileId, this.rootBucketPointer.getPageIndex(), false);
OCachePointer rootPointer = rootCacheEntry.getCachePointer();
try {
OSBTreeBonsaiBucket<K, V> rootBucket = new OSBTreeBonsaiBucket<K, V>(rootPointer.getDataPointer(),
this.rootBucketPointer.getPageOffset(), keySerializer, valueSerializer, ODurablePage.TrackMode.NONE);
keySerializer = (OBinarySerializer<K>) OBinarySerializerFactory.INSTANCE.getObjectSerializer(rootBucket
.getKeySerializerId());
valueSerializer = (OBinarySerializer<V>) OBinarySerializerFactory.INSTANCE.getObjectSerializer(rootBucket
.getValueSerializerId());
} finally {
diskCache.release(rootCacheEntry);
}
initDurableComponent(storageLocal);
} catch (IOException e) {
throw new OSBTreeException("Exception during loading of sbtree " + fileId, e);
} finally {
releaseExclusiveLock();
}
}
private String resolveTreeName(long fileId) {
final String fileName = diskCache.fileNameById(fileId);
return fileName.substring(0, fileName.length() - dataFileExtension.length());
}
private void setSize(long size) throws IOException {
OCacheEntry rootCacheEntry = diskCache.load(fileId, rootBucketPointer.getPageIndex(), false);
OCachePointer rootPointer = rootCacheEntry.getCachePointer();
rootPointer.acquireExclusiveLock();
try {
OSBTreeBonsaiBucket<K, V> rootBucket = new OSBTreeBonsaiBucket<K, V>(rootPointer.getDataPointer(),
rootBucketPointer.getPageOffset(), keySerializer, valueSerializer, getTrackMode());
rootBucket.setTreeSize(size);
logPageChanges(rootBucket, fileId, rootBucketPointer.getPageIndex(), false);
rootCacheEntry.markDirty();
} finally {
rootPointer.releaseExclusiveLock();
diskCache.release(rootCacheEntry);
}
}
public long size() {
acquireSharedLock();
try {
OCacheEntry rootCacheEntry = diskCache.load(fileId, rootBucketPointer.getPageIndex(), false);
OCachePointer rootPointer = rootCacheEntry.getCachePointer();
try {
OSBTreeBonsaiBucket rootBucket = new OSBTreeBonsaiBucket<K, V>(rootPointer.getDataPointer(),
rootBucketPointer.getPageOffset(), keySerializer, valueSerializer, ODurablePage.TrackMode.NONE);
return rootBucket.getTreeSize();
} finally {
diskCache.release(rootCacheEntry);
}
} catch (IOException e) {
throw new OSBTreeException("Error during retrieving of size of index " + name);
} finally {
releaseSharedLock();
}
}
public V remove(K key) {
acquireExclusiveLock();
OStorageTransaction transaction = storage.getStorageTransaction();
try {
BucketSearchResult bucketSearchResult = findBucket(key, PartialSearchMode.NONE);
if (bucketSearchResult.itemIndex < 0)
return null;
OBonsaiBucketPointer bucketPointer = bucketSearchResult.getLastPathItem();
OCacheEntry keyBucketCacheEntry = diskCache.load(fileId, bucketPointer.getPageIndex(), false);
OCachePointer keyBucketPointer = keyBucketCacheEntry.getCachePointer();
final V removed;
keyBucketPointer.acquireExclusiveLock();
try {
startDurableOperation(transaction);
OSBTreeBonsaiBucket<K, V> keyBucket = new OSBTreeBonsaiBucket<K, V>(keyBucketPointer.getDataPointer(),
bucketPointer.getPageOffset(), keySerializer, valueSerializer, getTrackMode());
removed = keyBucket.getEntry(bucketSearchResult.itemIndex).value;
keyBucket.remove(bucketSearchResult.itemIndex);
logPageChanges(keyBucket, fileId, keyBucketCacheEntry.getPageIndex(), false);
keyBucketCacheEntry.markDirty();
} finally {
keyBucketPointer.releaseExclusiveLock();
diskCache.release(keyBucketCacheEntry);
}
setSize(size() - 1);
endDurableOperation(transaction, false);
return removed;
} catch (IOException e) {
rollback(transaction);
throw new OSBTreeException("Error during removing key " + key + " from sbtree " + name, e);
} finally {
releaseExclusiveLock();
}
}
@Override
protected void endDurableOperation(OStorageTransaction transaction, boolean rollback) throws IOException {
if (transaction == null && !durableInNonTxMode)
return;
super.endDurableOperation(transaction, rollback);
}
@Override
protected void startDurableOperation(OStorageTransaction transaction) throws IOException {
if (transaction == null && !durableInNonTxMode)
return;
super.startDurableOperation(transaction);
}
@Override
protected void logPageChanges(ODurablePage localPage, long fileId, long pageIndex, boolean isNewPage) throws IOException {
final OStorageTransaction transaction = storage.getStorageTransaction();
if (transaction == null && !durableInNonTxMode)
return;
super.logPageChanges(localPage, fileId, pageIndex, isNewPage);
}
@Override
protected ODurablePage.TrackMode getTrackMode() {
final OStorageTransaction transaction = storage.getStorageTransaction();
if (transaction == null && !durableInNonTxMode)
return ODurablePage.TrackMode.NONE;
return super.getTrackMode();
}
public Collection<V> getValuesMinor(K key, boolean inclusive, final int maxValuesToFetch) {
final List<V> result = new ArrayList<V>();
loadEntriesMinor(key, inclusive, new RangeResultListener<K, V>() {
@Override
public boolean addResult(Map.Entry<K, V> entry) {
result.add(entry.getValue());
if (maxValuesToFetch > -1 && result.size() >= maxValuesToFetch)
return false;
return true;
}
});
return result;
}
public void loadEntriesMinor(K key, boolean inclusive, RangeResultListener<K, V> listener) {
acquireSharedLock();
try {
final PartialSearchMode partialSearchMode;
if (inclusive)
partialSearchMode = PartialSearchMode.HIGHEST_BOUNDARY;
else
partialSearchMode = PartialSearchMode.LOWEST_BOUNDARY;
BucketSearchResult bucketSearchResult = findBucket(key, partialSearchMode);
OBonsaiBucketPointer bucketPointer = bucketSearchResult.getLastPathItem();
int index;
if (bucketSearchResult.itemIndex >= 0) {
index = inclusive ? bucketSearchResult.itemIndex : bucketSearchResult.itemIndex - 1;
} else {
index = -bucketSearchResult.itemIndex - 2;
}
boolean firstBucket = true;
do {
OCacheEntry cacheEntry = diskCache.load(fileId, bucketPointer.getPageIndex(), false);
final OCachePointer pointer = cacheEntry.getCachePointer();
try {
OSBTreeBonsaiBucket<K, V> bucket = new OSBTreeBonsaiBucket<K, V>(pointer.getDataPointer(), bucketPointer.getPageOffset(),
keySerializer, valueSerializer, ODurablePage.TrackMode.NONE);
if (!firstBucket)
index = bucket.size() - 1;
for (int i = index; i >= 0; i--) {
if (!listener.addResult(bucket.getEntry(i)))
return;
}
bucketPointer = bucket.getLeftSibling();
firstBucket = false;
} finally {
diskCache.release(cacheEntry);
}
} while (bucketPointer.getPageIndex() >= 0);
} catch (IOException ioe) {
throw new OSBTreeException("Error during fetch of minor values for key " + key + " in sbtree " + name);
} finally {
releaseSharedLock();
}
}
public Collection<V> getValuesMajor(K key, boolean inclusive, final int maxValuesToFetch) {
final List<V> result = new ArrayList<V>();
loadEntriesMajor(key, inclusive, new RangeResultListener<K, V>() {
@Override
public boolean addResult(Map.Entry<K, V> entry) {
result.add(entry.getValue());
if (maxValuesToFetch > -1 && result.size() >= maxValuesToFetch)
return false;
return true;
}
});
return result;
}
public void loadEntriesMajor(K key, boolean inclusive, RangeResultListener<K, V> listener) {
acquireSharedLock();
try {
final PartialSearchMode partialSearchMode;
if (inclusive)
partialSearchMode = PartialSearchMode.LOWEST_BOUNDARY;
else
partialSearchMode = PartialSearchMode.HIGHEST_BOUNDARY;
BucketSearchResult bucketSearchResult = findBucket(key, partialSearchMode);
OBonsaiBucketPointer bucketPointer = bucketSearchResult.getLastPathItem();
int index;
if (bucketSearchResult.itemIndex >= 0) {
index = inclusive ? bucketSearchResult.itemIndex : bucketSearchResult.itemIndex + 1;
} else {
index = -bucketSearchResult.itemIndex - 1;
}
do {
final OCacheEntry cacheEntry = diskCache.load(fileId, bucketPointer.getPageIndex(), false);
final OCachePointer pointer = cacheEntry.getCachePointer();
try {
OSBTreeBonsaiBucket<K, V> bucket = new OSBTreeBonsaiBucket<K, V>(pointer.getDataPointer(), bucketPointer.getPageOffset(),
keySerializer, valueSerializer, ODurablePage.TrackMode.NONE);
int bucketSize = bucket.size();
for (int i = index; i < bucketSize; i++) {
if (!listener.addResult(bucket.getEntry(i)))
return;
}
bucketPointer = bucket.getRightSibling();
index = 0;
} finally {
diskCache.release(cacheEntry);
}
} while (bucketPointer.getPageIndex() >= 0);
} catch (IOException ioe) {
throw new OSBTreeException("Error during fetch of major values for key " + key + " in sbtree " + name);
} finally {
releaseSharedLock();
}
}
public Collection<V> getValuesBetween(K keyFrom, boolean fromInclusive, K keyTo, boolean toInclusive, final int maxValuesToFetch) {
final List<V> result = new ArrayList<V>();
loadEntriesBetween(keyFrom, fromInclusive, keyTo, toInclusive, new RangeResultListener<K, V>() {
@Override
public boolean addResult(Map.Entry<K, V> entry) {
result.add(entry.getValue());
if (maxValuesToFetch > 0 && result.size() >= maxValuesToFetch)
return false;
return true;
}
});
return result;
}
public K firstKey() {
acquireSharedLock();
try {
LinkedList<PagePathItemUnit> path = new LinkedList<PagePathItemUnit>();
OBonsaiBucketPointer bucketPointer = rootBucketPointer;
OCacheEntry cacheEntry = diskCache.load(fileId, rootBucketPointer.getPageIndex(), false);
OCachePointer cachePointer = cacheEntry.getCachePointer();
int itemIndex = 0;
OSBTreeBonsaiBucket<K, V> bucket = new OSBTreeBonsaiBucket<K, V>(cachePointer.getDataPointer(),
bucketPointer.getPageOffset(), keySerializer, valueSerializer, ODurablePage.TrackMode.NONE);
try {
while (true) {
if (bucket.isLeaf()) {
if (bucket.isEmpty()) {
if (path.isEmpty()) {
return null;
} else {
PagePathItemUnit pagePathItemUnit = path.removeLast();
bucketPointer = pagePathItemUnit.bucketPointer;
itemIndex = pagePathItemUnit.itemIndex + 1;
}
} else {
return bucket.getKey(0);
}
} else {
if (bucket.isEmpty() || itemIndex > bucket.size()) {
if (path.isEmpty()) {
return null;
} else {
PagePathItemUnit pagePathItemUnit = path.removeLast();
bucketPointer = pagePathItemUnit.bucketPointer;
itemIndex = pagePathItemUnit.itemIndex + 1;
}
} else {
path.add(new PagePathItemUnit(bucketPointer, itemIndex));
if (itemIndex < bucket.size()) {
OSBTreeBonsaiBucket.SBTreeEntry<K, V> entry = bucket.getEntry(itemIndex);
bucketPointer = entry.leftChild;
} else {
OSBTreeBonsaiBucket.SBTreeEntry<K, V> entry = bucket.getEntry(itemIndex - 1);
bucketPointer = entry.rightChild;
}
itemIndex = 0;
}
}
diskCache.release(cacheEntry);
cacheEntry = diskCache.load(fileId, bucketPointer.getPageIndex(), false);
cachePointer = cacheEntry.getCachePointer();
bucket = new OSBTreeBonsaiBucket<K, V>(cachePointer.getDataPointer(), bucketPointer.getPageOffset(), keySerializer,
valueSerializer, ODurablePage.TrackMode.NONE);
}
} finally {
diskCache.release(cacheEntry);
}
} catch (IOException e) {
throw new OSBTreeException("Error during finding first key in sbtree [" + name + "]");
} finally {
releaseSharedLock();
}
}
public K lastKey() {
acquireSharedLock();
try {
LinkedList<PagePathItemUnit> path = new LinkedList<PagePathItemUnit>();
OBonsaiBucketPointer bucketPointer = rootBucketPointer;
OCacheEntry cacheEntry = diskCache.load(fileId, bucketPointer.getPageIndex(), false);
OCachePointer cachePointer = cacheEntry.getCachePointer();
OSBTreeBonsaiBucket<K, V> bucket = new OSBTreeBonsaiBucket<K, V>(cachePointer.getDataPointer(),
bucketPointer.getPageOffset(), keySerializer, valueSerializer, ODurablePage.TrackMode.NONE);
int itemIndex = bucket.size() - 1;
try {
while (true) {
if (bucket.isLeaf()) {
if (bucket.isEmpty()) {
if (path.isEmpty()) {
return null;
} else {
PagePathItemUnit pagePathItemUnit = path.removeLast();
bucketPointer = pagePathItemUnit.bucketPointer;
itemIndex = pagePathItemUnit.itemIndex - 1;
}
} else {
return bucket.getKey(bucket.size() - 1);
}
} else {
if (itemIndex < -1) {
if (!path.isEmpty()) {
PagePathItemUnit pagePathItemUnit = path.removeLast();
bucketPointer = pagePathItemUnit.bucketPointer;
itemIndex = pagePathItemUnit.itemIndex - 1;
} else
return null;
} else {
path.add(new PagePathItemUnit(bucketPointer, itemIndex));
if (itemIndex > -1) {
OSBTreeBonsaiBucket.SBTreeEntry<K, V> entry = bucket.getEntry(itemIndex);
bucketPointer = entry.rightChild;
} else {
OSBTreeBonsaiBucket.SBTreeEntry<K, V> entry = bucket.getEntry(0);
bucketPointer = entry.leftChild;
}
itemIndex = OSBTreeBonsaiBucket.MAX_BUCKET_SIZE_BYTES + 1;
}
}
diskCache.release(cacheEntry);
cacheEntry = diskCache.load(fileId, bucketPointer.getPageIndex(), false);
cachePointer = cacheEntry.getCachePointer();
bucket = new OSBTreeBonsaiBucket<K, V>(cachePointer.getDataPointer(), bucketPointer.getPageOffset(), keySerializer,
valueSerializer, ODurablePage.TrackMode.NONE);
if (itemIndex == OSBTreeBonsaiBucket.MAX_BUCKET_SIZE_BYTES + 1)
itemIndex = bucket.size() - 1;
}
} finally {
diskCache.release(cacheEntry);
}
} catch (IOException e) {
throw new OSBTreeException("Error during finding first key in sbtree [" + name + "]");
} finally {
releaseSharedLock();
}
}
public void loadEntriesBetween(K keyFrom, boolean fromInclusive, K keyTo, boolean toInclusive, RangeResultListener<K, V> listener) {
acquireSharedLock();
try {
PartialSearchMode partialSearchModeFrom;
if (fromInclusive)
partialSearchModeFrom = PartialSearchMode.LOWEST_BOUNDARY;
else
partialSearchModeFrom = PartialSearchMode.HIGHEST_BOUNDARY;
BucketSearchResult bucketSearchResultFrom = findBucket(keyFrom, partialSearchModeFrom);
OBonsaiBucketPointer bucketPointerFrom = bucketSearchResultFrom.getLastPathItem();
int indexFrom;
if (bucketSearchResultFrom.itemIndex >= 0) {
indexFrom = fromInclusive ? bucketSearchResultFrom.itemIndex : bucketSearchResultFrom.itemIndex + 1;
} else {
indexFrom = -bucketSearchResultFrom.itemIndex - 1;
}
PartialSearchMode partialSearchModeTo;
if (toInclusive)
partialSearchModeTo = PartialSearchMode.HIGHEST_BOUNDARY;
else
partialSearchModeTo = PartialSearchMode.LOWEST_BOUNDARY;
BucketSearchResult bucketSearchResultTo = findBucket(keyTo, partialSearchModeTo);
OBonsaiBucketPointer bucketPointerTo = bucketSearchResultTo.getLastPathItem();
int indexTo;
if (bucketSearchResultTo.itemIndex >= 0) {
indexTo = toInclusive ? bucketSearchResultTo.itemIndex : bucketSearchResultTo.itemIndex - 1;
} else {
indexTo = -bucketSearchResultTo.itemIndex - 2;
}
int startIndex = indexFrom;
int endIndex;
OBonsaiBucketPointer bucketPointer = bucketPointerFrom;
resultsLoop: while (true) {
final OCacheEntry cacheEntry = diskCache.load(fileId, bucketPointer.getPageIndex(), false);
final OCachePointer pointer = cacheEntry.getCachePointer();
try {
OSBTreeBonsaiBucket<K, V> bucket = new OSBTreeBonsaiBucket<K, V>(pointer.getDataPointer(), bucketPointer.getPageOffset(),
keySerializer, valueSerializer, ODurablePage.TrackMode.NONE);
if (!bucketPointer.equals(bucketPointerTo))
endIndex = bucket.size() - 1;
else
endIndex = indexTo;
for (int i = startIndex; i <= endIndex; i++) {
if (!listener.addResult(bucket.getEntry(i)))
break resultsLoop;
}
if (bucketPointer.equals(bucketPointerTo))
break;
bucketPointer = bucket.getRightSibling();
if (bucketPointer.getPageIndex() < 0)
break;
} finally {
diskCache.release(cacheEntry);
}
startIndex = 0;
}
} catch (IOException ioe) {
throw new OSBTreeException("Error during fetch of values between key " + keyFrom + " and key " + keyTo + " in sbtree " + name);
} finally {
releaseSharedLock();
}
}
public void flush() {
acquireSharedLock();
try {
try {
diskCache.flushBuffer();
} catch (IOException e) {
throw new OSBTreeException("Error during flush of sbtree [" + name + "] data");
}
} finally {
releaseSharedLock();
}
}
private BucketSearchResult splitBucket(List<OBonsaiBucketPointer> path, int keyIndex, K keyToInsert) throws IOException {
final OBonsaiBucketPointer bucketPointer = path.get(path.size() - 1);
OCacheEntry bucketEntry = diskCache.load(fileId, bucketPointer.getPageIndex(), false);
OCachePointer pointer = bucketEntry.getCachePointer();
pointer.acquireExclusiveLock();
try {
OSBTreeBonsaiBucket<K, V> bucketToSplit = new OSBTreeBonsaiBucket<K, V>(pointer.getDataPointer(),
bucketPointer.getPageOffset(), keySerializer, valueSerializer, getTrackMode());
final boolean splitLeaf = bucketToSplit.isLeaf();
final int bucketSize = bucketToSplit.size();
int indexToSplit = bucketSize >>> 1;
final K separationKey = bucketToSplit.getKey(indexToSplit);
final List<OSBTreeBonsaiBucket.SBTreeEntry<K, V>> rightEntries = new ArrayList<OSBTreeBonsaiBucket.SBTreeEntry<K, V>>(
indexToSplit);
final int startRightIndex = splitLeaf ? indexToSplit : indexToSplit + 1;
for (int i = startRightIndex; i < bucketSize; i++)
rightEntries.add(bucketToSplit.getEntry(i));
if (!bucketPointer.equals(rootBucketPointer)) {
final AllocationResult allocationResult = allocateBucket();
OCacheEntry rightBucketEntry = allocationResult.getCacheEntry();
final OBonsaiBucketPointer rightBucketPointer = allocationResult.getPointer();
OCachePointer rightPointer = rightBucketEntry.getCachePointer();
rightPointer.acquireExclusiveLock();
try {
OSBTreeBonsaiBucket<K, V> newRightBucket = new OSBTreeBonsaiBucket<K, V>(rightPointer.getDataPointer(),
rightBucketPointer.getPageOffset(), splitLeaf, keySerializer, valueSerializer, getTrackMode());
newRightBucket.addAll(rightEntries);
bucketToSplit.shrink(indexToSplit);
if (splitLeaf) {
OBonsaiBucketPointer rightSiblingBucketPointer = bucketToSplit.getRightSibling();
newRightBucket.setRightSibling(rightSiblingBucketPointer);
newRightBucket.setLeftSibling(bucketPointer);
bucketToSplit.setRightSibling(rightBucketPointer);
if (rightSiblingBucketPointer.isValid()) {
final OCacheEntry rightSiblingBucketEntry = diskCache.load(fileId, rightSiblingBucketPointer.getPageIndex(), false);
final OCachePointer rightSiblingPointer = rightSiblingBucketEntry.getCachePointer();
rightSiblingPointer.acquireExclusiveLock();
OSBTreeBonsaiBucket<K, V> rightSiblingBucket = new OSBTreeBonsaiBucket<K, V>(rightSiblingPointer.getDataPointer(),
rightSiblingBucketPointer.getPageOffset(), keySerializer, valueSerializer, getTrackMode());
try {
rightSiblingBucket.setLeftSibling(rightBucketPointer);
logPageChanges(rightSiblingBucket, fileId, rightSiblingBucketPointer.getPageIndex(), false);
rightSiblingBucketEntry.markDirty();
} finally {
rightSiblingPointer.releaseExclusiveLock();
diskCache.release(rightSiblingBucketEntry);
}
}
}
OBonsaiBucketPointer parentBucketPointer = path.get(path.size() - 2);
OCacheEntry parentCacheEntry = diskCache.load(fileId, parentBucketPointer.getPageIndex(), false);
OCachePointer parentPointer = parentCacheEntry.getCachePointer();
parentPointer.acquireExclusiveLock();
try {
OSBTreeBonsaiBucket<K, V> parentBucket = new OSBTreeBonsaiBucket<K, V>(parentPointer.getDataPointer(),
parentBucketPointer.getPageOffset(), keySerializer, valueSerializer, getTrackMode());
OSBTreeBonsaiBucket.SBTreeEntry<K, V> parentEntry = new OSBTreeBonsaiBucket.SBTreeEntry<K, V>(bucketPointer,
rightBucketPointer, separationKey, null);
int insertionIndex = parentBucket.find(separationKey);
assert insertionIndex < 0;
insertionIndex = -insertionIndex - 1;
while (!parentBucket.addEntry(insertionIndex, parentEntry, true)) {
parentPointer.releaseExclusiveLock();
diskCache.release(parentCacheEntry);
BucketSearchResult bucketSearchResult = splitBucket(path.subList(0, path.size() - 1), insertionIndex, separationKey);
parentBucketPointer = bucketSearchResult.getLastPathItem();
parentCacheEntry = diskCache.load(fileId, parentBucketPointer.getPageIndex(), false);
parentPointer = parentCacheEntry.getCachePointer();
parentPointer.acquireExclusiveLock();
insertionIndex = bucketSearchResult.itemIndex;
parentBucket = new OSBTreeBonsaiBucket<K, V>(parentPointer.getDataPointer(), parentBucketPointer.getPageOffset(),
keySerializer, valueSerializer, getTrackMode());
}
logPageChanges(parentBucket, fileId, parentBucketPointer.getPageIndex(), false);
} finally {
parentCacheEntry.markDirty();
parentPointer.releaseExclusiveLock();
diskCache.release(parentCacheEntry);
}
logPageChanges(newRightBucket, fileId, rightBucketEntry.getPageIndex(), allocationResult.isNewPage());
} finally {
rightBucketEntry.markDirty();
rightPointer.releaseExclusiveLock();
diskCache.release(rightBucketEntry);
}
logPageChanges(bucketToSplit, fileId, bucketPointer.getPageIndex(), false);
ArrayList<OBonsaiBucketPointer> resultPath = new ArrayList<OBonsaiBucketPointer>(path.subList(0, path.size() - 1));
if (comparator.compare(keyToInsert, separationKey) < 0) {
resultPath.add(bucketPointer);
return new BucketSearchResult(keyIndex, resultPath);
}
resultPath.add(rightBucketPointer);
if (splitLeaf) {
return new BucketSearchResult(keyIndex - indexToSplit, resultPath);
}
return new BucketSearchResult(keyIndex - indexToSplit - 1, resultPath);
} else {
long treeSize = bucketToSplit.getTreeSize();
final List<OSBTreeBonsaiBucket.SBTreeEntry<K, V>> leftEntries = new ArrayList<OSBTreeBonsaiBucket.SBTreeEntry<K, V>>(
indexToSplit);
for (int i = 0; i < indexToSplit; i++)
leftEntries.add(bucketToSplit.getEntry(i));
final AllocationResult leftAllocationResult = allocateBucket();
OCacheEntry leftBucketEntry = leftAllocationResult.getCacheEntry();
OBonsaiBucketPointer leftBucketPointer = leftAllocationResult.getPointer();
OCachePointer leftPointer = leftBucketEntry.getCachePointer();
final AllocationResult rightAllocationResult = allocateBucket();
OCacheEntry rightBucketEntry = rightAllocationResult.getCacheEntry();
OBonsaiBucketPointer rightBucketPointer = rightAllocationResult.getPointer();
leftPointer.acquireExclusiveLock();
try {
OSBTreeBonsaiBucket<K, V> newLeftBucket = new OSBTreeBonsaiBucket<K, V>(leftPointer.getDataPointer(),
leftBucketPointer.getPageOffset(), splitLeaf, keySerializer, valueSerializer, getTrackMode());
newLeftBucket.addAll(leftEntries);
if (splitLeaf)
newLeftBucket.setRightSibling(rightBucketPointer);
logPageChanges(newLeftBucket, fileId, leftBucketEntry.getPageIndex(), leftAllocationResult.isNewPage());
leftBucketEntry.markDirty();
} finally {
leftPointer.releaseExclusiveLock();
diskCache.release(leftBucketEntry);
}
OCachePointer rightPointer = rightBucketEntry.getCachePointer();
rightPointer.acquireExclusiveLock();
try {
OSBTreeBonsaiBucket<K, V> newRightBucket = new OSBTreeBonsaiBucket<K, V>(rightPointer.getDataPointer(),
rightBucketPointer.getPageOffset(), splitLeaf, keySerializer, valueSerializer, getTrackMode());
newRightBucket.addAll(rightEntries);
if (splitLeaf)
newRightBucket.setLeftSibling(leftBucketPointer);
logPageChanges(newRightBucket, fileId, rightBucketEntry.getPageIndex(), rightAllocationResult.isNewPage());
rightBucketEntry.markDirty();
} finally {
rightPointer.releaseExclusiveLock();
diskCache.release(rightBucketEntry);
}
bucketToSplit = new OSBTreeBonsaiBucket<K, V>(pointer.getDataPointer(), bucketPointer.getPageOffset(), false,
keySerializer, valueSerializer, getTrackMode());
bucketToSplit.setTreeSize(treeSize);
bucketToSplit.addEntry(0, new OSBTreeBonsaiBucket.SBTreeEntry<K, V>(leftBucketPointer, rightBucketPointer, separationKey,
null), true);
logPageChanges(bucketToSplit, fileId, bucketPointer.getPageIndex(), false);
ArrayList<OBonsaiBucketPointer> resultPath = new ArrayList<OBonsaiBucketPointer>(path.subList(0, path.size() - 1));
if (comparator.compare(keyToInsert, separationKey) < 0) {
resultPath.add(leftBucketPointer);
return new BucketSearchResult(keyIndex, resultPath);
}
resultPath.add(rightBucketPointer);
if (splitLeaf)
return new BucketSearchResult(keyIndex - indexToSplit, resultPath);
return new BucketSearchResult(keyIndex - indexToSplit - 1, resultPath);
}
} finally {
bucketEntry.markDirty();
pointer.releaseExclusiveLock();
diskCache.release(bucketEntry);
}
}
private BucketSearchResult findBucket(K key, PartialSearchMode partialSearchMode) throws IOException {
OBonsaiBucketPointer bucketPointer = rootBucketPointer;
final ArrayList<OBonsaiBucketPointer> path = new ArrayList<OBonsaiBucketPointer>();
if (!(keySize == 1 || ((OCompositeKey) key).getKeys().size() == keySize || partialSearchMode.equals(PartialSearchMode.NONE))) {
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);
key = (K) fullKey;
}
while (true) {
path.add(bucketPointer);
final OCacheEntry bucketEntry = diskCache.load(fileId, bucketPointer.getPageIndex(), false);
final OCachePointer pointer = bucketEntry.getCachePointer();
final OSBTreeBonsaiBucket.SBTreeEntry<K, V> entry;
try {
final OSBTreeBonsaiBucket<K, V> keyBucket = new OSBTreeBonsaiBucket<K, V>(pointer.getDataPointer(),
bucketPointer.getPageOffset(), keySerializer, valueSerializer, ODurablePage.TrackMode.NONE);
final int index = keyBucket.find(key);
if (keyBucket.isLeaf())
return new BucketSearchResult(index, path);
if (index >= 0)
entry = keyBucket.getEntry(index);
else {
final int insertionIndex = -index - 1;
if (insertionIndex >= keyBucket.size())
entry = keyBucket.getEntry(insertionIndex - 1);
else
entry = keyBucket.getEntry(insertionIndex);
}
} finally {
diskCache.release(bucketEntry);
}
if (comparator.compare(key, entry.key) >= 0)
bucketPointer = entry.rightChild;
else
bucketPointer = entry.leftChild;
}
}
private void initSysBucket() throws IOException {
final OCacheEntry sysCacheEntry = diskCache.load(fileId, SYS_BUCKET.getPageIndex(), false);
final OCachePointer cachePointer = sysCacheEntry.getCachePointer();
cachePointer.acquireExclusiveLock();
try {
final OSysBucket sysBucket = new OSysBucket(cachePointer.getDataPointer(), getTrackMode());
if (sysBucket.isInitialized()) {
super.startDurableOperation(null);
sysBucket.init();
super.logPageChanges(sysBucket, fileId, SYS_BUCKET.getPageIndex(), true);
sysCacheEntry.markDirty();
super.endDurableOperation(null, false);
}
} finally {
cachePointer.releaseExclusiveLock();
diskCache.release(sysCacheEntry);
}
}
private AllocationResult allocateBucket() throws IOException {
final OCacheEntry sysCacheEntry = diskCache.load(fileId, SYS_BUCKET.getPageIndex(), false);
final OCachePointer cachePointer = sysCacheEntry.getCachePointer();
cachePointer.acquireExclusiveLock();
try {
final OSysBucket sysBucket = new OSysBucket(cachePointer.getDataPointer(), getTrackMode());
if (sysBucket.freeListLength() > diskCache.getFilledUpTo(fileId) * PAGE_SIZE / OSBTreeBonsaiBucket.MAX_BUCKET_SIZE_BYTES / 2) {
final AllocationResult allocationResult = reuseBucketFromFreeList(sysBucket);
sysCacheEntry.markDirty();
return allocationResult;
} else {
final OBonsaiBucketPointer freeSpacePointer = sysBucket.getFreeSpacePointer();
if (freeSpacePointer.getPageOffset() + OSBTreeBonsaiBucket.MAX_BUCKET_SIZE_BYTES > PAGE_SIZE) {
final OCacheEntry cacheEntry = diskCache.allocateNewPage(fileId);
final long pageIndex = cacheEntry.getPageIndex();
sysBucket.setFreeSpacePointer(new OBonsaiBucketPointer(pageIndex, OSBTreeBonsaiBucket.MAX_BUCKET_SIZE_BYTES));
logPageChanges(sysBucket, fileId, SYS_BUCKET.getPageIndex(), false);
sysCacheEntry.markDirty();
return new AllocationResult(new OBonsaiBucketPointer(pageIndex, 0), cacheEntry, true);
} else {
sysBucket.setFreeSpacePointer(new OBonsaiBucketPointer(freeSpacePointer.getPageIndex(), freeSpacePointer.getPageOffset()
+ OSBTreeBonsaiBucket.MAX_BUCKET_SIZE_BYTES));
final OCacheEntry cacheEntry = diskCache.load(fileId, freeSpacePointer.getPageIndex(), false);
logPageChanges(sysBucket, fileId, SYS_BUCKET.getPageIndex(), false);
sysCacheEntry.markDirty();
return new AllocationResult(freeSpacePointer, cacheEntry, false);
}
}
} finally {
cachePointer.releaseExclusiveLock();
diskCache.release(sysCacheEntry);
}
}
private AllocationResult reuseBucketFromFreeList(OSysBucket sysBucket) throws IOException {
final OBonsaiBucketPointer oldFreeListHead = sysBucket.getFreeListHead();
assert oldFreeListHead.isValid();
OCacheEntry cacheEntry = diskCache.load(fileId, oldFreeListHead.getPageIndex(), false);
OCachePointer pointer = cacheEntry.getCachePointer();
pointer.acquireExclusiveLock();
try {
final OSBTreeBonsaiBucket<K, V> bucket = new OSBTreeBonsaiBucket<K, V>(pointer.getDataPointer(),
oldFreeListHead.getPageOffset(), keySerializer, valueSerializer, getTrackMode());
sysBucket.setFreeListHead(bucket.getFreeListPointer());
sysBucket.setFreeListLength(sysBucket.freeListLength() - 1);
logPageChanges(bucket, fileId, oldFreeListHead.getPageIndex(), false);
cacheEntry.markDirty();
} finally {
pointer.releaseExclusiveLock();
}
return new AllocationResult(oldFreeListHead, cacheEntry, false);
}
public String getFileName() {
return name + dataFileExtension;
}
private static class AllocationResult {
private final OBonsaiBucketPointer pointer;
private final OCacheEntry cacheEntry;
private final boolean newPage;
private AllocationResult(OBonsaiBucketPointer pointer, OCacheEntry cacheEntry, boolean newPage) {
this.pointer = pointer;
this.cacheEntry = cacheEntry;
this.newPage = newPage;
}
private OBonsaiBucketPointer getPointer() {
return pointer;
}
private OCacheEntry getCacheEntry() {
return cacheEntry;
}
private boolean isNewPage() {
return newPage;
}
}
private static class BucketSearchResult {
private final int itemIndex;
private final ArrayList<OBonsaiBucketPointer> path;
private BucketSearchResult(int itemIndex, ArrayList<OBonsaiBucketPointer> path) {
this.itemIndex = itemIndex;
this.path = path;
}
public OBonsaiBucketPointer getLastPathItem() {
return path.get(path.size() - 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.
*
*
*/
private 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
}
private static final class PagePathItemUnit {
private final OBonsaiBucketPointer bucketPointer;
private final int itemIndex;
private PagePathItemUnit(OBonsaiBucketPointer bucketPointer, int itemIndex) {
this.bucketPointer = bucketPointer;
this.itemIndex = itemIndex;
}
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_sbtreebonsai_local_OSBTreeBonsai.java |
132 | public abstract class RecursiveAction extends ForkJoinTask<Void> {
private static final long serialVersionUID = 5232453952276485070L;
/**
* The main computation performed by this task.
*/
protected abstract void compute();
/**
* Always returns {@code null}.
*
* @return {@code null} always
*/
public final Void getRawResult() { return null; }
/**
* Requires null completion value.
*/
protected final void setRawResult(Void mustBeNull) { }
/**
* Implements execution conventions for RecursiveActions.
*/
protected final boolean exec() {
compute();
return true;
}
} | 0true
| src_main_java_jsr166e_RecursiveAction.java |
399 | add(store1, "restore-doc2", new HashMap<String, Object>() {{
put(NAME, "second");
put(TIME, 2L);
put(WEIGHT, 4.7d);
}}, true); | 0true
| titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexProviderTest.java |
3,557 | public static class Values {
public final static BytesRef TRUE = new BytesRef("T");
public final static BytesRef FALSE = new BytesRef("F");
} | 0true
| src_main_java_org_elasticsearch_index_mapper_core_BooleanFieldMapper.java |
331 | static final class Fields {
static final XContentBuilderString PLUGINS = new XContentBuilderString("plugins");
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_node_info_PluginsInfo.java |
1,535 | public class JcaBase {
/**
* Class LOGGER from hazelcast's logging framework
*/
private static final ILogger LOGGER = Logger.getLogger("com.hazelcast.jca");
/**
* Container's LOGGER
*/
private PrintWriter logWriter;
/**
* Convenient method for {@link log(Level, String, null)}
*
* @param logLevel The level to log on
* @param message The message to be logged
* @see #log(Level, String, Throwable)
*/
void log(Level logLevel, String message) {
log(logLevel, message, null);
}
/**
* Logs the given message and throwable (if any) if the
* configured logging level is set for the given one.
* The message (and throwable) is logged to Hazelcast's logging
* framework <b>and</b> the container specific print writer
*
* @param logLevel The level to log on
* @param message The message to be logged
* @param t The throwable to also log (message with stacktrace)
*/
void log(Level logLevel, String message, Throwable t) {
if (LOGGER.isLoggable(logLevel)) {
//Log to hazelcast loggin framework itself
LOGGER.log(logLevel, message, t);
final PrintWriter logWriter = getLogWriter();
//Log via the container if possible
if (logWriter != null) {
logWriter.write(message);
if (t != null) {
t.printStackTrace(logWriter);
}
}
}
}
/**
* @return The container-specific LOGGER
*/
public PrintWriter getLogWriter() {
return logWriter;
}
/**
* Sets the container specific container LOGGER
*
* @param printWriter the new LOGGER to be used
*/
public void setLogWriter(PrintWriter printWriter) {
this.logWriter = printWriter;
}
} | 0true
| hazelcast-ra_hazelcast-jca_src_main_java_com_hazelcast_jca_JcaBase.java |
3,631 | public class GeoEncodingTests extends ElasticsearchTestCase {
public void test() {
for (int i = 0; i < 10000; ++i) {
final double lat = randomDouble() * 180 - 90;
final double lon = randomDouble() * 360 - 180;
final Distance precision = new Distance(1+(randomDouble() * 9), randomFrom(Arrays.asList(DistanceUnit.MILLIMETERS, DistanceUnit.METERS, DistanceUnit.KILOMETERS)));
final GeoPointFieldMapper.Encoding encoding = GeoPointFieldMapper.Encoding.of(precision);
assertThat(encoding.precision().convert(DistanceUnit.METERS).value, lessThanOrEqualTo(precision.convert(DistanceUnit.METERS).value));
final GeoPoint geoPoint = encoding.decode(encoding.encodeCoordinate(lat), encoding.encodeCoordinate(lon), new GeoPoint());
final double error = GeoDistance.PLANE.calculate(lat, lon, geoPoint.lat(), geoPoint.lon(), DistanceUnit.METERS);
assertThat(error, lessThanOrEqualTo(precision.convert(DistanceUnit.METERS).value));
}
}
} | 0true
| src_test_java_org_elasticsearch_index_mapper_geo_GeoEncodingTests.java |
655 | public class PutIndexTemplateRequest extends MasterNodeOperationRequest<PutIndexTemplateRequest> {
private String name;
private String cause = "";
private String template;
private int order;
private boolean create;
private Settings settings = EMPTY_SETTINGS;
private Map<String, String> mappings = newHashMap();
private Map<String, IndexMetaData.Custom> customs = newHashMap();
PutIndexTemplateRequest() {
}
/**
* Constructs a new put index template request with the provided name.
*/
public PutIndexTemplateRequest(String name) {
this.name = name;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (name == null) {
validationException = addValidationError("name is missing", validationException);
}
if (template == null) {
validationException = addValidationError("template is missing", validationException);
}
return validationException;
}
/**
* Sets the name of the index template.
*/
public PutIndexTemplateRequest name(String name) {
this.name = name;
return this;
}
/**
* The name of the index template.
*/
public String name() {
return this.name;
}
public PutIndexTemplateRequest template(String template) {
this.template = template;
return this;
}
public String template() {
return this.template;
}
public PutIndexTemplateRequest order(int order) {
this.order = order;
return this;
}
public int order() {
return this.order;
}
/**
* Set to <tt>true</tt> to force only creation, not an update of an index template. If it already
* exists, it will fail with an {@link org.elasticsearch.indices.IndexTemplateAlreadyExistsException}.
*/
public PutIndexTemplateRequest create(boolean create) {
this.create = create;
return this;
}
public boolean create() {
return create;
}
/**
* The settings to create the index template with.
*/
public PutIndexTemplateRequest settings(Settings settings) {
this.settings = settings;
return this;
}
/**
* The settings to create the index template with.
*/
public PutIndexTemplateRequest settings(Settings.Builder settings) {
this.settings = settings.build();
return this;
}
/**
* The settings to create the index template with (either json/yaml/properties format).
*/
public PutIndexTemplateRequest settings(String source) {
this.settings = ImmutableSettings.settingsBuilder().loadFromSource(source).build();
return this;
}
/**
* The settings to crete the index template with (either json/yaml/properties format).
*/
public PutIndexTemplateRequest settings(Map<String, Object> source) {
try {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.map(source);
settings(builder.string());
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
}
return this;
}
Settings settings() {
return this.settings;
}
/**
* Adds mapping that will be added when the index gets created.
*
* @param type The mapping type
* @param source The mapping source
*/
public PutIndexTemplateRequest mapping(String type, String source) {
mappings.put(type, source);
return this;
}
/**
* The cause for this index template creation.
*/
public PutIndexTemplateRequest cause(String cause) {
this.cause = cause;
return this;
}
public String cause() {
return this.cause;
}
/**
* Adds mapping that will be added when the index gets created.
*
* @param type The mapping type
* @param source The mapping source
*/
public PutIndexTemplateRequest mapping(String type, XContentBuilder source) {
try {
mappings.put(type, source.string());
} catch (IOException e) {
throw new ElasticsearchIllegalArgumentException("Failed to build json for mapping request", e);
}
return this;
}
/**
* Adds mapping that will be added when the index gets created.
*
* @param type The mapping type
* @param source The mapping source
*/
public PutIndexTemplateRequest mapping(String type, Map<String, Object> source) {
// wrap it in a type map if its not
if (source.size() != 1 || !source.containsKey(type)) {
source = MapBuilder.<String, Object>newMapBuilder().put(type, source).map();
}
try {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.map(source);
return mapping(type, builder.string());
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
}
}
Map<String, String> mappings() {
return this.mappings;
}
/**
* The template source definition.
*/
public PutIndexTemplateRequest source(XContentBuilder templateBuilder) {
try {
return source(templateBuilder.bytes());
} catch (Exception e) {
throw new ElasticsearchIllegalArgumentException("Failed to build json for template request", e);
}
}
/**
* The template source definition.
*/
public PutIndexTemplateRequest source(Map templateSource) {
Map<String, Object> source = templateSource;
for (Map.Entry<String, Object> entry : source.entrySet()) {
String name = entry.getKey();
if (name.equals("template")) {
template(entry.getValue().toString());
} else if (name.equals("order")) {
order(XContentMapValues.nodeIntegerValue(entry.getValue(), order()));
} else if (name.equals("settings")) {
if (!(entry.getValue() instanceof Map)) {
throw new ElasticsearchIllegalArgumentException("Malformed settings section, should include an inner object");
}
settings((Map<String, Object>) entry.getValue());
} else if (name.equals("mappings")) {
Map<String, Object> mappings = (Map<String, Object>) entry.getValue();
for (Map.Entry<String, Object> entry1 : mappings.entrySet()) {
if (!(entry1.getValue() instanceof Map)) {
throw new ElasticsearchIllegalArgumentException("Malformed mappings section for type [" + entry1.getKey() + "], should include an inner object describing the mapping");
}
mapping(entry1.getKey(), (Map<String, Object>) entry1.getValue());
}
} else {
// maybe custom?
IndexMetaData.Custom.Factory factory = IndexMetaData.lookupFactory(name);
if (factory != null) {
try {
customs.put(name, factory.fromMap((Map<String, Object>) entry.getValue()));
} catch (IOException e) {
throw new ElasticsearchParseException("failed to parse custom metadata for [" + name + "]");
}
}
}
}
return this;
}
/**
* The template source definition.
*/
public PutIndexTemplateRequest source(String templateSource) {
try {
return source(XContentFactory.xContent(templateSource).createParser(templateSource).mapOrderedAndClose());
} catch (Exception e) {
throw new ElasticsearchIllegalArgumentException("failed to parse template source [" + templateSource + "]", e);
}
}
/**
* The template source definition.
*/
public PutIndexTemplateRequest source(byte[] source) {
return source(source, 0, source.length);
}
/**
* The template source definition.
*/
public PutIndexTemplateRequest source(byte[] source, int offset, int length) {
try {
return source(XContentFactory.xContent(source, offset, length).createParser(source, offset, length).mapOrderedAndClose());
} catch (IOException e) {
throw new ElasticsearchIllegalArgumentException("failed to parse template source", e);
}
}
/**
* The template source definition.
*/
public PutIndexTemplateRequest source(BytesReference source) {
try {
return source(XContentFactory.xContent(source).createParser(source).mapOrderedAndClose());
} catch (IOException e) {
throw new ElasticsearchIllegalArgumentException("failed to parse template source", e);
}
}
public PutIndexTemplateRequest custom(IndexMetaData.Custom custom) {
customs.put(custom.type(), custom);
return this;
}
Map<String, IndexMetaData.Custom> customs() {
return this.customs;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
cause = in.readString();
name = in.readString();
template = in.readString();
order = in.readInt();
create = in.readBoolean();
settings = readSettingsFromStream(in);
int size = in.readVInt();
for (int i = 0; i < size; i++) {
mappings.put(in.readString(), in.readString());
}
int customSize = in.readVInt();
for (int i = 0; i < customSize; i++) {
String type = in.readString();
IndexMetaData.Custom customIndexMetaData = IndexMetaData.lookupFactorySafe(type).readFrom(in);
customs.put(type, customIndexMetaData);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(cause);
out.writeString(name);
out.writeString(template);
out.writeInt(order);
out.writeBoolean(create);
writeSettingsToStream(settings, out);
out.writeVInt(mappings.size());
for (Map.Entry<String, String> entry : mappings.entrySet()) {
out.writeString(entry.getKey());
out.writeString(entry.getValue());
}
out.writeVInt(customs.size());
for (Map.Entry<String, IndexMetaData.Custom> entry : customs.entrySet()) {
out.writeString(entry.getKey());
IndexMetaData.lookupFactorySafe(entry.getKey()).writeTo(entry.getValue(), out);
}
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_template_put_PutIndexTemplateRequest.java |
112 | class FindTypeParameterConstraintVisitor extends Visitor {
List<ProducedType> result;
@Override
public void visit(Tree.SimpleType that) {
super.visit(that);
TypeDeclaration dm = that.getDeclarationModel();
if (dm!=null) {
List<TypeParameter> tps = dm.getTypeParameters();
Tree.TypeArgumentList tal = that.getTypeArgumentList();
if (tal!=null) {
List<Tree.Type> tas = tal.getTypes();
for (int i=0; i<tas.size(); i++) {
if (tas.get(i)==node) {
result = tps.get(i).getSatisfiedTypes();
}
}
}
}
}
@Override
public void visit(Tree.StaticMemberOrTypeExpression that) {
super.visit(that);
Declaration d = that.getDeclaration();
if (d instanceof Generic) {
List<TypeParameter> tps = ((Generic) d).getTypeParameters();
Tree.TypeArguments tal = that.getTypeArguments();
if (tal instanceof Tree.TypeArgumentList) {
List<Tree.Type> tas = ((Tree.TypeArgumentList) tal).getTypes();
for (int i=0; i<tas.size(); i++) {
if (tas.get(i)==node) {
result = tps.get(i).getSatisfiedTypes();
}
}
}
}
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_CreateTypeParameterProposal.java |
1,040 | public class MultiTermVectorsAction extends Action<MultiTermVectorsRequest, MultiTermVectorsResponse, MultiTermVectorsRequestBuilder> {
public static final MultiTermVectorsAction INSTANCE = new MultiTermVectorsAction();
public static final String NAME = "mtv";
private MultiTermVectorsAction() {
super(NAME);
}
@Override
public MultiTermVectorsResponse newResponse() {
return new MultiTermVectorsResponse();
}
@Override
public MultiTermVectorsRequestBuilder newRequestBuilder(Client client) {
return new MultiTermVectorsRequestBuilder(client);
}
} | 0true
| src_main_java_org_elasticsearch_action_termvector_MultiTermVectorsAction.java |
1,978 | public static final Scoping SINGLETON_INSTANCE = new Scoping() {
public <V> V acceptVisitor(BindingScopingVisitor<V> visitor) {
return visitor.visitScope(Scopes.SINGLETON);
}
@Override
public Scope getScopeInstance() {
return Scopes.SINGLETON;
}
@Override
public String toString() {
return Scopes.SINGLETON.toString();
}
public void applyTo(ScopedBindingBuilder scopedBindingBuilder) {
scopedBindingBuilder.in(Scopes.SINGLETON);
}
}; | 0true
| src_main_java_org_elasticsearch_common_inject_internal_Scoping.java |
3,677 | public class RoutingFieldMapper extends AbstractFieldMapper<String> implements InternalMapper, RootMapper {
public static final String NAME = "_routing";
public static final String CONTENT_TYPE = "_routing";
public static class Defaults extends AbstractFieldMapper.Defaults {
public static final String NAME = "_routing";
public static final FieldType FIELD_TYPE = new FieldType(AbstractFieldMapper.Defaults.FIELD_TYPE);
static {
FIELD_TYPE.setIndexed(true);
FIELD_TYPE.setTokenized(false);
FIELD_TYPE.setStored(true);
FIELD_TYPE.setOmitNorms(true);
FIELD_TYPE.setIndexOptions(IndexOptions.DOCS_ONLY);
FIELD_TYPE.freeze();
}
public static final boolean REQUIRED = false;
public static final String PATH = null;
}
public static class Builder extends AbstractFieldMapper.Builder<Builder, RoutingFieldMapper> {
private boolean required = Defaults.REQUIRED;
private String path = Defaults.PATH;
public Builder() {
super(Defaults.NAME, new FieldType(Defaults.FIELD_TYPE));
}
public Builder required(boolean required) {
this.required = required;
return builder;
}
public Builder path(String path) {
this.path = path;
return builder;
}
@Override
public RoutingFieldMapper build(BuilderContext context) {
return new RoutingFieldMapper(fieldType, required, path, postingsProvider, docValuesProvider, fieldDataSettings, context.indexSettings());
}
}
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;
}
}
private boolean required;
private final String path;
public RoutingFieldMapper() {
this(new FieldType(Defaults.FIELD_TYPE), Defaults.REQUIRED, Defaults.PATH, null, null, null, ImmutableSettings.EMPTY);
}
protected RoutingFieldMapper(FieldType fieldType, boolean required, String path, PostingsFormatProvider postingsProvider,
DocValuesFormatProvider docValuesProvider, @Nullable Settings fieldDataSettings, Settings indexSettings) {
super(new Names(Defaults.NAME, Defaults.NAME, Defaults.NAME, Defaults.NAME), 1.0f, fieldType, null, Lucene.KEYWORD_ANALYZER,
Lucene.KEYWORD_ANALYZER, postingsProvider, docValuesProvider, null, null, fieldDataSettings, indexSettings);
this.required = required;
this.path = path;
}
@Override
public FieldType defaultFieldType() {
return Defaults.FIELD_TYPE;
}
@Override
public FieldDataType defaultFieldDataType() {
return new FieldDataType("string");
}
@Override
public boolean hasDocValues() {
return false;
}
public void markAsRequired() {
this.required = true;
}
public boolean required() {
return this.required;
}
public String path() {
return this.path;
}
public String value(Document document) {
Field field = (Field) document.getField(names.indexName());
return field == null ? null : value(field);
}
@Override
public String value(Object value) {
if (value == null) {
return null;
}
return value.toString();
}
@Override
public void validate(ParseContext context) throws MapperParsingException {
String routing = context.sourceToParse().routing();
if (path != null && routing != null) {
// we have a path, check if we can validate we have the same routing value as the one in the doc...
String value = null;
Field field = (Field) context.doc().getField(path);
if (field != null) {
value = field.stringValue();
if (value == null) {
// maybe its a numeric field...
if (field instanceof NumberFieldMapper.CustomNumericField) {
value = ((NumberFieldMapper.CustomNumericField) field).numericAsString();
}
}
}
if (value == null) {
value = context.ignoredValue(path);
}
if (!routing.equals(value)) {
throw new MapperParsingException("External routing [" + routing + "] and document path routing [" + value + "] mismatch");
}
}
}
@Override
public void preParse(ParseContext context) throws IOException {
super.parse(context);
}
@Override
public void postParse(ParseContext context) throws IOException {
}
@Override
public void parse(ParseContext context) throws IOException {
// no need ot parse here, we either get the routing in the sourceToParse
// or we don't have routing, if we get it in sourceToParse, we process it in preParse
// which will always be called
}
@Override
public boolean includeInObject() {
return true;
}
@Override
protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException {
if (context.sourceToParse().routing() != null) {
String routing = context.sourceToParse().routing();
if (routing != null) {
if (!fieldType.indexed() && !fieldType.stored()) {
context.ignoredValue(names.indexName(), routing);
return;
}
fields.add(new Field(names.indexName(), routing, fieldType));
}
}
}
@Override
protected String contentType() {
return CONTENT_TYPE;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
boolean includeDefaults = params.paramAsBoolean("include_defaults", false);
// if all are defaults, no sense to write it at all
if (!includeDefaults && fieldType.indexed() == Defaults.FIELD_TYPE.indexed() &&
fieldType.stored() == Defaults.FIELD_TYPE.stored() && required == Defaults.REQUIRED && path == Defaults.PATH) {
return builder;
}
builder.startObject(CONTENT_TYPE);
if (includeDefaults || fieldType.indexed() != Defaults.FIELD_TYPE.indexed()) {
builder.field("index", indexTokenizeOptionToString(fieldType.indexed(), fieldType.tokenized()));
}
if (includeDefaults || fieldType.stored() != Defaults.FIELD_TYPE.stored()) {
builder.field("store", fieldType.stored());
}
if (includeDefaults || required != Defaults.REQUIRED) {
builder.field("required", required);
}
if (includeDefaults || path != Defaults.PATH) {
builder.field("path", path);
}
builder.endObject();
return builder;
}
@Override
public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException {
// do nothing here, no merging, but also no exception
}
} | 1no label
| src_main_java_org_elasticsearch_index_mapper_internal_RoutingFieldMapper.java |
3 | {
@Override
public void enteredCluster( ClusterConfiguration clusterConfiguration )
{
clusterClient.performRoleElections();
clusterClient.removeClusterListener( this );
}
}); | 1no label
| enterprise_ha_src_main_java_org_neo4j_kernel_ha_backup_HaBackupProvider.java |
289 | public interface ListenableActionFuture<T> extends ActionFuture<T> {
/**
* Add an action listener to be invoked when a response has received.
*/
void addListener(final ActionListener<T> listener);
/**
* Add an action listener (runnable) to be invoked when a response has received.
*/
void addListener(final Runnable listener);
} | 0true
| src_main_java_org_elasticsearch_action_ListenableActionFuture.java |
1,712 | return new UnmodifiableIterator<VType>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public VType next() {
return iterator.next().value;
}
}; | 0true
| src_main_java_org_elasticsearch_common_collect_ImmutableOpenIntMap.java |
701 | public class OCacheEntry {
OCachePointer dataPointer;
final long fileId;
final long pageIndex;
boolean isDirty;
int usagesCount;
public OCacheEntry(long fileId, long pageIndex, OCachePointer dataPointer, boolean dirty) {
this.fileId = fileId;
this.pageIndex = pageIndex;
this.dataPointer = dataPointer;
isDirty = dirty;
}
public void markDirty() {
this.isDirty = true;
}
public OCachePointer getCachePointer() {
return dataPointer;
}
public long getFileId() {
return fileId;
}
public long getPageIndex() {
return pageIndex;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
OCacheEntry that = (OCacheEntry) o;
if (fileId != that.fileId)
return false;
if (isDirty != that.isDirty)
return false;
if (pageIndex != that.pageIndex)
return false;
if (usagesCount != that.usagesCount)
return false;
if (dataPointer != null ? !dataPointer.equals(that.dataPointer) : that.dataPointer != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (fileId ^ (fileId >>> 32));
result = 31 * result + (int) (pageIndex ^ (pageIndex >>> 32));
result = 31 * result + (dataPointer != null ? dataPointer.hashCode() : 0);
result = 31 * result + (isDirty ? 1 : 0);
result = 31 * result + usagesCount;
return result;
}
@Override
public String toString() {
return "OReadCacheEntry{" + "fileId=" + fileId + ", pageIndex=" + pageIndex + ", dataPointer=" + dataPointer + ", isDirty="
+ isDirty + ", usagesCount=" + usagesCount + '}';
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_index_hashindex_local_cache_OCacheEntry.java |
102 | @Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "BLC_PAGE")
@EntityListeners(value = { AdminAuditableListener.class })
@AdminPresentationOverrides(
{
@AdminPresentationOverride(name="auditable.createdBy.id", value=@AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)),
@AdminPresentationOverride(name="auditable.updatedBy.id", value=@AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)),
@AdminPresentationOverride(name="auditable.createdBy.name", value=@AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)),
@AdminPresentationOverride(name="auditable.updatedBy.name", value=@AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)),
@AdminPresentationOverride(name="auditable.dateCreated", value=@AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)),
@AdminPresentationOverride(name="auditable.dateUpdated", value=@AdminPresentation(readOnly = true, visibility = VisibilityEnum.HIDDEN_ALL)),
@AdminPresentationOverride(name="pageTemplate.templateDescription", value=@AdminPresentation(excluded = true)),
@AdminPresentationOverride(name="pageTemplate.templateName", value=@AdminPresentation(excluded = true)),
@AdminPresentationOverride(name="pageTemplate.locale", value=@AdminPresentation(excluded = true))
}
)
@AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "PageImpl_basePage")
public class PageImpl implements Page, AdminMainEntity {
private static final long serialVersionUID = 1L;
private static final Integer ZERO = new Integer(0);
@Id
@GeneratedValue(generator = "PageId")
@GenericGenerator(
name="PageId",
strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="PageImpl"),
@Parameter(name="entity_name", value="org.broadleafcommerce.cms.page.domain.PageImpl")
}
)
@Column(name = "PAGE_ID")
protected Long id;
@ManyToOne(targetEntity = PageTemplateImpl.class)
@JoinColumn(name = "PAGE_TMPLT_ID")
@AdminPresentation(friendlyName = "PageImpl_Page_Template", order = 2,
group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic, prominent = true,
requiredOverride = RequiredOverride.REQUIRED)
@AdminPresentationToOneLookup(lookupDisplayProperty = "templateName")
protected PageTemplate pageTemplate;
@Column (name = "DESCRIPTION")
@AdminPresentation(friendlyName = "PageImpl_Description", order = 3,
group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic,
prominent = true, gridOrder = 1)
protected String description;
@Column (name = "FULL_URL")
@Index(name="PAGE_FULL_URL_INDEX", columnNames={"FULL_URL"})
@AdminPresentation(friendlyName = "PageImpl_Full_Url", order = 1,
group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic,
prominent = true, gridOrder = 2,
validationConfigurations = { @ValidationConfiguration(validationImplementation = "blUriPropertyValidator") })
protected String fullUrl;
@ManyToMany(targetEntity = PageFieldImpl.class, cascade = CascadeType.ALL)
@JoinTable(name = "BLC_PAGE_FLD_MAP",
joinColumns = @JoinColumn(name = "PAGE_ID", referencedColumnName = "PAGE_ID"),
inverseJoinColumns = @JoinColumn(name = "PAGE_FLD_ID", referencedColumnName = "PAGE_FLD_ID"))
@MapKeyColumn(name = "MAP_KEY")
@Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@BatchSize(size = 20)
protected Map<String,PageField> pageFields = new HashMap<String,PageField>();
@ManyToOne (targetEntity = SandBoxImpl.class)
@JoinColumn(name="SANDBOX_ID")
@AdminPresentation(excluded = true)
protected SandBox sandbox;
@ManyToOne(targetEntity = SandBoxImpl.class)
@JoinColumn(name = "ORIG_SANDBOX_ID")
@AdminPresentation(excluded = true)
protected SandBox originalSandBox;
@Column (name = "DELETED_FLAG")
@Index(name="PAGE_DLTD_FLG_INDX", columnNames={"DELETED_FLAG"})
@AdminPresentation(friendlyName = "PageImpl_Deleted", order = 2,
group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic,
visibility = VisibilityEnum.HIDDEN_ALL)
protected Boolean deletedFlag = false;
@Column (name = "ARCHIVED_FLAG")
@AdminPresentation(friendlyName = "PageImpl_Archived", order = 5,
group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic,
visibility = VisibilityEnum.HIDDEN_ALL)
@Index(name="PAGE_ARCHVD_FLG_INDX", columnNames={"ARCHIVED_FLAG"})
protected Boolean archivedFlag = false;
@Column (name = "LOCKED_FLAG")
@AdminPresentation(friendlyName = "PageImpl_Is_Locked",
group = Presentation.Group.Name.Page, groupOrder = Presentation.Group.Order.Page,
visibility = VisibilityEnum.HIDDEN_ALL)
@Index(name="PAGE_LCKD_FLG_INDX", columnNames={"LOCKED_FLAG"})
protected Boolean lockedFlag = false;
@Column (name = "ORIG_PAGE_ID")
@AdminPresentation(friendlyName = "PageImpl_Original_Page_ID", order = 6,
group = Presentation.Group.Name.Page, groupOrder = Presentation.Group.Order.Page,
visibility = VisibilityEnum.HIDDEN_ALL)
@Index(name="ORIG_PAGE_ID_INDX", columnNames={"ORIG_PAGE_ID"})
protected Long originalPageId;
@Column(name = "PRIORITY")
@AdminPresentation(friendlyName = "PageImpl_Priority", order = 3,
group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic)
protected Integer priority;
@Column(name = "OFFLINE_FLAG")
@AdminPresentation(friendlyName = "PageImpl_Offline", order = 4,
group = Presentation.Group.Name.Basic, groupOrder = Presentation.Group.Order.Basic)
protected Boolean offlineFlag = false;
@ManyToMany(targetEntity = PageRuleImpl.class, cascade = {CascadeType.ALL})
@JoinTable(name = "BLC_PAGE_RULE_MAP",
inverseJoinColumns = @JoinColumn(name = "PAGE_RULE_ID", referencedColumnName = "PAGE_RULE_ID"))
@Cascade(value = { org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
@MapKeyColumn(name = "MAP_KEY", nullable = false)
@AdminPresentationMapFields(
mapDisplayFields = {
@AdminPresentationMapField(
fieldName = RuleIdentifier.CUSTOMER_FIELD_KEY,
fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.RULE_SIMPLE, order = 1,
tab = Presentation.Tab.Name.Rules, tabOrder = Presentation.Tab.Order.Rules,
group = Presentation.Group.Name.Rules, groupOrder = Presentation.Group.Order.Rules,
ruleIdentifier = RuleIdentifier.CUSTOMER, friendlyName = "Generic_Customer_Rule")
),
@AdminPresentationMapField(
fieldName = RuleIdentifier.TIME_FIELD_KEY,
fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.RULE_SIMPLE, order = 2,
tab = Presentation.Tab.Name.Rules, tabOrder = Presentation.Tab.Order.Rules,
group = Presentation.Group.Name.Rules, groupOrder = Presentation.Group.Order.Rules,
ruleIdentifier = RuleIdentifier.TIME, friendlyName = "Generic_Time_Rule")
),
@AdminPresentationMapField(
fieldName = RuleIdentifier.REQUEST_FIELD_KEY,
fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.RULE_SIMPLE, order = 3,
tab = Presentation.Tab.Name.Rules, tabOrder = Presentation.Tab.Order.Rules,
group = Presentation.Group.Name.Rules, groupOrder = Presentation.Group.Order.Rules,
ruleIdentifier = RuleIdentifier.REQUEST, friendlyName = "Generic_Request_Rule")
),
@AdminPresentationMapField(
fieldName = RuleIdentifier.PRODUCT_FIELD_KEY,
fieldPresentation = @AdminPresentation(fieldType = SupportedFieldType.RULE_SIMPLE, order = 4,
tab = Presentation.Tab.Name.Rules, tabOrder = Presentation.Tab.Order.Rules,
group = Presentation.Group.Name.Rules, groupOrder = Presentation.Group.Order.Rules,
ruleIdentifier = RuleIdentifier.PRODUCT, friendlyName = "Generic_Product_Rule")
)
}
)
Map<String, PageRule> pageMatchRules = new HashMap<String, PageRule>();
@OneToMany(fetch = FetchType.LAZY, targetEntity = PageItemCriteriaImpl.class, cascade={CascadeType.ALL})
@JoinTable(name = "BLC_QUAL_CRIT_PAGE_XREF",
joinColumns = @JoinColumn(name = "PAGE_ID"),
inverseJoinColumns = @JoinColumn(name = "PAGE_ITEM_CRITERIA_ID"))
@Cascade(value={org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
@AdminPresentation(friendlyName = "Generic_Item_Rule", order = 5,
tab = Presentation.Tab.Name.Rules, tabOrder = Presentation.Tab.Order.Rules,
group = Presentation.Group.Name.Rules, groupOrder = Presentation.Group.Order.Rules,
fieldType = SupportedFieldType.RULE_WITH_QUANTITY,
ruleIdentifier = RuleIdentifier.ORDERITEM)
protected Set<PageItemCriteria> qualifyingItemCriteria = new HashSet<PageItemCriteria>();
@Embedded
@AdminPresentation(excluded = true)
protected AdminAuditable auditable = new AdminAuditable();
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public PageTemplate getPageTemplate() {
return pageTemplate;
}
@Override
public void setPageTemplate(PageTemplate pageTemplate) {
this.pageTemplate = pageTemplate;
}
@Override
public Map<String, PageField> getPageFields() {
return pageFields;
}
@Override
public void setPageFields(Map<String, PageField> pageFields) {
this.pageFields = pageFields;
}
@Override
public Boolean getDeletedFlag() {
if (deletedFlag == null) {
return Boolean.FALSE;
} else {
return deletedFlag;
}
}
@Override
public void setDeletedFlag(Boolean deletedFlag) {
this.deletedFlag = deletedFlag;
}
@Override
public Boolean getArchivedFlag() {
if (archivedFlag == null) {
return Boolean.FALSE;
} else {
return archivedFlag;
}
}
@Override
public void setArchivedFlag(Boolean archivedFlag) {
this.archivedFlag = archivedFlag;
}
@Override
public SandBox getSandbox() {
return sandbox;
}
@Override
public void setSandbox(SandBox sandbox) {
this.sandbox = sandbox;
}
@Override
public Long getOriginalPageId() {
return originalPageId;
}
@Override
public void setOriginalPageId(Long originalPageId) {
this.originalPageId = originalPageId;
}
@Override
public String getFullUrl() {
return fullUrl;
}
@Override
public void setFullUrl(String fullUrl) {
this.fullUrl = fullUrl;
}
@Override
public String getDescription() {
return description;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public SandBox getOriginalSandBox() {
return originalSandBox;
}
@Override
public void setOriginalSandBox(SandBox originalSandBox) {
this.originalSandBox = originalSandBox;
}
@Override
public AdminAuditable getAuditable() {
return auditable;
}
@Override
public void setAuditable(AdminAuditable auditable) {
this.auditable = auditable;
}
@Override
public Boolean getLockedFlag() {
if (lockedFlag == null) {
return Boolean.FALSE;
} else {
return lockedFlag;
}
}
@Override
public void setLockedFlag(Boolean lockedFlag) {
this.lockedFlag = lockedFlag;
}
@Override
public Boolean getOfflineFlag() {
if (offlineFlag == null) {
return Boolean.FALSE;
} else {
return offlineFlag;
}
}
@Override
public void setOfflineFlag(Boolean offlineFlag) {
this.offlineFlag = offlineFlag;
}
@Override
public Integer getPriority() {
if (priority == null) {
return ZERO;
}
return priority;
}
@Override
public void setPriority(Integer priority) {
this.priority = priority;
}
@Override
public Map<String, PageRule> getPageMatchRules() {
return pageMatchRules;
}
@Override
public void setPageMatchRules(Map<String, PageRule> pageMatchRules) {
this.pageMatchRules = pageMatchRules;
}
@Override
public Set<PageItemCriteria> getQualifyingItemCriteria() {
return qualifyingItemCriteria;
}
@Override
public void setQualifyingItemCriteria(Set<PageItemCriteria> qualifyingItemCriteria) {
this.qualifyingItemCriteria = qualifyingItemCriteria;
}
@Override
public Page cloneEntity() {
PageImpl newPage = new PageImpl();
newPage.archivedFlag = archivedFlag;
newPage.deletedFlag = deletedFlag;
newPage.pageTemplate = pageTemplate;
newPage.description = description;
newPage.sandbox = sandbox;
newPage.originalPageId = originalPageId;
newPage.offlineFlag = offlineFlag;
newPage.priority = priority;
newPage.originalSandBox = originalSandBox;
newPage.fullUrl = fullUrl;
Map<String, PageRule> ruleMap = newPage.getPageMatchRules();
for (String key : pageMatchRules.keySet()) {
PageRule newField = pageMatchRules.get(key).cloneEntity();
ruleMap.put(key, newField);
}
Set<PageItemCriteria> criteriaList = newPage.getQualifyingItemCriteria();
for (PageItemCriteria pageItemCriteria : qualifyingItemCriteria) {
PageItemCriteria newField = pageItemCriteria.cloneEntity();
criteriaList.add(newField);
}
for (PageField oldPageField: pageFields.values()) {
PageField newPageField = oldPageField.cloneEntity();
newPageField.setPage(newPage);
newPage.getPageFields().put(newPageField.getFieldKey(), newPageField);
}
return newPage;
}
public static class Presentation {
public static class Tab {
public static class Name {
public static final String Rules = "PageImpl_Rules_Tab";
}
public static class Order {
public static final int Rules = 1000;
}
}
public static class Group {
public static class Name {
public static final String Basic = "PageImpl_Basic";
public static final String Page = "PageImpl_Page";
public static final String Rules = "PageImpl_Rules";
}
public static class Order {
public static final int Basic = 1000;
public static final int Page = 2000;
public static final int Rules = 1000;
}
}
}
@Override
public String getMainEntityName() {
return getFullUrl();
}
} | 0true
| admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_domain_PageImpl.java |
10 | public interface TextCommand extends TextCommandConstants, SocketWritable, SocketReadable {
TextCommandType getType();
void init(SocketTextReader socketTextReader, long requestId);
SocketTextReader getSocketTextReader();
SocketTextWriter getSocketTextWriter();
long getRequestId();
boolean shouldReply();
} | 0true
| hazelcast_src_main_java_com_hazelcast_ascii_TextCommand.java |
546 | public static class Col {
String title;
int width;
public Col(String title) {
this.title = title;
this.width = title.length();
}
public Col(String title, int width) {
this.title = title;
this.width = width;
}
} | 0true
| common_src_main_java_org_broadleafcommerce_common_util_TableCreator.java |
2,266 | CollectionUtil.timSort(intfsList, new Comparator<NetworkInterface>() {
@Override
public int compare(NetworkInterface o1, NetworkInterface o2) {
try {
return ((Integer) getIndexMethod.invoke(o1)).intValue() - ((Integer) getIndexMethod.invoke(o2)).intValue();
} catch (Exception e) {
throw new ElasticsearchIllegalStateException("failed to fetch index of network interface");
}
}
}); | 0true
| src_main_java_org_elasticsearch_common_network_NetworkUtils.java |
1,259 | public class ConsolidateFulfillmentFeesActivity extends BaseActivity<PricingContext> {
@SuppressWarnings("unchecked")
protected static final Map EXPRESSION_CACHE = Collections.synchronizedMap(new LRUMap(1000));
@Resource(name = "blFulfillmentGroupService")
protected FulfillmentGroupService fulfillmentGroupService;
@Override
public PricingContext execute(PricingContext context) throws Exception {
Order order = context.getSeedData();
for (FulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) {
//create and associate all the Fulfillment Fees
for (FulfillmentGroupItem item : fulfillmentGroup.getFulfillmentGroupItems()) {
List<SkuFee> fees = null;
if (item.getOrderItem() instanceof BundleOrderItem) {
fees = ((BundleOrderItem)item.getOrderItem()).getSku().getFees();
} else if (item.getOrderItem() instanceof DiscreteOrderItem) {
fees = ((DiscreteOrderItem)item.getOrderItem()).getSku().getFees();
}
if (fees != null) {
for (SkuFee fee : fees) {
if (SkuFeeType.FULFILLMENT.equals(fee.getFeeType())) {
if (shouldApplyFeeToFulfillmentGroup(fee, fulfillmentGroup)) {
FulfillmentGroupFee fulfillmentFee = fulfillmentGroupService.createFulfillmentGroupFee();
fulfillmentFee.setName(fee.getName());
fulfillmentFee.setTaxable(fee.getTaxable());
fulfillmentFee.setAmount(fee.getAmount());
fulfillmentFee.setFulfillmentGroup(fulfillmentGroup);
fulfillmentGroup.addFulfillmentGroupFee(fulfillmentFee);
}
}
}
}
}
if (fulfillmentGroup.getFulfillmentGroupFees().size() > 0) {
fulfillmentGroup = fulfillmentGroupService.save(fulfillmentGroup);
}
}
context.setSeedData(order);
return context;
}
/**
* If the SkuFee expression is null or empty, this method will always return true
*
* @param fee
* @param fulfillmentGroup
* @return
*/
protected boolean shouldApplyFeeToFulfillmentGroup(SkuFee fee, FulfillmentGroup fulfillmentGroup) {
boolean appliesToFulfillmentGroup = true;
String feeExpression = fee.getExpression();
if (!StringUtils.isEmpty(feeExpression)) {
Serializable exp = (Serializable) EXPRESSION_CACHE.get(feeExpression);
if (exp == null) {
ParserContext mvelContext = new ParserContext();
mvelContext.addImport("MVEL", MVEL.class);
mvelContext.addImport("MvelHelper", MvelHelper.class);
exp = MVEL.compileExpression(feeExpression, mvelContext);
EXPRESSION_CACHE.put(feeExpression, exp);
}
HashMap<String, Object> vars = new HashMap<String, Object>();
vars.put("fulfillmentGroup", fulfillmentGroup);
return (Boolean)MVEL.executeExpression(feeExpression, vars);
}
return appliesToFulfillmentGroup;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_pricing_service_workflow_ConsolidateFulfillmentFeesActivity.java |
1,240 | public interface InternalClusterAdminClient extends ClusterAdminClient, InternalGenericClient {
} | 0true
| src_main_java_org_elasticsearch_client_internal_InternalClusterAdminClient.java |
1,510 | private class ManagedContextImpl implements ManagedContext, HazelcastInstanceAware {
private HazelcastInstance hz;
@Override
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
this.hz= hazelcastInstance;
}
@Override
public Object initialize(Object obj) {
return null;
}
} | 0true
| hazelcast_src_test_java_com_hazelcast_instance_ManagedContextInstanceAwareTest.java |
1,002 | public abstract class SingleCustomOperationRequest<T extends SingleCustomOperationRequest> extends ActionRequest<T> {
private boolean threadedOperation = true;
private boolean preferLocal = true;
protected SingleCustomOperationRequest() {
}
@Override
public ActionRequestValidationException validate() {
return null;
}
/**
* Controls if the operation will be executed on a separate thread when executed locally.
*/
public boolean operationThreaded() {
return threadedOperation;
}
/**
* Controls if the operation will be executed on a separate thread when executed locally.
*/
@SuppressWarnings("unchecked")
public final T operationThreaded(boolean threadedOperation) {
this.threadedOperation = threadedOperation;
return (T) this;
}
/**
* if this operation hits a node with a local relevant shard, should it be preferred
* to be executed on, or just do plain round robin. Defaults to <tt>true</tt>
*/
@SuppressWarnings("unchecked")
public final T preferLocal(boolean preferLocal) {
this.preferLocal = preferLocal;
return (T) this;
}
/**
* if this operation hits a node with a local relevant shard, should it be preferred
* to be executed on, or just do plain round robin. Defaults to <tt>true</tt>
*/
public boolean preferLocalShard() {
return this.preferLocal;
}
public void beforeLocalFork() {
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
preferLocal = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(preferLocal);
}
} | 0true
| src_main_java_org_elasticsearch_action_support_single_custom_SingleCustomOperationRequest.java |
1,080 | public interface OSQLFilterItem {
public Object getValue(OIdentifiable iRecord, OCommandContext iContetx);
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_sql_filter_OSQLFilterItem.java |
1,967 | abstract class AbstractReachabilityHandler implements ReachabilityHandler<Record> {
private static final boolean DEBUG = false;
protected ReachabilityHandler<Record> successorHandler;
protected AbstractReachabilityHandler() {
}
protected abstract Record handle(Record record, long criteria, long time);
@Override
public Record process(Record record, long criteria, long time) {
final Record handledRecord = handle(record, criteria, time);
if (handledRecord == null || successorHandler == null) {
return handledRecord;
}
return successorHandler.process(handledRecord, criteria, time);
}
@Override
public void setSuccessorHandler(ReachabilityHandler successorHandler) {
this.successorHandler = successorHandler;
}
@Override
public ReachabilityHandler<Record> getSuccessorHandler() {
return successorHandler;
}
@Override
public void resetHandler() {
successorHandler = null;
}
protected static final PrintStream log(String msg, Object... args) {
if (!DEBUG) {
return null;
}
return System.out.printf(msg + "\n", args);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_map_eviction_AbstractReachabilityHandler.java |
1,362 | public class OClusterMemoryHashing extends OClusterMemory implements OCluster {
public static final String TYPE = "MEMORY";
private NavigableMap<OClusterPosition, OPhysicalPosition> content = new TreeMap<OClusterPosition, OPhysicalPosition>();
private long tombstonesCount = 0;
@Override
public boolean addPhysicalPosition(OPhysicalPosition physicalPosition) {
acquireExclusiveLock();
try {
if (content.containsKey(physicalPosition.clusterPosition))
return false;
content.put(physicalPosition.clusterPosition, physicalPosition);
return true;
} finally {
releaseExclusiveLock();
}
}
@Override
public OPhysicalPosition getPhysicalPosition(OPhysicalPosition physicalPosition) {
acquireSharedLock();
try {
if (physicalPosition.clusterPosition.isNew())
return null;
return content.get(physicalPosition.clusterPosition);
} finally {
releaseSharedLock();
}
}
@Override
public void updateDataSegmentPosition(OClusterPosition clusterPosition, int dataSegmentId, long dataPosition) {
acquireExclusiveLock();
try {
final OPhysicalPosition physicalPosition = content.get(clusterPosition);
physicalPosition.dataSegmentId = dataSegmentId;
physicalPosition.dataSegmentPos = dataPosition;
} finally {
releaseExclusiveLock();
}
}
@Override
public void removePhysicalPosition(OClusterPosition clusterPosition) {
acquireExclusiveLock();
try {
final OPhysicalPosition physicalPosition = content.remove(clusterPosition);
if (physicalPosition != null && physicalPosition.recordVersion.isTombstone())
tombstonesCount--;
} finally {
releaseExclusiveLock();
}
}
@Override
public void updateRecordType(OClusterPosition clusterPosition, byte recordType) {
acquireExclusiveLock();
try {
content.get(clusterPosition).recordType = recordType;
} finally {
releaseExclusiveLock();
}
}
@Override
public void updateVersion(OClusterPosition clusterPosition, ORecordVersion version) {
acquireExclusiveLock();
try {
content.get(clusterPosition).recordVersion = version;
} finally {
releaseExclusiveLock();
}
}
@Override
public void convertToTombstone(OClusterPosition clusterPosition) throws IOException {
acquireExclusiveLock();
try {
content.get(clusterPosition).recordVersion.convertToTombstone();
tombstonesCount++;
} finally {
releaseExclusiveLock();
}
}
@Override
public long getTombstonesCount() {
return tombstonesCount;
}
@Override
public boolean hasTombstonesSupport() {
return true;
}
@Override
public OModificationLock getExternalModificationLock() {
throw new UnsupportedOperationException("getExternalModificationLock");
}
@Override
public OPhysicalPosition createRecord(byte[] content, ORecordVersion recordVersion, byte recordType) throws IOException {
throw new UnsupportedOperationException("createRecord");
}
@Override
public boolean deleteRecord(OClusterPosition clusterPosition) throws IOException {
throw new UnsupportedOperationException("deleteRecord");
}
@Override
public void updateRecord(OClusterPosition clusterPosition, byte[] content, ORecordVersion recordVersion, byte recordType)
throws IOException {
throw new UnsupportedOperationException("updateRecord");
}
@Override
public ORawBuffer readRecord(OClusterPosition clusterPosition) throws IOException {
throw new UnsupportedOperationException("readRecord");
}
@Override
public long getEntries() {
acquireSharedLock();
try {
return content.size();
} finally {
releaseSharedLock();
}
}
@Override
public OClusterPosition getFirstPosition() {
acquireSharedLock();
try {
if (content.isEmpty())
return OClusterPosition.INVALID_POSITION;
final OClusterPosition clusterPosition = content.firstKey();
if (clusterPosition == null)
return OClusterPosition.INVALID_POSITION;
return clusterPosition;
} finally {
releaseSharedLock();
}
}
@Override
public OClusterPosition getLastPosition() {
acquireSharedLock();
try {
if (content.isEmpty())
return OClusterPosition.INVALID_POSITION;
final OClusterPosition clusterPosition = content.lastKey();
if (clusterPosition == null)
return OClusterPosition.INVALID_POSITION;
return clusterPosition;
} finally {
releaseSharedLock();
}
}
@Override
public long getRecordsSize() {
// TODO implement in future
return 0; // TODO realization missed!
}
@Override
public boolean isHashBased() {
return true;
}
@Override
public OClusterEntryIterator absoluteIterator() {
return new OClusterEntryIterator(this);
}
@Override
protected void clear() {
content.clear();
}
@Override
public OPhysicalPosition[] higherPositions(OPhysicalPosition position) {
acquireSharedLock();
try {
Map.Entry<OClusterPosition, OPhysicalPosition> entry = content.higherEntry(position.clusterPosition);
if (entry != null) {
return new OPhysicalPosition[] { entry.getValue() };
} else {
return new OPhysicalPosition[0];
}
} finally {
releaseSharedLock();
}
}
@Override
public OPhysicalPosition[] ceilingPositions(OPhysicalPosition position) throws IOException {
acquireSharedLock();
try {
Map.Entry<OClusterPosition, OPhysicalPosition> entry = content.ceilingEntry(position.clusterPosition);
if (entry != null) {
return new OPhysicalPosition[] { entry.getValue() };
} else {
return new OPhysicalPosition[0];
}
} finally {
releaseSharedLock();
}
}
@Override
public OPhysicalPosition[] lowerPositions(OPhysicalPosition position) {
acquireSharedLock();
try {
Map.Entry<OClusterPosition, OPhysicalPosition> entry = content.lowerEntry(position.clusterPosition);
if (entry != null) {
return new OPhysicalPosition[] { entry.getValue() };
} else {
return new OPhysicalPosition[0];
}
} finally {
releaseSharedLock();
}
}
@Override
public OPhysicalPosition[] floorPositions(OPhysicalPosition position) throws IOException {
acquireSharedLock();
try {
Map.Entry<OClusterPosition, OPhysicalPosition> entry = content.floorEntry(position.clusterPosition);
if (entry != null) {
return new OPhysicalPosition[] { entry.getValue() };
} else {
return new OPhysicalPosition[0];
}
} finally {
releaseSharedLock();
}
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_impl_memory_OClusterMemoryHashing.java |
2,567 | public class LocalDiscoveryModule extends AbstractModule {
@Override
protected void configure() {
bind(Discovery.class).to(LocalDiscovery.class).asEagerSingleton();
}
} | 0true
| src_main_java_org_elasticsearch_discovery_local_LocalDiscoveryModule.java |
4,031 | public class MatchQuery {
public static enum Type {
BOOLEAN,
PHRASE,
PHRASE_PREFIX
}
public static enum ZeroTermsQuery {
NONE,
ALL
}
protected final QueryParseContext parseContext;
protected String analyzer;
protected BooleanClause.Occur occur = BooleanClause.Occur.SHOULD;
protected boolean enablePositionIncrements = true;
protected int phraseSlop = 0;
protected Fuzziness fuzziness = null;
protected int fuzzyPrefixLength = FuzzyQuery.defaultPrefixLength;
protected int maxExpansions = FuzzyQuery.defaultMaxExpansions;
//LUCENE 4 UPGRADE we need a default value for this!
protected boolean transpositions = false;
protected MultiTermQuery.RewriteMethod rewriteMethod;
protected MultiTermQuery.RewriteMethod fuzzyRewriteMethod;
protected boolean lenient;
protected ZeroTermsQuery zeroTermsQuery = ZeroTermsQuery.NONE;
protected Float commonTermsCutoff = null;
public MatchQuery(QueryParseContext parseContext) {
this.parseContext = parseContext;
}
public void setAnalyzer(String analyzer) {
this.analyzer = analyzer;
}
public void setOccur(BooleanClause.Occur occur) {
this.occur = occur;
}
public void setCommonTermsCutoff(float cutoff) {
this.commonTermsCutoff = Float.valueOf(cutoff);
}
public void setEnablePositionIncrements(boolean enablePositionIncrements) {
this.enablePositionIncrements = enablePositionIncrements;
}
public void setPhraseSlop(int phraseSlop) {
this.phraseSlop = phraseSlop;
}
public void setFuzziness(Fuzziness fuzziness) {
this.fuzziness = fuzziness;
}
public void setFuzzyPrefixLength(int fuzzyPrefixLength) {
this.fuzzyPrefixLength = fuzzyPrefixLength;
}
public void setMaxExpansions(int maxExpansions) {
this.maxExpansions = maxExpansions;
}
public void setTranspositions(boolean transpositions) {
this.transpositions = transpositions;
}
public void setRewriteMethod(MultiTermQuery.RewriteMethod rewriteMethod) {
this.rewriteMethod = rewriteMethod;
}
public void setFuzzyRewriteMethod(MultiTermQuery.RewriteMethod fuzzyRewriteMethod) {
this.fuzzyRewriteMethod = fuzzyRewriteMethod;
}
public void setLenient(boolean lenient) {
this.lenient = lenient;
}
public void setZeroTermsQuery(ZeroTermsQuery zeroTermsQuery) {
this.zeroTermsQuery = zeroTermsQuery;
}
public Query parse(Type type, String fieldName, Object value) throws IOException {
FieldMapper mapper = null;
final String field;
MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName);
if (smartNameFieldMappers != null && smartNameFieldMappers.hasMapper()) {
mapper = smartNameFieldMappers.mapper();
field = mapper.names().indexName();
} else {
field = fieldName;
}
if (mapper != null && mapper.useTermQueryWithQueryString()) {
if (smartNameFieldMappers.explicitTypeInNameWithDocMapper()) {
String[] previousTypes = QueryParseContext.setTypesWithPrevious(new String[]{smartNameFieldMappers.docMapper().type()});
try {
return wrapSmartNameQuery(mapper.termQuery(value, parseContext), smartNameFieldMappers, parseContext);
} catch (RuntimeException e) {
if (lenient) {
return null;
}
throw e;
} finally {
QueryParseContext.setTypes(previousTypes);
}
} else {
try {
return wrapSmartNameQuery(mapper.termQuery(value, parseContext), smartNameFieldMappers, parseContext);
} catch (RuntimeException e) {
if (lenient) {
return null;
}
throw e;
}
}
}
Analyzer analyzer = null;
if (this.analyzer == null) {
if (mapper != null) {
analyzer = mapper.searchAnalyzer();
}
if (analyzer == null && smartNameFieldMappers != null) {
analyzer = smartNameFieldMappers.searchAnalyzer();
}
if (analyzer == null) {
analyzer = parseContext.mapperService().searchAnalyzer();
}
} else {
analyzer = parseContext.mapperService().analysisService().analyzer(this.analyzer);
if (analyzer == null) {
throw new ElasticsearchIllegalArgumentException("No analyzer found for [" + this.analyzer + "]");
}
}
// Logic similar to QueryParser#getFieldQuery
final TokenStream source = analyzer.tokenStream(field, value.toString());
source.reset();
int numTokens = 0;
int positionCount = 0;
boolean severalTokensAtSamePosition = false;
final CachingTokenFilter buffer = new CachingTokenFilter(source);
buffer.reset();
final CharTermAttribute termAtt = buffer.addAttribute(CharTermAttribute.class);
final PositionIncrementAttribute posIncrAtt = buffer.addAttribute(PositionIncrementAttribute.class);
boolean hasMoreTokens = buffer.incrementToken();
while (hasMoreTokens) {
numTokens++;
int positionIncrement = posIncrAtt.getPositionIncrement();
if (positionIncrement != 0) {
positionCount += positionIncrement;
} else {
severalTokensAtSamePosition = true;
}
hasMoreTokens = buffer.incrementToken();
}
// rewind the buffer stream
buffer.reset();
source.close();
if (numTokens == 0) {
return zeroTermsQuery();
} else if (type == Type.BOOLEAN) {
if (numTokens == 1) {
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
final Query q = newTermQuery(mapper, new Term(field, termToByteRef(termAtt)));
return wrapSmartNameQuery(q, smartNameFieldMappers, parseContext);
}
if (commonTermsCutoff != null) {
ExtendedCommonTermsQuery q = new ExtendedCommonTermsQuery(occur, occur, commonTermsCutoff, positionCount == 1);
for (int i = 0; i < numTokens; i++) {
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
q.add(new Term(field, termToByteRef(termAtt)));
}
return wrapSmartNameQuery(q, smartNameFieldMappers, parseContext);
} if (severalTokensAtSamePosition && occur == Occur.MUST) {
BooleanQuery q = new BooleanQuery(positionCount == 1);
Query currentQuery = null;
for (int i = 0; i < numTokens; i++) {
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
if (posIncrAtt != null && posIncrAtt.getPositionIncrement() == 0) {
if (!(currentQuery instanceof BooleanQuery)) {
Query t = currentQuery;
currentQuery = new BooleanQuery(true);
((BooleanQuery)currentQuery).add(t, BooleanClause.Occur.SHOULD);
}
((BooleanQuery)currentQuery).add(newTermQuery(mapper, new Term(field, termToByteRef(termAtt))), BooleanClause.Occur.SHOULD);
} else {
if (currentQuery != null) {
q.add(currentQuery, occur);
}
currentQuery = newTermQuery(mapper, new Term(field, termToByteRef(termAtt)));
}
}
q.add(currentQuery, occur);
return wrapSmartNameQuery(q, smartNameFieldMappers, parseContext);
} else {
BooleanQuery q = new BooleanQuery(positionCount == 1);
for (int i = 0; i < numTokens; i++) {
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
final Query currentQuery = newTermQuery(mapper, new Term(field, termToByteRef(termAtt)));
q.add(currentQuery, occur);
}
return wrapSmartNameQuery(q, smartNameFieldMappers, parseContext);
}
} else if (type == Type.PHRASE) {
if (severalTokensAtSamePosition) {
final MultiPhraseQuery mpq = new MultiPhraseQuery();
mpq.setSlop(phraseSlop);
final List<Term> multiTerms = new ArrayList<Term>();
int position = -1;
for (int i = 0; i < numTokens; i++) {
int positionIncrement = 1;
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
positionIncrement = posIncrAtt.getPositionIncrement();
if (positionIncrement > 0 && multiTerms.size() > 0) {
if (enablePositionIncrements) {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]), position);
} else {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]));
}
multiTerms.clear();
}
position += positionIncrement;
//LUCENE 4 UPGRADE instead of string term we can convert directly from utf-16 to utf-8
multiTerms.add(new Term(field, termToByteRef(termAtt)));
}
if (enablePositionIncrements) {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]), position);
} else {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]));
}
return wrapSmartNameQuery(mpq, smartNameFieldMappers, parseContext);
} else {
PhraseQuery pq = new PhraseQuery();
pq.setSlop(phraseSlop);
int position = -1;
for (int i = 0; i < numTokens; i++) {
int positionIncrement = 1;
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
positionIncrement = posIncrAtt.getPositionIncrement();
if (enablePositionIncrements) {
position += positionIncrement;
//LUCENE 4 UPGRADE instead of string term we can convert directly from utf-16 to utf-8
pq.add(new Term(field, termToByteRef(termAtt)), position);
} else {
pq.add(new Term(field, termToByteRef(termAtt)));
}
}
return wrapSmartNameQuery(pq, smartNameFieldMappers, parseContext);
}
} else if (type == Type.PHRASE_PREFIX) {
MultiPhrasePrefixQuery mpq = new MultiPhrasePrefixQuery();
mpq.setSlop(phraseSlop);
mpq.setMaxExpansions(maxExpansions);
List<Term> multiTerms = new ArrayList<Term>();
int position = -1;
for (int i = 0; i < numTokens; i++) {
int positionIncrement = 1;
boolean hasNext = buffer.incrementToken();
assert hasNext == true;
positionIncrement = posIncrAtt.getPositionIncrement();
if (positionIncrement > 0 && multiTerms.size() > 0) {
if (enablePositionIncrements) {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]), position);
} else {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]));
}
multiTerms.clear();
}
position += positionIncrement;
multiTerms.add(new Term(field, termToByteRef(termAtt)));
}
if (enablePositionIncrements) {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]), position);
} else {
mpq.add(multiTerms.toArray(new Term[multiTerms.size()]));
}
return wrapSmartNameQuery(mpq, smartNameFieldMappers, parseContext);
}
throw new ElasticsearchIllegalStateException("No type found for [" + type + "]");
}
private Query newTermQuery(@Nullable FieldMapper mapper, Term term) {
if (fuzziness != null) {
if (mapper != null) {
Query query = mapper.fuzzyQuery(term.text(), fuzziness, fuzzyPrefixLength, maxExpansions, transpositions);
if (query instanceof FuzzyQuery) {
QueryParsers.setRewriteMethod((FuzzyQuery) query, fuzzyRewriteMethod);
}
}
int edits = fuzziness.asDistance(term.text());
FuzzyQuery query = new FuzzyQuery(term, edits, fuzzyPrefixLength, maxExpansions, transpositions);
QueryParsers.setRewriteMethod(query, rewriteMethod);
return query;
}
if (mapper != null) {
Query termQuery = mapper.queryStringTermQuery(term);
if (termQuery != null) {
return termQuery;
}
}
return new TermQuery(term);
}
private static BytesRef termToByteRef(CharTermAttribute attr) {
final BytesRef ref = new BytesRef();
UnicodeUtil.UTF16toUTF8(attr.buffer(), 0, attr.length(), ref);
return ref;
}
protected Query zeroTermsQuery() {
return zeroTermsQuery == ZeroTermsQuery.NONE ? Queries.newMatchNoDocsQuery() : Queries.newMatchAllQuery();
}
} | 1no label
| src_main_java_org_elasticsearch_index_search_MatchQuery.java |
2,862 | public class FrenchStemTokenFilterFactory extends AbstractTokenFilterFactory {
private final CharArraySet exclusions;
@Inject
public FrenchStemTokenFilterFactory(Index index, @IndexSettings Settings indexSettings, @Assisted String name, @Assisted Settings settings) {
super(index, indexSettings, name, settings);
this.exclusions = Analysis.parseStemExclusion(settings, CharArraySet.EMPTY_SET, version);
}
@Override
public TokenStream create(TokenStream tokenStream) {
return new FrenchStemFilter(new SetKeywordMarkerFilter(tokenStream, exclusions));
}
} | 0true
| src_main_java_org_elasticsearch_index_analysis_FrenchStemTokenFilterFactory.java |
1,515 | public interface NodeInitializer {
void beforeInitialize(Node node);
void printNodeInfo(Node node);
void afterInitialize(Node node);
SecurityContext getSecurityContext();
Storage<DataRef> getOffHeapStorage();
WanReplicationService geWanReplicationService();
void destroy();
} | 0true
| hazelcast_src_main_java_com_hazelcast_instance_NodeInitializer.java |
1,353 | tokenStream.getTokens()) {
@Override
protected boolean reuseExistingDescriptorModels() {
return true;
}
}; | 1no label
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_core_model_ProjectSourceFile.java |
19 | abstract static class Completion extends AtomicInteger implements Runnable {
} | 0true
| src_main_java_jsr166e_CompletableFuture.java |
329 | EntryListener listener = new EntryAdapter() {
@Override
public void entryAdded(EntryEvent event) {
atomicInteger.incrementAndGet();
countDownLatch.countDown();
}
}; | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_map_ClientMapTest.java |
400 | index.restore(new HashMap<String, Map<String, List<IndexEntry>>>() {{
put(store1, new HashMap<String, List<IndexEntry>>() {{
put("restore-doc1", Collections.<IndexEntry>emptyList());
put("restore-doc2", new ArrayList<IndexEntry>() {{
add(new IndexEntry(NAME, "not-second"));
add(new IndexEntry(WEIGHT, 2.1d));
add(new IndexEntry(TIME, 0L));
}});
put("restore-doc3", new ArrayList<IndexEntry>() {{
add(new IndexEntry(NAME, "third"));
add(new IndexEntry(WEIGHT, 11.5d));
add(new IndexEntry(TIME, 3L));
}});
}});
}}, indexRetriever, tx); | 0true
| titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_indexing_IndexProviderTest.java |
2,128 | public class Slf4jESLogger extends AbstractESLogger {
private final Logger logger;
public Slf4jESLogger(String prefix, Logger logger) {
super(prefix);
this.logger = logger;
}
@Override
public void setLevel(String level) {
// can't set it in slf4j...
}
@Override
public String getLevel() {
// can't get it in slf4j...
return null;
}
@Override
public String getName() {
return logger.getName();
}
@Override
public boolean isTraceEnabled() {
return logger.isTraceEnabled();
}
@Override
public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
@Override
public boolean isInfoEnabled() {
return logger.isInfoEnabled();
}
@Override
public boolean isWarnEnabled() {
return logger.isWarnEnabled();
}
@Override
public boolean isErrorEnabled() {
return logger.isErrorEnabled();
}
@Override
protected void internalTrace(String msg) {
logger.trace(msg);
}
@Override
protected void internalTrace(String msg, Throwable cause) {
logger.trace(msg, cause);
}
@Override
protected void internalDebug(String msg) {
logger.debug(msg);
}
@Override
protected void internalDebug(String msg, Throwable cause) {
logger.debug(msg, cause);
}
@Override
protected void internalInfo(String msg) {
logger.info(msg);
}
@Override
protected void internalInfo(String msg, Throwable cause) {
logger.info(msg, cause);
}
@Override
protected void internalWarn(String msg) {
logger.warn(msg);
}
@Override
protected void internalWarn(String msg, Throwable cause) {
logger.warn(msg, cause);
}
@Override
protected void internalError(String msg) {
logger.error(msg);
}
@Override
protected void internalError(String msg, Throwable cause) {
logger.error(msg, cause);
}
} | 0true
| src_main_java_org_elasticsearch_common_logging_slf4j_Slf4jESLogger.java |
1,047 | @SuppressWarnings("unchecked")
public class OCommandExecutorSQLRebuildIndex extends OCommandExecutorSQLAbstract implements OCommandDistributedReplicateRequest {
public static final String KEYWORD_REBUILD = "REBUILD";
public static final String KEYWORD_INDEX = "INDEX";
private String name;
public OCommandExecutorSQLRebuildIndex parse(final OCommandRequest iRequest) {
init((OCommandRequestText) iRequest);
final StringBuilder word = new StringBuilder();
int oldPos = 0;
int pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
if (pos == -1 || !word.toString().equals(KEYWORD_REBUILD))
throw new OCommandSQLParsingException("Keyword " + KEYWORD_REBUILD + " not found. Use " + getSyntax(), parserText, oldPos);
oldPos = pos;
pos = nextWord(parserText, parserTextUpperCase, pos, word, true);
if (pos == -1 || !word.toString().equals(KEYWORD_INDEX))
throw new OCommandSQLParsingException("Keyword " + KEYWORD_INDEX + " not found. Use " + getSyntax(), parserText, oldPos);
oldPos = pos;
pos = nextWord(parserText, parserTextUpperCase, oldPos, word, false);
if (pos == -1)
throw new OCommandSQLParsingException("Expected index name", parserText, oldPos);
name = word.toString();
return this;
}
/**
* Execute the REMOVE INDEX.
*/
public Object execute(final Map<Object, Object> iArgs) {
if (name == null)
throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
final ODatabaseRecord database = getDatabase();
if (name.equals("*")) {
long totalIndexed = 0;
for (OIndex<?> idx : database.getMetadata().getIndexManager().getIndexes()) {
if (idx.isAutomatic())
totalIndexed += idx.rebuild();
}
return totalIndexed;
} else {
final OIndex<?> idx = database.getMetadata().getIndexManager().getIndex(name);
if (idx == null)
throw new OCommandExecutionException("Index '" + name + "' not found");
if (!idx.isAutomatic())
throw new OCommandExecutionException("Cannot rebuild index '" + name
+ "' because it's manual and there aren't indications of what to index");
return idx.rebuild();
}
}
@Override
public String getSyntax() {
return "REBUILD INDEX <index-name>";
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_sql_OCommandExecutorSQLRebuildIndex.java |
634 | public class IndicesStatusRequest extends BroadcastOperationRequest<IndicesStatusRequest> {
private boolean recovery = false;
private boolean snapshot = false;
public IndicesStatusRequest() {
this(Strings.EMPTY_ARRAY);
}
public IndicesStatusRequest(String... indices) {
super(indices);
}
/**
* Should the status include recovery information. Defaults to <tt>false</tt>.
*/
public IndicesStatusRequest recovery(boolean recovery) {
this.recovery = recovery;
return this;
}
public boolean recovery() {
return this.recovery;
}
/**
* Should the status include recovery information. Defaults to <tt>false</tt>.
*/
public IndicesStatusRequest snapshot(boolean snapshot) {
this.snapshot = snapshot;
return this;
}
public boolean snapshot() {
return this.snapshot;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(recovery);
out.writeBoolean(snapshot);
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
recovery = in.readBoolean();
snapshot = in.readBoolean();
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_status_IndicesStatusRequest.java |
661 | class ShardValidateQueryRequest extends BroadcastShardOperationRequest {
private BytesReference source;
private String[] types = Strings.EMPTY_ARRAY;
private boolean explain;
private long nowInMillis;
@Nullable
private String[] filteringAliases;
ShardValidateQueryRequest() {
}
public ShardValidateQueryRequest(String index, int shardId, @Nullable String[] filteringAliases, ValidateQueryRequest request) {
super(index, shardId, request);
this.source = request.source();
this.types = request.types();
this.explain = request.explain();
this.filteringAliases = filteringAliases;
this.nowInMillis = request.nowInMillis;
}
public BytesReference source() {
return source;
}
public String[] types() {
return this.types;
}
public boolean explain() {
return this.explain;
}
public String[] filteringAliases() {
return filteringAliases;
}
public long nowInMillis() {
return this.nowInMillis;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
source = in.readBytesReference();
int typesSize = in.readVInt();
if (typesSize > 0) {
types = new String[typesSize];
for (int i = 0; i < typesSize; i++) {
types[i] = in.readString();
}
}
int aliasesSize = in.readVInt();
if (aliasesSize > 0) {
filteringAliases = new String[aliasesSize];
for (int i = 0; i < aliasesSize; i++) {
filteringAliases[i] = in.readString();
}
}
explain = in.readBoolean();
nowInMillis = in.readVLong();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBytesReference(source);
out.writeVInt(types.length);
for (String type : types) {
out.writeString(type);
}
if (filteringAliases != null) {
out.writeVInt(filteringAliases.length);
for (String alias : filteringAliases) {
out.writeString(alias);
}
} else {
out.writeVInt(0);
}
out.writeBoolean(explain);
out.writeVLong(nowInMillis);
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_indices_validate_query_ShardValidateQueryRequest.java |
328 | public class PluginInfo implements Streamable, Serializable, ToXContent {
public static final String DESCRIPTION_NOT_AVAILABLE = "No description found.";
public static final String VERSION_NOT_AVAILABLE = "NA";
static final class Fields {
static final XContentBuilderString NAME = new XContentBuilderString("name");
static final XContentBuilderString DESCRIPTION = new XContentBuilderString("description");
static final XContentBuilderString URL = new XContentBuilderString("url");
static final XContentBuilderString JVM = new XContentBuilderString("jvm");
static final XContentBuilderString SITE = new XContentBuilderString("site");
static final XContentBuilderString VERSION = new XContentBuilderString("version");
}
private String name;
private String description;
private boolean site;
private boolean jvm;
private String version;
public PluginInfo() {
}
/**
* Information about plugins
*
* @param name Its name
* @param description Its description
* @param site true if it's a site plugin
* @param jvm true if it's a jvm plugin
* @param version Version number is applicable (NA otherwise)
*/
public PluginInfo(String name, String description, boolean site, boolean jvm, String version) {
this.name = name;
this.description = description;
this.site = site;
this.jvm = jvm;
if (Strings.hasText(version)) {
this.version = version;
} else {
this.version = VERSION_NOT_AVAILABLE;
}
}
/**
* @return Plugin's name
*/
public String getName() {
return name;
}
/**
* @return Plugin's description if any
*/
public String getDescription() {
return description;
}
/**
* @return true if it's a site plugin
*/
public boolean isSite() {
return site;
}
/**
* @return true if it's a plugin running in the jvm
*/
public boolean isJvm() {
return jvm;
}
/**
* We compute the URL for sites: "/_plugin/" + name + "/"
*
* @return relative URL for site plugin
*/
public String getUrl() {
if (site) {
return ("/_plugin/" + name + "/");
} else {
return null;
}
}
/**
* @return Version number for the plugin
*/
public String getVersion() {
return version;
}
public static PluginInfo readPluginInfo(StreamInput in) throws IOException {
PluginInfo info = new PluginInfo();
info.readFrom(in);
return info;
}
@Override
public void readFrom(StreamInput in) throws IOException {
this.name = in.readString();
this.description = in.readString();
this.site = in.readBoolean();
this.jvm = in.readBoolean();
if (in.getVersion().onOrAfter(Version.V_1_0_0_RC2)) {
this.version = in.readString();
} else {
this.version = VERSION_NOT_AVAILABLE;
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(name);
out.writeString(description);
out.writeBoolean(site);
out.writeBoolean(jvm);
if (out.getVersion().onOrAfter(Version.V_1_0_0_RC2)) {
out.writeString(version);
}
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(Fields.NAME, name);
builder.field(Fields.VERSION, version);
builder.field(Fields.DESCRIPTION, description);
if (site) {
builder.field(Fields.URL, getUrl());
}
builder.field(Fields.JVM, jvm);
builder.field(Fields.SITE, site);
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PluginInfo that = (PluginInfo) o;
if (!name.equals(that.name)) return false;
if (version != null ? !version.equals(that.version) : that.version != null) return false;
return true;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("PluginInfo{");
sb.append("name='").append(name).append('\'');
sb.append(", description='").append(description).append('\'');
sb.append(", site=").append(site);
sb.append(", jvm=").append(jvm);
sb.append(", version='").append(version).append('\'');
sb.append('}');
return sb.toString();
}
} | 0true
| src_main_java_org_elasticsearch_action_admin_cluster_node_info_PluginInfo.java |
1,335 | public class OFuzzyCheckpointStartRecord extends OAbstractCheckPointStartRecord {
private OLogSequenceNumber lsn;
public OFuzzyCheckpointStartRecord() {
}
public OFuzzyCheckpointStartRecord(OLogSequenceNumber previousCheckpoint) {
super(previousCheckpoint);
}
@Override
public OLogSequenceNumber getLsn() {
return lsn;
}
@Override
public void setLsn(OLogSequenceNumber lsn) {
this.lsn = lsn;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
return true;
}
@Override
public String toString() {
return "OFuzzyCheckpointStartRecord{" + "lsn=" + lsn + "} " + super.toString();
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_impl_local_paginated_wal_OFuzzyCheckpointStartRecord.java |
242 | service.submit(callable, new ExecutionCallback() {
public void onResponse(Object response) {
result.set(response);
responseLatch.countDown();
}
public void onFailure(Throwable t) {
}
}); | 0true
| hazelcast-client_src_test_java_com_hazelcast_client_executor_ClientExecutorServiceSubmitTest.java |
2,063 | public class MapKeySetOperation extends AbstractMapOperation implements PartitionAwareOperation {
Set<Data> keySet;
public MapKeySetOperation(String name) {
super(name);
}
public MapKeySetOperation() {
}
public void run() {
MapService mapService = (MapService) getService();
RecordStore recordStore = mapService.getRecordStore(getPartitionId(), name);
keySet = recordStore.keySet();
if (mapContainer.getMapConfig().isStatisticsEnabled()) {
((MapService) getService()).getLocalMapStatsImpl(name).incrementOtherOperations();
}
}
@Override
public Object getResponse() {
return new MapKeySet(keySet);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_map_operation_MapKeySetOperation.java |
1,247 | new OProfilerHookValue() {
public Object getValue() {
return totalMemory;
}
}); | 0true
| core_src_main_java_com_orientechnologies_orient_core_storage_fs_OMMapManagerOld.java |
171 | public abstract class OPollerThread extends OSoftThread {
protected final long delay;
public OPollerThread(final long iDelay) {
delay = iDelay;
}
public OPollerThread(long iDelay, final ThreadGroup iThreadGroup) {
super(iThreadGroup, OPollerThread.class.getSimpleName());
delay = iDelay;
}
public OPollerThread(final long iDelay, final String name) {
super(name);
delay = iDelay;
}
public OPollerThread(final long iDelay, final ThreadGroup group, final String name) {
super(group, name);
delay = iDelay;
}
@Override
protected void afterExecution() throws InterruptedException {
pauseCurrentThread(delay);
}
} | 0true
| commons_src_main_java_com_orientechnologies_common_thread_OPollerThread.java |
1,908 | new AbstractMatcher<TypeLiteral<?>>() {
public boolean matches(TypeLiteral<?> typeLiteral) {
return typeLiteral.getRawType() == Class.class;
}
@Override
public String toString() {
return "Class<?>";
}
}, | 0true
| src_main_java_org_elasticsearch_common_inject_TypeConverterBindingProcessor.java |
991 | threadPool.executor(executor).execute(new Runnable() {
@Override
public void run() {
try {
performOnPrimary(shard.id(), shard, clusterState);
} catch (Throwable t) {
listener.onFailure(t);
}
}
}); | 0true
| src_main_java_org_elasticsearch_action_support_replication_TransportShardReplicationOperationAction.java |
1,843 | InternalFactory<T> internalFactory = new InternalFactory<T>() {
public T get(Errors errors, InternalContext context, Dependency<?> dependency)
throws ErrorsException {
return targetBinding.getInternalFactory().get(
errors.withSource(targetKey), context, dependency);
}
}; | 0true
| src_main_java_org_elasticsearch_common_inject_InjectorImpl.java |
259 | public class OBasicCommandContext implements OCommandContext {
public static final String EXECUTION_BEGUN = "EXECUTION_BEGUN";
public static final String TIMEOUT_MS = "TIMEOUT_MS";
public static final String TIMEOUT_STRATEGY = "TIMEOUT_STARTEGY";
protected boolean recordMetrics = false;
protected OCommandContext parent;
protected OCommandContext child;
protected Map<String, Object> variables;
// MANAGES THE TIMEOUT
private long executionStartedOn;
private long timeoutMs;
private com.orientechnologies.orient.core.command.OCommandContext.TIMEOUT_STRATEGY timeoutStrategy;
public OBasicCommandContext() {
}
public Object getVariable(String iName) {
return getVariable(iName, null);
}
public Object getVariable(String iName, final Object iDefault) {
if (iName == null)
return iDefault;
Object result = null;
if (iName.startsWith("$"))
iName = iName.substring(1);
int pos = OStringSerializerHelper.getLowerIndexOf(iName, 0, ".", "[");
String firstPart;
String lastPart;
if (pos > -1) {
firstPart = iName.substring(0, pos);
if (iName.charAt(pos) == '.')
pos++;
lastPart = iName.substring(pos);
if (firstPart.equalsIgnoreCase("PARENT") && parent != null) {
// UP TO THE PARENT
if (lastPart.startsWith("$"))
result = parent.getVariable(lastPart.substring(1));
else
result = ODocumentHelper.getFieldValue(parent, lastPart);
return result != null ? result : iDefault;
} else if (firstPart.equalsIgnoreCase("ROOT")) {
OCommandContext p = this;
while (p.getParent() != null)
p = p.getParent();
if (lastPart.startsWith("$"))
result = p.getVariable(lastPart.substring(1));
else
result = ODocumentHelper.getFieldValue(p, lastPart, this);
return result != null ? result : iDefault;
}
} else {
firstPart = iName;
lastPart = null;
}
if (firstPart.equalsIgnoreCase("CONTEXT"))
result = getVariables();
else if (firstPart.equalsIgnoreCase("PARENT"))
result = parent;
else if (firstPart.equalsIgnoreCase("ROOT")) {
OCommandContext p = this;
while (p.getParent() != null)
p = p.getParent();
result = p;
} else {
if (variables != null && variables.containsKey(firstPart))
result = variables.get(firstPart);
else if (child != null)
result = child.getVariable(firstPart);
}
if (pos > -1)
result = ODocumentHelper.getFieldValue(result, lastPart, this);
return result != null ? result : iDefault;
}
public OCommandContext setVariable(String iName, final Object iValue) {
if (iName == null)
return null;
if (iName.startsWith("$"))
iName = iName.substring(1);
init();
int pos = OStringSerializerHelper.getHigherIndexOf(iName, 0, ".", "[");
if (pos > -1) {
Object nested = getVariable(iName.substring(0, pos));
if (nested != null && nested instanceof OCommandContext)
((OCommandContext) nested).setVariable(iName.substring(pos + 1), iValue);
} else
variables.put(iName, iValue);
return this;
}
public long updateMetric(final String iName, final long iValue) {
if (!recordMetrics)
return -1;
init();
Long value = (Long) variables.get(iName);
if (value == null)
value = iValue;
else
value = new Long(value.longValue() + iValue);
variables.put(iName, value);
return value.longValue();
}
/**
* Returns a read-only map with all the variables.
*/
public Map<String, Object> getVariables() {
final HashMap<String, Object> map = new HashMap<String, Object>();
if (child != null)
map.putAll(child.getVariables());
if (variables != null)
map.putAll(variables);
return map;
}
/**
* Set the inherited context avoiding to copy all the values every time.
*
* @return
*/
public OCommandContext setChild(final OCommandContext iContext) {
if (iContext == null) {
if (child != null) {
// REMOVE IT
child.setParent(null);
child = null;
}
} else if (child != iContext) {
// ADD IT
child = iContext;
iContext.setParent(this);
}
return this;
}
public OCommandContext getParent() {
return parent;
}
public OCommandContext setParent(final OCommandContext iParentContext) {
if (parent != iParentContext) {
parent = iParentContext;
if (parent != null)
parent.setChild(this);
}
return this;
}
@Override
public String toString() {
return getVariables().toString();
}
private void init() {
if (variables == null)
variables = new HashMap<String, Object>();
}
public boolean isRecordingMetrics() {
return recordMetrics;
}
public OCommandContext setRecordingMetrics(final boolean recordMetrics) {
this.recordMetrics = recordMetrics;
return this;
}
@Override
public void beginExecution(final long iTimeout, final TIMEOUT_STRATEGY iStrategy) {
if (iTimeout > 0) {
executionStartedOn = System.currentTimeMillis();
timeoutMs = iTimeout;
timeoutStrategy = iStrategy;
}
}
public boolean checkTimeout() {
if (timeoutMs > 0) {
if (System.currentTimeMillis() - executionStartedOn > timeoutMs) {
// TIMEOUT!
switch (timeoutStrategy) {
case RETURN:
return false;
case EXCEPTION:
throw new OTimeoutException("Command execution timeout exceed (" + timeoutMs + "ms)");
}
}
}
return true;
}
} | 0true
| core_src_main_java_com_orientechnologies_orient_core_command_OBasicCommandContext.java |
1,351 | @Entity
@Table(name = "BLC_STORE")
@Inheritance(strategy = InheritanceType.JOINED)
public class StoreImpl implements Store {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "STORE_ID", nullable = false)
private String id;
@Column(name = "STORE_NAME")
@Index(name="STORE_NAME_INDEX", columnNames={"STORE_NAME"})
private String name;
@Column(name = "ADDRESS_1")
private String address1;
@Column(name = "ADDRESS_2")
private String address2;
@Column(name = "STORE_CITY")
@Index(name="STORE_CITY_INDEX", columnNames={"STORE_CITY"})
private String city;
@Column(name = "STORE_STATE")
@Index(name="STORE_STATE_INDEX", columnNames={"STORE_STATE"})
private String state;
@Column(name = "STORE_ZIP")
@Index(name="STORE_ZIP_INDEX", columnNames={"STORE_ZIP"})
private String zip;
@Column(name = "STORE_COUNTRY")
@Index(name="STORE_COUNTRY_INDEX", columnNames={"STORE_COUNTRY"})
private String country;
@Column(name = "STORE_PHONE")
private String phone;
@Column(name = "LATITUDE")
@Index(name="STORE_LATITUDE_INDEX", columnNames={"LATITUDE"})
private Double latitude;
@Column(name = "LONGITUDE")
@Index(name="STORE_LONGITUDE_INDEX", columnNames={"LONGITUDE"})
private Double longitude;
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getId()
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getId()
*/
public String getId() {
return id;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setId(java.lang.String)
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setId(java.lang.String)
*/
public void setId(String id) {
this.id = id;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getName()
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getName()
*/
public String getName() {
return name;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setName(java.lang.String)
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setName(java.lang.String)
*/
public void setName(String name) {
this.name = name;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getAddress1()
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getAddress1()
*/
public String getAddress1() {
return address1;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setAddress1(java.lang.String)
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setAddress1(java.lang.String)
*/
public void setAddress1(String address1) {
this.address1 = address1;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getAddress2()
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getAddress2()
*/
public String getAddress2() {
return address2;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setAddress2(java.lang.String)
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setAddress2(java.lang.String)
*/
public void setAddress2(String address2) {
this.address2 = address2;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getCity()
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getCity()
*/
public String getCity() {
return city;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setCity(java.lang.String)
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setCity(java.lang.String)
*/
public void setCity(String city) {
this.city = city;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getZip()
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getZip()
*/
public String getZip() {
return zip;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setZip(java.lang.String)
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setZip(java.lang.String)
*/
public void setZip(String zip) {
this.zip = zip;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getCountry()
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getCountry()
*/
public String getCountry() {
return country;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setCountry(java.lang.String)
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setCountry(java.lang.String)
*/
public void setCountry(String country) {
this.country = country;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getPhone()
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getPhone()
*/
public String getPhone() {
return phone;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setPhone(java.lang.String)
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setPhone(java.lang.String)
*/
public void setPhone(String phone) {
this.phone = phone;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getLongitude()
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getLongitude()
*/
public Double getLongitude() {
return longitude;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setLongitude(java.lang.Float)
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setLongitude(java.lang.Float)
*/
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getLatitude()
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getLatitude()
*/
public Double getLatitude() {
return latitude;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setLatitude(java.lang.Float)
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setLatitude(java.lang.Float)
*/
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setState(java.lang.String)
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#setState(java.lang.String)
*/
public void setState(String state) {
this.state = state;
}
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getState()
*/
/* (non-Javadoc)
* @see org.broadleafcommerce.core.store.domain.Store#getState()
*/
public String getState() {
return state;
}
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_store_domain_StoreImpl.java |
223 | public class CeylonSelectAnnotationRulerAction extends SelectMarkerRulerAction {
IVerticalRulerInfo ruler;
CeylonEditor editor;
public CeylonSelectAnnotationRulerAction(ResourceBundle bundle, String prefix,
ITextEditor editor, IVerticalRulerInfo ruler) {
super(bundle, prefix, editor, ruler);
this.ruler = ruler;
this.editor = (CeylonEditor) editor;
}
@Override
public void update() {
//don't let super.update() be called!
}
@Override
public void run() {
//super.run();
int line = ruler.getLineOfLastMouseButtonActivity()+1;
IAnnotationModel model= editor.getDocumentProvider()
.getAnnotationModel(editor.getEditorInput());
for (@SuppressWarnings("unchecked")
Iterator<Annotation> iter = model.getAnnotationIterator();
iter.hasNext();) {
Annotation ann = iter.next();
if (ann instanceof RefinementAnnotation) {
RefinementAnnotation ra = (RefinementAnnotation) ann;
if (ra.getLine()==line) {
ra.gotoRefinedDeclaration(editor);
}
}
}
}
} | 0true
| plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_editor_CeylonSelectAnnotationRulerAction.java |
1,819 | @Component("blMapFieldPersistenceProvider")
@Scope("prototype")
public class MapFieldPersistenceProvider extends BasicFieldPersistenceProvider {
@Override
protected boolean canHandlePersistence(PopulateValueRequest populateValueRequest, Serializable instance) {
return populateValueRequest.getProperty().getName().contains(FieldManager.MAPFIELDSEPARATOR);
}
@Override
protected boolean canHandleExtraction(ExtractValueRequest extractValueRequest, Property property) {
return property.getName().contains(FieldManager.MAPFIELDSEPARATOR);
}
@Override
public FieldProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) {
try {
//handle some additional field settings (if applicable)
Class<?> valueType = null;
String valueClassName = populateValueRequest.getMetadata().getMapFieldValueClass();
if (valueClassName != null) {
valueType = Class.forName(valueClassName);
}
if (valueType == null) {
valueType = populateValueRequest.getReturnType();
}
if (valueType == null) {
throw new IllegalAccessException("Unable to determine the valueType for the rule field (" + populateValueRequest.getProperty().getName() + ")");
}
if (ValueAssignable.class.isAssignableFrom(valueType)) {
ValueAssignable assignableValue;
try {
assignableValue = (ValueAssignable) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
} catch (FieldNotAvailableException e) {
throw new IllegalArgumentException(e);
}
String key = populateValueRequest.getProperty().getName().substring(populateValueRequest.getProperty().getName().indexOf(FieldManager.MAPFIELDSEPARATOR) + FieldManager.MAPFIELDSEPARATOR.length(), populateValueRequest.getProperty().getName().length());
boolean persistValue = false;
if (assignableValue == null) {
assignableValue = (ValueAssignable) valueType.newInstance();
persistValue = true;
}
assignableValue.setName(key);
assignableValue.setValue(populateValueRequest.getProperty().getValue());
String fieldName = populateValueRequest.getProperty().getName().substring(0, populateValueRequest.getProperty().getName().indexOf(FieldManager.MAPFIELDSEPARATOR));
Field field = populateValueRequest.getFieldManager().getField(instance.getClass(), fieldName);
FieldInfo fieldInfo = buildFieldInfo(field);
String manyToField = null;
if (populateValueRequest.getMetadata().getManyToField() != null) {
manyToField = populateValueRequest.getMetadata().getManyToField();
}
if (manyToField == null) {
manyToField = fieldInfo.getManyToManyMappedBy();
}
if (manyToField == null) {
manyToField = fieldInfo.getOneToManyMappedBy();
}
if (manyToField != null) {
String propertyName = populateValueRequest.getProperty().getName();
Object middleInstance = instance;
if (propertyName.contains(".")) {
propertyName = propertyName.substring(0, propertyName.lastIndexOf("."));
middleInstance = populateValueRequest.getFieldManager().getFieldValue(instance, propertyName);
}
populateValueRequest.getFieldManager().setFieldValue(assignableValue, manyToField, middleInstance);
}
if (Searchable.class.isAssignableFrom(valueType)) {
((Searchable) assignableValue).setSearchable(populateValueRequest.getMetadata().getSearchable());
}
if (persistValue) {
populateValueRequest.getPersistenceManager().getDynamicEntityDao().persist(assignableValue);
populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), assignableValue);
}
} else {
//handle the map value set itself
if (FieldProviderResponse.NOT_HANDLED==super.populateValue(populateValueRequest, instance)) {
return FieldProviderResponse.NOT_HANDLED;
}
}
} catch (Exception e) {
throw new PersistenceException(e);
}
return FieldProviderResponse.HANDLED;
}
@Override
public FieldProviderResponse extractValue(ExtractValueRequest extractValueRequest, Property property) throws PersistenceException {
if (extractValueRequest.getRequestedValue() != null && extractValueRequest.getRequestedValue() instanceof ValueAssignable) {
ValueAssignable assignableValue = (ValueAssignable) extractValueRequest.getRequestedValue();
String val = (String) assignableValue.getValue();
property.setValue(val);
property.setDisplayValue(extractValueRequest.getDisplayVal());
} else {
if (FieldProviderResponse.NOT_HANDLED==super.extractValue(extractValueRequest, property)) {
return FieldProviderResponse.NOT_HANDLED;
}
}
return FieldProviderResponse.HANDLED;
}
@Override
public FieldProviderResponse addSearchMapping(AddSearchMappingRequest addSearchMappingRequest, List<FilterMapping> filterMappings) {
return FieldProviderResponse.NOT_HANDLED;
}
@Override
public int getOrder() {
return FieldPersistenceProvider.MAP_FIELD;
}
} | 1no label
| admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_server_service_persistence_module_provider_MapFieldPersistenceProvider.java |
2,053 | public interface ProviderWithDependencies<T> extends Provider<T>, HasDependencies {
} | 0true
| src_main_java_org_elasticsearch_common_inject_spi_ProviderWithDependencies.java |
71 | @SuppressWarnings("serial")
static final class MapReduceEntriesToIntTask<K,V>
extends BulkTask<K,V,Integer> {
final ObjectToInt<Map.Entry<K,V>> transformer;
final IntByIntToInt reducer;
final int basis;
int result;
MapReduceEntriesToIntTask<K,V> rights, nextRight;
MapReduceEntriesToIntTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
MapReduceEntriesToIntTask<K,V> nextRight,
ObjectToInt<Map.Entry<K,V>> transformer,
int basis,
IntByIntToInt reducer) {
super(p, b, i, f, t); this.nextRight = nextRight;
this.transformer = transformer;
this.basis = basis; this.reducer = reducer;
}
public final Integer getRawResult() { return result; }
public final void compute() {
final ObjectToInt<Map.Entry<K,V>> transformer;
final IntByIntToInt reducer;
if ((transformer = this.transformer) != null &&
(reducer = this.reducer) != null) {
int r = this.basis;
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
(rights = new MapReduceEntriesToIntTask<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));
result = r;
CountedCompleter<?> c;
for (c = firstComplete(); c != null; c = c.nextComplete()) {
@SuppressWarnings("unchecked") MapReduceEntriesToIntTask<K,V>
t = (MapReduceEntriesToIntTask<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 |
13 | public interface FeedAggregator {
/**
* Returns a map of data for each feed. This allows the data to be queried in batch and improves performance.
* @param feedIDs to retrieve data for
* @param timeUnit the time unit of startTime and endTime parameters.
* @param startTime the start time of the return data set.
* @param endTime the end time of the return data set.
* @return map of data for the specified feeds. Each entry in the map has data
* with a timestamp that is >= startTime and < endTime.
*/
public Map<String, List<Map<String, String>>> getData(Set<String> feedIDs, TimeUnit timeUnit, long startTime, long endTime);
} | 0true
| mctcore_src_main_java_gov_nasa_arc_mct_api_feed_FeedAggregator.java |
321 | Comparator<Object> nameCompare = new Comparator<Object>() {
public int compare(Object arg0, Object arg1) {
return ((MergeHandler) arg0).getName().compareTo(((MergeHandler) arg1).getName());
}
}; | 0true
| common_src_main_java_org_broadleafcommerce_common_extensibility_context_merge_MergeManager.java |
3,523 | public class ParsedDocument {
private final Field uid, version;
private final String id;
private final String type;
private final String routing;
private final long timestamp;
private final long ttl;
private final List<Document> documents;
private final Analyzer analyzer;
private BytesReference source;
private boolean mappingsModified;
private String parent;
public ParsedDocument(Field uid, Field version, String id, String type, String routing, long timestamp, long ttl, List<Document> documents, Analyzer analyzer, BytesReference source, boolean mappingsModified) {
this.uid = uid;
this.version = version;
this.id = id;
this.type = type;
this.routing = routing;
this.timestamp = timestamp;
this.ttl = ttl;
this.documents = documents;
this.source = source;
this.analyzer = analyzer;
this.mappingsModified = mappingsModified;
}
public Field uid() {
return this.uid;
}
public Field version() {
return version;
}
public String id() {
return this.id;
}
public String type() {
return this.type;
}
public String routing() {
return this.routing;
}
public long timestamp() {
return this.timestamp;
}
public long ttl() {
return this.ttl;
}
public Document rootDoc() {
return documents.get(documents.size() - 1);
}
public List<Document> docs() {
return this.documents;
}
public Analyzer analyzer() {
return this.analyzer;
}
public BytesReference source() {
return this.source;
}
public void setSource(BytesReference source) {
this.source = source;
}
public ParsedDocument parent(String parent) {
this.parent = parent;
return this;
}
public String parent() {
return this.parent;
}
/**
* Has the parsed document caused mappings to be modified?
*/
public boolean mappingsModified() {
return mappingsModified;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Document ").append("uid[").append(uid).append("] doc [").append(documents).append("]");
return sb.toString();
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_ParsedDocument.java |
810 | public interface OfferCode extends Serializable {
public Long getId() ;
public void setId(Long id) ;
public Offer getOffer() ;
public void setOffer(Offer offer) ;
public String getOfferCode();
public void setOfferCode(String offerCode);
public Date getStartDate();
public void setStartDate(Date startDate);
public Date getEndDate();
public void setEndDate(Date endDate);
/**
* Returns the maximum number of times that this code can be used regardless of Order or Customer
*
* 0 indicates unlimited usage.
*
* @return
*/
public int getMaxUses();
/**
* Sets the maximum number of times that this code can be used regardless of Order or Customer
*
* 0 indicates unlimited usage.
*
* @param maxUses
*/
public void setMaxUses(int maxUses);
/**
* Indicates that this is an unlimited-use code. By default this is true if {@link #getMaxUses()} == 0
*/
public boolean isUnlimitedUse();
/**
* Indicates that this code has a limit on how many times it can be used. By default this is true if {@link #getMaxUses()} > 0
*/
public boolean isLimitedUse();
/**
* @deprecated replaced by the {@link OfferAudit} table
*/
@Deprecated
public int getUses() ;
/**
* @deprecated replaced by the {@link OfferAudit} table
*/
@Deprecated
public void setUses(int uses);
public List<Order> getOrders();
public void setOrders(List<Order> orders);
} | 0true
| core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_offer_domain_OfferCode.java |
1,968 | public final class EvictionHelper {
private static final int ONE_HUNDRED_PERCENT = 100;
private static final int EVICTION_START_THRESHOLD_PERCENTAGE = 95;
private static final int ONE_KILOBYTE = 1024;
private EvictionHelper() {
}
public static boolean checkEvictable(MapContainer mapContainer) {
final MaxSizeConfig maxSizeConfig = mapContainer.getMapConfig().getMaxSizeConfig();
final MaxSizeConfig.MaxSizePolicy maxSizePolicy = maxSizeConfig.getMaxSizePolicy();
boolean result;
switch (maxSizePolicy) {
case PER_NODE:
result = isEvictablePerNode(mapContainer);
break;
case PER_PARTITION:
result = isEvictablePerPartition(mapContainer);
break;
case USED_HEAP_PERCENTAGE:
result = isEvictableHeapPercentage(mapContainer);
break;
case USED_HEAP_SIZE:
result = isEvictableHeapSize(mapContainer);
break;
default:
throw new IllegalArgumentException("Not an appropriate max size policy [" + maxSizePolicy + ']');
}
return result;
}
public static void removeEvictableRecords(final RecordStore recordStore, final MapConfig mapConfig,
final MapService mapService) {
final int partitionSize = recordStore.size();
if (partitionSize < 1) {
return;
}
final int evictableSize = getEvictableSize(partitionSize, mapConfig, mapService);
if (evictableSize < 1) {
return;
}
final MapConfig.EvictionPolicy evictionPolicy = mapConfig.getEvictionPolicy();
final Map<Data, Record> entries = recordStore.getReadonlyRecordMap();
final int size = entries.size();
// size have a tendency to change to here so check again.
if (entries.isEmpty()) {
return;
}
// criteria is a long value, like last access times or hits,
// used for calculating LFU or LRU.
final long[] criterias = new long[size];
int index = 0;
for (final Record record : entries.values()) {
criterias[index] = getEvictionCriteriaValue(record, evictionPolicy);
index++;
//in case size may change (increase or decrease) when iterating.
if (index == size) {
break;
}
}
if (criterias.length == 0) {
return;
}
// just in case there may be unassigned indexes in criterias array due to size variances
// assign them to Long.MAX_VALUE so when sorting asc they will locate
// in the upper array indexes and we wont care about them.
if (index < criterias.length) {
for (int i = index; i < criterias.length; i++) {
criterias[i] = Long.MAX_VALUE;
}
}
Arrays.sort(criterias);
// check in case record store size may be smaller than evictable size.
final int evictableBaseIndex = index == 0 ? index : Math.min(evictableSize, index - 1);
final long criteriaValue = criterias[evictableBaseIndex];
int evictedRecordCounter = 0;
for (final Map.Entry<Data, Record> entry : entries.entrySet()) {
final Record record = entry.getValue();
final long value = getEvictionCriteriaValue(record, evictionPolicy);
if (value <= criteriaValue) {
final Data tmpKey = record.getKey();
final Object tmpValue = record.getValue();
if (evictIfNotLocked(tmpKey, recordStore)) {
evictedRecordCounter++;
final String mapName = mapConfig.getName();
mapService.interceptAfterRemove(mapName, value);
if (mapService.isNearCacheAndInvalidationEnabled(mapName)) {
mapService.invalidateAllNearCaches(mapName, tmpKey);
}
fireEvent(tmpKey, tmpValue, mapName, mapService);
}
}
if (evictedRecordCounter >= evictableSize) {
break;
}
}
}
public static void fireEvent(Data key, Object value, String mapName, MapService mapService) {
final NodeEngine nodeEngine = mapService.getNodeEngine();
mapService.publishEvent(nodeEngine.getThisAddress(), mapName, EntryEventType.EVICTED,
key, mapService.toData(value), null);
}
public static boolean evictIfNotLocked(Data key, RecordStore recordStore) {
if (recordStore.isLocked(key)) {
return false;
}
recordStore.evict(key);
return true;
}
public static int getEvictableSize(int currentPartitionSize, MapConfig mapConfig, MapService mapService) {
int evictableSize;
final MaxSizeConfig.MaxSizePolicy maxSizePolicy = mapConfig.getMaxSizeConfig().getMaxSizePolicy();
final int evictionPercentage = mapConfig.getEvictionPercentage();
switch (maxSizePolicy) {
case PER_PARTITION:
int maxSize = mapConfig.getMaxSizeConfig().getSize();
int targetSizePerPartition = Double.valueOf(maxSize
* ((ONE_HUNDRED_PERCENT - evictionPercentage) / (1D * ONE_HUNDRED_PERCENT))).intValue();
int diffFromTargetSize = currentPartitionSize - targetSizePerPartition;
int prunedSize = currentPartitionSize * evictionPercentage / ONE_HUNDRED_PERCENT + 1;
evictableSize = Math.max(diffFromTargetSize, prunedSize);
break;
case PER_NODE:
maxSize = mapConfig.getMaxSizeConfig().getSize();
int memberCount = mapService.getNodeEngine().getClusterService().getMembers().size();
int maxPartitionSize = (maxSize
* memberCount / mapService.getNodeEngine().getPartitionService().getPartitionCount());
targetSizePerPartition = Double.valueOf(maxPartitionSize
* ((ONE_HUNDRED_PERCENT - evictionPercentage) / (1D * ONE_HUNDRED_PERCENT))).intValue();
diffFromTargetSize = currentPartitionSize - targetSizePerPartition;
prunedSize = currentPartitionSize * evictionPercentage / ONE_HUNDRED_PERCENT + 1;
evictableSize = Math.max(diffFromTargetSize, prunedSize);
break;
case USED_HEAP_PERCENTAGE:
case USED_HEAP_SIZE:
evictableSize = currentPartitionSize * evictionPercentage / ONE_HUNDRED_PERCENT;
break;
default:
throw new IllegalArgumentException("Max size policy is not defined [" + maxSizePolicy + "]");
}
return evictableSize;
}
private static long getEvictionCriteriaValue(Record record, MapConfig.EvictionPolicy evictionPolicy) {
long value;
switch (evictionPolicy) {
case LRU:
case LFU:
value = record.getEvictionCriteriaNumber();
break;
default:
throw new IllegalArgumentException("Not an appropriate eviction policy [" + evictionPolicy + ']');
}
return value;
}
private static boolean isEvictablePerNode(MapContainer mapContainer) {
int nodeTotalSize = 0;
final MapService mapService = mapContainer.getMapService();
final MaxSizeConfig maxSizeConfig = mapContainer.getMapConfig().getMaxSizeConfig();
final int maxSize = getApproximateMaxSize(maxSizeConfig.getSize());
final String mapName = mapContainer.getName();
final NodeEngine nodeEngine = mapService.getNodeEngine();
final InternalPartitionService partitionService = nodeEngine.getPartitionService();
final int partitionCount = partitionService.getPartitionCount();
for (int i = 0; i < partitionCount; i++) {
final Address owner = partitionService.getPartitionOwner(i);
if (nodeEngine.getThisAddress().equals(owner)) {
final PartitionContainer container = mapService.getPartitionContainer(i);
if (container == null) {
return false;
}
nodeTotalSize += getRecordStoreSize(mapName, container);
if (nodeTotalSize >= maxSize) {
return true;
}
}
}
return false;
}
private static int getRecordStoreSize(String mapName, PartitionContainer partitionContainer) {
final RecordStore existingRecordStore = partitionContainer.getExistingRecordStore(mapName);
if (existingRecordStore == null) {
return 0;
}
return existingRecordStore.size();
}
private static long getRecordStoreHeapCost(String mapName, PartitionContainer partitionContainer) {
final RecordStore existingRecordStore = partitionContainer.getExistingRecordStore(mapName);
if (existingRecordStore == null) {
return 0L;
}
return existingRecordStore.getHeapCost();
}
/**
* used when deciding evictable or not.
*/
private static int getApproximateMaxSize(int maxSizeFromConfig) {
// because not to exceed the max size much we start eviction early.
// so decrease the max size with ratio .95 below
return maxSizeFromConfig * EVICTION_START_THRESHOLD_PERCENTAGE / ONE_HUNDRED_PERCENT;
}
private static boolean isEvictablePerPartition(final MapContainer mapContainer) {
final MapService mapService = mapContainer.getMapService();
final MaxSizeConfig maxSizeConfig = mapContainer.getMapConfig().getMaxSizeConfig();
final int maxSize = getApproximateMaxSize(maxSizeConfig.getSize());
final String mapName = mapContainer.getName();
final NodeEngine nodeEngine = mapService.getNodeEngine();
final InternalPartitionService partitionService = nodeEngine.getPartitionService();
for (int i = 0; i < partitionService.getPartitionCount(); i++) {
final Address owner = partitionService.getPartitionOwner(i);
if (nodeEngine.getThisAddress().equals(owner)) {
final PartitionContainer container = mapService.getPartitionContainer(i);
if (container == null) {
return false;
}
final int size = getRecordStoreSize(mapName, container);
if (size >= maxSize) {
return true;
}
}
}
return false;
}
private static boolean isEvictableHeapSize(final MapContainer mapContainer) {
final long usedHeapSize = getUsedHeapSize(mapContainer);
if (usedHeapSize == -1L) {
return false;
}
final MaxSizeConfig maxSizeConfig = mapContainer.getMapConfig().getMaxSizeConfig();
final int maxSize = getApproximateMaxSize(maxSizeConfig.getSize());
return maxSize < (usedHeapSize / ONE_KILOBYTE / ONE_KILOBYTE);
}
private static boolean isEvictableHeapPercentage(final MapContainer mapContainer) {
final long usedHeapSize = getUsedHeapSize(mapContainer);
if (usedHeapSize == -1L) {
return false;
}
final MaxSizeConfig maxSizeConfig = mapContainer.getMapConfig().getMaxSizeConfig();
final int maxSize = getApproximateMaxSize(maxSizeConfig.getSize());
final long total = Runtime.getRuntime().totalMemory();
return maxSize < (1D * ONE_HUNDRED_PERCENT * usedHeapSize / total);
}
private static long getUsedHeapSize(final MapContainer mapContainer) {
long heapCost = 0L;
final MapService mapService = mapContainer.getMapService();
final String mapName = mapContainer.getName();
final NodeEngine nodeEngine = mapService.getNodeEngine();
final Address thisAddress = nodeEngine.getThisAddress();
for (int i = 0; i < nodeEngine.getPartitionService().getPartitionCount(); i++) {
if (nodeEngine.getPartitionService().getPartition(i).isOwnerOrBackup(thisAddress)) {
final PartitionContainer container = mapService.getPartitionContainer(i);
if (container == null) {
return -1L;
}
heapCost += getRecordStoreHeapCost(mapName, container);
}
}
heapCost += mapContainer.getNearCacheSizeEstimator().getSize();
return heapCost;
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_map_eviction_EvictionHelper.java |
3,589 | public static class TypeParser implements Mapper.TypeParser {
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
IntegerFieldMapper.Builder builder = integerField(name);
parseNumberField(builder, name, node, parserContext);
for (Map.Entry<String, Object> entry : node.entrySet()) {
String propName = Strings.toUnderscoreCase(entry.getKey());
Object propNode = entry.getValue();
if (propName.equals("null_value")) {
builder.nullValue(nodeIntegerValue(propNode));
}
}
return builder;
}
} | 0true
| src_main_java_org_elasticsearch_index_mapper_core_IntegerFieldMapper.java |
970 | transportService.sendRequest(node, transportNodeAction, nodeRequest, transportRequestOptions, new BaseTransportResponseHandler<NodeResponse>() {
@Override
public NodeResponse newInstance() {
return newNodeResponse();
}
@Override
public void handleResponse(NodeResponse response) {
onOperation(idx, response);
}
@Override
public void handleException(TransportException exp) {
onFailure(idx, node.id(), exp);
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
}); | 0true
| src_main_java_org_elasticsearch_action_support_nodes_TransportNodesOperationAction.java |
1,518 | public class SideEffectMap {
public static final String CLASS = Tokens.makeNamespace(SideEffectMap.class) + ".class";
public static final String CLOSURE = Tokens.makeNamespace(SideEffectMap.class) + ".closure";
private static final ScriptEngine engine = new GremlinGroovyScriptEngine();
public enum Counters {
VERTICES_PROCESSED,
IN_EDGES_PROCESSED,
OUT_EDGES_PROCESSED
}
public static Configuration createConfiguration(final Class<? extends Element> klass, final String closure) {
final Configuration configuration = new EmptyConfiguration();
configuration.setClass(CLASS, klass, Element.class);
configuration.set(CLOSURE, closure);
return configuration;
}
public static class Map extends Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex> {
private Closure closure;
private boolean isVertex;
@Override
public void setup(final Mapper.Context context) throws IOException, InterruptedException {
this.isVertex = context.getConfiguration().getClass(CLASS, Element.class, Element.class).equals(Vertex.class);
try {
this.closure = (Closure) engine.eval(context.getConfiguration().get(CLOSURE));
} catch (final ScriptException e) {
throw new IOException(e.getMessage(), e);
}
}
@Override
public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException {
if (this.isVertex) {
if (value.hasPaths()) {
//for (int i = 0; i < value.pathCount(); i++) {
this.closure.call(value);
//}
DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_PROCESSED, 1L);
}
} else {
long edgesProcessed = 0;
for (final Edge e : value.getEdges(Direction.IN)) {
final StandardFaunusEdge edge = (StandardFaunusEdge) e;
if (edge.hasPaths()) {
edgesProcessed++;
//for (int i = 0; i < edge.pathCount(); i++) {
this.closure.call(edge);
//}
}
}
DEFAULT_COMPAT.incrementContextCounter(context, Counters.IN_EDGES_PROCESSED, edgesProcessed);
edgesProcessed = 0;
for (final Edge e : value.getEdges(Direction.OUT)) {
final StandardFaunusEdge edge = (StandardFaunusEdge) e;
if (edge.hasPaths()) {
edgesProcessed++;
//for (int i = 0; i < edge.pathCount(); i++) {
this.closure.call(edge);
//}
}
}
DEFAULT_COMPAT.incrementContextCounter(context, Counters.OUT_EDGES_PROCESSED, edgesProcessed);
}
context.write(NullWritable.get(), value);
}
}
} | 1no label
| titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_sideeffect_SideEffectMap.java |
1,082 | public class UpdateRequest extends InstanceShardOperationRequest<UpdateRequest> {
private String type;
private String id;
@Nullable
private String routing;
@Nullable
String script;
@Nullable
String scriptLang;
@Nullable
Map<String, Object> scriptParams;
private String[] fields;
private long version = Versions.MATCH_ANY;
private VersionType versionType = VersionType.INTERNAL;
private int retryOnConflict = 0;
private boolean refresh = false;
private ReplicationType replicationType = ReplicationType.DEFAULT;
private WriteConsistencyLevel consistencyLevel = WriteConsistencyLevel.DEFAULT;
private IndexRequest upsertRequest;
private boolean docAsUpsert = false;
@Nullable
private IndexRequest doc;
public UpdateRequest() {
}
public UpdateRequest(String index, String type, String id) {
this.index = index;
this.type = type;
this.id = id;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = super.validate();
if (type == null) {
validationException = addValidationError("type is missing", validationException);
}
if (id == null) {
validationException = addValidationError("id is missing", validationException);
}
if (version != Versions.MATCH_ANY && retryOnConflict > 0) {
validationException = addValidationError("can't provide both retry_on_conflict and a specific version", validationException);
}
if (script == null && doc == null) {
validationException = addValidationError("script or doc is missing", validationException);
}
if (script != null && doc != null) {
validationException = addValidationError("can't provide both script and doc", validationException);
}
if (doc == null && docAsUpsert) {
validationException = addValidationError("doc must be specified if doc_as_upsert is enabled", validationException);
}
return validationException;
}
/**
* The type of the indexed document.
*/
public String type() {
return type;
}
/**
* Sets the type of the indexed document.
*/
public UpdateRequest type(String type) {
this.type = type;
return this;
}
/**
* The id of the indexed document.
*/
public String id() {
return id;
}
/**
* Sets the id of the indexed document.
*/
public UpdateRequest id(String id) {
this.id = id;
return this;
}
/**
* Controls the shard routing of the request. Using this value to hash the shard
* and not the id.
*/
public UpdateRequest routing(String routing) {
if (routing != null && routing.length() == 0) {
this.routing = null;
} else {
this.routing = routing;
}
return this;
}
/**
* Sets the parent id of this document. Will simply set the routing to this value, as it is only
* used for routing with delete requests.
*/
public UpdateRequest parent(String parent) {
if (routing == null) {
routing = parent;
}
return this;
}
/**
* Controls the shard routing of the request. Using this value to hash the shard
* and not the id.
*/
public String routing() {
return this.routing;
}
int shardId() {
return this.shardId;
}
public String script() {
return this.script;
}
public Map<String, Object> scriptParams() {
return this.scriptParams;
}
/**
* The script to execute. Note, make sure not to send different script each times and instead
* use script params if possible with the same (automatically compiled) script.
*/
public UpdateRequest script(String script) {
this.script = script;
return this;
}
/**
* The language of the script to execute.
*/
public UpdateRequest scriptLang(String scriptLang) {
this.scriptLang = scriptLang;
return this;
}
public String scriptLang() {
return scriptLang;
}
/**
* Add a script parameter.
*/
public UpdateRequest addScriptParam(String name, Object value) {
if (scriptParams == null) {
scriptParams = Maps.newHashMap();
}
scriptParams.put(name, value);
return this;
}
/**
* Sets the script parameters to use with the script.
*/
public UpdateRequest scriptParams(Map<String, Object> scriptParams) {
if (this.scriptParams == null) {
this.scriptParams = scriptParams;
} else {
this.scriptParams.putAll(scriptParams);
}
return this;
}
/**
* The script to execute. Note, make sure not to send different script each times and instead
* use script params if possible with the same (automatically compiled) script.
*/
public UpdateRequest script(String script, @Nullable Map<String, Object> scriptParams) {
this.script = script;
if (this.scriptParams != null) {
this.scriptParams.putAll(scriptParams);
} else {
this.scriptParams = scriptParams;
}
return this;
}
/**
* The script to execute. Note, make sure not to send different script each times and instead
* use script params if possible with the same (automatically compiled) script.
*
* @param script The script to execute
* @param scriptLang The script language
* @param scriptParams The script parameters
*/
public UpdateRequest script(String script, @Nullable String scriptLang, @Nullable Map<String, Object> scriptParams) {
this.script = script;
this.scriptLang = scriptLang;
if (this.scriptParams != null) {
this.scriptParams.putAll(scriptParams);
} else {
this.scriptParams = scriptParams;
}
return this;
}
/**
* Explicitly specify the fields that will be returned. By default, nothing is returned.
*/
public UpdateRequest fields(String... fields) {
this.fields = fields;
return this;
}
/**
* Get the fields to be returned.
*/
public String[] fields() {
return this.fields;
}
/**
* Sets the number of retries of a version conflict occurs because the document was updated between
* getting it and updating it. Defaults to 0.
*/
public UpdateRequest retryOnConflict(int retryOnConflict) {
this.retryOnConflict = retryOnConflict;
return this;
}
public int retryOnConflict() {
return this.retryOnConflict;
}
/**
* Sets the version, which will cause the index operation to only be performed if a matching
* version exists and no changes happened on the doc since then.
*/
public UpdateRequest version(long version) {
this.version = version;
return this;
}
public long version() {
return this.version;
}
/**
* Sets the versioning type. Defaults to {@link VersionType#INTERNAL}.
*/
public UpdateRequest versionType(VersionType versionType) {
this.versionType = versionType;
return this;
}
public VersionType versionType() {
return this.versionType;
}
/**
* Should a refresh be executed post this update operation causing the operation to
* be searchable. Note, heavy indexing should not set this to <tt>true</tt>. Defaults
* to <tt>false</tt>.
*/
public UpdateRequest refresh(boolean refresh) {
this.refresh = refresh;
return this;
}
public boolean refresh() {
return this.refresh;
}
/**
* The replication type.
*/
public ReplicationType replicationType() {
return this.replicationType;
}
/**
* Sets the replication type.
*/
public UpdateRequest replicationType(ReplicationType replicationType) {
this.replicationType = replicationType;
return this;
}
public WriteConsistencyLevel consistencyLevel() {
return this.consistencyLevel;
}
/**
* Sets the consistency level of write. Defaults to {@link org.elasticsearch.action.WriteConsistencyLevel#DEFAULT}
*/
public UpdateRequest consistencyLevel(WriteConsistencyLevel consistencyLevel) {
this.consistencyLevel = consistencyLevel;
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(IndexRequest doc) {
this.doc = doc;
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(XContentBuilder source) {
safeDoc().source(source);
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(Map source) {
safeDoc().source(source);
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(Map source, XContentType contentType) {
safeDoc().source(source, contentType);
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(String source) {
safeDoc().source(source);
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(byte[] source) {
safeDoc().source(source);
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(byte[] source, int offset, int length) {
safeDoc().source(source, offset, length);
return this;
}
/**
* Sets the doc to use for updates when a script is not specified, the doc provided
* is a field and value pairs.
*/
public UpdateRequest doc(Object... source) {
safeDoc().source(source);
return this;
}
/**
* Sets the doc to use for updates when a script is not specified.
*/
public UpdateRequest doc(String field, Object value) {
safeDoc().source(field, value);
return this;
}
public IndexRequest doc() {
return this.doc;
}
private IndexRequest safeDoc() {
if (doc == null) {
doc = new IndexRequest();
}
return doc;
}
/**
* Sets the index request to be used if the document does not exists. Otherwise, a {@link org.elasticsearch.index.engine.DocumentMissingException}
* is thrown.
*/
public UpdateRequest upsert(IndexRequest upsertRequest) {
this.upsertRequest = upsertRequest;
return this;
}
/**
* Sets the doc source of the update request to be used when the document does not exists.
*/
public UpdateRequest upsert(XContentBuilder source) {
safeUpsertRequest().source(source);
return this;
}
/**
* Sets the doc source of the update request to be used when the document does not exists.
*/
public UpdateRequest upsert(Map source) {
safeUpsertRequest().source(source);
return this;
}
/**
* Sets the doc source of the update request to be used when the document does not exists.
*/
public UpdateRequest upsert(Map source, XContentType contentType) {
safeUpsertRequest().source(source, contentType);
return this;
}
/**
* Sets the doc source of the update request to be used when the document does not exists.
*/
public UpdateRequest upsert(String source) {
safeUpsertRequest().source(source);
return this;
}
/**
* Sets the doc source of the update request to be used when the document does not exists.
*/
public UpdateRequest upsert(byte[] source) {
safeUpsertRequest().source(source);
return this;
}
/**
* Sets the doc source of the update request to be used when the document does not exists.
*/
public UpdateRequest upsert(byte[] source, int offset, int length) {
safeUpsertRequest().source(source, offset, length);
return this;
}
/**
* Sets the doc source of the update request to be used when the document does not exists. The doc
* includes field and value pairs.
*/
public UpdateRequest upsert(Object... source) {
safeUpsertRequest().source(source);
return this;
}
public IndexRequest upsertRequest() {
return this.upsertRequest;
}
private IndexRequest safeUpsertRequest() {
if (upsertRequest == null) {
upsertRequest = new IndexRequest();
}
return upsertRequest;
}
public UpdateRequest source(XContentBuilder source) throws Exception {
return source(source.bytes());
}
public UpdateRequest source(byte[] source) throws Exception {
return source(source, 0, source.length);
}
public UpdateRequest source(byte[] source, int offset, int length) throws Exception {
return source(new BytesArray(source, offset, length));
}
public UpdateRequest source(BytesReference source) throws Exception {
XContentType xContentType = XContentFactory.xContentType(source);
XContentParser parser = XContentFactory.xContent(xContentType).createParser(source);
try {
XContentParser.Token t = parser.nextToken();
if (t == null) {
return this;
}
String currentFieldName = null;
while ((t = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (t == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if ("script".equals(currentFieldName)) {
script = parser.textOrNull();
} else if ("params".equals(currentFieldName)) {
scriptParams = parser.map();
} else if ("lang".equals(currentFieldName)) {
scriptLang = parser.text();
} else if ("upsert".equals(currentFieldName)) {
XContentBuilder builder = XContentFactory.contentBuilder(xContentType);
builder.copyCurrentStructure(parser);
safeUpsertRequest().source(builder);
} else if ("doc".equals(currentFieldName)) {
XContentBuilder docBuilder = XContentFactory.contentBuilder(xContentType);
docBuilder.copyCurrentStructure(parser);
safeDoc().source(docBuilder);
} else if ("doc_as_upsert".equals(currentFieldName)) {
docAsUpsert(parser.booleanValue());
}
}
} finally {
parser.close();
}
return this;
}
public boolean docAsUpsert() {
return this.docAsUpsert;
}
public void docAsUpsert(boolean shouldUpsertDoc) {
this.docAsUpsert = shouldUpsertDoc;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
replicationType = ReplicationType.fromId(in.readByte());
consistencyLevel = WriteConsistencyLevel.fromId(in.readByte());
type = in.readSharedString();
id = in.readString();
routing = in.readOptionalString();
script = in.readOptionalString();
scriptLang = in.readOptionalString();
scriptParams = in.readMap();
retryOnConflict = in.readVInt();
refresh = in.readBoolean();
if (in.readBoolean()) {
doc = new IndexRequest();
doc.readFrom(in);
}
int size = in.readInt();
if (size >= 0) {
fields = new String[size];
for (int i = 0; i < size; i++) {
fields[i] = in.readString();
}
}
if (in.readBoolean()) {
upsertRequest = new IndexRequest();
upsertRequest.readFrom(in);
}
docAsUpsert = in.readBoolean();
version = in.readLong();
versionType = VersionType.fromValue(in.readByte());
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeByte(replicationType.id());
out.writeByte(consistencyLevel.id());
out.writeSharedString(type);
out.writeString(id);
out.writeOptionalString(routing);
out.writeOptionalString(script);
out.writeOptionalString(scriptLang);
out.writeMap(scriptParams);
out.writeVInt(retryOnConflict);
out.writeBoolean(refresh);
if (doc == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
// make sure the basics are set
doc.index(index);
doc.type(type);
doc.id(id);
doc.writeTo(out);
}
if (fields == null) {
out.writeInt(-1);
} else {
out.writeInt(fields.length);
for (String field : fields) {
out.writeString(field);
}
}
if (upsertRequest == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
// make sure the basics are set
upsertRequest.index(index);
upsertRequest.type(type);
upsertRequest.id(id);
upsertRequest.writeTo(out);
}
out.writeBoolean(docAsUpsert);
out.writeLong(version);
out.writeByte(versionType.getValue());
}
} | 1no label
| src_main_java_org_elasticsearch_action_update_UpdateRequest.java |
1,558 | public static class Factory implements AllocationCommand.Factory<CancelAllocationCommand> {
@Override
public CancelAllocationCommand readFrom(StreamInput in) throws IOException {
return new CancelAllocationCommand(ShardId.readShardId(in), in.readString(), in.readBoolean());
}
@Override
public void writeTo(CancelAllocationCommand command, StreamOutput out) throws IOException {
command.shardId().writeTo(out);
out.writeString(command.node());
out.writeBoolean(command.allowPrimary());
}
@Override
public CancelAllocationCommand fromXContent(XContentParser parser) throws IOException {
String index = null;
int shardId = -1;
String nodeId = null;
boolean allowPrimary = false;
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if ("index".equals(currentFieldName)) {
index = parser.text();
} else if ("shard".equals(currentFieldName)) {
shardId = parser.intValue();
} else if ("node".equals(currentFieldName)) {
nodeId = parser.text();
} else if ("allow_primary".equals(currentFieldName) || "allowPrimary".equals(currentFieldName)) {
allowPrimary = parser.booleanValue();
} else {
throw new ElasticsearchParseException("[cancel] command does not support field [" + currentFieldName + "]");
}
} else {
throw new ElasticsearchParseException("[cancel] command does not support complex json tokens [" + token + "]");
}
}
if (index == null) {
throw new ElasticsearchParseException("[cancel] command missing the index parameter");
}
if (shardId == -1) {
throw new ElasticsearchParseException("[cancel] command missing the shard parameter");
}
if (nodeId == null) {
throw new ElasticsearchParseException("[cancel] command missing the node parameter");
}
return new CancelAllocationCommand(new ShardId(index, shardId), nodeId, allowPrimary);
}
@Override
public void toXContent(CancelAllocationCommand command, XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.startObject();
builder.field("index", command.shardId().index());
builder.field("shard", command.shardId().id());
builder.field("node", command.node());
builder.field("allow_primary", command.allowPrimary());
builder.endObject();
}
} | 0true
| src_main_java_org_elasticsearch_cluster_routing_allocation_command_CancelAllocationCommand.java |
199 | public interface ClientConnectionManager {
void shutdown();
void start();
ClientConnection tryToConnect(Address address) throws Exception;
ClientConnection ownerConnection(Address address) throws Exception;
boolean removeEventHandler(Integer callId);
} | 0true
| hazelcast-client_src_main_java_com_hazelcast_client_connection_ClientConnectionManager.java |
3,612 | public class TransactionManagerServiceImpl implements TransactionManagerService, ManagedService,
MembershipAwareService, ClientAwareService {
public static final String SERVICE_NAME = "hz:core:txManagerService";
public static final int RECOVER_TIMEOUT = 5000;
private final NodeEngineImpl nodeEngine;
private final ILogger logger;
private final ConcurrentMap<String, TxBackupLog> txBackupLogs = new ConcurrentHashMap<String, TxBackupLog>();
private final ConcurrentMap<SerializableXID, Transaction>
managedTransactions = new ConcurrentHashMap<SerializableXID, Transaction>();
private final ConcurrentMap<SerializableXID, RecoveredTransaction>
clientRecoveredTransactions = new ConcurrentHashMap<SerializableXID, RecoveredTransaction>();
public TransactionManagerServiceImpl(NodeEngineImpl nodeEngine) {
this.nodeEngine = nodeEngine;
logger = nodeEngine.getLogger(TransactionManagerService.class);
}
@Override
public <T> T executeTransaction(TransactionOptions options, TransactionalTask<T> task) throws TransactionException {
if (task == null) {
throw new NullPointerException("TransactionalTask is required!");
}
final TransactionContextImpl context = new TransactionContextImpl(this, nodeEngine, options, null);
context.beginTransaction();
try {
final T value = task.execute(context);
context.commitTransaction();
return value;
} catch (Throwable e) {
context.rollbackTransaction();
if (e instanceof TransactionException) {
throw (TransactionException) e;
}
if (e.getCause() instanceof TransactionException) {
throw (TransactionException) e.getCause();
}
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new TransactionException(e);
}
}
@Override
public TransactionContext newTransactionContext(TransactionOptions options) {
return new TransactionContextImpl(this, nodeEngine, options, null);
}
@Override
public TransactionContext newClientTransactionContext(TransactionOptions options, String clientUuid) {
return new TransactionContextImpl(this, nodeEngine, options, clientUuid);
}
@Override
public void init(NodeEngine nodeEngine, Properties properties) {
}
@Override
public void reset() {
txBackupLogs.clear();
}
@Override
public void shutdown(boolean terminate) {
reset();
}
@Override
public void memberAdded(MembershipServiceEvent event) {
}
public void addClientRecoveredTransaction(RecoveredTransaction rt) {
clientRecoveredTransactions.put(rt.getXid(), rt);
}
public void recoverClientTransaction(SerializableXID sXid, boolean commit) {
final RecoveredTransaction rt = clientRecoveredTransactions.remove(sXid);
if (rt == null) {
return;
}
TransactionImpl tx = new TransactionImpl(this, nodeEngine, rt.getTxnId(), rt.getTxLogs(),
rt.getTimeoutMillis(), rt.getStartTime(), rt.getCallerUuid());
if (commit) {
try {
tx.commit();
} catch (Throwable e) {
logger.warning("Error during committing recovered client transaction!", e);
}
} else {
try {
tx.rollback();
} catch (Throwable e) {
logger.warning("Error during rolling-back recovered client transaction!", e);
}
}
}
@Override
public void memberRemoved(MembershipServiceEvent event) {
final MemberImpl member = event.getMember();
String uuid = member.getUuid();
finalizeTransactionsOf(uuid);
}
@Override
public void memberAttributeChanged(MemberAttributeServiceEvent event) {
}
public void addManagedTransaction(Xid xid, Transaction transaction) {
final SerializableXID sXid = new SerializableXID(xid.getFormatId(),
xid.getGlobalTransactionId(), xid.getBranchQualifier());
((TransactionImpl) transaction).setXid(sXid);
managedTransactions.put(sXid, transaction);
}
public Transaction getManagedTransaction(Xid xid) {
final SerializableXID sXid = new SerializableXID(xid.getFormatId(),
xid.getGlobalTransactionId(), xid.getBranchQualifier());
return managedTransactions.get(sXid);
}
public void removeManagedTransaction(Xid xid) {
final SerializableXID sXid = new SerializableXID(xid.getFormatId(),
xid.getGlobalTransactionId(), xid.getBranchQualifier());
managedTransactions.remove(sXid);
}
private void finalizeTransactionsOf(String uuid) {
for (Map.Entry<String, TxBackupLog> entry : txBackupLogs.entrySet()) {
finalize(uuid, entry.getKey(), entry.getValue());
}
}
private void finalize(String uuid, String txnId, TxBackupLog log) {
OperationService operationService = nodeEngine.getOperationService();
if (!uuid.equals(log.callerUuid)) {
return;
}
//TODO shouldn't we remove TxBackupLog from map ?
if (log.state == State.ACTIVE) {
Collection<MemberImpl> memberList = nodeEngine.getClusterService().getMemberList();
Collection<Future> futures = new ArrayList<Future>(memberList.size());
for (MemberImpl member : memberList) {
Operation op = new BroadcastTxRollbackOperation(txnId);
Future f = operationService.invokeOnTarget(SERVICE_NAME, op, member.getAddress());
futures.add(f);
}
for (Future future : futures) {
try {
future.get(TransactionOptions.getDefault().getTimeoutMillis(), TimeUnit.MILLISECONDS);
} catch (Exception e) {
logger.warning("Error while rolling-back tx!");
}
}
} else {
if (log.state == State.COMMITTING && log.xid != null) {
logger.warning("This log is XA Managed " + log);
//Marking for recovery
log.state = State.NO_TXN;
return;
}
TransactionImpl tx = new TransactionImpl(this, nodeEngine, txnId, log.txLogs,
log.timeoutMillis, log.startTime, log.callerUuid);
if (log.state == State.COMMITTING) {
try {
tx.commit();
} catch (Throwable e) {
logger.warning("Error during committing from tx backup!", e);
}
} else {
try {
tx.rollback();
} catch (Throwable e) {
logger.warning("Error during rolling-back from tx backup!", e);
}
}
}
}
@Override
public void clientDisconnected(String clientUuid) {
finalizeTransactionsOf(clientUuid);
}
Address[] pickBackupAddresses(int durability) {
final ClusterService clusterService = nodeEngine.getClusterService();
final List<MemberImpl> members = new ArrayList<MemberImpl>(clusterService.getMemberList());
members.remove(nodeEngine.getLocalMember());
final int c = Math.min(members.size(), durability);
Collections.shuffle(members);
Address[] addresses = new Address[c];
for (int i = 0; i < c; i++) {
addresses[i] = members.get(i).getAddress();
}
return addresses;
}
public void addTxBackupLogForClientRecovery(Transaction transaction) {
TransactionImpl txnImpl = (TransactionImpl) transaction;
final String callerUuid = txnImpl.getOwnerUuid();
final SerializableXID xid = txnImpl.getXid();
final List<TransactionLog> txLogs = txnImpl.getTxLogs();
final long timeoutMillis = txnImpl.getTimeoutMillis();
final long startTime = txnImpl.getStartTime();
TxBackupLog log = new TxBackupLog(txLogs, callerUuid, State.COMMITTING, timeoutMillis, startTime, xid);
txBackupLogs.put(txnImpl.getTxnId(), log);
}
void beginTxBackupLog(String callerUuid, String txnId, SerializableXID xid) {
TxBackupLog log
= new TxBackupLog(Collections.<TransactionLog>emptyList(), callerUuid, State.ACTIVE, -1, -1, xid);
if (txBackupLogs.putIfAbsent(txnId, log) != null) {
throw new TransactionException("TxLog already exists!");
}
}
void prepareTxBackupLog(List<TransactionLog> txLogs, String callerUuid, String txnId,
long timeoutMillis, long startTime) {
TxBackupLog beginLog = txBackupLogs.get(txnId);
if (beginLog == null) {
throw new TransactionException("Could not find begin tx log!");
}
if (beginLog.state != State.ACTIVE) {
throw new TransactionException("TxLog already exists!");
}
TxBackupLog newTxBackupLog
= new TxBackupLog(txLogs, callerUuid, State.COMMITTING, timeoutMillis, startTime, beginLog.xid);
if (!txBackupLogs.replace(txnId, beginLog, newTxBackupLog)) {
throw new TransactionException("TxLog already exists!");
}
}
void rollbackTxBackupLog(String txnId) {
final TxBackupLog log = txBackupLogs.get(txnId);
if (log != null) {
log.state = State.ROLLING_BACK;
} else {
logger.warning("No tx backup log is found, tx -> " + txnId);
}
}
void purgeTxBackupLog(String txnId) {
txBackupLogs.remove(txnId);
}
public Xid[] recover() {
List<Future<SerializableCollection>> futures = invokeRecoverOperations();
Set<SerializableXID> xidSet = new HashSet<SerializableXID>();
for (Future<SerializableCollection> future : futures) {
try {
final SerializableCollection collectionWrapper = future.get(RECOVER_TIMEOUT, TimeUnit.MILLISECONDS);
for (Data data : collectionWrapper) {
final RecoveredTransaction rt = (RecoveredTransaction) nodeEngine.toObject(data);
final SerializableXID xid = rt.getXid();
TransactionImpl tx = new TransactionImpl(this, nodeEngine, rt.getTxnId(), rt.getTxLogs(),
rt.getTimeoutMillis(), rt.getStartTime(), rt.getCallerUuid());
tx.setXid(xid);
xidSet.add(xid);
managedTransactions.put(xid, tx);
}
} catch (MemberLeftException e) {
logger.warning("Member left while recovering: " + e);
} catch (Throwable e) {
if (e instanceof ExecutionException) {
e = e.getCause() != null ? e.getCause() : e;
}
if (e instanceof TargetNotMemberException) {
nodeEngine.getLogger(Transaction.class).warning("Member left while recovering: " + e);
} else {
throw ExceptionUtil.rethrow(e);
}
}
}
final Set<RecoveredTransaction> localSet = recoverLocal();
for (RecoveredTransaction rt : localSet) {
xidSet.add(rt.getXid());
}
return xidSet.toArray(new Xid[xidSet.size()]);
}
private List<Future<SerializableCollection>> invokeRecoverOperations() {
final OperationService operationService = nodeEngine.getOperationService();
final ClusterService clusterService = nodeEngine.getClusterService();
final Collection<MemberImpl> memberList = clusterService.getMemberList();
List<Future<SerializableCollection>> futures
= new ArrayList<Future<SerializableCollection>>(memberList.size() - 1);
for (MemberImpl member : memberList) {
if (member.localMember()) {
continue;
}
final Future f = operationService.createInvocationBuilder(TransactionManagerServiceImpl.SERVICE_NAME,
new RecoverTxnOperation(), member.getAddress()).invoke();
futures.add(f);
}
return futures;
}
public Set<RecoveredTransaction> recoverLocal() {
Set<RecoveredTransaction> recovered = new HashSet<RecoveredTransaction>();
if (!txBackupLogs.isEmpty()) {
final Set<Map.Entry<String, TxBackupLog>> entries = txBackupLogs.entrySet();
final Iterator<Map.Entry<String, TxBackupLog>> iter = entries.iterator();
while (iter.hasNext()) {
final Map.Entry<String, TxBackupLog> entry = iter.next();
final TxBackupLog log = entry.getValue();
final String txnId = entry.getKey();
if (log.state == State.NO_TXN && log.xid != null) {
final RecoveredTransaction rt = new RecoveredTransaction();
rt.setTxLogs(log.txLogs);
rt.setXid(log.xid);
rt.setCallerUuid(log.callerUuid);
rt.setStartTime(log.startTime);
rt.setTimeoutMillis(log.timeoutMillis);
rt.setTxnId(txnId);
recovered.add(rt);
iter.remove();
}
}
}
return recovered;
}
private static final class TxBackupLog {
private final List<TransactionLog> txLogs;
private final String callerUuid;
private final long timeoutMillis;
private final long startTime;
private final SerializableXID xid;
private volatile State state;
private TxBackupLog(List<TransactionLog> txLogs, String callerUuid, State state, long timeoutMillis,
long startTime, SerializableXID xid) {
this.txLogs = txLogs;
this.callerUuid = callerUuid;
this.state = state;
this.timeoutMillis = timeoutMillis;
this.startTime = startTime;
this.xid = xid;
}
}
} | 1no label
| hazelcast_src_main_java_com_hazelcast_transaction_impl_TransactionManagerServiceImpl.java |
798 | public abstract class AbstractAlterRequest extends PartitionClientRequest implements Portable, SecureRequest {
protected String name;
protected Data function;
public AbstractAlterRequest() {
}
public AbstractAlterRequest(String name, Data function) {
this.name = name;
this.function = function;
}
@Override
protected int getPartition() {
ClientEngine clientEngine = getClientEngine();
Data key = clientEngine.getSerializationService().toData(name);
return getClientEngine().getPartitionService().getPartitionId(key);
}
@Override
public String getServiceName() {
return AtomicLongService.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return AtomicLongPortableHook.F_ID;
}
@Override
public void write(PortableWriter writer) throws IOException {
writer.writeUTF("n", name);
ObjectDataOutput out = writer.getRawDataOutput();
writeNullableData(out, function);
}
@Override
public void read(PortableReader reader) throws IOException {
name = reader.readUTF("n");
ObjectDataInput in = reader.getRawDataInput();
function = readNullableData(in);
}
protected IFunction<Long, Long> getFunction() {
SerializationService serializationService = getClientEngine().getSerializationService();
//noinspection unchecked
return (IFunction<Long, Long>) serializationService.toObject(function);
}
@Override
public Permission getRequiredPermission() {
return new AtomicLongPermission(name, ActionConstants.ACTION_MODIFY);
}
} | 0true
| hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_client_AbstractAlterRequest.java |
3,756 | public final class IndexUpgraderMergePolicy extends MergePolicy {
private final MergePolicy delegate;
/** @param delegate the merge policy to wrap */
public IndexUpgraderMergePolicy(MergePolicy delegate) {
this.delegate = delegate;
}
/** Return an "upgraded" view of the reader. */
static AtomicReader filter(AtomicReader reader) throws IOException {
final FieldInfos fieldInfos = reader.getFieldInfos();
final FieldInfo versionInfo = fieldInfos.fieldInfo(VersionFieldMapper.NAME);
if (versionInfo != null && versionInfo.hasDocValues()) {
// the reader is a recent one, it has versions and they are stored
// in a numeric doc values field
return reader;
}
// The segment is an old one, load all versions in memory and hide
// them behind a numeric doc values field
final Terms terms = reader.terms(UidFieldMapper.NAME);
if (terms == null || !terms.hasPayloads()) {
// The segment doesn't have an _uid field or doesn't have paylods
// don't try to do anything clever. If any other segment has versions
// all versions of this segment will be initialized to 0
return reader;
}
final TermsEnum uids = terms.iterator(null);
final GrowableWriter versions = new GrowableWriter(2, reader.maxDoc(), PackedInts.DEFAULT);
DocsAndPositionsEnum dpe = null;
for (BytesRef uid = uids.next(); uid != null; uid = uids.next()) {
dpe = uids.docsAndPositions(reader.getLiveDocs(), dpe, DocsAndPositionsEnum.FLAG_PAYLOADS);
assert dpe != null : "field has payloads";
for (int doc = dpe.nextDoc(); doc != DocsEnum.NO_MORE_DOCS; doc = dpe.nextDoc()) {
dpe.nextPosition();
final BytesRef payload = dpe.getPayload();
if (payload != null && payload.length == 8) {
final long version = Numbers.bytesToLong(payload);
versions.set(doc, version);
break;
}
}
}
// Build new field infos, doc values, and return a filter reader
final FieldInfo newVersionInfo;
if (versionInfo == null) {
// Find a free field number
int fieldNumber = 0;
for (FieldInfo fi : fieldInfos) {
fieldNumber = Math.max(fieldNumber, fi.number + 1);
}
newVersionInfo = new FieldInfo(VersionFieldMapper.NAME, false, fieldNumber, false, true, false,
IndexOptions.DOCS_ONLY, DocValuesType.NUMERIC, DocValuesType.NUMERIC, Collections.<String, String>emptyMap());
} else {
newVersionInfo = new FieldInfo(VersionFieldMapper.NAME, versionInfo.isIndexed(), versionInfo.number,
versionInfo.hasVectors(), versionInfo.omitsNorms(), versionInfo.hasPayloads(),
versionInfo.getIndexOptions(), versionInfo.getDocValuesType(), versionInfo.getNormType(), versionInfo.attributes());
}
final ArrayList<FieldInfo> fieldInfoList = new ArrayList<FieldInfo>();
for (FieldInfo info : fieldInfos) {
if (info != versionInfo) {
fieldInfoList.add(info);
}
}
fieldInfoList.add(newVersionInfo);
final FieldInfos newFieldInfos = new FieldInfos(fieldInfoList.toArray(new FieldInfo[fieldInfoList.size()]));
final NumericDocValues versionValues = new NumericDocValues() {
@Override
public long get(int index) {
return versions.get(index);
}
};
return new FilterAtomicReader(reader) {
@Override
public FieldInfos getFieldInfos() {
return newFieldInfos;
}
@Override
public NumericDocValues getNumericDocValues(String field) throws IOException {
if (VersionFieldMapper.NAME.equals(field)) {
return versionValues;
}
return super.getNumericDocValues(field);
}
@Override
public Bits getDocsWithField(String field) throws IOException {
return new Bits.MatchAllBits(in.maxDoc());
}
};
}
static class IndexUpgraderOneMerge extends OneMerge {
public IndexUpgraderOneMerge(List<SegmentCommitInfo> segments) {
super(segments);
}
@Override
public List<AtomicReader> getMergeReaders() throws IOException {
final List<AtomicReader> readers = super.getMergeReaders();
ImmutableList.Builder<AtomicReader> newReaders = ImmutableList.builder();
for (AtomicReader reader : readers) {
newReaders.add(filter(reader));
}
return newReaders.build();
}
}
static class IndexUpgraderMergeSpecification extends MergeSpecification {
@Override
public void add(OneMerge merge) {
super.add(new IndexUpgraderOneMerge(merge.segments));
}
@Override
public String segString(Directory dir) {
return "IndexUpgraderMergeSpec[" + super.segString(dir) + "]";
}
}
static MergeSpecification upgradedMergeSpecification(MergeSpecification spec) {
if (spec == null) {
return null;
}
MergeSpecification upgradedSpec = new IndexUpgraderMergeSpecification();
for (OneMerge merge : spec.merges) {
upgradedSpec.add(merge);
}
return upgradedSpec;
}
@Override
public MergeSpecification findMerges(MergeTrigger mergeTrigger,
SegmentInfos segmentInfos) throws IOException {
return upgradedMergeSpecification(delegate.findMerges(mergeTrigger, segmentInfos));
}
@Override
public MergeSpecification findForcedMerges(SegmentInfos segmentInfos,
int maxSegmentCount, Map<SegmentCommitInfo,Boolean> segmentsToMerge)
throws IOException {
return upgradedMergeSpecification(delegate.findForcedMerges(segmentInfos, maxSegmentCount, segmentsToMerge));
}
@Override
public MergeSpecification findForcedDeletesMerges(SegmentInfos segmentInfos)
throws IOException {
return upgradedMergeSpecification(delegate.findForcedDeletesMerges(segmentInfos));
}
@Override
public MergePolicy clone() {
return new IndexUpgraderMergePolicy(delegate.clone());
}
@Override
public void close() {
delegate.close();
}
@Override
public boolean useCompoundFile(SegmentInfos segments,
SegmentCommitInfo newSegment) throws IOException {
return delegate.useCompoundFile(segments, newSegment);
}
@Override
public void setIndexWriter(IndexWriter writer) {
delegate.setIndexWriter(writer);
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + delegate + ")";
}
} | 0true
| src_main_java_org_elasticsearch_index_merge_policy_IndexUpgraderMergePolicy.java |
29 | public class FeedIDKeyCreator implements SecondaryKeyCreator {
private TupleBinding<?> keyBinding;
FeedIDKeyCreator(TupleBinding<?> keyBinding) {
this.keyBinding = keyBinding;
}
@Override
public boolean createSecondaryKey(SecondaryDatabase secDb, DatabaseEntry keyEntry, DatabaseEntry valueEntry,
DatabaseEntry resultEntry) throws DatabaseException {
KeyValue kv = KeyValue.class.cast(keyBinding.entryToObject(keyEntry));
String feedID = kv.getFeedID();
TupleOutput to = new TupleOutput();
to.writeString(feedID);
resultEntry.setData(to.getBufferBytes());
return true;
}
} | 0true
| timeSequenceFeedAggregator_src_main_java_gov_nasa_arc_mct_buffer_disk_internal_FeedIDKeyCreator.java |
147 | public class AbstractKCVSTest {
protected static final TimestampProvider times = Timestamps.MICRO;
protected StandardBaseTransactionConfig getTxConfig() {
return StandardBaseTransactionConfig.of(times);
}
protected StandardBaseTransactionConfig getConsistentTxConfig(StoreManager manager) {
return StandardBaseTransactionConfig.of(times,manager.getFeatures().getKeyConsistentTxConfig());
}
} | 0true
| titan-test_src_main_java_com_thinkaurelius_titan_diskstorage_AbstractKCVSTest.java |
1,401 | @XmlRootElement(name = "orderItemAttribute")
@XmlAccessorType(value = XmlAccessType.FIELD)
public class OrderItemAttributeWrapper extends BaseWrapper implements
APIWrapper<OrderItemAttribute> {
@XmlElement
protected Long id;
@XmlElement
protected String name;
@XmlElement
protected String value;
@XmlElement
protected Long orderItemId;
@Override
public void wrapDetails(OrderItemAttribute model, HttpServletRequest request) {
this.id = model.getId();
this.name = model.getName();
this.value = model.getValue();
this.orderItemId = model.getOrderItem().getId();
}
@Override
public void wrapSummary(OrderItemAttribute model, HttpServletRequest request) {
wrapDetails(model, request);
}
} | 0true
| core_broadleaf-framework-web_src_main_java_org_broadleafcommerce_core_web_api_wrapper_OrderItemAttributeWrapper.java |
2,599 | private class MasterPinger implements Runnable {
private volatile boolean running = true;
public void stop() {
this.running = false;
}
@Override
public void run() {
if (!running) {
// return and don't spawn...
return;
}
final DiscoveryNode masterToPing = masterNode;
if (masterToPing == null) {
// master is null, should not happen, but we are still running, so reschedule
threadPool.schedule(pingInterval, ThreadPool.Names.SAME, MasterPinger.this);
return;
}
transportService.sendRequest(masterToPing, MasterPingRequestHandler.ACTION, new MasterPingRequest(nodesProvider.nodes().localNode().id(), masterToPing.id()), options().withType(TransportRequestOptions.Type.PING).withTimeout(pingRetryTimeout),
new BaseTransportResponseHandler<MasterPingResponseResponse>() {
@Override
public MasterPingResponseResponse newInstance() {
return new MasterPingResponseResponse();
}
@Override
public void handleResponse(MasterPingResponseResponse response) {
if (!running) {
return;
}
// reset the counter, we got a good result
MasterFaultDetection.this.retryCount = 0;
// check if the master node did not get switched on us..., if it did, we simply return with no reschedule
if (masterToPing.equals(MasterFaultDetection.this.masterNode())) {
if (!response.connectedToMaster) {
logger.trace("[master] [{}] does not have us registered with it...", masterToPing);
notifyDisconnectedFromMaster();
}
// we don't stop on disconnection from master, we keep pinging it
threadPool.schedule(pingInterval, ThreadPool.Names.SAME, MasterPinger.this);
}
}
@Override
public void handleException(TransportException exp) {
if (!running) {
return;
}
if (exp instanceof ConnectTransportException) {
// ignore this one, we already handle it by registering a connection listener
return;
}
synchronized (masterNodeMutex) {
// check if the master node did not get switched on us...
if (masterToPing.equals(MasterFaultDetection.this.masterNode())) {
if (exp.getCause() instanceof NoLongerMasterException) {
logger.debug("[master] pinging a master {} that is no longer a master", masterNode);
notifyMasterFailure(masterToPing, "no longer master");
return;
} else if (exp.getCause() instanceof NotMasterException) {
logger.debug("[master] pinging a master {} that is not the master", masterNode);
notifyMasterFailure(masterToPing, "not master");
return;
} else if (exp.getCause() instanceof NodeDoesNotExistOnMasterException) {
logger.debug("[master] pinging a master {} but we do not exists on it, act as if its master failure", masterNode);
notifyMasterFailure(masterToPing, "do not exists on master, act as master failure");
return;
}
int retryCount = ++MasterFaultDetection.this.retryCount;
logger.trace("[master] failed to ping [{}], retry [{}] out of [{}]", exp, masterNode, retryCount, pingRetryCount);
if (retryCount >= pingRetryCount) {
logger.debug("[master] failed to ping [{}], tried [{}] times, each with maximum [{}] timeout", masterNode, pingRetryCount, pingRetryTimeout);
// not good, failure
notifyMasterFailure(masterToPing, "failed to ping, tried [" + pingRetryCount + "] times, each with maximum [" + pingRetryTimeout + "] timeout");
} else {
// resend the request, not reschedule, rely on send timeout
transportService.sendRequest(masterToPing, MasterPingRequestHandler.ACTION, new MasterPingRequest(nodesProvider.nodes().localNode().id(), masterToPing.id()), options().withType(TransportRequestOptions.Type.PING).withTimeout(pingRetryTimeout), this);
}
}
}
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
});
}
} | 1no label
| src_main_java_org_elasticsearch_discovery_zen_fd_MasterFaultDetection.java |
Subsets and Splits