Unnamed: 0
int64
0
6.45k
func
stringlengths
37
161k
target
class label
2 classes
project
stringlengths
33
167
730
ItemListener listener = new ItemListener() { @Override public void itemAdded(ItemEvent item) { send(item); } @Override public void itemRemoved(ItemEvent item) { send(item); } private void send(ItemEvent event) { if (endpoint.live()) { Data item = clientEngine.toData(event.getItem()); final ItemEventType eventType = event.getEventType(); final String uuid = event.getMember().getUuid(); PortableItemEvent portableItemEvent = new PortableItemEvent(item, eventType, uuid); endpoint.sendEvent(portableItemEvent, getCallId()); } } };
1no label
hazelcast_src_main_java_com_hazelcast_collection_client_CollectionAddListenerRequest.java
418
public class ClientLockProxy extends ClientProxy implements ILock { private volatile Data key; public ClientLockProxy(String instanceName, String serviceName, String objectId) { super(instanceName, serviceName, objectId); } @Deprecated public Object getKey() { return getName(); } public boolean isLocked() { IsLockedRequest request = new IsLockedRequest(getKeyData()); Boolean result = invoke(request); return result; } public boolean isLockedByCurrentThread() { IsLockedRequest request = new IsLockedRequest(getKeyData(), ThreadUtil.getThreadId()); Boolean result = invoke(request); return result; } public int getLockCount() { GetLockCountRequest request = new GetLockCountRequest(getKeyData()); return (Integer) invoke(request); } public long getRemainingLeaseTime() { GetRemainingLeaseRequest request = new GetRemainingLeaseRequest(getKeyData()); return (Long) invoke(request); } public void lock(long leaseTime, TimeUnit timeUnit) { shouldBePositive(leaseTime, "leaseTime"); LockRequest request = new LockRequest(getKeyData(), ThreadUtil.getThreadId(), getTimeInMillis(leaseTime, timeUnit), -1); invoke(request); } public void forceUnlock() { UnlockRequest request = new UnlockRequest(getKeyData(), ThreadUtil.getThreadId(), true); invoke(request); } public ICondition newCondition(String name) { return new ClientConditionProxy(instanceName, this, name, getContext()); } public void lock() { lock(Long.MAX_VALUE, null); } public void lockInterruptibly() throws InterruptedException { lock(); } public boolean tryLock() { try { return tryLock(0, null); } catch (InterruptedException e) { return false; } } public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { LockRequest request = new LockRequest(getKeyData(), ThreadUtil.getThreadId(), Long.MAX_VALUE, getTimeInMillis(time, unit)); Boolean result = invoke(request); return result; } public void unlock() { UnlockRequest request = new UnlockRequest(getKeyData(), ThreadUtil.getThreadId()); invoke(request); } public Condition newCondition() { throw new UnsupportedOperationException(); } protected void onDestroy() { } private Data getKeyData() { if (key == null) { key = toData(getName()); } return key; } private long getTimeInMillis(final long time, final TimeUnit timeunit) { return timeunit != null ? timeunit.toMillis(time) : time; } protected <T> T invoke(ClientRequest req) { return super.invoke(req, getKeyData()); } @Override public String toString() { return "ILock{" + "name='" + getName() + '\'' + '}'; } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_proxy_ClientLockProxy.java
1,369
public enum ClusterBlockLevel { READ(0), WRITE(1), METADATA(2); public static final ClusterBlockLevel[] ALL = new ClusterBlockLevel[]{READ, WRITE, METADATA}; public static final ClusterBlockLevel[] READ_WRITE = new ClusterBlockLevel[]{READ, WRITE}; private final int id; ClusterBlockLevel(int id) { this.id = id; } public int id() { return this.id; } public static ClusterBlockLevel fromId(int id) { if (id == 0) { return READ; } else if (id == 1) { return WRITE; } else if (id == 2) { return METADATA; } throw new ElasticsearchIllegalArgumentException("No cluster block level matching [" + id + "]"); } }
0true
src_main_java_org_elasticsearch_cluster_block_ClusterBlockLevel.java
758
public class ListIndexOfOperation extends CollectionOperation { private boolean last; private Data value; public ListIndexOfOperation() { } public ListIndexOfOperation(String name, boolean last, Data value) { super(name); this.last = last; this.value = value; } @Override public int getId() { return CollectionDataSerializerHook.LIST_INDEX_OF; } @Override public void beforeRun() throws Exception { } @Override public void run() throws Exception { response = getOrCreateListContainer().indexOf(last, value); } @Override public void afterRun() throws Exception { } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeBoolean(last); value.writeData(out); } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); last = in.readBoolean(); value = new Data(); value.readData(in); } }
0true
hazelcast_src_main_java_com_hazelcast_collection_list_ListIndexOfOperation.java
211
class HeartBeat implements Runnable { long begin; final int heartBeatTimeout = heartBeatInterval/2; @Override public void run() { if (!live) { return; } begin = Clock.currentTimeMillis(); final Map<ClientConnection, Future> futureMap = new HashMap<ClientConnection, Future>(); for (ClientConnection connection : connections.values()) { if (begin - connection.lastReadTime() > heartBeatTimeout) { final ClientPingRequest request = new ClientPingRequest(); final ICompletableFuture future = invocationService.send(request, connection); futureMap.put(connection, future); } else { connection.heartBeatingSucceed(); } } for (Map.Entry<ClientConnection, Future> entry : futureMap.entrySet()) { final Future future = entry.getValue(); final ClientConnection connection = entry.getKey(); try { future.get(getRemainingTimeout(), TimeUnit.MILLISECONDS); connection.heartBeatingSucceed(); } catch (Exception ignored) { connection.heartBeatingFailed(); } } } private long getRemainingTimeout() { long timeout = heartBeatTimeout - Clock.currentTimeMillis() + begin; return timeout < 0 ? 0 : timeout; } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientConnectionManagerImpl.java
19
abstract static class Completion extends AtomicInteger implements Runnable { }
0true
src_main_java_jsr166e_CompletableFuture.java
2,565
discovery.clusterService.submitStateUpdateTask("local-disco-receive(from master)", new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { ClusterState.Builder builder = ClusterState.builder(nodeSpecificClusterState); // if the routing table did not change, use the original one if (nodeSpecificClusterState.routingTable().version() == currentState.routingTable().version()) { builder.routingTable(currentState.routingTable()); } if (nodeSpecificClusterState.metaData().version() == currentState.metaData().version()) { builder.metaData(currentState.metaData()); } return builder.build(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); publishResponseHandler.onFailure(discovery.localNode, t); } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { sendInitialStateEventIfNeeded(); publishResponseHandler.onResponse(discovery.localNode); } });
1no label
src_main_java_org_elasticsearch_discovery_local_LocalDiscovery.java
440
static final class Fields { static final XContentBuilderString COUNT = new XContentBuilderString("count"); static final XContentBuilderString VERSIONS = new XContentBuilderString("versions"); static final XContentBuilderString OS = new XContentBuilderString("os"); static final XContentBuilderString PROCESS = new XContentBuilderString("process"); static final XContentBuilderString JVM = new XContentBuilderString("jvm"); static final XContentBuilderString FS = new XContentBuilderString("fs"); static final XContentBuilderString PLUGINS = new XContentBuilderString("plugins"); }
0true
src_main_java_org_elasticsearch_action_admin_cluster_stats_ClusterStatsNodes.java
81
{ @Override public Object doWork( Void state ) throws Exception { try ( Transaction tx = db.beginTx() ) { node.getRelationships(); tx.success(); } return null; } };
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestCacheUpdateDeadlock.java
743
public class ExplainRequest extends SingleShardOperationRequest<ExplainRequest> { private static final XContentType contentType = Requests.CONTENT_TYPE; private String type = "_all"; private String id; private String routing; private String preference; private BytesReference source; private boolean sourceUnsafe; private String[] fields; private FetchSourceContext fetchSourceContext; private String[] filteringAlias = Strings.EMPTY_ARRAY; long nowInMillis; ExplainRequest() { } public ExplainRequest(String index, String type, String id) { this.index = index; this.type = type; this.id = id; } public String type() { return type; } public ExplainRequest type(String type) { this.type = type; return this; } public String id() { return id; } public ExplainRequest id(String id) { this.id = id; return this; } public String routing() { return routing; } public ExplainRequest routing(String routing) { this.routing = routing; return this; } /** * Simple sets the routing. Since the parent is only used to get to the right shard. */ public ExplainRequest parent(String parent) { this.routing = parent; return this; } public String preference() { return preference; } public ExplainRequest preference(String preference) { this.preference = preference; return this; } public BytesReference source() { return source; } public boolean sourceUnsafe() { return sourceUnsafe; } public ExplainRequest source(QuerySourceBuilder sourceBuilder) { this.source = sourceBuilder.buildAsBytes(contentType); this.sourceUnsafe = false; return this; } public ExplainRequest source(BytesReference source, boolean unsafe) { this.source = source; this.sourceUnsafe = unsafe; return this; } /** * Allows setting the {@link FetchSourceContext} for this request, controlling if and how _source should be returned. */ public ExplainRequest fetchSourceContext(FetchSourceContext context) { this.fetchSourceContext = context; return this; } public FetchSourceContext fetchSourceContext() { return fetchSourceContext; } public String[] fields() { return fields; } public ExplainRequest fields(String[] fields) { this.fields = fields; return this; } public String[] filteringAlias() { return filteringAlias; } public ExplainRequest filteringAlias(String[] filteringAlias) { if (filteringAlias != null) { this.filteringAlias = filteringAlias; } return this; } @Override protected void beforeLocalFork() { if (sourceUnsafe) { source = source.copyBytesArray(); sourceUnsafe = false; } } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = super.validate(); if (type == null) { validationException = ValidateActions.addValidationError("type is missing", validationException); } if (id == null) { validationException = ValidateActions.addValidationError("id is missing", validationException); } if (source == null) { validationException = ValidateActions.addValidationError("source is missing", validationException); } return validationException; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); type = in.readString(); id = in.readString(); routing = in.readOptionalString(); preference = in.readOptionalString(); source = in.readBytesReference(); sourceUnsafe = false; filteringAlias = in.readStringArray(); if (in.readBoolean()) { fields = in.readStringArray(); } fetchSourceContext = FetchSourceContext.optionalReadFromStream(in); nowInMillis = in.readVLong(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(type); out.writeString(id); out.writeOptionalString(routing); out.writeOptionalString(preference); out.writeBytesReference(source); out.writeStringArray(filteringAlias); if (fields != null) { out.writeBoolean(true); out.writeStringArray(fields); } else { out.writeBoolean(false); } FetchSourceContext.optionalWriteToStream(fetchSourceContext, out); out.writeVLong(nowInMillis); } }
0true
src_main_java_org_elasticsearch_action_explain_ExplainRequest.java
209
private final class ConnectionProcessor implements Callable<ClientConnection> { final Address address; final Authenticator authenticator; final boolean isBlock; private ConnectionProcessor(final Address address, final Authenticator authenticator, final boolean isBlock) { this.address = address; this.authenticator = authenticator; this.isBlock = isBlock; } @Override public ClientConnection call() throws Exception { if (!live) { throw new HazelcastException("ConnectionManager is not active!!!"); } SocketChannel socketChannel = null; try { socketChannel = SocketChannel.open(); Socket socket = socketChannel.socket(); socket.setKeepAlive(socketOptions.isKeepAlive()); socket.setTcpNoDelay(socketOptions.isTcpNoDelay()); socket.setReuseAddress(socketOptions.isReuseAddress()); if (socketOptions.getLingerSeconds() > 0) { socket.setSoLinger(true, socketOptions.getLingerSeconds()); } int bufferSize = socketOptions.getBufferSize() * KILO_BYTE; if (bufferSize < 0) { bufferSize = BUFFER_SIZE; } socket.setSendBufferSize(bufferSize); socket.setReceiveBufferSize(bufferSize); socketChannel.socket().connect(address.getInetSocketAddress(), connectionTimeout); SocketChannelWrapper socketChannelWrapper = socketChannelWrapperFactory.wrapSocketChannel(socketChannel, true); final ClientConnection clientConnection = new ClientConnection(ClientConnectionManagerImpl.this, inSelector, outSelector, connectionIdGen.incrementAndGet(), socketChannelWrapper, executionService, invocationService); socketChannel.configureBlocking(true); if (socketInterceptor != null) { socketInterceptor.onConnect(socket); } authenticator.auth(clientConnection); socketChannel.configureBlocking(isBlock); socket.setSoTimeout(0); if (!isBlock) { clientConnection.getReadHandler().register(); } return clientConnection; } catch (Exception e) { if (socketChannel != null) { socketChannel.close(); } throw ExceptionUtil.rethrow(e); } } }
1no label
hazelcast-client_src_main_java_com_hazelcast_client_connection_nio_ClientConnectionManagerImpl.java
538
public class ORemoteFetchListener implements OFetchListener { final Set<ODocument> recordsToSend; public ORemoteFetchListener(final Set<ODocument> iRecordsToSend) { recordsToSend = iRecordsToSend; } public void processStandardField(ORecordSchemaAware<?> iRecord, Object iFieldValue, String iFieldName, OFetchContext iContext, final Object iusObject, final String iFormat) throws OFetchException { } public void parseLinked(ORecordSchemaAware<?> iRootRecord, OIdentifiable iLinked, Object iUserObject, String iFieldName, OFetchContext iContext) throws OFetchException { } public void parseLinkedCollectionValue(ORecordSchemaAware<?> iRootRecord, OIdentifiable iLinked, Object iUserObject, String iFieldName, OFetchContext iContext) throws OFetchException { } public Object fetchLinkedMapEntry(ORecordSchemaAware<?> iRoot, Object iUserObject, String iFieldName, String iKey, ORecordSchemaAware<?> iLinked, OFetchContext iContext) throws OFetchException { if (iLinked.getIdentity().isValid()) return recordsToSend.add((ODocument) iLinked) ? iLinked : null; return null; } public Object fetchLinkedCollectionValue(ORecordSchemaAware<?> iRoot, Object iUserObject, String iFieldName, ORecordSchemaAware<?> iLinked, OFetchContext iContext) throws OFetchException { if (iLinked.getIdentity().isValid()) return recordsToSend.add((ODocument) iLinked) ? iLinked : null; return null; } @SuppressWarnings("unchecked") public Object fetchLinked(ORecordSchemaAware<?> iRoot, Object iUserObject, String iFieldName, ORecordSchemaAware<?> iLinked, OFetchContext iContext) throws OFetchException { if (iLinked instanceof ODocument) return recordsToSend.add((ODocument) iLinked) ? iLinked : null; // HOW THIS CODE CAN HAVE SENSE? else if (iLinked instanceof Collection<?>) return recordsToSend.addAll((Collection<? extends ODocument>) iLinked) ? iLinked : null; // HOW THIS CODE CAN HAVE SENSE? else if (iLinked instanceof Map<?, ?>) return recordsToSend.addAll(((Map<String, ? extends ODocument>) iLinked).values()) ? iLinked : null; else throw new OFetchException("Unrecognized type while fetching records: " + iLinked); } }
1no label
core_src_main_java_com_orientechnologies_orient_core_fetch_remote_ORemoteFetchListener.java
83
public static class Order { public static final int File_Details = 2000; public static final int Advanced = 3000; }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_file_domain_StaticAssetImpl.java
937
transportService.sendRequest(node, transportShardAction, shardRequest, new BaseTransportResponseHandler<ShardResponse>() { @Override public ShardResponse newInstance() { return newShardResponse(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void handleResponse(ShardResponse response) { onOperation(shard, shardIndex, response); } @Override public void handleException(TransportException e) { onOperation(shard, shardIt, shardIndex, e); } });
0true
src_main_java_org_elasticsearch_action_support_broadcast_TransportBroadcastOperationAction.java
1,222
public abstract class OStorageAbstract extends OSharedContainerImpl implements OStorage { protected final String url; protected final String mode; protected OStorageConfiguration configuration; protected String name; protected AtomicLong version = new AtomicLong(); protected OLevel2RecordCache level2Cache; protected volatile STATUS status = STATUS.CLOSED; protected final OSharedResourceAdaptiveExternal lock; public OStorageAbstract(final String name, final String URL, final String mode, final int timeout, final OCacheLevelTwoLocator cacheLocator) { if (OStringSerializerHelper.contains(name, '/')) this.name = name.substring(name.lastIndexOf("/") + 1); else this.name = name; if (OStringSerializerHelper.contains(name, ',')) throw new IllegalArgumentException("Invalid character in storage name: " + this.name); level2Cache = new OLevel2RecordCache(this, cacheLocator); level2Cache.startup(); url = URL; this.mode = mode; lock = new OSharedResourceAdaptiveExternal(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean(), timeout, true); } public OStorage getUnderlying() { return this; } public OStorageConfiguration getConfiguration() { return configuration; } public boolean isClosed() { return status == STATUS.CLOSED; } public boolean checkForRecordValidity(final OPhysicalPosition ppos) { return ppos != null && !ppos.recordVersion.isTombstone() && ppos.dataSegmentId > -1; } public String getName() { return name; } /** * Returns the configured local Level-2 cache component. Cache component is always created even if not used. * * @return */ public OLevel2RecordCache getLevel2Cache() { return level2Cache; } public String getURL() { return url; } public void close() { close(false); } public void close(final boolean iForce) { if (!checkForClose(iForce)) return; lock.acquireExclusiveLock(); try { for (Object resource : sharedResources.values()) { if (resource instanceof OSharedResource) ((OSharedResource) resource).releaseExclusiveLock(); if (resource instanceof OCloseable) ((OCloseable) resource).close(); } sharedResources.clear(); Orient.instance().unregisterStorage(this); } finally { lock.releaseExclusiveLock(); } } /** * Returns current storage's version as serial. */ public long getVersion() { return version.get(); } public boolean dropCluster(final String iClusterName, final boolean iTruncate) { return dropCluster(getClusterIdByName(iClusterName), iTruncate); } protected boolean checkForClose(final boolean iForce) { lock.acquireSharedLock(); try { if (status == STATUS.CLOSED) return false; final int remainingUsers = getUsers() > 0 ? removeUser() : 0; return iForce || (!OGlobalConfiguration.STORAGE_KEEP_OPEN.getValueAsBoolean() && remainingUsers == 0); } finally { lock.releaseSharedLock(); } } public int getUsers() { return lock.getUsers(); } public int addUser() { return lock.addUser(); } public int removeUser() { return lock.removeUser(); } public OSharedResourceAdaptiveExternal getLock() { return lock; } public long countRecords() { long tot = 0; for (OCluster c : getClusterInstances()) if (c != null) tot += c.getEntries() - c.getTombstonesCount(); return tot; } public <V> V callInLock(final Callable<V> iCallable, final boolean iExclusiveLock) { if (iExclusiveLock) lock.acquireExclusiveLock(); else lock.acquireSharedLock(); try { return iCallable.call(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new OException("Error on nested call in lock", e); } finally { if (iExclusiveLock) lock.releaseExclusiveLock(); else lock.releaseSharedLock(); } } @Override public String toString() { return url != null ? url : "?"; } public STATUS getStatus() { return status; } public void checkForClusterPermissions(final String iClusterName) { // CHECK FOR ORESTRICTED OMetadata metaData = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata(); if (metaData != null) { final Set<OClass> classes = metaData.getSchema().getClassesRelyOnCluster(iClusterName); for (OClass c : classes) { if (c.isSubClassOf(OSecurityShared.RESTRICTED_CLASSNAME)) throw new OSecurityException("Class " + c.getName() + " cannot be truncated because has record level security enabled (extends " + OSecurityShared.RESTRICTED_CLASSNAME + ")"); } } } @Override public boolean isDistributed() { return false; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_storage_OStorageAbstract.java
351
private class StressThread extends Thread { private final AtomicInteger counter; private final AtomicInteger errors; public StressThread(AtomicInteger counter, AtomicInteger errors) { this.counter = counter; this.errors = errors; } public void run() { try { for(;;){ int index = counter.decrementAndGet(); if(index<=0){ return; } IMap<Object, Object> map = client.getMap("juka" + index); map.set("aaaa", "bbbb"); map.clear(); map.destroy(); if(index % 1000 == 0){ System.out.println("At: "+index); } } } catch (Throwable t) { errors.incrementAndGet(); t.printStackTrace(); } } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_map_MapMemoryUsageStressTest.java
470
final Object key = makeDbCall(databaseDocumentTxOne, new ODbRelatedCall<Object>() { public Object call() { return indexOneEntry.getKey(); } });
0true
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java
2,164
class BothIterator extends DocIdSetIterator { private final int maxDoc; private final Bits acceptDocs; private int doc = -1; BothIterator(int maxDoc, Bits acceptDocs) { this.maxDoc = maxDoc; this.acceptDocs = acceptDocs; } @Override public int docID() { return doc; } @Override public int nextDoc() { do { doc++; if (doc >= maxDoc) { return doc = NO_MORE_DOCS; } } while (!(matchDoc(doc) && acceptDocs.get(doc))); return doc; } @Override public int advance(int target) { for (doc = target; doc < maxDoc; doc++) { if (matchDoc(doc) && acceptDocs.get(doc)) { return doc; } } return doc = NO_MORE_DOCS; } @Override public long cost() { return maxDoc; } }
1no label
src_main_java_org_elasticsearch_common_lucene_docset_MatchDocIdSet.java
565
trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() { public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) { firedEvents.add(event); } });
0true
core_src_test_java_com_orientechnologies_orient_core_index_OCompositeIndexDefinitionTest.java
593
public class OIndexDefinitionFactory { private static final Pattern FILED_NAME_PATTERN = Pattern.compile("\\s+"); /** * Creates an instance of {@link OIndexDefinition} for automatic index. * * @param oClass * class which will be indexed * @param fieldNames * list of properties which will be indexed. Format should be '<property> [by key|value]', use 'by key' or 'by value' to * describe how to index maps. By default maps indexed by key * @param types * types of indexed properties * @return index definition instance */ public static OIndexDefinition createIndexDefinition(final OClass oClass, final List<String> fieldNames, final List<OType> types) { checkTypes(oClass, fieldNames, types); if (fieldNames.size() == 1) return createSingleFieldIndexDefinition(oClass, fieldNames.get(0), types.get(0)); else return createMultipleFieldIndexDefinition(oClass, fieldNames, types); } /** * Extract field name from '<property> [by key|value]' field format. * * @param fieldDefinition * definition of field * @return extracted property name */ public static String extractFieldName(final String fieldDefinition) { String[] fieldNameParts = FILED_NAME_PATTERN.split(fieldDefinition); if (fieldNameParts.length == 1) return fieldDefinition; if (fieldNameParts.length == 3 && "by".equalsIgnoreCase(fieldNameParts[1])) return fieldNameParts[0]; throw new IllegalArgumentException("Illegal field name format, should be '<property> [by key|value]' but was '" + fieldDefinition + '\''); } private static OIndexDefinition createMultipleFieldIndexDefinition(final OClass oClass, final List<String> fieldsToIndex, final List<OType> types) { final String className = oClass.getName(); final OCompositeIndexDefinition compositeIndex = new OCompositeIndexDefinition(className); for (int i = 0, fieldsToIndexSize = fieldsToIndex.size(); i < fieldsToIndexSize; i++) { compositeIndex.addIndex(createSingleFieldIndexDefinition(oClass, fieldsToIndex.get(i), types.get(i))); } return compositeIndex; } private static void checkTypes(OClass oClass, List<String> fieldNames, List<OType> types) { if (fieldNames.size() != types.size()) throw new IllegalArgumentException("Count of field names doesn't match count of field types. It was " + fieldNames.size() + " fields, but " + types.size() + " types."); for (int i = 0, fieldNamesSize = fieldNames.size(); i < fieldNamesSize; i++) { String fieldName = fieldNames.get(i); OType type = types.get(i); final OProperty property = oClass.getProperty(fieldName); if (property != null && !type.equals(property.getType())) { throw new IllegalArgumentException("Property type list not match with real property types"); } } } private static OIndexDefinition createSingleFieldIndexDefinition(OClass oClass, final String field, final OType type) { final String fieldName = adjustFieldName(oClass, extractFieldName(field)); final OIndexDefinition indexDefinition; final OType indexType; if (type == OType.EMBEDDEDMAP || type == OType.LINKMAP) { final OPropertyMapIndexDefinition.INDEX_BY indexBy = extractMapIndexSpecifier(field); if (indexBy.equals(OPropertyMapIndexDefinition.INDEX_BY.KEY)) indexType = OType.STRING; else { if (type == OType.LINKMAP) indexType = OType.LINK; else { final OProperty propertyToIndex = oClass.getProperty(fieldName); indexType = propertyToIndex.getLinkedType(); if (indexType == null) throw new OIndexException("Linked type was not provided." + " You should provide linked type for embedded collections that are going to be indexed."); } } indexDefinition = new OPropertyMapIndexDefinition(oClass.getName(), fieldName, indexType, indexBy); } else if (type.equals(OType.EMBEDDEDLIST) || type.equals(OType.EMBEDDEDSET) || type.equals(OType.LINKLIST) || type.equals(OType.LINKSET)) { if (type.equals(OType.LINKSET)) throw new OIndexException("LINKSET indexing is not supported."); else if (type.equals(OType.LINKLIST)) { indexType = OType.LINK; } else { final OProperty propertyToIndex = oClass.getProperty(fieldName); indexType = propertyToIndex.getLinkedType(); if (indexType == null) throw new OIndexException("Linked type was not provided." + " You should provide linked type for embedded collections that are going to be indexed."); } indexDefinition = new OPropertyListIndexDefinition(oClass.getName(), fieldName, indexType); } else indexDefinition = new OPropertyIndexDefinition(oClass.getName(), fieldName, type); return indexDefinition; } private static OPropertyMapIndexDefinition.INDEX_BY extractMapIndexSpecifier(final String fieldName) { String[] fieldNameParts = FILED_NAME_PATTERN.split(fieldName); if (fieldNameParts.length == 1) return OPropertyMapIndexDefinition.INDEX_BY.KEY; if (fieldNameParts.length == 3) { if ("by".equals(fieldNameParts[1].toLowerCase())) try { return OPropertyMapIndexDefinition.INDEX_BY.valueOf(fieldNameParts[2].toUpperCase()); } catch (IllegalArgumentException iae) { throw new IllegalArgumentException("Illegal field name format, should be '<property> [by key|value]' but was '" + fieldName + '\''); } } throw new IllegalArgumentException("Illegal field name format, should be '<property> [by key|value]' but was '" + fieldName + '\''); } private static String adjustFieldName(final OClass clazz, final String fieldName) { final OProperty property = clazz.getProperty(fieldName); if (property != null) return property.getName(); else return fieldName; } }
0true
core_src_main_java_com_orientechnologies_orient_core_index_OIndexDefinitionFactory.java
129
public class LongAdderTable<K> implements Serializable { /** Relies on default serialization */ private static final long serialVersionUID = 7249369246863182397L; /** The underlying map */ private final ConcurrentHashMapV8<K, LongAdder> map; static final class CreateAdder implements ConcurrentHashMapV8.Fun<Object, LongAdder> { public LongAdder apply(Object unused) { return new LongAdder(); } } private static final CreateAdder createAdder = new CreateAdder(); /** * Creates a new empty table. */ public LongAdderTable() { map = new ConcurrentHashMapV8<K, LongAdder>(); } /** * If the given key does not already exist in the table, inserts * the key with initial sum of zero; in either case returning the * adder associated with this key. * * @param key the key * @return the adder associated with the key */ public LongAdder install(K key) { return map.computeIfAbsent(key, createAdder); } /** * Adds the given value to the sum associated with the given * key. If the key does not already exist in the table, it is * inserted. * * @param key the key * @param x the value to add */ public void add(K key, long x) { map.computeIfAbsent(key, createAdder).add(x); } /** * Increments the sum associated with the given key. If the key * does not already exist in the table, it is inserted. * * @param key the key */ public void increment(K key) { add(key, 1L); } /** * Decrements the sum associated with the given key. If the key * does not already exist in the table, it is inserted. * * @param key the key */ public void decrement(K key) { add(key, -1L); } /** * Returns the sum associated with the given key, or zero if the * key does not currently exist in the table. * * @param key the key * @return the sum associated with the key, or zero if the key is * not in the table */ public long sum(K key) { LongAdder a = map.get(key); return a == null ? 0L : a.sum(); } /** * Resets the sum associated with the given key to zero if the key * exists in the table. This method does <em>NOT</em> add or * remove the key from the table (see {@link #remove}). * * @param key the key */ public void reset(K key) { LongAdder a = map.get(key); if (a != null) a.reset(); } /** * Resets the sum associated with the given key to zero if the key * exists in the table. This method does <em>NOT</em> add or * remove the key from the table (see {@link #remove}). * * @param key the key * @return the previous sum, or zero if the key is not * in the table */ public long sumThenReset(K key) { LongAdder a = map.get(key); return a == null ? 0L : a.sumThenReset(); } /** * Returns the sum totalled across all keys. * * @return the sum totalled across all keys */ public long sumAll() { long sum = 0L; for (LongAdder a : map.values()) sum += a.sum(); return sum; } /** * Resets the sum associated with each key to zero. */ public void resetAll() { for (LongAdder a : map.values()) a.reset(); } /** * Totals, then resets, the sums associated with all keys. * * @return the sum totalled across all keys */ public long sumThenResetAll() { long sum = 0L; for (LongAdder a : map.values()) sum += a.sumThenReset(); return sum; } /** * Removes the given key from the table. * * @param key the key */ public void remove(K key) { map.remove(key); } /** * Removes all keys from the table. */ public void removeAll() { map.clear(); } /** * Returns the current set of keys. * * @return the current set of keys */ public Set<K> keySet() { return map.keySet(); } /** * Returns the current set of key-value mappings. * * @return the current set of key-value mappings */ public Set<Map.Entry<K,LongAdder>> entrySet() { return map.entrySet(); } }
0true
src_main_java_jsr166e_LongAdderTable.java
6,270
public class IsFalseAssertion extends Assertion { private static final ESLogger logger = Loggers.getLogger(IsFalseAssertion.class); public IsFalseAssertion(String field) { super(field, false); } @Override @SuppressWarnings("unchecked") protected void doAssert(Object actualValue, Object expectedValue) { logger.trace("assert that [{}] doesn't have a true value", actualValue); if (actualValue == null) { return; } String actualString = actualValue.toString(); assertThat(errorMessage(), actualString, anyOf( equalTo(""), equalToIgnoringCase(Boolean.FALSE.toString()), equalTo("0") )); } private String errorMessage() { return "field [" + getField() + "] has a true value but it shouldn't"; } }
1no label
src_test_java_org_elasticsearch_test_rest_section_IsFalseAssertion.java
10
CollectionUtils.collect(values, new Transformer() { @Override public Object transform(Object input) { return ((ProductOptionValue) input).getAttributeValue(); } }, stringValues);
0true
admin_broadleaf-admin-module_src_main_java_org_broadleafcommerce_admin_server_service_handler_SkuCustomPersistenceHandler.java
484
new ODbRelatedCall<Iterator<? extends OIndex<?>>>() { public Iterator<? extends OIndex<?>> call() { return indexesOne.iterator(); } });
0true
core_src_main_java_com_orientechnologies_orient_core_db_tool_ODatabaseCompare.java
285
public static class Config { // this is to keep backward compatibility with JDK 1.6, can be changed to ThreadLocalRandom once we fully switch private static final ThreadLocal<Random> THREAD_LOCAL_RANDOM = new ThreadLocal<Random>() { @Override public Random initialValue() { return new Random(); } }; private final String[] hostnames; private final int port; private final String username; private final String password; private int timeoutMS; private int frameSize; private String sslTruststoreLocation; private String sslTruststorePassword; private boolean isBuilt; public Config(String[] hostnames, int port, String username, String password) { this.hostnames = hostnames; this.port = port; this.username = username; this.password = password; } // TODO: we don't really need getters/setters here as all of the fields are final and immutable public String getHostname() { return hostnames[0]; } public int getPort() { return port; } public String getRandomHost() { return hostnames.length == 1 ? hostnames[0] : hostnames[THREAD_LOCAL_RANDOM.get().nextInt(hostnames.length)]; } public Config setTimeoutMS(int timeoutMS) { checkIfAlreadyBuilt(); this.timeoutMS = timeoutMS; return this; } public Config setFrameSize(int frameSize) { checkIfAlreadyBuilt(); this.frameSize = frameSize; return this; } public Config setSSLTruststoreLocation(String location) { checkIfAlreadyBuilt(); this.sslTruststoreLocation = location; return this; } public Config setSSLTruststorePassword(String password) { checkIfAlreadyBuilt(); this.sslTruststorePassword = password; return this; } public CTConnectionFactory build() { isBuilt = true; return new CTConnectionFactory(this); } public void checkIfAlreadyBuilt() { if (isBuilt) throw new IllegalStateException("Can't accept modifications when used with built factory."); } @Override public String toString() { return "Config[hostnames=" + StringUtils.join(hostnames, ',') + ", port=" + port + ", timeoutMS=" + timeoutMS + ", frameSize=" + frameSize + "]"; } }
1no label
titan-cassandra_src_main_java_com_thinkaurelius_titan_diskstorage_cassandra_thrift_thriftpool_CTConnectionFactory.java
376
public class PutRepositoryResponse extends AcknowledgedResponse { PutRepositoryResponse() { } PutRepositoryResponse(boolean acknowledged) { super(acknowledged); } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); readAcknowledged(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); writeAcknowledged(out); } }
0true
src_main_java_org_elasticsearch_action_admin_cluster_repositories_put_PutRepositoryResponse.java
484
public static class AnalyzeToken implements Streamable { private String term; private int startOffset; private int endOffset; private int position; private String type; AnalyzeToken() { } public AnalyzeToken(String term, int position, int startOffset, int endOffset, String type) { this.term = term; this.position = position; this.startOffset = startOffset; this.endOffset = endOffset; this.type = type; } public String getTerm() { return this.term; } public int getStartOffset() { return this.startOffset; } public int getEndOffset() { return this.endOffset; } public int getPosition() { return this.position; } public String getType() { return this.type; } public static AnalyzeToken readAnalyzeToken(StreamInput in) throws IOException { AnalyzeToken analyzeToken = new AnalyzeToken(); analyzeToken.readFrom(in); return analyzeToken; } @Override public void readFrom(StreamInput in) throws IOException { term = in.readString(); startOffset = in.readInt(); endOffset = in.readInt(); position = in.readVInt(); type = in.readOptionalString(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(term); out.writeInt(startOffset); out.writeInt(endOffset); out.writeVInt(position); out.writeOptionalString(type); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_analyze_AnalyzeResponse.java
1,089
public class OSQLPredicate extends OBaseParser implements OCommandPredicate { protected Set<OProperty> properties = new HashSet<OProperty>(); protected OSQLFilterCondition rootCondition; protected List<String> recordTransformed; protected List<OSQLFilterItemParameter> parameterItems; protected int braces; protected OCommandContext context; public OSQLPredicate() { } public OSQLPredicate(final String iText) { text(iText); } protected void throwSyntaxErrorException(final String iText) { final String syntax = getSyntax(); if (syntax.equals("?")) throw new OCommandSQLParsingException(iText, parserText, parserGetPreviousPosition()); throw new OCommandSQLParsingException(iText + ". Use " + syntax, parserText, parserGetPreviousPosition()); } public OSQLPredicate text(final String iText) { if (iText == null) throw new OCommandSQLParsingException("Query text is null"); try { parserText = iText; parserTextUpperCase = parserText.toUpperCase(Locale.ENGLISH); parserSetCurrentPosition(0); parserSkipWhiteSpaces(); rootCondition = (OSQLFilterCondition) extractConditions(null); optimize(); } catch (OQueryParsingException e) { if (e.getText() == null) // QUERY EXCEPTION BUT WITHOUT TEXT: NEST IT throw new OQueryParsingException("Error on parsing query", parserText, parserGetCurrentPosition(), e); throw e; } catch (Throwable t) { throw new OQueryParsingException("Error on parsing query", parserText, parserGetCurrentPosition(), t); } return this; } public Object evaluate() { return evaluate(null, null, null); } public Object evaluate(final OCommandContext iContext) { return evaluate(null, null, iContext); } public Object evaluate(final ORecord<?> iRecord, ODocument iCurrentResult, final OCommandContext iContext) { if (rootCondition == null) return true; return rootCondition.evaluate((ORecordSchemaAware<?>) iRecord, iCurrentResult, iContext); } private Object extractConditions(final OSQLFilterCondition iParentCondition) { final int oldPosition = parserGetCurrentPosition(); parserNextWord(true, " )=><,\r\n"); final String word = parserGetLastWord(); if (word.length() > 0 && (word.equalsIgnoreCase("SELECT") || word.equalsIgnoreCase("TRAVERSE"))) { // SUB QUERY final StringBuilder embedded = new StringBuilder(); OStringSerializerHelper.getEmbedded(parserText, oldPosition - 1, -1, embedded); parserSetCurrentPosition(oldPosition + embedded.length() + 1); return new OSQLSynchQuery<Object>(embedded.toString()); } parserSetCurrentPosition(oldPosition); OSQLFilterCondition currentCondition = extractCondition(); // CHECK IF THERE IS ANOTHER CONDITION ON RIGHT while (parserSkipWhiteSpaces()) { if (!parserIsEnded() && parserGetCurrentChar() == ')') return currentCondition; final OQueryOperator nextOperator = extractConditionOperator(); if (nextOperator == null) return currentCondition; if (nextOperator.precedence > currentCondition.getOperator().precedence) { // SWAP ITEMS final OSQLFilterCondition subCondition = new OSQLFilterCondition(currentCondition.right, nextOperator); currentCondition.right = subCondition; subCondition.right = extractConditionItem(false, 1); } else { final OSQLFilterCondition parentCondition = new OSQLFilterCondition(currentCondition, nextOperator); parentCondition.right = extractConditions(parentCondition); currentCondition = parentCondition; } } // END OF TEXT return currentCondition; } protected OSQLFilterCondition extractCondition() { if (!parserSkipWhiteSpaces()) // END OF TEXT return null; // EXTRACT ITEMS Object left = extractConditionItem(true, 1); if (left != null && checkForEnd(left.toString())) return null; OQueryOperator oper; final Object right; if (left instanceof OQueryOperator && ((OQueryOperator) left).isUnary()) { oper = (OQueryOperator) left; left = extractConditionItem(false, 1); right = null; } else { oper = extractConditionOperator(); if (oper instanceof OQueryOperatorNot) // SPECIAL CASE: READ NEXT OPERATOR oper = new OQueryOperatorNot(extractConditionOperator()); right = oper != null ? extractConditionItem(false, oper.expectedRightWords) : null; } // CREATE THE CONDITION OBJECT return new OSQLFilterCondition(left, oper, right); } protected boolean checkForEnd(final String iWord) { if (iWord != null && (iWord.equals(OCommandExecutorSQLSelect.KEYWORD_ORDER) || iWord.equals(OCommandExecutorSQLSelect.KEYWORD_LIMIT) || iWord .equals(OCommandExecutorSQLSelect.KEYWORD_SKIP))) { parserMoveCurrentPosition(iWord.length() * -1); return true; } return false; } private OQueryOperator extractConditionOperator() { if (!parserSkipWhiteSpaces()) // END OF PARSING: JUST RETURN return null; if (parserGetCurrentChar() == ')') // FOUND ')': JUST RETURN return null; final OQueryOperator[] operators = OSQLEngine.getInstance().getRecordOperators(); final String[] candidateOperators = new String[operators.length]; for (int i = 0; i < candidateOperators.length; ++i) candidateOperators[i] = operators[i].keyword; final int operatorPos = parserNextChars(true, false, candidateOperators); if (operatorPos == -1) { parserGoBack(); return null; } final OQueryOperator op = operators[operatorPos]; if (op.expectsParameters) { // PARSE PARAMETERS IF ANY parserGoBack(); parserNextWord(true, " 0123456789'\""); final String word = parserGetLastWord(); final List<String> params = new ArrayList<String>(); // CHECK FOR PARAMETERS if (word.length() > op.keyword.length() && word.charAt(op.keyword.length()) == OStringSerializerHelper.EMBEDDED_BEGIN) { int paramBeginPos = parserGetCurrentPosition() - (word.length() - op.keyword.length()); parserSetCurrentPosition(OStringSerializerHelper.getParameters(parserText, paramBeginPos, -1, params)); } else if (!word.equals(op.keyword)) throw new OQueryParsingException("Malformed usage of operator '" + op.toString() + "'. Parsed operator is: " + word); try { // CONFIGURE COULD INSTANTIATE A NEW OBJECT: ACT AS A FACTORY return op.configure(params); } catch (Exception e) { throw new OQueryParsingException("Syntax error using the operator '" + op.toString() + "'. Syntax is: " + op.getSyntax()); } } else parserMoveCurrentPosition(+1); return op; } private Object extractConditionItem(final boolean iAllowOperator, final int iExpectedWords) { final Object[] result = new Object[iExpectedWords]; for (int i = 0; i < iExpectedWords; ++i) { parserNextWord(false, " =><,\r\n"); String word = parserGetLastWord(); if (word.length() == 0) break; final String uWord = word.toUpperCase(); final int lastPosition = parserIsEnded() ? parserText.length() : parserGetCurrentPosition(); if (word.length() > 0 && word.charAt(0) == OStringSerializerHelper.EMBEDDED_BEGIN) { braces++; // SUB-CONDITION parserSetCurrentPosition(lastPosition - word.length() + 1); final Object subCondition = extractConditions(null); if (!parserSkipWhiteSpaces() || parserGetCurrentChar() == ')') { braces--; parserMoveCurrentPosition(+1); } result[i] = subCondition; } else if (word.charAt(0) == OStringSerializerHelper.LIST_BEGIN) { // COLLECTION OF ELEMENTS parserSetCurrentPosition(lastPosition - word.length()); final List<String> stringItems = new ArrayList<String>(); parserSetCurrentPosition(OStringSerializerHelper.getCollection(parserText, parserGetCurrentPosition(), stringItems)); result[i] = convertCollectionItems(stringItems); parserMoveCurrentPosition(+1); } else if (uWord.startsWith(OSQLFilterItemFieldAll.NAME + OStringSerializerHelper.EMBEDDED_BEGIN)) { result[i] = new OSQLFilterItemFieldAll(this, word); } else if (uWord.startsWith(OSQLFilterItemFieldAny.NAME + OStringSerializerHelper.EMBEDDED_BEGIN)) { result[i] = new OSQLFilterItemFieldAny(this, word); } else { if (uWord.equals("NOT")) { if (iAllowOperator) return new OQueryOperatorNot(); else { // GET THE NEXT VALUE parserNextWord(false, " )=><,\r\n"); final String nextWord = parserGetLastWord(); if (nextWord.length() > 0) { word += " " + nextWord; if (word.endsWith(")")) word = word.substring(0, word.length() - 1); } } } else if (uWord.equals("AND")) // SPECIAL CASE IN "BETWEEN X AND Y" result[i] = word; while (word.endsWith(")")) { final int openParenthesis = word.indexOf('('); if (openParenthesis == -1) { // DISCARD END PARENTHESIS word = word.substring(0, word.length() - 1); parserMoveCurrentPosition(-1); } else break; } result[i] = OSQLHelper.parseValue(this, this, word, context); } } return iExpectedWords == 1 ? result[0] : result; } private List<Object> convertCollectionItems(List<String> stringItems) { List<Object> coll = new ArrayList<Object>(); for (String s : stringItems) { coll.add(OSQLHelper.parseValue(this, this, s, context)); } return coll; } public OSQLFilterCondition getRootCondition() { return rootCondition; } @Override public String toString() { if (rootCondition != null) return "Parsed: " + rootCondition.toString(); return "Unparsed: " + parserText; } /** * Binds parameters. * * @param iArgs */ public void bindParameters(final Map<Object, Object> iArgs) { if (parameterItems == null || iArgs == null || iArgs.size() == 0) return; for (Entry<Object, Object> entry : iArgs.entrySet()) { if (entry.getKey() instanceof Integer) parameterItems.get(((Integer) entry.getKey())).setValue(entry.setValue(entry.getValue())); else { String paramName = entry.getKey().toString(); for (OSQLFilterItemParameter value : parameterItems) { if (value.getName().equalsIgnoreCase(paramName)) { value.setValue(entry.getValue()); break; } } } } } public OSQLFilterItemParameter addParameter(final String iName) { final String name; if (iName.charAt(0) == OStringSerializerHelper.PARAMETER_NAMED) { name = iName.substring(1); // CHECK THE PARAMETER NAME IS CORRECT if (!OStringSerializerHelper.isAlphanumeric(name)) { throw new OQueryParsingException("Parameter name '" + name + "' is invalid, only alphanumeric characters are allowed"); } } else name = iName; final OSQLFilterItemParameter param = new OSQLFilterItemParameter(name); if (parameterItems == null) parameterItems = new ArrayList<OSQLFilterItemParameter>(); parameterItems.add(param); return param; } public void setRootCondition(final OSQLFilterCondition iCondition) { rootCondition = iCondition; } protected void optimize() { if (rootCondition != null) computePrefetchFieldList(rootCondition, new HashSet<String>()); } protected Set<String> computePrefetchFieldList(final OSQLFilterCondition iCondition, final Set<String> iFields) { Object left = iCondition.getLeft(); Object right = iCondition.getRight(); if (left instanceof OSQLFilterItemField) { ((OSQLFilterItemField) left).setPreLoadedFields(iFields); iFields.add(((OSQLFilterItemField) left).getRoot()); } else if (left instanceof OSQLFilterCondition) computePrefetchFieldList((OSQLFilterCondition) left, iFields); if (right instanceof OSQLFilterItemField) { ((OSQLFilterItemField) right).setPreLoadedFields(iFields); iFields.add(((OSQLFilterItemField) right).getRoot()); } else if (right instanceof OSQLFilterCondition) computePrefetchFieldList((OSQLFilterCondition) right, iFields); return iFields; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_filter_OSQLPredicate.java
287
public class OScriptManager { protected final String DEF_LANGUAGE = "javascript"; protected ScriptEngineManager scriptEngineManager; protected Map<String, ScriptEngineFactory> engines = new HashMap<String, ScriptEngineFactory>(); protected Map<String, ScriptEngine> sharedEngines = new HashMap<String, ScriptEngine>(); protected String defaultLanguage = DEF_LANGUAGE; protected Map<String, OScriptFormatter> formatters = new HashMap<String, OScriptFormatter>(); protected List<OScriptInjection> injections = new ArrayList<OScriptInjection>(); protected static final Object[] EMPTY_PARAMS = new Object[] {}; protected static final int LINES_AROUND_ERROR = 5; public OScriptManager() { scriptEngineManager = new ScriptEngineManager(); registerSharedEngine(OSQLScriptEngine.NAME, new OSQLScriptEngineFactory().getScriptEngine()); for (ScriptEngineFactory f : scriptEngineManager.getEngineFactories()) { if (f.getParameter("THREADING") != null) // MULTI-THREAD: CACHE IT AS SHARED registerSharedEngine(f.getLanguageName().toLowerCase(), f.getScriptEngine()); else registerEngine(f.getLanguageName().toLowerCase(), f); if (defaultLanguage == null) defaultLanguage = f.getLanguageName(); } if (!existsEngine(DEF_LANGUAGE)) { final ScriptEngine defEngine = scriptEngineManager.getEngineByName(DEF_LANGUAGE); if (defEngine == null) { OLogManager.instance().warn(this, "Cannot find default script language for %s", DEF_LANGUAGE); } else { // GET DIRECTLY THE LANGUAGE BY NAME (DON'T KNOW WHY SOMETIMES DOESN'T RETURN IT WITH getEngineFactories() ABOVE! registerEngine(DEF_LANGUAGE, defEngine.getFactory()); defaultLanguage = DEF_LANGUAGE; } } registerFormatter(OSQLScriptEngine.NAME, new OSQLScriptFormatter()); registerFormatter(DEF_LANGUAGE, new OJSScriptFormatter()); registerFormatter("ruby", new ORubyScriptFormatter()); } public String getFunctionDefinition(final OFunction iFunction) { final OScriptFormatter formatter = formatters.get(iFunction.getLanguage().toLowerCase()); if (formatter == null) throw new IllegalArgumentException("Cannot find script formatter for the language '" + iFunction.getLanguage() + "'"); return formatter.getFunctionDefinition(iFunction); } public String getFunctionInvoke(final OFunction iFunction, final Object[] iArgs) { final OScriptFormatter formatter = formatters.get(iFunction.getLanguage().toLowerCase()); if (formatter == null) throw new IllegalArgumentException("Cannot find script formatter for the language '" + iFunction.getLanguage() + "'"); return formatter.getFunctionInvoke(iFunction, iArgs); } /** * Format the library of functions for a language. * * @param db * Current database instance * @param iLanguage * Language as filter * @return String containing all the functions */ public String getLibrary(final ODatabaseComplex<?> db, final String iLanguage) { if (db == null) // NO DB = NO LIBRARY return null; final StringBuilder code = new StringBuilder(); final Set<String> functions = db.getMetadata().getFunctionLibrary().getFunctionNames(); for (String fName : functions) { final OFunction f = db.getMetadata().getFunctionLibrary().getFunction(fName); if (f.getLanguage() == null) throw new OConfigurationException("Database function '" + fName + "' has no language"); if (f.getLanguage().equalsIgnoreCase(iLanguage)) { final String def = getFunctionDefinition(f); if (def != null) { code.append(def); code.append("\n"); } } } return code.length() == 0 ? null : code.toString(); } public boolean existsEngine(String iLanguage) { if (iLanguage == null) return false; iLanguage = iLanguage.toLowerCase(); return sharedEngines.containsKey(iLanguage) || engines.containsKey(iLanguage); } public ScriptEngine getEngine(final String iLanguage) { if (iLanguage == null) throw new OCommandScriptException("No language was specified"); final String lang = iLanguage.toLowerCase(); ScriptEngine scriptEngine = sharedEngines.get(lang); if (scriptEngine == null) { final ScriptEngineFactory scriptEngineFactory = engines.get(lang); if (scriptEngineFactory == null) throw new OCommandScriptException("Unsupported language: " + iLanguage + ". Supported languages are: " + getSupportedLanguages()); scriptEngine = scriptEngineFactory.getScriptEngine(); } return scriptEngine; } public Iterable<String> getSupportedLanguages() { final HashSet<String> result = new HashSet<String>(); result.addAll(sharedEngines.keySet()); result.addAll(engines.keySet()); return result; } public Bindings bind(final Bindings binding, final ODatabaseRecordTx db, final OCommandContext iContext, final Map<Object, Object> iArgs) { if (db != null) { // BIND FIXED VARIABLES binding.put("db", new OScriptDocumentDatabaseWrapper(db)); binding.put("gdb", new OScriptGraphDatabaseWrapper(db)); binding.put("orient", new OScriptOrientWrapper(db)); } binding.put("util", new OFunctionUtilWrapper(null)); for (OScriptInjection i : injections) i.bind(binding); // BIND CONTEXT VARIABLE INTO THE SCRIPT if (iContext != null) { binding.put("ctx", iContext); for (Entry<String, Object> a : iContext.getVariables().entrySet()) binding.put(a.getKey(), a.getValue()); } // BIND PARAMETERS INTO THE SCRIPT if (iArgs != null) { for (Entry<Object, Object> a : iArgs.entrySet()) binding.put(a.getKey().toString(), a.getValue()); binding.put("params", iArgs.values().toArray()); } else binding.put("params", EMPTY_PARAMS); return binding; } public String getErrorMessage(final ScriptException e, final String lib) { int errorLineNumber = e.getLineNumber(); if (errorLineNumber <= 0) { // FIX TO RHINO: SOMETIMES HAS THE LINE NUMBER INSIDE THE TEXT :-( final String excMessage = e.toString(); final int pos = excMessage.indexOf("<Unknown Source>#"); if (pos > -1) { final int end = excMessage.indexOf(')', pos + "<Unknown Source>#".length()); String lineNumberAsString = excMessage.substring(pos + "<Unknown Source>#".length(), end); errorLineNumber = Integer.parseInt(lineNumberAsString); } } if (errorLineNumber <= 0) { throw new OCommandScriptException("Error on evaluation of the script library. Error: " + e.getMessage() + "\nScript library was:\n" + lib); } else { final StringBuilder code = new StringBuilder(); final Scanner scanner = new Scanner(lib); try { scanner.useDelimiter("\n"); String currentLine = null; String lastFunctionName = "unknown"; for (int currentLineNumber = 1; scanner.hasNext(); currentLineNumber++) { currentLine = scanner.next(); int pos = currentLine.indexOf("function"); if (pos > -1) { final String[] words = OStringParser.getWords(currentLine.substring(pos + "function".length() + 1), " \r\n\t"); if (words.length > 0 && words[0] != "(") lastFunctionName = words[0]; } if (currentLineNumber == errorLineNumber) // APPEND X LINES BEFORE code.append(String.format("%4d: >>> %s\n", currentLineNumber, currentLine)); else if (Math.abs(currentLineNumber - errorLineNumber) <= LINES_AROUND_ERROR) // AROUND: APPEND IT code.append(String.format("%4d: %s\n", currentLineNumber, currentLine)); } code.insert(0, String.format("ScriptManager: error %s.\nFunction %s:\n\n", e.getMessage(), lastFunctionName)); } finally { scanner.close(); } throw new OCommandScriptException(code.toString()); } } /** * Unbinds variables * * @param binding */ public void unbind(Bindings binding) { for (OScriptInjection i : injections) i.unbind(binding); } public void registerInjection(final OScriptInjection iInj) { if (!injections.contains(iInj)) injections.add(iInj); } public void unregisterInjection(final OScriptInjection iInj) { injections.remove(iInj); } public List<OScriptInjection> getInjections() { return injections; } public OScriptManager registerEngine(final String iLanguage, final ScriptEngineFactory iEngine) { engines.put(iLanguage, iEngine); return this; } /** * Registers multi-thread engines can be cached and shared between threads. * * @param iLanguage * Language name * @param iEngine * Engine instance */ public OScriptManager registerSharedEngine(final String iLanguage, final ScriptEngine iEngine) { sharedEngines.put(iLanguage.toLowerCase(), iEngine); return this; } public OScriptManager registerFormatter(final String iLanguage, final OScriptFormatter iFormatterImpl) { formatters.put(iLanguage.toLowerCase(), iFormatterImpl); return this; } }
0true
core_src_main_java_com_orientechnologies_orient_core_command_script_OScriptManager.java
1,361
class ShardStartedTransportHandler extends BaseTransportRequestHandler<ShardRoutingEntry> { static final String ACTION = "cluster/shardStarted"; @Override public ShardRoutingEntry newInstance() { return new ShardRoutingEntry(); } @Override public void messageReceived(ShardRoutingEntry request, TransportChannel channel) throws Exception { innerShardStarted(request); channel.sendResponse(TransportResponse.Empty.INSTANCE); } @Override public String executor() { return ThreadPool.Names.SAME; } }
0true
src_main_java_org_elasticsearch_cluster_action_shard_ShardStateAction.java
5,836
public class SourceSimpleFragmentsBuilder extends SimpleFragmentsBuilder { private final SearchContext searchContext; public SourceSimpleFragmentsBuilder(FieldMapper<?> mapper, SearchContext searchContext, String[] preTags, String[] postTags, BoundaryScanner boundaryScanner) { super(mapper, preTags, postTags, boundaryScanner); this.searchContext = searchContext; } public static final Field[] EMPTY_FIELDS = new Field[0]; @Override protected Field[] getFields(IndexReader reader, int docId, String fieldName) throws IOException { // we know its low level reader, and matching docId, since that's how we call the highlighter with SearchLookup lookup = searchContext.lookup(); lookup.setNextReader((AtomicReaderContext) reader.getContext()); lookup.setNextDocId(docId); List<Object> values = lookup.source().extractRawValues(mapper.names().sourcePath()); if (values.isEmpty()) { return EMPTY_FIELDS; } Field[] fields = new Field[values.size()]; for (int i = 0; i < values.size(); i++) { fields[i] = new Field(mapper.names().indexName(), values.get(i).toString(), TextField.TYPE_NOT_STORED); } return fields; } }
1no label
src_main_java_org_elasticsearch_search_highlight_vectorhighlight_SourceSimpleFragmentsBuilder.java
919
final class LockResourceImpl implements DataSerializable, LockResource { private Data key; private String owner; private long threadId; private int lockCount; private long expirationTime = -1; private long acquireTime = -1L; private boolean transactional; private Map<String, ConditionInfo> conditions; private List<ConditionKey> signalKeys; private List<AwaitOperation> expiredAwaitOps; private LockStoreImpl lockStore; public LockResourceImpl() { } public LockResourceImpl(Data key, LockStoreImpl lockStore) { this.key = key; this.lockStore = lockStore; } @Override public Data getKey() { return key; } @Override public boolean isLocked() { return lockCount > 0; } @Override public boolean isLockedBy(String owner, long threadId) { return (this.threadId == threadId && owner != null && owner.equals(this.owner)); } boolean lock(String owner, long threadId, long leaseTime) { return lock(owner, threadId, leaseTime, false); } boolean lock(String owner, long threadId, long leaseTime, boolean transactional) { if (lockCount == 0) { this.owner = owner; this.threadId = threadId; lockCount++; acquireTime = Clock.currentTimeMillis(); setExpirationTime(leaseTime); this.transactional = transactional; return true; } else if (isLockedBy(owner, threadId)) { lockCount++; setExpirationTime(leaseTime); this.transactional = transactional; return true; } this.transactional = false; return false; } boolean extendLeaseTime(String caller, long threadId, long leaseTime) { if (!isLockedBy(caller, threadId)) { return false; } if (expirationTime < Long.MAX_VALUE) { setExpirationTime(expirationTime - Clock.currentTimeMillis() + leaseTime); lockStore.scheduleEviction(key, leaseTime); } return true; } private void setExpirationTime(long leaseTime) { if (leaseTime < 0) { expirationTime = Long.MAX_VALUE; } else { expirationTime = Clock.currentTimeMillis() + leaseTime; if (expirationTime < 0) { expirationTime = Long.MAX_VALUE; } else { lockStore.scheduleEviction(key, leaseTime); } } } boolean unlock(String owner, long threadId) { if (lockCount == 0) { return false; } if (!isLockedBy(owner, threadId)) { return false; } lockCount--; if (lockCount == 0) { clear(); } return true; } boolean canAcquireLock(String caller, long threadId) { return lockCount == 0 || getThreadId() == threadId && getOwner().equals(caller); } boolean addAwait(String conditionId, String caller, long threadId) { if (conditions == null) { conditions = new HashMap<String, ConditionInfo>(2); } ConditionInfo condition = conditions.get(conditionId); if (condition == null) { condition = new ConditionInfo(conditionId); conditions.put(conditionId, condition); } return condition.addWaiter(caller, threadId); } boolean removeAwait(String conditionId, String caller, long threadId) { if (conditions == null) { return false; } ConditionInfo condition = conditions.get(conditionId); if (condition == null) { return false; } boolean ok = condition.removeWaiter(caller, threadId); if (condition.getAwaitCount() == 0) { conditions.remove(conditionId); } return ok; } boolean startAwaiting(String conditionId, String caller, long threadId) { if (conditions == null) { return false; } ConditionInfo condition = conditions.get(conditionId); if (condition == null) { return false; } return condition.startWaiter(caller, threadId); } int getAwaitCount(String conditionId) { if (conditions == null) { return 0; } ConditionInfo condition = conditions.get(conditionId); if (condition == null) { return 0; } else { return condition.getAwaitCount(); } } void registerSignalKey(ConditionKey conditionKey) { if (signalKeys == null) { signalKeys = new LinkedList<ConditionKey>(); } signalKeys.add(conditionKey); } ConditionKey getSignalKey() { List<ConditionKey> keys = signalKeys; if (isNullOrEmpty(keys)) { return null; } return keys.iterator().next(); } void removeSignalKey(ConditionKey conditionKey) { if (signalKeys != null) { signalKeys.remove(conditionKey); } } void registerExpiredAwaitOp(AwaitOperation awaitResponse) { if (expiredAwaitOps == null) { expiredAwaitOps = new LinkedList<AwaitOperation>(); } expiredAwaitOps.add(awaitResponse); } AwaitOperation pollExpiredAwaitOp() { List<AwaitOperation> ops = expiredAwaitOps; if (isNullOrEmpty(ops)) { return null; } Iterator<AwaitOperation> iterator = ops.iterator(); AwaitOperation awaitResponse = iterator.next(); iterator.remove(); return awaitResponse; } void clear() { threadId = 0; lockCount = 0; owner = null; expirationTime = 0; acquireTime = -1L; cancelEviction(); } void cancelEviction() { lockStore.cancelEviction(key); } boolean isRemovable() { return !isLocked() && isNullOrEmpty(conditions) && isNullOrEmpty(expiredAwaitOps); } @Override public String getOwner() { return owner; } @Override public boolean isTransactional() { return transactional; } @Override public long getThreadId() { return threadId; } @Override public int getLockCount() { return lockCount; } @Override public long getAcquireTime() { return acquireTime; } @Override public long getRemainingLeaseTime() { long now = Clock.currentTimeMillis(); if (now >= expirationTime) { return 0; } return expirationTime - now; } void setLockStore(LockStoreImpl lockStore) { this.lockStore = lockStore; } @Override public void writeData(ObjectDataOutput out) throws IOException { key.writeData(out); out.writeUTF(owner); out.writeLong(threadId); out.writeInt(lockCount); out.writeLong(expirationTime); out.writeLong(acquireTime); out.writeBoolean(transactional); int conditionCount = getConditionCount(); out.writeInt(conditionCount); if (conditionCount > 0) { for (ConditionInfo condition : conditions.values()) { condition.writeData(out); } } int signalCount = getSignalCount(); out.writeInt(signalCount); if (signalCount > 0) { for (ConditionKey signalKey : signalKeys) { out.writeUTF(signalKey.getObjectName()); out.writeUTF(signalKey.getConditionId()); } } int expiredAwaitOpsCount = getExpiredAwaitsOpsCount(); out.writeInt(expiredAwaitOpsCount); if (expiredAwaitOpsCount > 0) { for (AwaitOperation op : expiredAwaitOps) { op.writeData(out); } } } private int getExpiredAwaitsOpsCount() { return expiredAwaitOps == null ? 0 : expiredAwaitOps.size(); } private int getSignalCount() { return signalKeys == null ? 0 : signalKeys.size(); } private int getConditionCount() { return conditions == null ? 0 : conditions.size(); } @Override public void readData(ObjectDataInput in) throws IOException { key = new Data(); key.readData(in); owner = in.readUTF(); threadId = in.readLong(); lockCount = in.readInt(); expirationTime = in.readLong(); acquireTime = in.readLong(); transactional = in.readBoolean(); int len = in.readInt(); if (len > 0) { conditions = new HashMap<String, ConditionInfo>(len); for (int i = 0; i < len; i++) { ConditionInfo condition = new ConditionInfo(); condition.readData(in); conditions.put(condition.getConditionId(), condition); } } len = in.readInt(); if (len > 0) { signalKeys = new ArrayList<ConditionKey>(len); for (int i = 0; i < len; i++) { signalKeys.add(new ConditionKey(in.readUTF(), key, in.readUTF())); } } len = in.readInt(); if (len > 0) { expiredAwaitOps = new ArrayList<AwaitOperation>(len); for (int i = 0; i < len; i++) { AwaitOperation op = new AwaitOperation(); op.readData(in); expiredAwaitOps.add(op); } } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LockResourceImpl that = (LockResourceImpl) o; if (threadId != that.threadId) { return false; } if (owner != null ? !owner.equals(that.owner) : that.owner != null) { return false; } return true; } @Override public int hashCode() { int result = owner != null ? owner.hashCode() : 0; result = 31 * result + (int) (threadId ^ (threadId >>> 32)); return result; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("LockResource"); sb.append("{owner='").append(owner).append('\''); sb.append(", threadId=").append(threadId); sb.append(", lockCount=").append(lockCount); sb.append(", acquireTime=").append(acquireTime); sb.append(", expirationTime=").append(expirationTime); sb.append('}'); return sb.toString(); } private static boolean isNullOrEmpty(Collection c) { return c == null || c.isEmpty(); } private static boolean isNullOrEmpty(Map m) { return m == null || m.isEmpty(); } }
1no label
hazelcast_src_main_java_com_hazelcast_concurrent_lock_LockResourceImpl.java
500
indexStateService.closeIndex(updateRequest, new ClusterStateUpdateListener() { @Override public void onResponse(ClusterStateUpdateResponse response) { listener.onResponse(new CloseIndexResponse(response.isAcknowledged())); } @Override public void onFailure(Throwable t) { logger.debug("failed to close indices [{}]", t, request.indices()); listener.onFailure(t); } });
1no label
src_main_java_org_elasticsearch_action_admin_indices_close_TransportCloseIndexAction.java
312
public class ResourceInputStream extends InputStream { private final InputStream is; private List<String> names = new ArrayList<String>(20); public ResourceInputStream(InputStream is, String name) { this.is = is; names.add(name); } public ResourceInputStream(InputStream is, String name, List<String> previousNames) { this.is = is; names.addAll(previousNames); if (!StringUtils.isEmpty(name)) { names.add(name); } } public List<String> getNames() { return names; } public String getName() { assert names.size() == 1; return names.get(0); } public String toString() { StringBuilder sb = new StringBuilder(100); int size = names.size(); for (int j=0;j<size;j++) { sb.append(names.get(j)); if (j < size - 1) { sb.append(" : "); } } return sb.toString(); } @Override public int available() throws IOException { return (is==null)?-1:is.available(); } @Override public void close() throws IOException { is.close(); } @Override public void mark(int i) { is.mark(i); } @Override public boolean markSupported() { return is.markSupported(); } @Override public int read() throws IOException { return is.read(); } @Override public int read(byte[] bytes) throws IOException { return is.read(bytes); } @Override public int read(byte[] bytes, int i, int i1) throws IOException { return is.read(bytes, i, i1); } @Override public void reset() throws IOException { is.reset(); } @Override public long skip(long l) throws IOException { return is.skip(l); } }
0true
common_src_main_java_org_broadleafcommerce_common_extensibility_context_ResourceInputStream.java
367
@Entity @Inheritance(strategy = InheritanceType.JOINED) @javax.persistence.Table(name = "BLC_TRANSLATION") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "blTranslationElements") @AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "baseProduct") //multi-column indexes don't appear to get exported correctly when declared at the field level, so declaring here as a workaround @Table(appliesTo = "BLC_TRANSLATION", indexes = { @Index(name = "TRANSLATION_INDEX", columnNames = {"ENTITY_TYPE","ENTITY_ID","FIELD_NAME","LOCALE_CODE"}) }) public class TranslationImpl implements Serializable, Translation { private static final long serialVersionUID = -122818474469147685L; @Id @GeneratedValue(generator = "TranslationId") @GenericGenerator( name = "TranslationId", strategy = "org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name = "segment_value", value = "TranslationImpl"), @Parameter(name = "entity_name", value = "org.broadleafcommerce.common.i18n.domain.TranslationImpl") } ) @Column(name = "TRANSLATION_ID") protected Long id; @Column(name = "ENTITY_TYPE") protected String entityType; @Column(name = "ENTITY_ID") protected String entityId; @Column(name = "FIELD_NAME") protected String fieldName; @Column(name = "LOCALE_CODE") protected String localeCode; @Column(name = "TRANSLATED_VALUE", length = Integer.MAX_VALUE - 1) @Lob @Type(type = "org.hibernate.type.StringClobType") protected String translatedValue; /* ************************ */ /* CUSTOM GETTERS / SETTERS */ /* ************************ */ @Override public TranslatedEntity getEntityType() { return TranslatedEntity.getInstanceFromFriendlyType(entityType); } @Override public void setEntityType(TranslatedEntity entityType) { this.entityType = entityType.getFriendlyType(); } /* ************************** */ /* STANDARD GETTERS / SETTERS */ /* ************************** */ @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getEntityId() { return entityId; } @Override public void setEntityId(String entityId) { this.entityId = entityId; } @Override public String getFieldName() { return fieldName; } @Override public void setFieldName(String fieldName) { this.fieldName = fieldName; } @Override public String getLocaleCode() { return localeCode; } @Override public void setLocaleCode(String localeCode) { this.localeCode = localeCode; } @Override public String getTranslatedValue() { return translatedValue; } @Override public void setTranslatedValue(String translatedValue) { this.translatedValue = translatedValue; } }
0true
common_src_main_java_org_broadleafcommerce_common_i18n_domain_TranslationImpl.java
584
getValuesBetween(iRangeFrom, iFromInclusive, iRangeTo, iToInclusive, new IndexValuesResultListener() { @Override public boolean addResult(OIdentifiable value) { result.add(value); return true; } });
0true
core_src_main_java_com_orientechnologies_orient_core_index_OIndexAbstract.java
162
public class StructuredContentRuleType implements Serializable, BroadleafEnumerationType { private static final long serialVersionUID = 1L; private static final Map<String, StructuredContentRuleType> TYPES = new LinkedHashMap<String, StructuredContentRuleType>(); public static final StructuredContentRuleType REQUEST = new StructuredContentRuleType("REQUEST", "Request"); public static final StructuredContentRuleType TIME = new StructuredContentRuleType("TIME", "Time"); public static final StructuredContentRuleType PRODUCT = new StructuredContentRuleType("PRODUCT", "Product"); public static final StructuredContentRuleType CUSTOMER = new StructuredContentRuleType("CUSTOMER", "Customer"); /** * Allows translation from the passed in String to a <code>StructuredContentRuleType</code> * @param type * @return The matching rule type */ public static StructuredContentRuleType getInstance(final String type) { return TYPES.get(type); } private String type; private String friendlyType; public StructuredContentRuleType() { //do nothing } /** * Initialize the type and friendlyType * @param <code>type</code> * @param <code>friendlyType</code> */ public StructuredContentRuleType(final String type, final String friendlyType) { this.friendlyType = friendlyType; setType(type); } /** * Sets the type * @param type */ public void setType(final String type) { this.type = type; if (!TYPES.containsKey(type)) { TYPES.put(type, this); } } /** * Gets the type * @return */ public String getType() { return type; } /** * Gets the name of the type * @return */ public String getFriendlyType() { return friendlyType; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StructuredContentRuleType other = (StructuredContentRuleType) obj; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }
1no label
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_service_type_StructuredContentRuleType.java
669
@Entity @Inheritance(strategy = InheritanceType.JOINED) @Table(name="BLC_CATEGORY_ATTRIBUTE") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="blStandardElements") @AdminPresentationClass(friendlyName = "baseCategoryAttribute") public class CategoryAttributeImpl implements CategoryAttribute { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator= "CategoryAttributeId") @GenericGenerator( name="CategoryAttributeId", strategy="org.broadleafcommerce.common.persistence.IdOverrideTableGenerator", parameters = { @Parameter(name="segment_value", value="CategoryAttributeImpl"), @Parameter(name="entity_name", value="org.broadleafcommerce.core.catalog.domain.CategoryAttributeImpl") } ) @Column(name = "CATEGORY_ATTRIBUTE_ID") protected Long id; @Column(name = "NAME", nullable=false) @Index(name="CATEGORYATTRIBUTE_NAME_INDEX", columnNames={"NAME"}) @AdminPresentation(visibility = VisibilityEnum.HIDDEN_ALL) protected String name; @Column(name = "VALUE") @AdminPresentation(friendlyName = "ProductAttributeImpl_Attribute_Value", order=2, group = "ProductAttributeImpl_Description", prominent=true) protected String value; @Column(name = "SEARCHABLE") @AdminPresentation(excluded = true) protected Boolean searchable = false; @ManyToOne(targetEntity = CategoryImpl.class, optional=false) @JoinColumn(name = "CATEGORY_ID") @Index(name="CATEGORYATTRIBUTE_INDEX", columnNames={"CATEGORY_ID"}) protected Category category; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getValue() { return value; } @Override public void setValue(String value) { this.value = value; } @Override public Boolean getSearchable() { if (searchable == null) { return Boolean.FALSE; } else { return searchable; } } @Override public void setSearchable(Boolean searchable) { this.searchable = searchable; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String toString() { return value; } @Override public Category getCategory() { return category; } @Override public void setCategory(Category category) { this.category = category; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((category == null) ? 0 : category.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CategoryAttributeImpl other = (CategoryAttributeImpl) obj; if (id != null && other.id != null) { return id.equals(other.id); } if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (category == null) { if (other.category != null) return false; } else if (!category.equals(other.category)) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } }
1no label
core_broadleaf-framework_src_main_java_org_broadleafcommerce_core_catalog_domain_CategoryAttributeImpl.java
423
public class NullBroadleafEnumerationType { public String getType() { return null; } }
0true
common_src_main_java_org_broadleafcommerce_common_presentation_NullBroadleafEnumerationType.java
4,666
private final PercolatorType scoringPercolator = new PercolatorType() { @Override public byte id() { return 0x05; } @Override public ReduceResult reduce(List<PercolateShardResponse> shardResults) { return matchPercolator.reduce(shardResults); } @Override public PercolateShardResponse doPercolate(PercolateShardRequest request, PercolateContext context) { Engine.Searcher percolatorSearcher = context.indexShard().acquireSearcher("percolate"); try { MatchAndScore matchAndScore = matchAndScore(logger, context, highlightPhase); queryBasedPercolating(percolatorSearcher, context, matchAndScore); List<BytesRef> matches = matchAndScore.matches(); List<Map<String, HighlightField>> hls = matchAndScore.hls(); float[] scores = matchAndScore.scores().toArray(); long count = matchAndScore.counter(); BytesRef[] finalMatches = matches.toArray(new BytesRef[matches.size()]); return new PercolateShardResponse(finalMatches, hls, count, scores, context, request.index(), request.shardId()); } catch (Throwable e) { logger.debug("failed to execute", e); throw new PercolateException(context.indexShard().shardId(), "failed to execute", e); } finally { percolatorSearcher.release(); } } };
1no label
src_main_java_org_elasticsearch_percolator_PercolatorService.java
1,007
threadPool.executor(executor()).execute(new Runnable() { @Override public void run() { try { Response response = shardOperation(request, shard.id()); listener.onResponse(response); } catch (Throwable e) { shardsIt.reset(); onFailure(shard, e); } } });
0true
src_main_java_org_elasticsearch_action_support_single_custom_TransportSingleCustomOperationAction.java
56
public interface TitanEdge extends TitanRelation, Edge { /** * Returns the edge label of this edge * * @return edge label of this edge */ public EdgeLabel getEdgeLabel(); /** * Returns the vertex for the specified direction. * The direction cannot be Direction.BOTH. * * @return the vertex for the specified direction */ public TitanVertex getVertex(Direction dir); /** * Returns the vertex at the opposite end of the edge. * * @param vertex vertex on which this edge is incident * @return The vertex at the opposite end of the edge. * @throws InvalidElementException if the edge is not incident on the specified vertex */ public TitanVertex getOtherVertex(TitanVertex vertex); /** * Checks whether this relation is directed, i.e. has a start and end vertex * both of which are aware of the incident edge. * * @return true, if this relation is directed, else false. */ public boolean isDirected(); /** * Checks whether this relation is unidirected, i.e. only the start vertex is aware of * the edge's existence. A unidirected edge is similar to a link. * * @return true, if this relation is unidirected, else false. */ public boolean isUnidirected(); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_TitanEdge.java
88
public interface ObjectByObjectToLong<A,B> { long apply(A a, B b); }
0true
src_main_java_jsr166e_ConcurrentHashMapV8.java
1,498
public class CommitVerticesMapReduce { // public static final String ACTION = Tokens.makeNamespace(CommitVerticesMapReduce.class) + ".action"; public enum Counters { VERTICES_KEPT, VERTICES_DROPPED, OUT_EDGES_KEPT, IN_EDGES_KEPT } public static org.apache.hadoop.conf.Configuration createConfiguration(final Tokens.Action action) { ModifiableHadoopConfiguration c = ModifiableHadoopConfiguration.withoutResources(); c.set(COMMIT_VERTICES_ACTION, action); return c.getHadoopConfiguration(); } public static class Map extends Mapper<NullWritable, FaunusVertex, LongWritable, Holder> { private boolean drop; private final Holder<FaunusVertex> holder = new Holder<FaunusVertex>(); private final LongWritable longWritable = new LongWritable(); private Configuration faunusConf; @Override public void setup(final Mapper.Context context) throws IOException, InterruptedException { faunusConf = ModifiableHadoopConfiguration.of(DEFAULT_COMPAT.getContextConfiguration(context)); Tokens.Action configuredAction = faunusConf.get(COMMIT_VERTICES_ACTION); drop = Tokens.Action.DROP.equals(configuredAction); } @Override public void map(final NullWritable key, final FaunusVertex value, final Mapper<NullWritable, FaunusVertex, LongWritable, Holder>.Context context) throws IOException, InterruptedException { final boolean keep; final boolean hasPaths = value.hasPaths(); long verticesKept = 0; long verticesDropped = 0; if (this.drop && hasPaths) keep = false; else if (!this.drop && hasPaths) keep = true; else keep = this.drop && !hasPaths; if (keep) { this.longWritable.set(value.getLongId()); context.write(this.longWritable, this.holder.set('v', value)); verticesKept++; } else { final long vertexId = value.getLongId(); this.holder.set('k', new FaunusVertex(faunusConf, vertexId)); Iterator<Edge> itty = value.getEdges(OUT).iterator(); while (itty.hasNext()) { Edge edge = itty.next(); final Long id = (Long) edge.getVertex(IN).getId(); if (!id.equals(vertexId)) { this.longWritable.set(id); context.write(this.longWritable, this.holder); } } itty = value.getEdges(IN).iterator(); while (itty.hasNext()) { Edge edge = itty.next(); final Long id = (Long) edge.getVertex(OUT).getId(); if (!id.equals(vertexId)) { this.longWritable.set(id); context.write(this.longWritable, this.holder); } } this.longWritable.set(value.getLongId()); context.write(this.longWritable, this.holder.set('d', value)); verticesDropped++; } DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_DROPPED, verticesDropped); DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTICES_KEPT, verticesKept); } } public static class Combiner extends Reducer<LongWritable, Holder, LongWritable, Holder> { private final Holder<FaunusVertex> holder = new Holder<FaunusVertex>(); private Configuration faunusConf; @Override public void setup(final Combiner.Context context) { faunusConf = ModifiableHadoopConfiguration.of(DEFAULT_COMPAT.getContextConfiguration(context)); } @Override public void reduce(final LongWritable key, final Iterable<Holder> values, final Reducer<LongWritable, Holder, LongWritable, Holder>.Context context) throws IOException, InterruptedException { FaunusVertex vertex = null; final Set<Long> ids = new HashSet<Long>(); boolean isDeleted = false; for (final Holder holder : values) { char tag = holder.getTag(); if (tag == 'k') { ids.add(holder.get().getLongId()); // todo: once vertex is found, do individual removes to save memory } else { vertex = (FaunusVertex) holder.get(); isDeleted = tag == 'd'; } } if (null != vertex) { if (ids.size() > 0) vertex.removeEdgesToFrom(ids); context.write(key, this.holder.set(isDeleted ? 'd' : 'v', vertex)); } else { // vertex not on the same machine as the vertices being deleted for (final Long id : ids) { context.write(key, this.holder.set('k', new FaunusVertex(faunusConf, id))); } } } } public static class Reduce extends Reducer<LongWritable, Holder, NullWritable, FaunusVertex> { private boolean trackState; @Override public void setup(final Reducer.Context context) { this.trackState = context.getConfiguration().getBoolean(Tokens.TITAN_HADOOP_PIPELINE_TRACK_STATE, false); } @Override public void reduce(final LongWritable key, final Iterable<Holder> values, final Reducer<LongWritable, Holder, NullWritable, FaunusVertex>.Context context) throws IOException, InterruptedException { FaunusVertex vertex = null; final Set<Long> ids = new HashSet<Long>(); for (final Holder holder : values) { final char tag = holder.getTag(); if (tag == 'k') { ids.add(holder.get().getLongId()); // todo: once vertex is found, do individual removes to save memory } else if (tag == 'v') { vertex = (FaunusVertex) holder.get(); } else { vertex = (FaunusVertex) holder.get(); Iterator<Edge> itty = vertex.getEdges(Direction.BOTH).iterator(); while (itty.hasNext()) { itty.next(); itty.remove(); } vertex.updateLifeCycle(ElementLifeCycle.Event.REMOVED); } } if (null != vertex) { if (ids.size() > 0) vertex.removeEdgesToFrom(ids); if (this.trackState) context.write(NullWritable.get(), vertex); else if (!vertex.isRemoved()) context.write(NullWritable.get(), vertex); DEFAULT_COMPAT.incrementContextCounter(context, Counters.OUT_EDGES_KEPT, Iterables.size(vertex.getEdges(OUT))); DEFAULT_COMPAT.incrementContextCounter(context, Counters.IN_EDGES_KEPT, Iterables.size(vertex.getEdges(IN))); } } } }
1no label
titan-hadoop-parent_titan-hadoop-core_src_main_java_com_thinkaurelius_titan_hadoop_mapreduce_sideeffect_CommitVerticesMapReduce.java
124
public interface EdgeLabelMaker extends RelationTypeMaker { /** * Sets the multiplicity of this label. The default multiplicity is {@link com.thinkaurelius.titan.core.Multiplicity#MULTI}. * @return this EdgeLabelMaker * @see Multiplicity */ public EdgeLabelMaker multiplicity(Multiplicity multiplicity); /** * Configures the label to be directed. * <p/> * By default, the label is directed. * * @return this EdgeLabelMaker * @see com.thinkaurelius.titan.core.EdgeLabel#isDirected() */ public EdgeLabelMaker directed(); /** * Configures the label to be unidirected. * <p/> * By default, the type is directed. * * @return this EdgeLabelMaker * @see com.thinkaurelius.titan.core.EdgeLabel#isUnidirected() */ public EdgeLabelMaker unidirected(); @Override public EdgeLabelMaker signature(RelationType... types); /** * Defines the {@link com.thinkaurelius.titan.core.EdgeLabel} specified by this EdgeLabelMaker and returns the resulting label * * @return the created {@link EdgeLabel} */ @Override public EdgeLabel make(); }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_schema_EdgeLabelMaker.java
774
public class ORecordIteratorClass<REC extends ORecordInternal<?>> extends ORecordIteratorClusters<REC> { protected final OClass targetClass; protected boolean polymorphic; protected boolean useCache; /** * This method is only to maintain the retro compatibility with TinkerPop BP 2.2 */ public ORecordIteratorClass(final ODatabaseRecord iDatabase, final ODatabaseRecordAbstract iLowLevelDatabase, final String iClassName, final boolean iPolymorphic) { this(iDatabase, iLowLevelDatabase, iClassName, iPolymorphic, true, false); } public ORecordIteratorClass(final ODatabaseRecord iDatabase, final ODatabaseRecord iLowLevelDatabase, final String iClassName, final boolean iPolymorphic) { this(iDatabase, iLowLevelDatabase, iClassName, iPolymorphic, true, false); } public ORecordIteratorClass(final ODatabaseRecord iDatabase, final ODatabaseRecord iLowLevelDatabase, final String iClassName, final boolean iPolymorphic, final boolean iUseCache, final boolean iterateThroughTombstones) { super(iDatabase, iLowLevelDatabase, iUseCache, iterateThroughTombstones); targetClass = database.getMetadata().getSchema().getClass(iClassName); if (targetClass == null) throw new IllegalArgumentException("Class '" + iClassName + "' was not found in database schema"); polymorphic = iPolymorphic; clusterIds = polymorphic ? targetClass.getPolymorphicClusterIds() : targetClass.getClusterIds(); clusterIds = OClassImpl.readableClusters(iDatabase, clusterIds); config(); } @SuppressWarnings("unchecked") @Override public REC next() { final OIdentifiable rec = super.next(); if (rec == null) return null; return (REC) rec.getRecord(); } @SuppressWarnings("unchecked") @Override public REC previous() { final OIdentifiable rec = super.previous(); if (rec == null) return null; return (REC) rec.getRecord(); } @Override protected boolean include(final ORecord<?> record) { return record instanceof ODocument && targetClass.isSuperClassOf(((ODocument) record).getSchemaClass()); } public boolean isPolymorphic() { return polymorphic; } @Override public String toString() { return String.format("ORecordIteratorClass.targetClass(%s).polymorphic(%s)", targetClass, polymorphic); } }
1no label
core_src_main_java_com_orientechnologies_orient_core_iterator_ORecordIteratorClass.java
182
final class Itr implements Iterator<E> { private Node nextNode; // next node to return item for private E nextItem; // the corresponding item private Node lastRet; // last returned node, to support remove private Node lastPred; // predecessor to unlink lastRet /** * Moves to next node after prev, or first node if prev null. */ private void advance(Node prev) { /* * To track and avoid buildup of deleted nodes in the face * of calls to both Queue.remove and Itr.remove, we must * include variants of unsplice and sweep upon each * advance: Upon Itr.remove, we may need to catch up links * from lastPred, and upon other removes, we might need to * skip ahead from stale nodes and unsplice deleted ones * found while advancing. */ Node r, b; // reset lastPred upon possible deletion of lastRet if ((r = lastRet) != null && !r.isMatched()) lastPred = r; // next lastPred is old lastRet else if ((b = lastPred) == null || b.isMatched()) lastPred = null; // at start of list else { Node s, n; // help with removal of lastPred.next while ((s = b.next) != null && s != b && s.isMatched() && (n = s.next) != null && n != s) b.casNext(s, n); } this.lastRet = prev; for (Node p = prev, s, n;;) { s = (p == null) ? head : p.next; if (s == null) break; else if (s == p) { p = null; continue; } Object item = s.item; if (s.isData) { if (item != null && item != s) { nextItem = LinkedTransferQueue.<E>cast(item); nextNode = s; return; } } else if (item == null) break; // assert s.isMatched(); if (p == null) p = s; else if ((n = s.next) == null) break; else if (s == n) p = null; else p.casNext(s, n); } nextNode = null; nextItem = null; } Itr() { advance(null); } public final boolean hasNext() { return nextNode != null; } public final E next() { Node p = nextNode; if (p == null) throw new NoSuchElementException(); E e = nextItem; advance(p); return e; } public final void remove() { final Node lastRet = this.lastRet; if (lastRet == null) throw new IllegalStateException(); this.lastRet = null; if (lastRet.tryMatchData()) unsplice(lastPred, lastRet); } }
0true
src_main_java_jsr166y_LinkedTransferQueue.java
1,695
public class OHttpResponse { public static final String JSON_FORMAT = "type,indent:-1,rid,version,attribSameRow,class,keepTypes,alwaysFetchEmbeddedDocuments"; public static final char[] URL_SEPARATOR = { '/' }; private final OutputStream out; public final String httpVersion; public String headers; public String[] additionalHeaders; public String characterSet; public String contentType; public String serverInfo; public String sessionId; public String callbackFunction; public String contentEncoding; public boolean sendStarted = false; public OHttpResponse(final OutputStream iOutStream, final String iHttpVersion, final String[] iAdditionalHeaders, final String iResponseCharSet, final String iServerInfo, final String iSessionId, final String iCallbackFunction) { out = iOutStream; httpVersion = iHttpVersion; additionalHeaders = iAdditionalHeaders; characterSet = iResponseCharSet; serverInfo = iServerInfo; sessionId = iSessionId; callbackFunction = iCallbackFunction; } public void send(final int iCode, final String iReason, final String iContentType, final Object iContent, final String iHeaders) throws IOException { send(iCode, iReason, iContentType, iContent, iHeaders, true); } public void send(final int iCode, final String iReason, final String iContentType, final Object iContent, final String iHeaders, final boolean iKeepAlive) throws IOException { if (sendStarted) // AVOID TO SEND RESPONSE TWICE return; sendStarted = true; final String content; final String contentType; if (callbackFunction != null) { content = callbackFunction + "(" + iContent + ")"; contentType = "text/javascript"; } else { content = iContent != null ? iContent.toString() : null; contentType = iContentType; } final boolean empty = content == null || content.length() == 0; writeStatus(empty && iCode == 200 ? 204 : iCode, iReason); writeHeaders(contentType, iKeepAlive); if (iHeaders != null) writeLine(iHeaders); final String sessId = sessionId != null ? sessionId : "-"; writeLine("Set-Cookie: " + OHttpUtils.OSESSIONID + "=" + sessId + "; Path=/; HttpOnly"); byte[] binaryContent = null; if (!empty) { if (contentEncoding != null && contentEncoding.equals(OHttpUtils.CONTENT_ACCEPT_GZIP_ENCODED)) binaryContent = compress(content); else binaryContent = OBinaryProtocol.string2bytes(content); } writeLine(OHttpUtils.HEADER_CONTENT_LENGTH + (empty ? 0 : binaryContent.length)); writeLine(null); if (binaryContent != null) out.write(binaryContent); out.flush(); } public void writeStatus(final int iStatus, final String iReason) throws IOException { writeLine(httpVersion + " " + iStatus + " " + iReason); } public void writeHeaders(final String iContentType) throws IOException { writeHeaders(iContentType, true); } public void writeHeaders(final String iContentType, final boolean iKeepAlive) throws IOException { if (headers != null) writeLine(headers); writeLine("Date: " + new Date()); writeLine("Content-Type: " + iContentType + "; charset=" + characterSet); writeLine("Server: " + serverInfo); writeLine("Connection: " + (iKeepAlive ? "Keep-Alive" : "close")); // SET CONTENT ENCDOING if (contentEncoding != null && contentEncoding.length() > 0) { writeLine("Content-Encoding: " + contentEncoding); } // INCLUDE COMMON CUSTOM HEADERS if (additionalHeaders != null) for (String h : additionalHeaders) writeLine(h); } public void writeLine(final String iContent) throws IOException { writeContent(iContent); out.write(OHttpUtils.EOL); } public void writeContent(final String iContent) throws IOException { if (iContent != null) out.write(OBinaryProtocol.string2bytes(iContent)); } public void writeResult(Object iResult) throws InterruptedException, IOException { writeResult(iResult, null); } @SuppressWarnings("unchecked") public void writeResult(Object iResult, final String iFormat) throws InterruptedException, IOException { if (iResult == null) send(OHttpUtils.STATUS_OK_NOCONTENT_CODE, "", OHttpUtils.CONTENT_TEXT_PLAIN, null, null, true); else { if (iResult instanceof Map<?, ?>) { iResult = ((Map<?, ?>) iResult).entrySet().iterator(); } else if (OMultiValue.isMultiValue(iResult) && (OMultiValue.getSize(iResult) > 0 && !(OMultiValue.getFirstValue(iResult) instanceof OIdentifiable))) { final List<OIdentifiable> resultSet = new ArrayList<OIdentifiable>(); resultSet.add(new ODocument().field("value", iResult)); iResult = resultSet.iterator(); } else if (iResult instanceof OIdentifiable) { // CONVERT SIGLE VALUE IN A COLLECTION final List<OIdentifiable> resultSet = new ArrayList<OIdentifiable>(); resultSet.add((OIdentifiable) iResult); iResult = resultSet.iterator(); } else if (iResult instanceof Iterable<?>) iResult = ((Iterable<OIdentifiable>) iResult).iterator(); else if (OMultiValue.isMultiValue(iResult)) iResult = OMultiValue.getMultiValueIterator(iResult); else { final List<OIdentifiable> resultSet = new ArrayList<OIdentifiable>(); resultSet.add(new ODocument().field("value", iResult)); iResult = resultSet.iterator(); } if (iResult == null) send(OHttpUtils.STATUS_OK_NOCONTENT_CODE, "", OHttpUtils.CONTENT_TEXT_PLAIN, null, null, true); else if (iResult instanceof Iterator<?>) writeRecords((Iterator<OIdentifiable>) iResult, null, iFormat); } } public void writeRecords(final Iterable<OIdentifiable> iRecords) throws IOException { if (iRecords == null) return; writeRecords(iRecords.iterator(), null, null); } public void writeRecords(final Iterable<OIdentifiable> iRecords, final String iFetchPlan) throws IOException { if (iRecords == null) return; writeRecords(iRecords.iterator(), iFetchPlan, null); } public void writeRecords(final Iterator<OIdentifiable> iRecords) throws IOException { writeRecords(iRecords, null, null); } public void writeRecords(final Iterator<OIdentifiable> iRecords, final String iFetchPlan, String iFormat) throws IOException { if (iRecords == null) return; if (iFormat == null) iFormat = JSON_FORMAT; else iFormat = JSON_FORMAT + "," + iFormat; final StringWriter buffer = new StringWriter(); final OJSONWriter json = new OJSONWriter(buffer, iFormat); json.beginObject(); final String format = iFetchPlan != null ? iFormat + ",fetchPlan:" + iFetchPlan : iFormat; // WRITE RECORDS json.beginCollection(-1, true, "result"); formatMultiValue(iRecords, buffer, format); json.endCollection(-1, true); json.endObject(); send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, buffer.toString(), null); } public void formatMultiValue(final Iterator<?> iIterator, final StringWriter buffer, final String format) throws IOException { if (iIterator != null) { int counter = 0; String objectJson; while (iIterator.hasNext()) { final Object entry = iIterator.next(); if (entry != null) { if (counter++ > 0) buffer.append(", "); if (entry instanceof OIdentifiable) { ORecord<?> rec = ((OIdentifiable) entry).getRecord(); try { objectJson = rec.getRecord().toJSON(format); buffer.append(objectJson); } catch (Exception e) { OLogManager.instance().error(this, "Error transforming record " + rec.getIdentity() + " to JSON", e); } } else if (OMultiValue.isMultiValue(entry)) formatMultiValue(OMultiValue.getMultiValueIterator(entry), buffer, format); else buffer.append(OJSONWriter.writeValue(entry, format)); } } } } public void writeRecord(final ORecord<?> iRecord) throws IOException { writeRecord(iRecord, null, null); } public void writeRecord(final ORecord<?> iRecord, final String iFetchPlan, String iFormat) throws IOException { if (iFormat == null) iFormat = JSON_FORMAT; final String format = iFetchPlan != null ? iFormat + ",fetchPlan:" + iFetchPlan : iFormat; if (iRecord != null) send(OHttpUtils.STATUS_OK_CODE, "OK", OHttpUtils.CONTENT_JSON, iRecord.toJSON(format), null); } public void sendStream(final int iCode, final String iReason, final String iContentType, InputStream iContent, long iSize) throws IOException { sendStream(iCode, iReason, iContentType, iContent, iSize, null); } public void sendStream(final int iCode, final String iReason, final String iContentType, InputStream iContent, long iSize, final String iFileName) throws IOException { writeStatus(iCode, iReason); writeHeaders(iContentType); writeLine("Content-Transfer-Encoding: binary"); if (iFileName != null) writeLine("Content-Disposition: attachment; filename=\"" + iFileName + "\""); if (iSize < 0) { // SIZE UNKNOWN: USE A MEMORY BUFFER final ByteArrayOutputStream o = new ByteArrayOutputStream(); if (iContent != null) { int b; while ((b = iContent.read()) > -1) o.write(b); } byte[] content = o.toByteArray(); iContent = new ByteArrayInputStream(content); iSize = content.length; } writeLine(OHttpUtils.HEADER_CONTENT_LENGTH + (iSize)); writeLine(null); if (iContent != null) { int b; while ((b = iContent.read()) > -1) out.write(b); } out.flush(); } // Compress content string public byte[] compress(String jsonStr) { if (jsonStr == null || jsonStr.length() == 0) return null; GZIPOutputStream gout = null; ByteArrayOutputStream baos = null; try { byte[] incoming = jsonStr.getBytes("UTF-8"); baos = new ByteArrayOutputStream(); gout = new GZIPOutputStream(baos, 16384); // 16KB gout.write(incoming); gout.finish(); return baos.toByteArray(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (gout != null) gout.close(); if (baos != null) baos.close(); } catch (Exception ex) { ex.printStackTrace(); } } return null; } /** * Stores additional headers to send * * @param iHeader */ public void setHeader(final String iHeader) { headers = iHeader; } public OutputStream getOutputStream() { return out; } public void flush() throws IOException { out.flush(); } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public String getContentEncoding() { return contentEncoding; } public void setContentEncoding(String contentEncoding) { this.contentEncoding = contentEncoding; } }
1no label
server_src_main_java_com_orientechnologies_orient_server_network_protocol_http_OHttpResponse.java
120
public class ExtractValueProposal implements ICompletionProposal { private CeylonEditor editor; public ExtractValueProposal(CeylonEditor editor) { this.editor = editor; } @Override public Point getSelection(IDocument doc) { return null; } @Override public Image getImage() { return CHANGE; } @Override public String getDisplayString() { return "Extract value"; } @Override public IContextInformation getContextInformation() { return null; } @Override public String getAdditionalProposalInfo() { return null; } @Override public void apply(IDocument doc) { if (useLinkedMode()) { new ExtractValueLinkedMode(editor).start(); } else { new ExtractValueRefactoringAction(editor).run(); } } public static void add(Collection<ICompletionProposal> proposals, CeylonEditor editor, Node node) { if (node instanceof Tree.BaseMemberExpression) { Tree.Identifier id = ((Tree.BaseMemberExpression) node).getIdentifier(); if (id==null || id.getToken().getType()==CeylonLexer.AIDENTIFIER) { return; } } ExtractValueRefactoring evr = new ExtractValueRefactoring(editor); if (evr.isEnabled()) { proposals.add(new ExtractValueProposal(editor)); } } }
0true
plugins_com.redhat.ceylon.eclipse.ui_src_com_redhat_ceylon_eclipse_code_correct_ExtractValueProposal.java
58
public class TestXaFramework extends AbstractNeo4jTestCase { private TransactionManager tm; private XaDataSourceManager xaDsMgr; private final TransactionStateFactory stateFactory = new TransactionStateFactory( new DevNullLoggingService() ) { @Override public TransactionState create( Transaction tx ) { return new NoTransactionState() { @Override @SuppressWarnings("deprecation") public TxIdGenerator getTxIdGenerator() { return TxIdGenerator.DEFAULT; } }; } }; private File path() { String path = getStorePath( "xafrmwrk" ); File file = new File( path ); try { FileUtils.deleteRecursively( file ); } catch ( IOException e ) { throw new RuntimeException( e ); } assertTrue( "create directory: " + file, file.mkdirs() ); return file; } private File file( String name ) { return new File( path(), name); } private File resourceFile() { return file( "dummy_resource" ); } @Before public void setUpFramework() { getTransaction().finish(); tm = getGraphDbAPI().getDependencyResolver().resolveDependency( TransactionManager.class ); xaDsMgr = getGraphDbAPI().getDependencyResolver().resolveDependency( XaDataSourceManager.class ); } @Test public void testCreateXaResource() throws Exception { Map<String, String> config = new HashMap<String, String>(); config.put( "store_dir", "target/var" ); FileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction(); KernelHealth kernelHealth = mock( KernelHealth.class ); xaDsMgr.registerDataSource( new DummyXaDataSource( UTF8.encode( "DDDDDD" ), "dummy_datasource", new XaFactory( new Config( config, GraphDatabaseSettings.class ), TxIdGenerator.DEFAULT, new PlaceboTm( null, getGraphDbAPI().getDependencyResolver() .resolveDependency( TxIdGenerator.class ) ), fileSystem, new Monitors(), new DevNullLoggingService(), RecoveryVerifier.ALWAYS_VALID, LogPruneStrategies.NO_PRUNING, kernelHealth ), stateFactory, resourceFile() ) ); XaDataSource xaDs = xaDsMgr.getXaDataSource( "dummy_datasource" ); DummyXaConnection xaC = null; try { xaC = (DummyXaConnection) xaDs.getXaConnection(); try { xaC.doStuff1(); fail( "Non enlisted resource should throw exception" ); } catch ( XAException e ) { // good } Xid xid = new XidImpl( new byte[0], new byte[0] ); xaC.getXaResource().start( xid, XAResource.TMNOFLAGS ); try { xaC.doStuff1(); xaC.doStuff2(); } catch ( XAException e ) { fail( "Enlisted resource should not throw exception" ); } xaC.getXaResource().end( xid, XAResource.TMSUCCESS ); xaC.getXaResource().prepare( xid ); xaC.getXaResource().commit( xid, false ); } finally { xaDsMgr.unregisterDataSource( "dummy_datasource" ); if ( xaC != null ) { xaC.destroy(); } } // cleanup dummy resource log deleteAllResourceFiles(); } @Test public void testTxIdGeneration() throws Exception { DummyXaConnection xaC1 = null; try { Map<String, String> config = new HashMap<String, String>(); config.put( "store_dir", "target/var" ); FileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction(); KernelHealth kernelHealth = mock( KernelHealth.class ); xaDsMgr.registerDataSource( new DummyXaDataSource( UTF8.encode( "DDDDDD" ), "dummy_datasource1", new XaFactory( new Config( config, GraphDatabaseSettings.class ), TxIdGenerator.DEFAULT, (AbstractTransactionManager)tm, fileSystem, new Monitors(), new DevNullLoggingService(), RecoveryVerifier.ALWAYS_VALID, LogPruneStrategies.NO_PRUNING, kernelHealth ), stateFactory, resourceFile() ) ); DummyXaDataSource xaDs1 = (DummyXaDataSource) xaDsMgr.getXaDataSource( "dummy_datasource1" ); xaC1 = (DummyXaConnection) xaDs1.getXaConnection(); tm.begin(); // get xaC1.enlistWithTx( tm ); int currentTxId = xaC1.getTransactionId(); xaC1.doStuff1(); xaC1.delistFromTx( tm ); tm.commit(); // xaC2 = ( DummyXaConnection ) xaDs2.getXaConnection(); tm.begin(); Node node = getGraphDb().createNode(); // get resource in tx xaC1.enlistWithTx( tm ); assertEquals( ++currentTxId, xaC1.getTransactionId() ); xaC1.doStuff1(); xaC1.delistFromTx( tm ); tm.commit(); tm.begin(); node = getGraphDb().getNodeById( node.getId() ); xaC1.enlistWithTx( tm ); assertEquals( ++currentTxId, xaC1.getTransactionId() ); xaC1.doStuff2(); xaC1.delistFromTx( tm ); node.delete(); tm.commit(); } finally { xaDsMgr.unregisterDataSource( "dummy_datasource1" ); // xaDsMgr.unregisterDataSource( "dummy_datasource1" ); if ( xaC1 != null ) { xaC1.destroy(); } } // cleanup dummy resource log deleteAllResourceFiles(); } private void deleteAllResourceFiles() { File dir = new File( "." ); final String prefix = resourceFile().getPath(); File files[] = dir.listFiles( new FilenameFilter() { @Override public boolean accept( File dir, String fileName ) { return fileName.startsWith( prefix ); } } ); boolean allDeleted = true; for ( File file : files ) { if ( !file.delete() ) { allDeleted = false; } } assertTrue( "delete all files starting with " + prefix, allDeleted ); } }
0true
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestXaFramework.java
106
REGEX { @Override public boolean evaluate(Object value, Object condition) { this.preevaluate(value,condition); if (value == null) return false; return evaluateRaw(value.toString(),(String)condition); } public boolean evaluateRaw(String value, String regex) { return value.matches(regex); } @Override public boolean isValidCondition(Object condition) { return condition != null && condition instanceof String && StringUtils.isNotBlank(condition.toString()); } };
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Text.java
232
XPostingsHighlighter highlighter = new XPostingsHighlighter() { @Override protected PassageFormatter getFormatter(String field) { return new PassageFormatter() { PassageFormatter defaultFormatter = new DefaultPassageFormatter(); @Override public String[] format(Passage passages[], String content) { // Just turns the String snippet into a length 2 // array of String return new String[] {"blah blah", defaultFormatter.format(passages, content).toString()}; } }; } };
0true
src_test_java_org_apache_lucene_search_postingshighlight_XPostingsHighlighterTests.java
471
public class AliasesExistRequestBuilder extends BaseAliasesRequestBuilder<AliasesExistResponse, AliasesExistRequestBuilder> { public AliasesExistRequestBuilder(IndicesAdminClient client, String... aliases) { super(client, aliases); } @Override protected void doExecute(ActionListener<AliasesExistResponse> listener) { ((IndicesAdminClient) client).aliasesExist(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_alias_exists_AliasesExistRequestBuilder.java
363
public static class TestCollator implements Collator<Map.Entry<String, Integer>, Integer> { @Override public Integer collate(Iterable<Map.Entry<String, Integer>> values) { int sum = 0; for (Map.Entry<String, Integer> entry : values) { sum += entry.getValue(); } return sum; } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_mapreduce_ClientMapReduceTest.java
214
Collections.sort(indexes, new Comparator<OIndex<?>>() { public int compare(OIndex<?> o1, OIndex<?> o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } });
0true
tools_src_main_java_com_orientechnologies_orient_console_OConsoleDatabaseApp.java
559
public class TypedQueryBuilder<T> { protected Class<T> rootClass; protected String rootAlias; protected List<TQRestriction> restrictions = new ArrayList<TQRestriction>(); protected Map<String, Object> paramMap = new HashMap<String, Object>(); /** * Creates a new TypedQueryBuilder that will utilize the rootAlias as the named object of the class * * @param rootClass * @param rootAlias */ public TypedQueryBuilder(Class<T> rootClass, String rootAlias) { this.rootClass = rootClass; this.rootAlias = rootAlias; } /** * Adds a simple restriction to the query. Note that all restrictions present on the TypedQueryBuilder will be joined * with an AND clause. * * @param expression * @param operation * @param parameter */ public TypedQueryBuilder<T> addRestriction(String expression, String operation, Object parameter) { restrictions.add(new TQRestriction(expression, operation, parameter)); return this; } /** * Adds an explicit TQRestriction object. Note that all restrictions present on the TypedQueryBuilder will be joined * with an AND clause. * * @param restriction * @return */ public TypedQueryBuilder<T> addRestriction(TQRestriction restriction) { restrictions.add(restriction); return this; } /** * Generates the query string based on the current contents of this builder. As the string is generated, this method * will also populate the paramMap, which binds actual restriction values. * * Note that this method should typically not be invoked through DAOs. Instead, utilize {@link #toQuery(EntityManager)}, * which will automatically generate the TypedQuery and populate the required parameters. * * @return the QL string */ public String toQueryString() { return toQueryString(false); } /** * Generates the query string based on the current contents of this builder. As the string is generated, this method * will also populate the paramMap, which binds actual restriction values. * * Note that this method should typically not be invoked through DAOs. Instead, utilize {@link #toQuery(EntityManager)}, * which will automatically generate the TypedQuery and populate the required parameters. * * If you are using this as a COUNT query, you should look at the corresponding {@link #toCountQuery(EntityManager)} * * @param whether or not the resulting query string should be used as a count query or not * @return the QL string */ public String toQueryString(boolean count) { StringBuilder sb = getSelectClause(new StringBuilder(), count) .append(" FROM ").append(rootClass.getName()).append(" ").append(rootAlias); if (CollectionUtils.isNotEmpty(restrictions)) { sb.append(" WHERE "); for (int i = 0; i < restrictions.size(); i++) { TQRestriction r = restrictions.get(i); sb.append(r.toQl("p" + i, paramMap)); if (i != restrictions.size() - 1) { sb.append(" AND "); } } } return sb.toString(); } /** * Adds the select query from {@link #toQueryString()} * * @return <b>sb</b> with the select query appended to it */ protected StringBuilder getSelectClause(StringBuilder sb, boolean count) { sb.append("SELECT "); if (count) { return sb.append("COUNT(*)"); } else { return sb.append(rootAlias); } } /** * Returns a TypedQuery that represents this builder object. It will already have all of the appropriate parameter * values set and is able to be immediately queried against. * * @param em * @return the TypedQuery */ public TypedQuery<T> toQuery(EntityManager em) { TypedQuery<T> q = em.createQuery(toQueryString(), rootClass); fillParameterMap(q); return q; } public TypedQuery<Long> toCountQuery(EntityManager em) { TypedQuery<Long> q = em.createQuery(toQueryString(true), Long.class); fillParameterMap(q); return q; } protected void fillParameterMap(TypedQuery<?> q) { for (Entry<String, Object> entry : paramMap.entrySet()) { if (entry.getValue() != null) { q.setParameter(entry.getKey(), entry.getValue()); } } } /** * @return the paramMap */ public Map<String, Object> getParamMap() { return paramMap; } }
1no label
common_src_main_java_org_broadleafcommerce_common_util_dao_TypedQueryBuilder.java
731
public class CollectionAddRequest extends CollectionRequest { protected Data value; public CollectionAddRequest() { } public CollectionAddRequest(String name, Data value) { super(name); this.value = value; } @Override protected Operation prepareOperation() { return new CollectionAddOperation(name, value); } @Override public int getClassId() { return CollectionPortableHook.COLLECTION_ADD; } public void write(PortableWriter writer) throws IOException { super.write(writer); value.writeData(writer.getRawDataOutput()); } public void read(PortableReader reader) throws IOException { super.read(reader); value = new Data(); value.readData(reader.getRawDataInput()); } @Override public String getRequiredAction() { return ActionConstants.ACTION_ADD; } }
0true
hazelcast_src_main_java_com_hazelcast_collection_client_CollectionAddRequest.java
1,354
public class ShardStateAction extends AbstractComponent { private final TransportService transportService; private final ClusterService clusterService; private final AllocationService allocationService; private final ThreadPool threadPool; private final BlockingQueue<ShardRoutingEntry> startedShardsQueue = ConcurrentCollections.newBlockingQueue(); private final BlockingQueue<ShardRoutingEntry> failedShardQueue = ConcurrentCollections.newBlockingQueue(); @Inject public ShardStateAction(Settings settings, ClusterService clusterService, TransportService transportService, AllocationService allocationService, ThreadPool threadPool) { super(settings); this.clusterService = clusterService; this.transportService = transportService; this.allocationService = allocationService; this.threadPool = threadPool; transportService.registerHandler(ShardStartedTransportHandler.ACTION, new ShardStartedTransportHandler()); transportService.registerHandler(ShardFailedTransportHandler.ACTION, new ShardFailedTransportHandler()); } public void shardFailed(final ShardRouting shardRouting, final String indexUUID, final String reason) throws ElasticsearchException { ShardRoutingEntry shardRoutingEntry = new ShardRoutingEntry(shardRouting, indexUUID, reason); logger.warn("{} sending failed shard for {}", shardRouting.shardId(), shardRoutingEntry); DiscoveryNodes nodes = clusterService.state().nodes(); if (nodes.localNodeMaster()) { innerShardFailed(shardRoutingEntry); } else { transportService.sendRequest(clusterService.state().nodes().masterNode(), ShardFailedTransportHandler.ACTION, shardRoutingEntry, new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleException(TransportException exp) { logger.warn("failed to send failed shard to [{}]", exp, clusterService.state().nodes().masterNode()); } }); } } public void shardStarted(final ShardRouting shardRouting, String indexUUID, final String reason) throws ElasticsearchException { ShardRoutingEntry shardRoutingEntry = new ShardRoutingEntry(shardRouting, indexUUID, reason); logger.debug("sending shard started for {}", shardRoutingEntry); DiscoveryNodes nodes = clusterService.state().nodes(); if (nodes.localNodeMaster()) { innerShardStarted(shardRoutingEntry); } else { transportService.sendRequest(clusterService.state().nodes().masterNode(), ShardStartedTransportHandler.ACTION, new ShardRoutingEntry(shardRouting, indexUUID, reason), new EmptyTransportResponseHandler(ThreadPool.Names.SAME) { @Override public void handleException(TransportException exp) { logger.warn("failed to send shard started to [{}]", exp, clusterService.state().nodes().masterNode()); } }); } } private void innerShardFailed(final ShardRoutingEntry shardRoutingEntry) { logger.warn("{} received shard failed for {}", shardRoutingEntry.shardRouting.shardId(), shardRoutingEntry); failedShardQueue.add(shardRoutingEntry); clusterService.submitStateUpdateTask("shard-failed (" + shardRoutingEntry.shardRouting + "), reason [" + shardRoutingEntry.reason + "]", Priority.HIGH, new ClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { List<ShardRoutingEntry> shardRoutingEntries = new ArrayList<ShardRoutingEntry>(); failedShardQueue.drainTo(shardRoutingEntries); // nothing to process (a previous event has processed it already) if (shardRoutingEntries.isEmpty()) { return currentState; } MetaData metaData = currentState.getMetaData(); List<ShardRouting> shardRoutingsToBeApplied = new ArrayList<ShardRouting>(shardRoutingEntries.size()); for (int i = 0; i < shardRoutingEntries.size(); i++) { ShardRoutingEntry shardRoutingEntry = shardRoutingEntries.get(i); ShardRouting shardRouting = shardRoutingEntry.shardRouting; IndexMetaData indexMetaData = metaData.index(shardRouting.index()); // if there is no metadata or the current index is not of the right uuid, the index has been deleted while it was being allocated // which is fine, we should just ignore this if (indexMetaData == null) { continue; } if (!indexMetaData.isSameUUID(shardRoutingEntry.indexUUID)) { logger.debug("{} ignoring shard failed, different index uuid, current {}, got {}", shardRouting.shardId(), indexMetaData.getUUID(), shardRoutingEntry); continue; } logger.debug("{} will apply shard failed {}", shardRouting.shardId(), shardRoutingEntry); shardRoutingsToBeApplied.add(shardRouting); } RoutingAllocation.Result routingResult = allocationService.applyFailedShards(currentState, shardRoutingsToBeApplied); if (!routingResult.changed()) { return currentState; } return ClusterState.builder(currentState).routingResult(routingResult).build(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); } }); } private void innerShardStarted(final ShardRoutingEntry shardRoutingEntry) { logger.debug("received shard started for {}", shardRoutingEntry); // buffer shard started requests, and the state update tasks will simply drain it // this is to optimize the number of "started" events we generate, and batch them // possibly, we can do time based batching as well, but usually, we would want to // process started events as fast as possible, to make shards available startedShardsQueue.add(shardRoutingEntry); clusterService.submitStateUpdateTask("shard-started (" + shardRoutingEntry.shardRouting + "), reason [" + shardRoutingEntry.reason + "]", Priority.URGENT, new ClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { List<ShardRoutingEntry> shardRoutingEntries = new ArrayList<ShardRoutingEntry>(); startedShardsQueue.drainTo(shardRoutingEntries); // nothing to process (a previous event has processed it already) if (shardRoutingEntries.isEmpty()) { return currentState; } RoutingTable routingTable = currentState.routingTable(); MetaData metaData = currentState.getMetaData(); List<ShardRouting> shardRoutingToBeApplied = new ArrayList<ShardRouting>(shardRoutingEntries.size()); for (int i = 0; i < shardRoutingEntries.size(); i++) { ShardRoutingEntry shardRoutingEntry = shardRoutingEntries.get(i); ShardRouting shardRouting = shardRoutingEntry.shardRouting; try { IndexMetaData indexMetaData = metaData.index(shardRouting.index()); IndexRoutingTable indexRoutingTable = routingTable.index(shardRouting.index()); // if there is no metadata, no routing table or the current index is not of the right uuid, the index has been deleted while it was being allocated // which is fine, we should just ignore this if (indexMetaData == null) { continue; } if (indexRoutingTable == null) { continue; } if (!indexMetaData.isSameUUID(shardRoutingEntry.indexUUID)) { logger.debug("{} ignoring shard started, different index uuid, current {}, got {}", shardRouting.shardId(), indexMetaData.getUUID(), shardRoutingEntry); continue; } // find the one that maps to us, if its already started, no need to do anything... // the shard might already be started since the nodes that is starting the shards might get cluster events // with the shard still initializing, and it will try and start it again (until the verification comes) IndexShardRoutingTable indexShardRoutingTable = indexRoutingTable.shard(shardRouting.id()); boolean applyShardEvent = true; for (ShardRouting entry : indexShardRoutingTable) { if (shardRouting.currentNodeId().equals(entry.currentNodeId())) { // we found the same shard that exists on the same node id if (!entry.initializing()) { // shard is in initialized state, skipping event (probable already started) logger.debug("{} ignoring shard started event for {}, current state: {}", shardRouting.shardId(), shardRoutingEntry, entry.state()); applyShardEvent = false; } } } if (applyShardEvent) { shardRoutingToBeApplied.add(shardRouting); logger.debug("{} will apply shard started {}", shardRouting.shardId(), shardRoutingEntry); } } catch (Throwable t) { logger.error("{} unexpected failure while processing shard started [{}]", t, shardRouting.shardId(), shardRouting); } } if (shardRoutingToBeApplied.isEmpty()) { return currentState; } RoutingAllocation.Result routingResult = allocationService.applyStartedShards(currentState, shardRoutingToBeApplied, true); if (!routingResult.changed()) { return currentState; } return ClusterState.builder(currentState).routingResult(routingResult).build(); } @Override public void onFailure(String source, Throwable t) { logger.error("unexpected failure during [{}]", t, source); } }); } private class ShardFailedTransportHandler extends BaseTransportRequestHandler<ShardRoutingEntry> { static final String ACTION = "cluster/shardFailure"; @Override public ShardRoutingEntry newInstance() { return new ShardRoutingEntry(); } @Override public void messageReceived(ShardRoutingEntry request, TransportChannel channel) throws Exception { innerShardFailed(request); channel.sendResponse(TransportResponse.Empty.INSTANCE); } @Override public String executor() { return ThreadPool.Names.SAME; } } class ShardStartedTransportHandler extends BaseTransportRequestHandler<ShardRoutingEntry> { static final String ACTION = "cluster/shardStarted"; @Override public ShardRoutingEntry newInstance() { return new ShardRoutingEntry(); } @Override public void messageReceived(ShardRoutingEntry request, TransportChannel channel) throws Exception { innerShardStarted(request); channel.sendResponse(TransportResponse.Empty.INSTANCE); } @Override public String executor() { return ThreadPool.Names.SAME; } } static class ShardRoutingEntry extends TransportRequest { private ShardRouting shardRouting; private String indexUUID = IndexMetaData.INDEX_UUID_NA_VALUE; private String reason; private ShardRoutingEntry() { } private ShardRoutingEntry(ShardRouting shardRouting, String indexUUID, String reason) { this.shardRouting = shardRouting; this.reason = reason; this.indexUUID = indexUUID; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); shardRouting = readShardRoutingEntry(in); reason = in.readString(); indexUUID = in.readString(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); shardRouting.writeTo(out); out.writeString(reason); out.writeString(indexUUID); } @Override public String toString() { return "" + shardRouting + ", indexUUID [" + indexUUID + "], reason [" + reason + "]"; } } }
0true
src_main_java_org_elasticsearch_cluster_action_shard_ShardStateAction.java
253
public class OUnboundedWeakCache extends OAbstractMapCache<WeakHashMap<ORID, ORecordInternal<?>>> implements OCache { public OUnboundedWeakCache() { super(new WeakHashMap<ORID, ORecordInternal<?>>()); } @Override public int limit() { return Integer.MAX_VALUE; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_cache_OUnboundedWeakCache.java
114
public interface PageTemplate extends Serializable { public Long getId(); public void setId(Long id); public String getTemplateName(); public void setTemplateName(String templateName); public String getTemplateDescription(); public void setTemplateDescription(String templateDescription); public String getTemplatePath(); public void setTemplatePath(String templatePath); public Locale getLocale(); public void setLocale(Locale locale); public List<FieldGroup> getFieldGroups(); public void setFieldGroups(List<FieldGroup> fieldGroups); }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_page_domain_PageTemplate.java
15
static final class DescendingSubMap<K, V> extends NavigableSubMap<K, V> { private static final long serialVersionUID = 912986545866120460L; private final Comparator<? super K> reverseComparator = Collections.reverseOrder(m.comparator); DescendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd, final K hi, final boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } public Comparator<? super K> comparator() { return reverseComparator; } public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap<K, V>(m, false, toKey, toInclusive, false, fromKey, fromInclusive); } public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap<K, V>(m, false, toKey, inclusive, toEnd, hi, hiInclusive); } public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) { if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, fromKey, inclusive); } public ONavigableMap<K, V> descendingMap() { ONavigableMap<K, V> mv = descendingMapView; return (mv != null) ? mv : (descendingMapView = new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive)); } @Override OLazyIterator<K> keyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } @Override OLazyIterator<K> descendingKeyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } final class DescendingEntrySetView extends EntrySetView { @Override public Iterator<Map.Entry<K, V>> iterator() { return new DescendingSubMapEntryIterator(absHighest(), absLowFence()); } } @Override public Set<Map.Entry<K, V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : new DescendingEntrySetView(); } @Override OMVRBTreeEntry<K, V> subLowest() { return absHighest().entry; } @Override OMVRBTreeEntry<K, V> subHighest() { return absLowest().entry; } @Override OMVRBTreeEntry<K, V> subCeiling(final K key) { return absFloor(key).entry; } @Override OMVRBTreeEntry<K, V> subHigher(final K key) { return absLower(key).entry; } @Override OMVRBTreeEntry<K, V> subFloor(final K key) { return absCeiling(key).entry; } @Override OMVRBTreeEntry<K, V> subLower(final K key) { return absHigher(key).entry; } }
0true
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
651
public class GetIndexTemplatesRequestBuilder extends MasterNodeReadOperationRequestBuilder<GetIndexTemplatesRequest, GetIndexTemplatesResponse, GetIndexTemplatesRequestBuilder> { public GetIndexTemplatesRequestBuilder(IndicesAdminClient indicesClient) { super((InternalIndicesAdminClient) indicesClient, new GetIndexTemplatesRequest()); } public GetIndexTemplatesRequestBuilder(IndicesAdminClient indicesClient, String... names) { super((InternalIndicesAdminClient) indicesClient, new GetIndexTemplatesRequest(names)); } @Override protected void doExecute(ActionListener<GetIndexTemplatesResponse> listener) { ((IndicesAdminClient) client).getTemplates(request, listener); } }
0true
src_main_java_org_elasticsearch_action_admin_indices_template_get_GetIndexTemplatesRequestBuilder.java
29
public class BerkeleyBlueprintsTest extends TitanBlueprintsTest { private static final String DEFAULT_SUBDIR = "standard"; private static final Logger log = LoggerFactory.getLogger(BerkeleyBlueprintsTest.class); @Override public Graph generateGraph() { return generateGraph(DEFAULT_SUBDIR); } @Override public void beforeOpeningGraph(String uid) { String dir = BerkeleyStorageSetup.getHomeDir(uid); log.debug("Cleaning directory {} before opening it for the first time", dir); try { BerkeleyJEStoreManager s = new BerkeleyJEStoreManager(BerkeleyStorageSetup.getBerkeleyJEConfiguration(dir)); s.clearStorage(); s.close(); File dirFile = new File(dir); Assert.assertFalse(dirFile.exists() && dirFile.listFiles().length > 0); } catch (BackendException e) { throw new RuntimeException(e); } } @Override public TitanGraph openGraph(String uid) { String dir = BerkeleyStorageSetup.getHomeDir(uid); return TitanFactory.open(BerkeleyStorageSetup.getBerkeleyJEConfiguration(dir)); } @Override public void extraCleanUp(String uid) throws BackendException { String dir = BerkeleyStorageSetup.getHomeDir(uid); BerkeleyJEStoreManager s = new BerkeleyJEStoreManager(BerkeleyStorageSetup.getBerkeleyJEConfiguration(dir)); s.clearStorage(); s.close(); File dirFile = new File(dir); Assert.assertFalse(dirFile.exists() && dirFile.listFiles().length > 0); } @Override public boolean supportsMultipleGraphs() { return true; } @Override public void beforeSuite() { //Nothing } @Override public void afterSuite() { synchronized (openGraphs) { for (String dir : openGraphs.keySet()) { File dirFile = new File(dir); Assert.assertFalse(dirFile.exists() && dirFile.listFiles().length > 0); } } } }
0true
titan-berkeleyje_src_test_java_com_thinkaurelius_titan_blueprints_BerkeleyBlueprintsTest.java
286
public abstract class ActionResponse extends TransportResponse { @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); } }
0true
src_main_java_org_elasticsearch_action_ActionResponse.java
165
return executeRead(new Callable<EntryList>() { @Override public EntryList call() throws Exception { return cacheEnabled?indexStore.getSlice(query, storeTx): indexStore.getSliceNoCache(query, storeTx); } @Override public String toString() { return "VertexIndexQuery"; } });
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_BackendTransaction.java
4,108
abstract class NestedFieldComparator extends FieldComparator { final Filter rootDocumentsFilter; final Filter innerDocumentsFilter; final int spareSlot; FieldComparator wrappedComparator; FixedBitSet rootDocuments; FixedBitSet innerDocuments; int bottomSlot; NestedFieldComparator(FieldComparator wrappedComparator, Filter rootDocumentsFilter, Filter innerDocumentsFilter, int spareSlot) { this.wrappedComparator = wrappedComparator; this.rootDocumentsFilter = rootDocumentsFilter; this.innerDocumentsFilter = innerDocumentsFilter; this.spareSlot = spareSlot; } @Override public final int compare(int slot1, int slot2) { return wrappedComparator.compare(slot1, slot2); } @Override public final void setBottom(int slot) { wrappedComparator.setBottom(slot); this.bottomSlot = slot; } @Override public FieldComparator setNextReader(AtomicReaderContext context) throws IOException { DocIdSet innerDocuments = innerDocumentsFilter.getDocIdSet(context, null); if (DocIdSets.isEmpty(innerDocuments)) { this.innerDocuments = null; } else if (innerDocuments instanceof FixedBitSet) { this.innerDocuments = (FixedBitSet) innerDocuments; } else { this.innerDocuments = DocIdSets.toFixedBitSet(innerDocuments.iterator(), context.reader().maxDoc()); } DocIdSet rootDocuments = rootDocumentsFilter.getDocIdSet(context, null); if (DocIdSets.isEmpty(rootDocuments)) { this.rootDocuments = null; } else if (rootDocuments instanceof FixedBitSet) { this.rootDocuments = (FixedBitSet) rootDocuments; } else { this.rootDocuments = DocIdSets.toFixedBitSet(rootDocuments.iterator(), context.reader().maxDoc()); } wrappedComparator = wrappedComparator.setNextReader(context); return this; } @Override public final Object value(int slot) { return wrappedComparator.value(slot); } @Override public final int compareDocToValue(int rootDoc, Object value) throws IOException { throw new UnsupportedOperationException("compareDocToValue() not used for sorting in ES"); } final static class Lowest extends NestedFieldComparator { Lowest(FieldComparator wrappedComparator, Filter parentFilter, Filter childFilter, int spareSlot) { super(wrappedComparator, parentFilter, childFilter, spareSlot); } @Override public int compareBottom(int rootDoc) throws IOException { if (rootDoc == 0 || rootDocuments == null || innerDocuments == null) { return compareBottomMissing(wrappedComparator); } // We need to copy the lowest value from all nested docs into slot. int prevRootDoc = rootDocuments.prevSetBit(rootDoc - 1); int nestedDoc = innerDocuments.nextSetBit(prevRootDoc + 1); if (nestedDoc >= rootDoc || nestedDoc == -1) { return compareBottomMissing(wrappedComparator); } // We only need to emit a single cmp value for any matching nested doc int cmp = wrappedComparator.compareBottom(nestedDoc); if (cmp > 0) { return cmp; } while (true) { nestedDoc = innerDocuments.nextSetBit(nestedDoc + 1); if (nestedDoc >= rootDoc || nestedDoc == -1) { return cmp; } int cmp1 = wrappedComparator.compareBottom(nestedDoc); if (cmp1 > 0) { return cmp1; } else { if (cmp1 == 0) { cmp = 0; } } } } @Override public void copy(int slot, int rootDoc) throws IOException { if (rootDoc == 0 || rootDocuments == null || innerDocuments == null) { copyMissing(wrappedComparator, slot); return; } // We need to copy the lowest value from all nested docs into slot. int prevRootDoc = rootDocuments.prevSetBit(rootDoc - 1); int nestedDoc = innerDocuments.nextSetBit(prevRootDoc + 1); if (nestedDoc >= rootDoc || nestedDoc == -1) { copyMissing(wrappedComparator, slot); return; } wrappedComparator.copy(slot, nestedDoc); while (true) { nestedDoc = innerDocuments.nextSetBit(nestedDoc + 1); if (nestedDoc >= rootDoc || nestedDoc == -1) { return; } wrappedComparator.copy(spareSlot, nestedDoc); if (wrappedComparator.compare(spareSlot, slot) < 0) { wrappedComparator.copy(slot, nestedDoc); } } } } final static class Highest extends NestedFieldComparator { Highest(FieldComparator wrappedComparator, Filter parentFilter, Filter childFilter, int spareSlot) { super(wrappedComparator, parentFilter, childFilter, spareSlot); } @Override public int compareBottom(int rootDoc) throws IOException { if (rootDoc == 0 || rootDocuments == null || innerDocuments == null) { return compareBottomMissing(wrappedComparator); } int prevRootDoc = rootDocuments.prevSetBit(rootDoc - 1); int nestedDoc = innerDocuments.nextSetBit(prevRootDoc + 1); if (nestedDoc >= rootDoc || nestedDoc == -1) { return compareBottomMissing(wrappedComparator); } int cmp = wrappedComparator.compareBottom(nestedDoc); if (cmp < 0) { return cmp; } while (true) { nestedDoc = innerDocuments.nextSetBit(nestedDoc + 1); if (nestedDoc >= rootDoc || nestedDoc == -1) { return cmp; } int cmp1 = wrappedComparator.compareBottom(nestedDoc); if (cmp1 < 0) { return cmp1; } else if (cmp1 == 0) { cmp = 0; } } } @Override public void copy(int slot, int rootDoc) throws IOException { if (rootDoc == 0 || rootDocuments == null || innerDocuments == null) { copyMissing(wrappedComparator, slot); return; } int prevRootDoc = rootDocuments.prevSetBit(rootDoc - 1); int nestedDoc = innerDocuments.nextSetBit(prevRootDoc + 1); if (nestedDoc >= rootDoc || nestedDoc == -1) { copyMissing(wrappedComparator, slot); return; } wrappedComparator.copy(slot, nestedDoc); while (true) { nestedDoc = innerDocuments.nextSetBit(nestedDoc + 1); if (nestedDoc >= rootDoc || nestedDoc == -1) { return; } wrappedComparator.copy(spareSlot, nestedDoc); if (wrappedComparator.compare(spareSlot, slot) > 0) { wrappedComparator.copy(slot, nestedDoc); } } } } static abstract class NumericNestedFieldComparatorBase extends NestedFieldComparator { protected NumberComparatorBase numberComparator; NumericNestedFieldComparatorBase(NumberComparatorBase wrappedComparator, Filter rootDocumentsFilter, Filter innerDocumentsFilter, int spareSlot) { super(wrappedComparator, rootDocumentsFilter, innerDocumentsFilter, spareSlot); this.numberComparator = wrappedComparator; } @Override public final int compareBottom(int rootDoc) throws IOException { if (rootDoc == 0 || rootDocuments == null || innerDocuments == null) { return compareBottomMissing(wrappedComparator); } final int prevRootDoc = rootDocuments.prevSetBit(rootDoc - 1); int nestedDoc = innerDocuments.nextSetBit(prevRootDoc + 1); if (nestedDoc >= rootDoc || nestedDoc == -1) { return compareBottomMissing(wrappedComparator); } int counter = 1; wrappedComparator.copy(spareSlot, nestedDoc); nestedDoc = innerDocuments.nextSetBit(nestedDoc + 1); while (nestedDoc > prevRootDoc && nestedDoc < rootDoc) { onNested(spareSlot, nestedDoc); nestedDoc = innerDocuments.nextSetBit(nestedDoc + 1); counter++; } afterNested(spareSlot, counter); return compare(bottomSlot, spareSlot); } @Override public final void copy(int slot, int rootDoc) throws IOException { if (rootDoc == 0 || rootDocuments == null || innerDocuments == null) { copyMissing(wrappedComparator, slot); return; } final int prevRootDoc = rootDocuments.prevSetBit(rootDoc - 1); int nestedDoc = innerDocuments.nextSetBit(prevRootDoc + 1); if (nestedDoc >= rootDoc || nestedDoc == -1) { copyMissing(wrappedComparator, slot); return; } int counter = 1; wrappedComparator.copy(slot, nestedDoc); nestedDoc = innerDocuments.nextSetBit(nestedDoc + 1); while (nestedDoc > prevRootDoc && nestedDoc < rootDoc) { onNested(slot, nestedDoc); nestedDoc = innerDocuments.nextSetBit(nestedDoc + 1); counter++; } afterNested(slot, counter); } protected abstract void onNested(int slot, int nestedDoc); protected abstract void afterNested(int slot, int count); @Override public final FieldComparator setNextReader(AtomicReaderContext context) throws IOException { super.setNextReader(context); numberComparator = (NumberComparatorBase) super.wrappedComparator; return this; } } final static class Sum extends NumericNestedFieldComparatorBase { Sum(NumberComparatorBase wrappedComparator, Filter rootDocumentsFilter, Filter innerDocumentsFilter, int spareSlot) { super(wrappedComparator, rootDocumentsFilter, innerDocumentsFilter, spareSlot); } @Override protected void onNested(int slot, int nestedDoc) { numberComparator.add(slot, nestedDoc); } @Override protected void afterNested(int slot, int count) { } } final static class Avg extends NumericNestedFieldComparatorBase { Avg(NumberComparatorBase wrappedComparator, Filter rootDocumentsFilter, Filter innerDocumentsFilter, int spareSlot) { super(wrappedComparator, rootDocumentsFilter, innerDocumentsFilter, spareSlot); } @Override protected void onNested(int slot, int nestedDoc) { numberComparator.add(slot, nestedDoc); } @Override protected void afterNested(int slot, int count) { numberComparator.divide(slot, count); } } static final void copyMissing(FieldComparator<?> comparator, int slot) { if (comparator instanceof NestedWrappableComparator<?>) { ((NestedWrappableComparator<?>) comparator).missing(slot); } } static final int compareBottomMissing(FieldComparator<?> comparator) { if (comparator instanceof NestedWrappableComparator<?>) { return ((NestedWrappableComparator<?>) comparator).compareBottomMissing(); } else { return 0; } } }
1no label
src_main_java_org_elasticsearch_index_search_nested_NestedFieldComparatorSource.java
710
static class WriteResult { final Object response; final long preVersion; final Tuple<String, String> mappingToUpdate; final Engine.IndexingOperation op; WriteResult(Object response, long preVersion, Tuple<String, String> mappingToUpdate, Engine.IndexingOperation op) { this.response = response; this.preVersion = preVersion; this.mappingToUpdate = mappingToUpdate; this.op = op; } @SuppressWarnings("unchecked") <T> T response() { return (T) response; } }
0true
src_main_java_org_elasticsearch_action_bulk_TransportShardBulkAction.java
367
new ActionListener<RepositoriesService.UnregisterRepositoryResponse>() { @Override public void onResponse(RepositoriesService.UnregisterRepositoryResponse unregisterRepositoryResponse) { listener.onResponse(new DeleteRepositoryResponse(unregisterRepositoryResponse.isAcknowledged())); } @Override public void onFailure(Throwable e) { listener.onFailure(e); } });
0true
src_main_java_org_elasticsearch_action_admin_cluster_repositories_delete_TransportDeleteRepositoryAction.java
1,961
@Repository("blRoleDao") public class RoleDaoImpl implements RoleDao { @PersistenceContext(unitName = "blPU") protected EntityManager em; @Resource(name = "blEntityConfiguration") protected EntityConfiguration entityConfiguration; public Address readAddressById(Long id) { return (Address) em.find(AddressImpl.class, id); } @SuppressWarnings("unchecked") public List<CustomerRole> readCustomerRolesByCustomerId(Long customerId) { Query query = em.createNamedQuery("BC_READ_CUSTOMER_ROLES_BY_CUSTOMER_ID"); query.setParameter("customerId", customerId); return query.getResultList(); } public Role readRoleByName(String name) { Query query = em.createNamedQuery("BC_READ_ROLE_BY_NAME"); query.setParameter("name", name); return (Role) query.getSingleResult(); } public void addRoleToCustomer(CustomerRole customerRole) { em.persist(customerRole); } }
1no label
core_broadleaf-profile_src_main_java_org_broadleafcommerce_profile_core_dao_RoleDaoImpl.java
2,596
private static class MasterPingRequest extends TransportRequest { private String nodeId; private String masterNodeId; private MasterPingRequest() { } private MasterPingRequest(String nodeId, String masterNodeId) { this.nodeId = nodeId; this.masterNodeId = masterNodeId; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); nodeId = in.readString(); masterNodeId = in.readString(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(nodeId); out.writeString(masterNodeId); } }
1no label
src_main_java_org_elasticsearch_discovery_zen_fd_MasterFaultDetection.java
1,386
public static class ParseContext { final boolean shouldParseId; final boolean shouldParseRouting; final boolean shouldParseTimestamp; int locationId = 0; int locationRouting = 0; int locationTimestamp = 0; boolean idResolved; boolean routingResolved; boolean timestampResolved; String id; String routing; String timestamp; public ParseContext(boolean shouldParseId, boolean shouldParseRouting, boolean shouldParseTimestamp) { this.shouldParseId = shouldParseId; this.shouldParseRouting = shouldParseRouting; this.shouldParseTimestamp = shouldParseTimestamp; } /** * The id value parsed, <tt>null</tt> if does not require parsing, or not resolved. */ public String id() { return id; } /** * Does id parsing really needed at all? */ public boolean shouldParseId() { return shouldParseId; } /** * Has id been resolved during the parsing phase. */ public boolean idResolved() { return idResolved; } /** * Is id parsing still needed? */ public boolean idParsingStillNeeded() { return shouldParseId && !idResolved; } /** * The routing value parsed, <tt>null</tt> if does not require parsing, or not resolved. */ public String routing() { return routing; } /** * Does routing parsing really needed at all? */ public boolean shouldParseRouting() { return shouldParseRouting; } /** * Has routing been resolved during the parsing phase. */ public boolean routingResolved() { return routingResolved; } /** * Is routing parsing still needed? */ public boolean routingParsingStillNeeded() { return shouldParseRouting && !routingResolved; } /** * The timestamp value parsed, <tt>null</tt> if does not require parsing, or not resolved. */ public String timestamp() { return timestamp; } /** * Does timestamp parsing really needed at all? */ public boolean shouldParseTimestamp() { return shouldParseTimestamp; } /** * Has timestamp been resolved during the parsing phase. */ public boolean timestampResolved() { return timestampResolved; } /** * Is timestamp parsing still needed? */ public boolean timestampParsingStillNeeded() { return shouldParseTimestamp && !timestampResolved; } /** * Do we really need parsing? */ public boolean shouldParse() { return shouldParseId || shouldParseRouting || shouldParseTimestamp; } /** * Is parsing still needed? */ public boolean parsingStillNeeded() { return idParsingStillNeeded() || routingParsingStillNeeded() || timestampParsingStillNeeded(); } }
0true
src_main_java_org_elasticsearch_cluster_metadata_MappingMetaData.java
1,067
execute(request, new ActionListener<MultiTermVectorsResponse>() { @Override public void onResponse(MultiTermVectorsResponse response) { try { channel.sendResponse(response); } catch (Throwable t) { onFailure(t); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(e); } catch (Throwable t) { logger.warn("Failed to send error response for action [" + MultiTermVectorsAction.NAME + "] and request [" + request + "]", t); } } });
0true
src_main_java_org_elasticsearch_action_termvector_TransportMultiTermVectorsAction.java
152
public class StructuredContentDTO implements Serializable { private static final long serialVersionUID = 1L; protected Long id; protected String contentName; protected String contentType; protected String localeCode; protected Integer priority; protected Long sandboxId; protected Map values = new HashMap<String,String>(); protected String ruleExpression; protected List<ItemCriteriaDTO> itemCriteriaDTOList; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getContentName() { return contentName; } public void setContentName(String contentName) { values.put("contentName", contentName); this.contentName = contentName; } public String getContentType() { return contentType; } public void setContentType(String contentType) { values.put("contentType", contentType); this.contentType = contentType; } public String getLocaleCode() { return localeCode; } public void setLocaleCode(String localeCode) { values.put("localeCode", localeCode); this.localeCode = localeCode; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { values.put("priority", priority); this.priority = priority; } public Long getSandboxId() { return sandboxId; } public void setSandboxId(Long sandboxId) { this.sandboxId = sandboxId; } public Map getValues() { return values; } public void setValues(Map values) { this.values = values; } public String getRuleExpression() { return ruleExpression; } public void setRuleExpression(String ruleExpression) { this.ruleExpression = ruleExpression; } public List<ItemCriteriaDTO> getItemCriteriaDTOList() { return itemCriteriaDTOList; } public void setItemCriteriaDTOList(List<ItemCriteriaDTO> itemCriteriaDTOList) { this.itemCriteriaDTOList = itemCriteriaDTOList; } }
0true
admin_broadleaf-contentmanagement-module_src_main_java_org_broadleafcommerce_cms_structure_dto_StructuredContentDTO.java
1,884
public class DynamicEntityFormInfo { public static final String FIELD_SEPARATOR = "|"; protected String criteriaName; protected String propertyName; protected String propertyValue; protected String ceilingClassName; public DynamicEntityFormInfo withCriteriaName(String criteriaName) { setCriteriaName(criteriaName); return this; } public DynamicEntityFormInfo withPropertyName(String propertyName) { setPropertyName(propertyName); return this; } public DynamicEntityFormInfo withPropertyValue(String propertyValue) { setPropertyValue(propertyValue); return this; } public DynamicEntityFormInfo withCeilingClassName(String ceilingClassName) { setCeilingClassName(ceilingClassName); return this; } public String getCriteriaName() { return criteriaName; } public void setCriteriaName(String criteriaName) { this.criteriaName = criteriaName; } public String getPropertyName() { return propertyName; } public void setPropertyName(String propertyName) { this.propertyName = propertyName; } public String getPropertyValue() { return propertyValue; } public void setPropertyValue(String propertyValue) { this.propertyValue = propertyValue; } public String getCeilingClassName() { return ceilingClassName; } public void setCeilingClassName(String ceilingClassName) { this.ceilingClassName = ceilingClassName; } }
1no label
admin_broadleaf-open-admin-platform_src_main_java_org_broadleafcommerce_openadmin_web_form_entity_DynamicEntityFormInfo.java
311
String.class, null, new OConfigurationChangeCallback() { public void change(final Object iCurrentValue, final Object iNewValue) { Orient.instance().getProfiler().configure(iNewValue.toString()); } }),
0true
core_src_main_java_com_orientechnologies_orient_core_config_OGlobalConfiguration.java
746
public class ListSubRequest extends CollectionRequest { private int from; private int to; public ListSubRequest() { } public ListSubRequest(String name, int from, int to) { super(name); this.from = from; this.to = to; } @Override protected Operation prepareOperation() { return new ListSubOperation(name, from, to); } @Override public int getClassId() { return CollectionPortableHook.LIST_SUB; } public void write(PortableWriter writer) throws IOException { super.write(writer); writer.writeInt("f", from); writer.writeInt("t", to); } public void read(PortableReader reader) throws IOException { super.read(reader); from = reader.readInt("f"); to = reader.readInt("t"); } @Override public String getRequiredAction() { return ActionConstants.ACTION_READ; } }
0true
hazelcast_src_main_java_com_hazelcast_collection_client_ListSubRequest.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
283
public class ThymeleafMessageCreator extends MessageCreator { private TemplateEngine templateEngine; public ThymeleafMessageCreator(TemplateEngine templateEngine, JavaMailSender mailSender) { super(mailSender); this.templateEngine = templateEngine; } @Override public String buildMessageBody(EmailInfo info, HashMap<String,Object> props) { BroadleafRequestContext blcContext = BroadleafRequestContext.getBroadleafRequestContext(); final Context thymeleafContext = new Context(); if (blcContext != null && blcContext.getJavaLocale() != null) { thymeleafContext.setLocale(blcContext.getJavaLocale()); } if (props != null) { Iterator<String> propsIterator = props.keySet().iterator(); while(propsIterator.hasNext()) { String key = propsIterator.next(); thymeleafContext.setVariable(key, props.get(key)); } } return this.templateEngine.process( info.getEmailTemplate(), thymeleafContext); } }
0true
common_src_main_java_org_broadleafcommerce_common_email_service_message_ThymeleafMessageCreator.java
6,422
targetTransport.threadPool().generic().execute(new Runnable() { @Override public void run() { targetTransport.messageReceived(data, action, sourceTransport, version, null); } });
1no label
src_main_java_org_elasticsearch_transport_local_LocalTransportChannel.java
414
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface AdminPresentationCollection { /** * <p>Optional - field name will be used if not specified</p> * * <p>The friendly name to present to a user for this field in a GUI. If supporting i18N, * the friendly name may be a key to retrieve a localized friendly name using * the GWT support for i18N.</p> * * @return the friendly name */ String friendlyName() default ""; /** * <p>Optional - only required if you wish to apply security to this field</p> * * <p>If a security level is specified, it is registered with the SecurityManager. * The SecurityManager checks the permission of the current user to * determine if this field should be disabled based on the specified level.</p> * * @return the security level */ String securityLevel() default ""; /** * <p>Optional - fields are not excluded by default</p> * * <p>Specify if this field should be excluded from inclusion in the * admin presentation layer</p> * * @return whether or not the field should be excluded */ boolean excluded() default false; /** * <p>Optional - only required if you want to make the field immutable</p> * * <p>Explicityly specify whether or not this field is mutable.</p> * * @return whether or not this field is read only */ boolean readOnly() default false; /** * <p>Optional - only required if you want to make the field ignore caching</p> * * <p>Explicitly specify whether or not this field will use server-side * caching during inspection</p> * * @return whether or not this field uses caching */ boolean useServerSideInspectionCache() default true; /** * <p>Optional - only required if you want to lookup an item * for this association, rather than creating a new instance of the * target item. Note - if the type is changed to LOOKUP, this has * the side effect of causing the only the association to be deleted * during a remove, leaving the target lookup entity intact.</p> * * <p>Define whether or not added items for this * collection are acquired via search or construction.</p> * * @return the item is acquired via lookup or construction */ AddMethodType addType() default AddMethodType.PERSIST; /** * <p>Optional - only required in the absence of a "mappedBy" property * on the JPA annotation</p> * * <p>For the target entity of this collection, specify the field * name that refers back to the parent entity.</p> * * <p>For collection definitions that use the "mappedBy" property * of the @OneToMany and @ManyToMany annotations, this value * can be safely ignored as the system will be able to infer * the proper value from this.</p> * * @return the parent entity referring field name */ String manyToField() default ""; /** * <p>Optional - only required if you want to specify ordering for this field</p> * * <p>The order in which this field will appear in a GUI relative to other collections from the same class</p> * * @return the display order */ int order() default 99999; /** * Optional - only required if you want the field to appear under a different tab * * Specify a GUI tab for this field * * @return the tab for this field */ String tab() default "General"; /** * Optional - only required if you want to order the appearance of the tabs in the UI * * Specify an order for this tab. Tabs will be sorted int he resulting form in * ascending order based on this parameter. * * The default tab will render with an order of 100. * * @return the order for this tab */ int tabOrder() default 100; /** * <p>Optional - only required if you need to specially handle crud operations for this * specific collection on the server</p> * * <p>Custom string values that will be passed to the server during CRUB operations on this * collection. These criteria values can be detected in a custom persistence handler * (@CustomPersistenceHandler) in order to engage special handling through custom server * side code for this collection.</p> * * @return the custom string array to pass to the server during CRUD operations */ String[] customCriteria() default {}; /** * <p>Optional - only required if a special operation type is required for a CRUD operation. This * setting is not normally changed and is an advanced setting</p> * * <p>The operation type for a CRUD operation</p> * * @return the operation type */ AdminPresentationOperationTypes operationTypes() default @AdminPresentationOperationTypes(addType = OperationType.BASIC, fetchType = OperationType.BASIC, inspectType = OperationType.BASIC, removeType = OperationType.BASIC, updateType = OperationType.BASIC); /** * <p>Optional - propertyName , only required if you want hide the field based on this property's value</p> * * <p>If the property is defined and found to be set to false, in the AppConfiguraionService, then this field will be excluded in the * admin presentation layer</p> * * @return name of the property */ String showIfProperty() default ""; /** * Optional - If you have FieldType set to SupportedFieldType.MONEY, * * then you can specify a money currency property field. * * * @return the currency property field */ String currencyCodeField() default ""; }
0true
common_src_main_java_org_broadleafcommerce_common_presentation_AdminPresentationCollection.java
156
public static final Map<String,String> REGISTERED_LOG_MANAGERS = new HashMap<String, String>() {{ put("default","com.thinkaurelius.titan.diskstorage.log.kcvs.KCVSLogManager"); }};
0true
titan-core_src_main_java_com_thinkaurelius_titan_diskstorage_Backend.java
1,133
public static class Factory implements NativeScriptFactory { @Override public ExecutableScript newScript(@Nullable Map<String, Object> params) { return new NativePayloadSumScoreScript(params); } }
0true
src_test_java_org_elasticsearch_benchmark_scripts_score_script_NativePayloadSumScoreScript.java
272
public class SelectAllMembers implements MemberSelector { @Override public boolean select(Member member) { return true; } }
0true
hazelcast-client_src_test_java_com_hazelcast_client_executor_tasks_SelectAllMembers.java
492
public class ServerCookie { private static final String tspecials = ",; "; private static final String tspecials2 = "()<>@,;:\\\"/[]?={} \t"; private static final String tspecials2NoSlash = "()<>@,;:\\\"[]?={} \t"; // Other fields private static final String OLD_COOKIE_PATTERN = "EEE, dd-MMM-yyyy HH:mm:ss z"; private static final ThreadLocal<DateFormat> OLD_COOKIE_FORMAT = new ThreadLocal<DateFormat>() { protected DateFormat initialValue() { DateFormat df = new SimpleDateFormat(OLD_COOKIE_PATTERN, Locale.US); df.setTimeZone(TimeZone.getTimeZone("GMT")); return df; } }; private static final String ancientDate; static { ancientDate = OLD_COOKIE_FORMAT.get().format(new Date(10000)); } /** * If set to true, we parse cookies according to the servlet spec, */ public static final boolean STRICT_SERVLET_COMPLIANCE = false; /** * If set to false, we don't use the IE6/7 Max-Age/Expires work around */ public static final boolean ALWAYS_ADD_EXPIRES = true; // TODO RFC2965 fields also need to be passed public static void appendCookieValue( StringBuffer headerBuf, int version, String name, String value, String path, String domain, String comment, int maxAge, boolean isSecure, boolean isHttpOnly) { StringBuffer buf = new StringBuffer(); // Servlet implementation checks name buf.append( name ); buf.append("="); // Servlet implementation does not check anything else version = maybeQuote2(version, buf, value,true); // Add version 1 specific information if (version == 1) { // Version=1 ... required buf.append ("; Version=1"); // Comment=comment if ( comment!=null ) { buf.append ("; Comment="); maybeQuote2(version, buf, comment); } } // Add domain information, if present if (domain!=null) { buf.append("; Domain="); maybeQuote2(version, buf, domain); } // Max-Age=secs ... or use old "Expires" format // TODO RFC2965 Discard if (maxAge >= 0) { if (version > 0) { buf.append ("; Max-Age="); buf.append (maxAge); } // IE6, IE7 and possibly other browsers don't understand Max-Age. // They do understand Expires, even with V1 cookies! if (version == 0 || ALWAYS_ADD_EXPIRES) { // Wdy, DD-Mon-YY HH:MM:SS GMT ( Expires Netscape format ) buf.append ("; Expires="); // To expire immediately we need to set the time in past if (maxAge == 0) buf.append( ancientDate ); else OLD_COOKIE_FORMAT.get().format( new Date(System.currentTimeMillis() + maxAge*1000L), buf, new FieldPosition(0)); } } // Path=path if (path!=null) { buf.append ("; Path="); if (version==0) { maybeQuote2(version, buf, path); } else { maybeQuote2(version, buf, path, ServerCookie.tspecials2NoSlash, false); } } // Secure if (isSecure) { buf.append ("; Secure"); } // HttpOnly if (isHttpOnly) { buf.append("; HttpOnly"); } headerBuf.append(buf); } public static int maybeQuote2 (int version, StringBuffer buf, String value) { return maybeQuote2(version,buf,value,false); } public static int maybeQuote2 (int version, StringBuffer buf, String value, boolean allowVersionSwitch) { return maybeQuote2(version,buf,value,null,allowVersionSwitch); } public static int maybeQuote2 (int version, StringBuffer buf, String value, String literals, boolean allowVersionSwitch) { if (value==null || value.length()==0) { buf.append("\"\""); }else if (containsCTL(value,version)) throw new IllegalArgumentException("Control character in cookie value, consider BASE64 encoding your value"); else if (alreadyQuoted(value)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,1,value.length()-1)); buf.append('"'); } else if (allowVersionSwitch && (!STRICT_SERVLET_COMPLIANCE) && version==0 && !isToken2(value, literals)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,0,value.length())); buf.append('"'); version = 1; } else if (version==0 && !isToken(value,literals)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,0,value.length())); buf.append('"'); } else if (version==1 && !isToken2(value,literals)) { buf.append('"'); buf.append(escapeDoubleQuotes(value,0,value.length())); buf.append('"'); }else { buf.append(value); } return version; } public static boolean containsCTL(String value, int version) { if( value==null) return false; int len = value.length(); for (int i = 0; i < len; i++) { char c = value.charAt(i); if (c < 0x20 || c >= 0x7f) { if (c == 0x09) continue; //allow horizontal tabs return true; } } return false; } public static boolean alreadyQuoted (String value) { if (value==null || value.length()==0) return false; return (value.charAt(0)=='\"' && value.charAt(value.length()-1)=='\"'); } /** * Escapes any double quotes in the given string. * * @param s the input string * @param beginIndex start index inclusive * @param endIndex exclusive * @return The (possibly) escaped string */ private static String escapeDoubleQuotes(String s, int beginIndex, int endIndex) { if (s == null || s.length() == 0 || s.indexOf('"') == -1) { return s; } StringBuffer b = new StringBuffer(); for (int i = beginIndex; i < endIndex; i++) { char c = s.charAt(i); if (c == '\\' ) { b.append(c); //ignore the character after an escape, just append it if (++i>=endIndex) throw new IllegalArgumentException("Invalid escape character in cookie value."); b.append(s.charAt(i)); } else if (c == '"') b.append('\\').append('"'); else b.append(c); } return b.toString(); } /* * Tests a string and returns true if the string counts as a * reserved token in the Java language. * * @param value the <code>String</code> to be tested * * @return <code>true</code> if the <code>String</code> is a reserved * token; <code>false</code> if it is not */ public static boolean isToken(String value) { return isToken(value,null); } public static boolean isToken(String value, String literals) { String tspecials = (literals==null?ServerCookie.tspecials:literals); if( value==null) return true; int len = value.length(); for (int i = 0; i < len; i++) { char c = value.charAt(i); if (tspecials.indexOf(c) != -1) return false; } return true; } public static boolean isToken2(String value) { return isToken2(value,null); } public static boolean isToken2(String value, String literals) { String tspecials2 = (literals==null?ServerCookie.tspecials2:literals); if( value==null) return true; int len = value.length(); for (int i = 0; i < len; i++) { char c = value.charAt(i); if (tspecials2.indexOf(c) != -1) return false; } return true; } }
0true
common_src_main_java_org_broadleafcommerce_common_security_util_ServerCookie.java
1,408
public class MetaDataIndexAliasesService extends AbstractComponent { private final ClusterService clusterService; private final IndicesService indicesService; @Inject public MetaDataIndexAliasesService(Settings settings, ClusterService clusterService, IndicesService indicesService) { super(settings); this.clusterService = clusterService; this.indicesService = indicesService; } public void indicesAliases(final IndicesAliasesClusterStateUpdateRequest request, final ClusterStateUpdateListener listener) { clusterService.submitStateUpdateTask("index-aliases", Priority.URGENT, new AckedClusterStateUpdateTask() { @Override public boolean mustAck(DiscoveryNode discoveryNode) { return true; } @Override public void onAllNodesAcked(@Nullable Throwable t) { listener.onResponse(new ClusterStateUpdateResponse(true)); } @Override public void onAckTimeout() { listener.onResponse(new ClusterStateUpdateResponse(false)); } @Override public TimeValue ackTimeout() { return request.ackTimeout(); } @Override public TimeValue timeout() { return request.masterNodeTimeout(); } @Override public void onFailure(String source, Throwable t) { listener.onFailure(t); } @Override public ClusterState execute(final ClusterState currentState) { List<String> indicesToClose = Lists.newArrayList(); Map<String, IndexService> indices = Maps.newHashMap(); try { for (AliasAction aliasAction : request.actions()) { if (!Strings.hasText(aliasAction.alias()) || !Strings.hasText(aliasAction.index())) { throw new ElasticsearchIllegalArgumentException("Index name and alias name are required"); } if (!currentState.metaData().hasIndex(aliasAction.index())) { throw new IndexMissingException(new Index(aliasAction.index())); } if (currentState.metaData().hasIndex(aliasAction.alias())) { throw new InvalidAliasNameException(new Index(aliasAction.index()), aliasAction.alias(), "an index exists with the same name as the alias"); } if (aliasAction.indexRouting() != null && aliasAction.indexRouting().indexOf(',') != -1) { throw new ElasticsearchIllegalArgumentException("alias [" + aliasAction.alias() + "] has several routing values associated with it"); } } boolean changed = false; MetaData.Builder builder = MetaData.builder(currentState.metaData()); for (AliasAction aliasAction : request.actions()) { IndexMetaData indexMetaData = builder.get(aliasAction.index()); if (indexMetaData == null) { throw new IndexMissingException(new Index(aliasAction.index())); } // TODO: not copy (putAll) IndexMetaData.Builder indexMetaDataBuilder = IndexMetaData.builder(indexMetaData); if (aliasAction.actionType() == AliasAction.Type.ADD) { String filter = aliasAction.filter(); if (Strings.hasLength(filter)) { // parse the filter, in order to validate it IndexService indexService = indices.get(indexMetaData.index()); if (indexService == null) { indexService = indicesService.indexService(indexMetaData.index()); if (indexService == null) { // temporarily create the index and add mappings so we have can parse the filter try { indexService = indicesService.createIndex(indexMetaData.index(), indexMetaData.settings(), clusterService.localNode().id()); if (indexMetaData.mappings().containsKey(MapperService.DEFAULT_MAPPING)) { indexService.mapperService().merge(MapperService.DEFAULT_MAPPING, indexMetaData.mappings().get(MapperService.DEFAULT_MAPPING).source(), false); } for (ObjectCursor<MappingMetaData> cursor : indexMetaData.mappings().values()) { MappingMetaData mappingMetaData = cursor.value; indexService.mapperService().merge(mappingMetaData.type(), mappingMetaData.source(), false); } } catch (Exception e) { logger.warn("[{}] failed to temporary create in order to apply alias action", e, indexMetaData.index()); continue; } indicesToClose.add(indexMetaData.index()); } indices.put(indexMetaData.index(), indexService); } // now, parse the filter IndexQueryParserService indexQueryParser = indexService.queryParserService(); try { XContentParser parser = XContentFactory.xContent(filter).createParser(filter); try { indexQueryParser.parseInnerFilter(parser); } finally { parser.close(); } } catch (Throwable e) { throw new ElasticsearchIllegalArgumentException("failed to parse filter for [" + aliasAction.alias() + "]", e); } } AliasMetaData newAliasMd = AliasMetaData.newAliasMetaDataBuilder( aliasAction.alias()) .filter(filter) .indexRouting(aliasAction.indexRouting()) .searchRouting(aliasAction.searchRouting()) .build(); // Check if this alias already exists AliasMetaData aliasMd = indexMetaData.aliases().get(aliasAction.alias()); if (aliasMd != null && aliasMd.equals(newAliasMd)) { // It's the same alias - ignore it continue; } indexMetaDataBuilder.putAlias(newAliasMd); } else if (aliasAction.actionType() == AliasAction.Type.REMOVE) { if (!indexMetaData.aliases().containsKey(aliasAction.alias())) { // This alias doesn't exist - ignore continue; } indexMetaDataBuilder.removerAlias(aliasAction.alias()); } changed = true; builder.put(indexMetaDataBuilder); } if (changed) { ClusterState updatedState = ClusterState.builder(currentState).metaData(builder).build(); // even though changes happened, they resulted in 0 actual changes to metadata // i.e. remove and add the same alias to the same index if (!updatedState.metaData().aliases().equals(currentState.metaData().aliases())) { return updatedState; } } return currentState; } finally { for (String index : indicesToClose) { indicesService.removeIndex(index, "created for alias processing"); } } } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { } }); } }
1no label
src_main_java_org_elasticsearch_cluster_metadata_MetaDataIndexAliasesService.java
2,667
public class DefaultPortableReader implements PortableReader { protected final ClassDefinition cd; private final PortableSerializer serializer; private final BufferObjectDataInput in; private final int finalPosition; private final int offset; private boolean raw; public DefaultPortableReader(PortableSerializer serializer, BufferObjectDataInput in, ClassDefinition cd) { this.in = in; this.serializer = serializer; this.cd = cd; try { // final position after portable is read finalPosition = in.readInt(); } catch (IOException e) { throw new HazelcastSerializationException(e); } this.offset = in.position(); } public int getVersion() { return cd.getVersion(); } public boolean hasField(String fieldName) { return cd.hasField(fieldName); } public Set<String> getFieldNames() { return cd.getFieldNames(); } public FieldType getFieldType(String fieldName) { return cd.getFieldType(fieldName); } public int getFieldClassId(String fieldName) { return cd.getFieldClassId(fieldName); } public int readInt(String fieldName) throws IOException { int pos = getPosition(fieldName); return in.readInt(pos); } public long readLong(String fieldName) throws IOException { int pos = getPosition(fieldName); return in.readLong(pos); } public String readUTF(String fieldName) throws IOException { final int currentPos = in.position(); try { int pos = getPosition(fieldName); in.position(pos); return in.readUTF(); } finally { in.position(currentPos); } } public boolean readBoolean(String fieldName) throws IOException { int pos = getPosition(fieldName); return in.readBoolean(pos); } public byte readByte(String fieldName) throws IOException { int pos = getPosition(fieldName); return in.readByte(pos); } public char readChar(String fieldName) throws IOException { int pos = getPosition(fieldName); return in.readChar(pos); } public double readDouble(String fieldName) throws IOException { int pos = getPosition(fieldName); return in.readDouble(pos); } public float readFloat(String fieldName) throws IOException { int pos = getPosition(fieldName); return in.readFloat(pos); } public short readShort(String fieldName) throws IOException { int pos = getPosition(fieldName); return in.readShort(pos); } public byte[] readByteArray(String fieldName) throws IOException { final int currentPos = in.position(); try { int pos = getPosition(fieldName); in.position(pos); return IOUtil.readByteArray(in); } finally { in.position(currentPos); } } public char[] readCharArray(String fieldName) throws IOException { final int currentPos = in.position(); try { int pos = getPosition(fieldName); in.position(pos); return in.readCharArray(); } finally { in.position(currentPos); } } public int[] readIntArray(String fieldName) throws IOException { final int currentPos = in.position(); try { int pos = getPosition(fieldName); in.position(pos); return in.readIntArray(); } finally { in.position(currentPos); } } public long[] readLongArray(String fieldName) throws IOException { final int currentPos = in.position(); try { int pos = getPosition(fieldName); in.position(pos); return in.readLongArray(); } finally { in.position(currentPos); } } public double[] readDoubleArray(String fieldName) throws IOException { final int currentPos = in.position(); try { int pos = getPosition(fieldName); in.position(pos); return in.readDoubleArray(); } finally { in.position(currentPos); } } public float[] readFloatArray(String fieldName) throws IOException { final int currentPos = in.position(); try { int pos = getPosition(fieldName); in.position(pos); return in.readFloatArray(); } finally { in.position(currentPos); } } public short[] readShortArray(String fieldName) throws IOException { final int currentPos = in.position(); try { int pos = getPosition(fieldName); in.position(pos); return in.readShortArray(); } finally { in.position(currentPos); } } public Portable readPortable(String fieldName) throws IOException { FieldDefinition fd = cd.get(fieldName); if (fd == null) { throw throwUnknownFieldException(fieldName); } final int currentPos = in.position(); try { int pos = getPosition(fd); in.position(pos); final boolean NULL = in.readBoolean(); if (!NULL) { final PortableContextAwareInputStream ctxIn = (PortableContextAwareInputStream) in; try { ctxIn.setFactoryId(fd.getFactoryId()); ctxIn.setClassId(fd.getClassId()); return serializer.readAndInitialize(in); } finally { ctxIn.setFactoryId(cd.getFactoryId()); ctxIn.setClassId(cd.getClassId()); } } return null; } finally { in.position(currentPos); } } private HazelcastSerializationException throwUnknownFieldException(String fieldName) { return new HazelcastSerializationException("Unknown field name: '" + fieldName + "' for ClassDefinition {id: " + cd.getClassId() + ", version: " + cd.getVersion() + "}"); } public Portable[] readPortableArray(String fieldName) throws IOException { FieldDefinition fd = cd.get(fieldName); if (fd == null) { throw throwUnknownFieldException(fieldName); } final int currentPos = in.position(); try { int pos = getPosition(fd); in.position(pos); final int len = in.readInt(); final Portable[] portables = new Portable[len]; if (len > 0) { final int offset = in.position(); final PortableContextAwareInputStream ctxIn = (PortableContextAwareInputStream) in; try { ctxIn.setFactoryId(fd.getFactoryId()); ctxIn.setClassId(fd.getClassId()); for (int i = 0; i < len; i++) { final int start = in.readInt(offset + i * 4); in.position(start); portables[i] = serializer.readAndInitialize(in); } } finally { ctxIn.setFactoryId(cd.getFactoryId()); ctxIn.setClassId(cd.getClassId()); } } return portables; } finally { in.position(currentPos); } } protected int getPosition(String fieldName) throws IOException { if (raw) { throw new HazelcastSerializationException("Cannot read Portable fields after getRawDataInput() is called!"); } FieldDefinition fd = cd.get(fieldName); if (fd == null) { throw throwUnknownFieldException(fieldName); } return getPosition(fd); } protected int getPosition(FieldDefinition fd) throws IOException { return in.readInt(offset + fd.getIndex() * 4); } public ObjectDataInput getRawDataInput() throws IOException { if (!raw) { int pos = in.readInt(offset + cd.getFieldCount() * 4); in.position(pos); } raw = true; return in; } void end() throws IOException { in.position(finalPosition); } }
1no label
hazelcast_src_main_java_com_hazelcast_nio_serialization_DefaultPortableReader.java
501
public interface Theme extends Serializable { public String getName(); public void setName(String name); /** * The display name for a site. Returns blank if no theme if no path is available. Should return * a path that does not start with "/" and that ends with a "/". For example, "store/". * @return */ public String getPath(); /** * Sets the path of the theme. * @param path */ public void setPath(String path); }
0true
common_src_main_java_org_broadleafcommerce_common_site_domain_Theme.java
1,172
public class OQueryOperatorBetween extends OQueryOperatorEqualityNotNulls { public OQueryOperatorBetween() { super("BETWEEN", 5, false, 3); } @Override @SuppressWarnings("unchecked") protected boolean evaluateExpression(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft, final Object iRight, OCommandContext iContext) { validate(iRight); final Iterator<?> valueIterator = OMultiValue.getMultiValueIterator(iRight); final Object right1 = OType.convert(valueIterator.next(), iLeft.getClass()); if (right1 == null) return false; valueIterator.next(); final Object right2 = OType.convert(valueIterator.next(), iLeft.getClass()); if (right2 == null) return false; return ((Comparable<Object>) iLeft).compareTo(right1) >= 0 && ((Comparable<Object>) iLeft).compareTo(right2) <= 0; } private void validate(Object iRight) { if (!OMultiValue.isMultiValue(iRight.getClass())) { throw new IllegalArgumentException("Found '" + iRight + "' while was expected: " + getSyntax()); } if (OMultiValue.getSize(iRight) != 3) throw new IllegalArgumentException("Found '" + OMultiValue.toString(iRight) + "' while was expected: " + getSyntax()); } @Override public String getSyntax() { return "<left> " + keyword + " <minRange> AND <maxRange>"; } @Override public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) { return OIndexReuseType.INDEX_METHOD; } @Override public Object executeIndexQuery(OCommandContext iContext, OIndex<?> index, INDEX_OPERATION_TYPE iOperationType, List<Object> keyParams, IndexResultListener resultListener, int fetchLimit) { final OIndexDefinition indexDefinition = index.getDefinition(); final Object result; final OIndexInternal<?> internalIndex = index.getInternal(); if (!internalIndex.canBeUsedInEqualityOperators() || !internalIndex.hasRangeQuerySupport()) return null; if (indexDefinition.getParamCount() == 1) { final Object[] betweenKeys = (Object[]) keyParams.get(0); final Object keyOne = indexDefinition.createValue(Collections.singletonList(OSQLHelper.getValue(betweenKeys[0]))); final Object keyTwo = indexDefinition.createValue(Collections.singletonList(OSQLHelper.getValue(betweenKeys[2]))); if (keyOne == null || keyTwo == null) return null; if (iOperationType == INDEX_OPERATION_TYPE.COUNT) result = index.count(keyOne, true, keyTwo, true, fetchLimit); else { if (resultListener != null) { index.getValuesBetween(keyOne, true, keyTwo, true, resultListener); result = resultListener.getResult(); } else result = index.getValuesBetween(keyOne, true, keyTwo, true); } } else { final OCompositeIndexDefinition compositeIndexDefinition = (OCompositeIndexDefinition) indexDefinition; final Object[] betweenKeys = (Object[]) keyParams.get(keyParams.size() - 1); final Object betweenKeyOne = OSQLHelper.getValue(betweenKeys[0]); if (betweenKeyOne == null) return null; final Object betweenKeyTwo = OSQLHelper.getValue(betweenKeys[2]); if (betweenKeyTwo == null) return null; final List<Object> betweenKeyOneParams = new ArrayList<Object>(keyParams.size()); betweenKeyOneParams.addAll(keyParams.subList(0, keyParams.size() - 1)); betweenKeyOneParams.add(betweenKeyOne); final List<Object> betweenKeyTwoParams = new ArrayList<Object>(keyParams.size()); betweenKeyTwoParams.addAll(keyParams.subList(0, keyParams.size() - 1)); betweenKeyTwoParams.add(betweenKeyTwo); final Object keyOne = compositeIndexDefinition.createSingleValue(betweenKeyOneParams); if (keyOne == null) return null; final Object keyTwo = compositeIndexDefinition.createSingleValue(betweenKeyTwoParams); if (keyTwo == null) return null; if (iOperationType == INDEX_OPERATION_TYPE.COUNT) result = index.count(keyOne, true, keyTwo, true, fetchLimit); else { if (resultListener != null) { index.getValuesBetween(keyOne, true, keyTwo, true, resultListener); result = resultListener.getResult(); } else result = index.getValuesBetween(keyOne, true, keyTwo, true); } } updateProfiler(iContext, index, keyParams, indexDefinition); return result; } @Override public ORID getBeginRidRange(final Object iLeft, final Object iRight) { validate(iRight); if (iLeft instanceof OSQLFilterItemField && ODocumentHelper.ATTRIBUTE_RID.equals(((OSQLFilterItemField) iLeft).getRoot())) { final Iterator<?> valueIterator = OMultiValue.getMultiValueIterator(iRight); final Object right1 = valueIterator.next(); if (right1 != null) return (ORID) right1; valueIterator.next(); return (ORID) valueIterator.next(); } return null; } @Override public ORID getEndRidRange(final Object iLeft, final Object iRight) { validate(iRight); validate(iRight); if (iLeft instanceof OSQLFilterItemField && ODocumentHelper.ATTRIBUTE_RID.equals(((OSQLFilterItemField) iLeft).getRoot())) { final Iterator<?> valueIterator = OMultiValue.getMultiValueIterator(iRight); final Object right1 = valueIterator.next(); valueIterator.next(); final Object right2 = valueIterator.next(); if (right2 == null) return (ORID) right1; return (ORID) right2; } return null; } }
1no label
core_src_main_java_com_orientechnologies_orient_core_sql_operator_OQueryOperatorBetween.java
595
public class JoinRequest extends JoinMessage implements DataSerializable { private Credentials credentials; private int tryCount; private Map<String, Object> attributes; public JoinRequest() { } public JoinRequest(byte packetVersion, int buildNumber, Address address, String uuid, ConfigCheck config, Credentials credentials, int memberCount, int tryCount, Map<String, Object> attributes) { super(packetVersion, buildNumber, address, uuid, config, memberCount); this.credentials = credentials; this.tryCount = tryCount; this.attributes = attributes; } public Credentials getCredentials() { return credentials; } public int getTryCount() { return tryCount; } public void setTryCount(int tryCount) { this.tryCount = tryCount; } public Map<String, Object> getAttributes() { return attributes; } @Override public void readData(ObjectDataInput in) throws IOException { super.readData(in); credentials = in.readObject(); if (credentials != null) { credentials.setEndpoint(getAddress().getHost()); } tryCount = in.readInt(); int size = in.readInt(); attributes = new HashMap<String, Object>(); for (int i = 0; i < size; i++) { String key = in.readUTF(); Object value = in.readObject(); attributes.put(key, value); } } @Override public void writeData(ObjectDataOutput out) throws IOException { super.writeData(out); out.writeObject(credentials); out.writeInt(tryCount); out.writeInt(attributes.size()); for (Map.Entry<String, Object> entry : attributes.entrySet()) { out.writeUTF(entry.getKey()); out.writeObject(entry.getValue()); } } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("JoinRequest"); sb.append("{packetVersion=").append(packetVersion); sb.append(", buildNumber=").append(buildNumber); sb.append(", address=").append(address); sb.append(", uuid='").append(uuid).append('\''); sb.append(", credentials=").append(credentials); sb.append(", memberCount=").append(memberCount); sb.append(", tryCount=").append(tryCount); sb.append('}'); return sb.toString(); } }
0true
hazelcast_src_main_java_com_hazelcast_cluster_JoinRequest.java
52
public class ClusterManager extends LifecycleAdapter { public static class Builder { private final File root; private final Provider provider = clusterOfSize( 3 ); private final Map<String, String> commonConfig = emptyMap(); private final Map<Integer, Map<String,String>> instanceConfig = new HashMap<>(); private HighlyAvailableGraphDatabaseFactory factory = new HighlyAvailableGraphDatabaseFactory(); private StoreDirInitializer initializer; public Builder( File root ) { this.root = root; } public Builder withSeedDir( final File seedDir ) { return withStoreDirInitializer( new StoreDirInitializer() { @Override public void initializeStoreDir( int serverId, File storeDir ) throws IOException { copyRecursively( seedDir, storeDir ); } } ); } public Builder withStoreDirInitializer( StoreDirInitializer initializer ) { this.initializer = initializer; return this; } public Builder withDbFactory( HighlyAvailableGraphDatabaseFactory dbFactory ) { this.factory = dbFactory; return this; } public ClusterManager build() { return new ClusterManager( this ); } } public interface StoreDirInitializer { void initializeStoreDir( int serverId, File storeDir ) throws IOException; } /** * Provides a specification of which clusters to start in {@link ClusterManager#start()}. */ public interface Provider { Clusters clusters() throws Throwable; } /** * Provider pointing out an XML file to read. * * @param clustersXml the XML file containing the cluster specifications. */ public static Provider fromXml( final URI clustersXml ) { return new Provider() { @Override public Clusters clusters() throws Exception { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document clustersXmlDoc = documentBuilder.parse( clustersXml.toURL().openStream() ); return new ClustersXMLSerializer( documentBuilder ).read( clustersXmlDoc ); } }; } /** * Provides a cluster specification with default values * * @param memberCount the total number of members in the cluster to start. */ public static Provider clusterOfSize( int memberCount ) { Clusters.Cluster cluster = new Clusters.Cluster( "neo4j.ha" ); for ( int i = 0; i < memberCount; i++ ) { cluster.getMembers().add( new Clusters.Member( 5001 + i, true ) ); } final Clusters clusters = new Clusters(); clusters.getClusters().add( cluster ); return provided( clusters ); } /** * Provides a cluster specification with default values * @param haMemberCount the total number of members in the cluster to start. */ public static Provider clusterWithAdditionalClients( int haMemberCount, int additionalClientCount ) { Clusters.Cluster cluster = new Clusters.Cluster( "neo4j.ha" ); int counter = 0; for ( int i = 0; i < haMemberCount; i++, counter++ ) { cluster.getMembers().add( new Clusters.Member( 5001 + counter, true ) ); } for ( int i = 0; i < additionalClientCount; i++, counter++ ) { cluster.getMembers().add( new Clusters.Member( 5001 + counter, false ) ); } final Clusters clusters = new Clusters(); clusters.getClusters().add( cluster ); return provided( clusters ); } /** * Provides a cluster specification with default values * @param haMemberCount the total number of members in the cluster to start. */ public static Provider clusterWithAdditionalArbiters( int haMemberCount, int arbiterCount) { Clusters.Cluster cluster = new Clusters.Cluster( "neo4j.ha" ); int counter = 0; for ( int i = 0; i < arbiterCount; i++, counter++ ) { cluster.getMembers().add( new Clusters.Member( 5001 + counter, false ) ); } for ( int i = 0; i < haMemberCount; i++, counter++ ) { cluster.getMembers().add( new Clusters.Member( 5001 + counter, true ) ); } final Clusters clusters = new Clusters(); clusters.getClusters().add( cluster ); return provided( clusters ); } public static Provider provided( final Clusters clusters ) { return new Provider() { @Override public Clusters clusters() throws Throwable { return clusters; } }; } LifeSupport life; private final File root; private final Map<String, String> commonConfig; private final Map<Integer, Map<String, String>> instanceConfig; private final Map<String, ManagedCluster> clusterMap = new HashMap<>(); private final Provider clustersProvider; private final HighlyAvailableGraphDatabaseFactory dbFactory; private final StoreDirInitializer storeDirInitializer; public ClusterManager( Provider clustersProvider, File root, Map<String, String> commonConfig, Map<Integer, Map<String, String>> instanceConfig, HighlyAvailableGraphDatabaseFactory dbFactory ) { this.clustersProvider = clustersProvider; this.root = root; this.commonConfig = commonConfig; this.instanceConfig = instanceConfig; this.dbFactory = dbFactory; this.storeDirInitializer = null; } private ClusterManager( Builder builder ) { this.clustersProvider = builder.provider; this.root = builder.root; this.commonConfig = builder.commonConfig; this.instanceConfig = builder.instanceConfig; this.dbFactory = builder.factory; this.storeDirInitializer = builder.initializer; } public ClusterManager( Provider clustersProvider, File root, Map<String, String> commonConfig, Map<Integer, Map<String, String>> instanceConfig ) { this( clustersProvider, root, commonConfig, instanceConfig, new HighlyAvailableGraphDatabaseFactory() ); } public ClusterManager( Provider clustersProvider, File root, Map<String, String> commonConfig ) { this( clustersProvider, root, commonConfig, Collections.<Integer, Map<String, String>>emptyMap(), new HighlyAvailableGraphDatabaseFactory() ); } @Override public void start() throws Throwable { Clusters clusters = clustersProvider.clusters(); life = new LifeSupport(); // Started so instances added here will be started immediately, and in case of exceptions they can be // shutdown() or stop()ped properly life.start(); for ( int i = 0; i < clusters.getClusters().size(); i++ ) { Clusters.Cluster cluster = clusters.getClusters().get( i ); ManagedCluster managedCluster = new ManagedCluster( cluster ); clusterMap.put( cluster.getName(), managedCluster ); life.add( managedCluster ); } } @Override public void stop() throws Throwable { life.stop(); } @Override public void shutdown() throws Throwable { life.shutdown(); } /** * Represent one cluster. It can retrieve the current master, random slave * or all members. It can also temporarily fail an instance or shut it down. */ public class ManagedCluster extends LifecycleAdapter { private final Clusters.Cluster spec; private final String name; private final Map<Integer, HighlyAvailableGraphDatabaseProxy> members = new ConcurrentHashMap<>(); private final List<ClusterMembers> arbiters = new ArrayList<>( ); ManagedCluster( Clusters.Cluster spec ) throws URISyntaxException, IOException { this.spec = spec; this.name = spec.getName(); for ( int i = 0; i < spec.getMembers().size(); i++ ) { startMember( i + 1 ); } for ( HighlyAvailableGraphDatabaseProxy member : members.values() ) { insertInitialData( member.get(), name, member.get().getConfig().get( ClusterSettings.server_id ) ); } } public String getInitialHostsConfigString() { StringBuilder result = new StringBuilder(); for ( HighlyAvailableGraphDatabase member : getAllMembers() ) { result.append( result.length() > 0 ? "," : "" ).append( ":" ) .append( member.getDependencyResolver().resolveDependency( ClusterClient.class ).getClusterServer().getPort() ); } return result.toString(); } @Override public void stop() throws Throwable { for ( HighlyAvailableGraphDatabaseProxy member : members.values() ) { member.get().shutdown(); } } /** * @return all started members in this cluster. */ public Iterable<HighlyAvailableGraphDatabase> getAllMembers() { return Iterables.map( new Function<HighlyAvailableGraphDatabaseProxy, HighlyAvailableGraphDatabase>() { @Override public HighlyAvailableGraphDatabase apply( HighlyAvailableGraphDatabaseProxy from ) { return from.get(); } }, members.values() ); } public Iterable<ClusterMembers> getArbiters() { return arbiters; } /** * @return the current master in the cluster. * @throws IllegalStateException if there's no current master. */ public HighlyAvailableGraphDatabase getMaster() { for ( HighlyAvailableGraphDatabase graphDatabaseService : getAllMembers() ) { if ( graphDatabaseService.isMaster() ) { return graphDatabaseService; } } throw new IllegalStateException( "No master found in cluster " + name ); } /** * @param except do not return any of the dbs found in this array * @return a slave in this cluster. * @throws IllegalStateException if no slave was found in this cluster. */ public HighlyAvailableGraphDatabase getAnySlave( HighlyAvailableGraphDatabase... except ) { Set<HighlyAvailableGraphDatabase> exceptSet = new HashSet<>( asList( except ) ); for ( HighlyAvailableGraphDatabase graphDatabaseService : getAllMembers() ) { if ( graphDatabaseService.getInstanceState().equals( "SLAVE" ) && !exceptSet.contains( graphDatabaseService ) ) { return graphDatabaseService; } } throw new IllegalStateException( "No slave found in cluster " + name ); } /** * @param serverId the server id to return the db for. * @return the {@link HighlyAvailableGraphDatabase} with the given server id. * @throws IllegalStateException if that db isn't started or no such * db exists in the cluster. */ public HighlyAvailableGraphDatabase getMemberByServerId( int serverId ) { HighlyAvailableGraphDatabase db = members.get( serverId ).get(); if ( db == null ) { throw new IllegalStateException( "Db " + serverId + " not found at the moment in " + name ); } return db; } /** * Shuts down a member of this cluster. A {@link RepairKit} is returned * which is able to restore the instance (i.e. start it again). * * @param db the {@link HighlyAvailableGraphDatabase} to shut down. * @return a {@link RepairKit} which can start it again. * @throws IllegalArgumentException if the given db isn't a member of this cluster. */ public RepairKit shutdown( HighlyAvailableGraphDatabase db ) { assertMember( db ); int serverId = db.getDependencyResolver().resolveDependency( Config.class ).get( ClusterSettings.server_id ); members.remove( serverId ); life.remove( db ); db.shutdown(); return new StartDatabaseAgainKit( this, serverId ); } private void assertMember( HighlyAvailableGraphDatabase db ) { for ( HighlyAvailableGraphDatabaseProxy highlyAvailableGraphDatabaseProxy : members.values() ) { if ( highlyAvailableGraphDatabaseProxy.get().equals( db ) ) { return; } } throw new IllegalArgumentException( "Db " + db + " not a member of this cluster " + name ); } /** * WARNING: beware of hacks. * <p/> * Fails a member of this cluster by making it not respond to heart beats. * A {@link RepairKit} is returned which is able to repair the instance * (i.e start the network) again. * * @param db the {@link HighlyAvailableGraphDatabase} to fail. * @return a {@link RepairKit} which can repair the failure. * @throws IllegalArgumentException if the given db isn't a member of this cluster. */ public RepairKit fail( HighlyAvailableGraphDatabase db ) throws Throwable { assertMember( db ); ClusterClient clusterClient = db.getDependencyResolver().resolveDependency( ClusterClient.class ); LifeSupport clusterClientLife = (LifeSupport) accessible( clusterClient.getClass().getDeclaredField( "life" ) ).get( clusterClient ); NetworkReceiver receiver = instance( NetworkReceiver.class, clusterClientLife.getLifecycleInstances() ); receiver.stop(); ExecutorLifecycleAdapter statemachineExecutor = instance(ExecutorLifecycleAdapter.class, clusterClientLife.getLifecycleInstances()); statemachineExecutor.stop(); NetworkSender sender = instance( NetworkSender.class, clusterClientLife.getLifecycleInstances() ); sender.stop(); List<Lifecycle> stoppedServices = new ArrayList<>(); stoppedServices.add( sender ); stoppedServices.add(statemachineExecutor); stoppedServices.add( receiver ); return new StartNetworkAgainKit( db, stoppedServices ); } private void startMember( int serverId ) throws URISyntaxException, IOException { Clusters.Member member = spec.getMembers().get( serverId-1 ); StringBuilder initialHosts = new StringBuilder( spec.getMembers().get( 0 ).getHost() ); for (int i = 1; i < spec.getMembers().size(); i++) { initialHosts.append( "," ).append( spec.getMembers().get( i ).getHost() ); } File parent = new File( root, name ); URI clusterUri = new URI( "cluster://" + member.getHost() ); if ( member.isFullHaMember() ) { int clusterPort = clusterUri.getPort(); int haPort = clusterUri.getPort() + 3000; File storeDir = new File( parent, "server" + serverId ); if ( storeDirInitializer != null) { storeDirInitializer.initializeStoreDir( serverId, storeDir ); } GraphDatabaseBuilder graphDatabaseBuilder = dbFactory.newHighlyAvailableDatabaseBuilder( storeDir.getAbsolutePath() ). setConfig( ClusterSettings.cluster_name, name ). setConfig( ClusterSettings.initial_hosts, initialHosts.toString() ). setConfig( ClusterSettings.server_id, serverId + "" ). setConfig( ClusterSettings.cluster_server, "0.0.0.0:"+clusterPort). setConfig( HaSettings.ha_server, ":" + haPort ). setConfig( OnlineBackupSettings.online_backup_enabled, Settings.FALSE ). setConfig( commonConfig ); if ( instanceConfig.containsKey( serverId ) ) { graphDatabaseBuilder.setConfig( instanceConfig.get( serverId ) ); } config( graphDatabaseBuilder, name, serverId ); final HighlyAvailableGraphDatabaseProxy graphDatabase = new HighlyAvailableGraphDatabaseProxy( graphDatabaseBuilder ); members.put( serverId, graphDatabase ); life.add( new LifecycleAdapter() { @Override public void stop() throws Throwable { graphDatabase.get().shutdown(); } } ); } else { Map<String, String> config = MapUtil.stringMap( ClusterSettings.cluster_name.name(), name, ClusterSettings.initial_hosts.name(), initialHosts.toString(), ClusterSettings.server_id.name(), serverId + "", ClusterSettings.cluster_server.name(), "0.0.0.0:"+clusterUri.getPort(), GraphDatabaseSettings.store_dir.name(), new File( parent, "arbiter" + serverId ).getAbsolutePath() ); Config config1 = new Config( config ); Logging clientLogging =life.add( new LogbackService( config1, new LoggerContext() ) ); ObjectStreamFactory objectStreamFactory = new ObjectStreamFactory(); ClusterClient clusterClient = new ClusterClient( ClusterClient.adapt( config1 ), clientLogging, new NotElectableElectionCredentialsProvider(), objectStreamFactory, objectStreamFactory ); arbiters.add(new ClusterMembers(clusterClient, clusterClient, new ClusterMemberEvents() { @Override public void addClusterMemberListener( ClusterMemberListener listener ) { // noop } @Override public void removeClusterMemberListener( ClusterMemberListener listener ) { // noop } }, clusterClient.getServerId() )); life.add( new FutureLifecycleAdapter<>( clusterClient ) ); } } /** * Will await a condition for the default max time. * * @param predicate {@link Predicate} that should return true * signalling that the condition has been met. * @throws IllegalStateException if the condition wasn't met * during within the max time. */ public void await( Predicate<ManagedCluster> predicate ) { await( predicate, 60 ); } /** * Will await a condition for the given max time. * * @param predicate {@link Predicate} that should return true * signalling that the condition has been met. * @throws IllegalStateException if the condition wasn't met * during within the max time. */ public void await( Predicate<ManagedCluster> predicate, int maxSeconds ) { long end = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis( maxSeconds ); while ( System.currentTimeMillis() < end ) { if ( predicate.accept( this ) ) { return; } try { Thread.sleep( 100 ); } catch ( InterruptedException e ) { // Ignore } } String state = printState( this ); throw new IllegalStateException( format( "Awaited condition never met, waited %s for %s:%n%s", maxSeconds, predicate, state ) ); } /** * The total number of members of the cluster. */ public int size() { return spec.getMembers().size(); } public int getServerId( HighlyAvailableGraphDatabase member ) { assertMember( member ); return member.getConfig().get( ClusterSettings.server_id ); } public File getStoreDir( HighlyAvailableGraphDatabase member ) { assertMember( member ); return member.getConfig().get( GraphDatabaseSettings.store_dir ); } public void sync( HighlyAvailableGraphDatabase... except ) { Set<HighlyAvailableGraphDatabase> exceptSet = new HashSet<>( asList( except ) ); for ( HighlyAvailableGraphDatabase db : getAllMembers() ) { if ( !exceptSet.contains( db ) ) { db.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates(); } } } } private static final class HighlyAvailableGraphDatabaseProxy { private GraphDatabaseService result; private Future<GraphDatabaseService> untilThen; private final ExecutorService executor; public HighlyAvailableGraphDatabaseProxy( final GraphDatabaseBuilder graphDatabaseBuilder ) { Callable<GraphDatabaseService> starter = new Callable<GraphDatabaseService>() { @Override public GraphDatabaseService call() throws Exception { return graphDatabaseBuilder.newGraphDatabase(); } }; executor = Executors.newFixedThreadPool( 1 ); untilThen = executor.submit( starter ); } public HighlyAvailableGraphDatabase get() { if ( result == null ) { try { result = untilThen.get(); } catch ( InterruptedException | ExecutionException e ) { throw new RuntimeException( e ); } finally { executor.shutdownNow(); } } return (HighlyAvailableGraphDatabase) result; } } private static final class FutureLifecycleAdapter<T extends Lifecycle> extends LifecycleAdapter { private final T wrapped; private Future<Void> currentFuture; private final ExecutorService starter; public FutureLifecycleAdapter( T toWrap) { wrapped = toWrap; starter = Executors.newFixedThreadPool( 1 ); } @Override public void init() throws Throwable { currentFuture = starter.submit( new Callable<Void>() { @Override public Void call() throws Exception { try { wrapped.init(); } catch ( Throwable throwable ) { throw new RuntimeException( throwable ); } return null; } } ); } @Override public void start() throws Throwable { currentFuture.get(); currentFuture = starter.submit( new Callable<Void>() { @Override public Void call() throws Exception { try { wrapped.start(); } catch ( Throwable throwable ) { throw new RuntimeException( throwable ); } return null; } } ); } @Override public void stop() throws Throwable { currentFuture.get(); currentFuture = starter.submit( new Callable<Void>() { @Override public Void call() throws Exception { try { wrapped.stop(); } catch ( Throwable throwable ) { throw new RuntimeException( throwable ); } return null; } } ); } @Override public void shutdown() throws Throwable { currentFuture = starter.submit( new Callable<Void>() { @Override public Void call() throws Exception { try { wrapped.shutdown(); } catch ( Throwable throwable ) { throw new RuntimeException( throwable ); } return null; } } ); currentFuture.get(); starter.shutdownNow(); } } /** * The current master sees this many slaves as available. * * @param count number of slaves to see as available. */ public static Predicate<ManagedCluster> masterSeesSlavesAsAvailable( final int count ) { return new Predicate<ClusterManager.ManagedCluster>() { @Override public boolean accept( ManagedCluster cluster ) { return count( cluster.getMaster().getDependencyResolver().resolveDependency( Slaves.class ).getSlaves () ) >= count; } @Override public String toString() { return "Master should see " + count + " slaves as available"; } }; } /** * The current master sees all slaves in the cluster as available. * Based on the total number of members in the cluster. */ public static Predicate<ManagedCluster> masterSeesAllSlavesAsAvailable() { return new Predicate<ClusterManager.ManagedCluster>() { @Override public boolean accept( ManagedCluster cluster ) { return count( cluster.getMaster().getDependencyResolver().resolveDependency( Slaves.class ).getSlaves () ) >= cluster.size() - 1; } @Override public String toString() { return "Master should see all slaves as available"; } }; } /** * There must be a master available. Optionally exceptions, useful for when awaiting a * re-election of a different master. */ public static Predicate<ManagedCluster> masterAvailable( HighlyAvailableGraphDatabase... except ) { final Set<HighlyAvailableGraphDatabase> exceptSet = new HashSet<>( asList( except ) ); return new Predicate<ClusterManager.ManagedCluster>() { @Override public boolean accept( ManagedCluster cluster ) { for ( HighlyAvailableGraphDatabase graphDatabaseService : cluster.getAllMembers() ) { if ( !exceptSet.contains( graphDatabaseService )) { if ( graphDatabaseService.isMaster() ) { return true; } } } return false; } @Override public String toString() { return "There's an available master"; } }; } /** * The current master sees this many slaves as available. * @param count number of slaves to see as available. */ public static Predicate<ManagedCluster> masterSeesMembers( final int count ) { return new Predicate<ClusterManager.ManagedCluster>() { @Override public boolean accept( ManagedCluster cluster ) { ClusterMembers members = cluster.getMaster().getDependencyResolver().resolveDependency( ClusterMembers.class ); return Iterables.count(members.getMembers()) == count; } @Override public String toString() { return "Master should see " + count + " members"; } }; } public static Predicate<ManagedCluster> allSeesAllAsAvailable() { return new Predicate<ManagedCluster>() { @Override public boolean accept( ManagedCluster cluster ) { if (!allSeesAllAsJoined().accept( cluster )) return false; for ( HighlyAvailableGraphDatabase database : cluster.getAllMembers() ) { ClusterMembers members = database.getDependencyResolver().resolveDependency( ClusterMembers.class ); for ( ClusterMember clusterMember : members.getMembers() ) { if ( clusterMember.getHARole().equals( "UNKNOWN" ) ) { return false; } } } // Everyone sees everyone else as available! return true; } @Override public String toString() { return "All instances should see all others as available"; } }; } public static Predicate<ManagedCluster> allSeesAllAsJoined( ) { return new Predicate<ManagedCluster>() { @Override public boolean accept( ManagedCluster cluster ) { int nrOfMembers = cluster.size(); for ( HighlyAvailableGraphDatabase database : cluster.getAllMembers() ) { ClusterMembers members = database.getDependencyResolver().resolveDependency( ClusterMembers.class ); if (Iterables.count( members.getMembers() ) < nrOfMembers) return false; } for ( ClusterMembers clusterMembers : cluster.getArbiters() ) { if (Iterables.count(clusterMembers.getMembers()) < nrOfMembers) { return false; } } // Everyone sees everyone else as joined! return true; } @Override public String toString() { return "All instances should see all others as joined"; } }; } public static Predicate<ManagedCluster> allAvailabilityGuardsReleased() { return new Predicate<ManagedCluster>() { @Override public boolean accept( ManagedCluster item ) { for ( HighlyAvailableGraphDatabaseProxy member : item.members.values() ) { try { member.get().beginTx().close(); } catch ( TransactionFailureException e ) { return false; } } return true; } }; } private static String printState(ManagedCluster cluster) { StringBuilder buf = new StringBuilder(); for ( HighlyAvailableGraphDatabase database : cluster.getAllMembers() ) { ClusterMembers members = database.getDependencyResolver().resolveDependency( ClusterMembers.class ); for ( ClusterMember clusterMember : members.getMembers() ) { buf.append( clusterMember.getInstanceId() ).append( ":" ).append( clusterMember.getHARole() ) .append( "\n" ); } buf.append( "\n" ); } return buf.toString(); } @SuppressWarnings("unchecked") private <T> T instance( Class<T> classToFind, Iterable<?> from ) { for ( Object item : from ) { if ( classToFind.isAssignableFrom( item.getClass() ) ) { return (T) item; } } fail( "Couldn't find the network instance to fail. Internal field, so fragile sensitive to changes though" ); return null; // it will never get here. } private Field accessible( Field field ) { field.setAccessible( true ); return field; } public ManagedCluster getCluster( String name ) { if ( !clusterMap.containsKey( name ) ) { throw new IllegalArgumentException( name ); } return clusterMap.get( name ); } public ManagedCluster getDefaultCluster() { return getCluster( "neo4j.ha" ); } protected void config( GraphDatabaseBuilder builder, String clusterName, int serverId ) { } protected void insertInitialData( GraphDatabaseService db, String name, int serverId ) { } public interface RepairKit { HighlyAvailableGraphDatabase repair() throws Throwable; } private class StartNetworkAgainKit implements RepairKit { private final HighlyAvailableGraphDatabase db; private final Iterable<Lifecycle> stoppedServices; StartNetworkAgainKit( HighlyAvailableGraphDatabase db, Iterable<Lifecycle> stoppedServices ) { this.db = db; this.stoppedServices = stoppedServices; } @Override public HighlyAvailableGraphDatabase repair() throws Throwable { for ( Lifecycle stoppedService : stoppedServices ) { stoppedService.start(); } return db; } } private class StartDatabaseAgainKit implements RepairKit { private final int serverId; private final ManagedCluster cluster; public StartDatabaseAgainKit( ManagedCluster cluster, int serverId ) { this.cluster = cluster; this.serverId = serverId; } @Override public HighlyAvailableGraphDatabase repair() throws Throwable { cluster.startMember( serverId ); return cluster.getMemberByServerId( serverId ); } } }
1no label
enterprise_ha_src_test_java_org_neo4j_test_ha_ClusterManager.java
628
c3.addListenerConfig(new ListenerConfig(new LifecycleListener() { public void stateChanged(final LifecycleEvent event) { if (event.getState() == LifecycleState.MERGING) { h1.shutdown(); } else if (event.getState() == LifecycleState.MERGED) { latch.countDown(); } } }));
0true
hazelcast_src_test_java_com_hazelcast_cluster_SplitBrainHandlerTest.java
804
return new PortableFactory() { @Override public Portable create(int classId) { switch (classId) { case ADD_AND_GET: return new AddAndGetRequest(); case COMPARE_AND_SET: return new CompareAndSetRequest(); case GET_AND_ADD: return new GetAndAddRequest(); case GET_AND_SET: return new GetAndSetRequest(); case SET: return new SetRequest(); case APPLY: return new ApplyRequest(); case ALTER: return new AlterRequest(); case ALTER_AND_GET: return new AlterAndGetRequest(); case GET_AND_ALTER: return new GetAndAlterRequest(); default: return null; } } };
0true
hazelcast_src_main_java_com_hazelcast_concurrent_atomiclong_client_AtomicLongPortableHook.java
299
public class ServiceException extends Exception { private static final long serialVersionUID = -7084792578727995587L; // for serialization purposes protected ServiceException() { super(); } public ServiceException(String message, Throwable cause) { super(message, cause); } public ServiceException(String message) { super(message); } public ServiceException(Throwable cause) { super(cause); } /** * Checks to see if any of the causes of the chain of exceptions that led to this ServiceException are an instance * of the given class. * * @param clazz * @return whether or not this exception's causes includes the given class. */ public boolean containsCause(Class<? extends Throwable> clazz) { Throwable current = this; do { if (clazz.isAssignableFrom(current.getClass())) { return true; } current = current.getCause(); } while (current.getCause() != null); return false; } }
1no label
common_src_main_java_org_broadleafcommerce_common_exception_ServiceException.java
248
@Service("blCurrencyService") public class BroadleafCurrencyServiceImpl implements BroadleafCurrencyService { @Resource(name="blCurrencyDao") protected BroadleafCurrencyDao currencyDao; /** * Returns the default Broadleaf currency * @return The default currency */ @Override public BroadleafCurrency findDefaultBroadleafCurrency() { return currencyDao.findDefaultBroadleafCurrency(); } /** * @return The currency for the passed in code */ @Override public BroadleafCurrency findCurrencyByCode(String currencyCode) { return currencyDao.findCurrencyByCode(currencyCode); } /** * Returns a list of all the Broadleaf Currencies *@return List of currencies */ @Override public List<BroadleafCurrency> getAllCurrencies() { return currencyDao.getAllCurrencies(); } @Override public BroadleafCurrency save(BroadleafCurrency currency) { return currencyDao.save(currency); } }
0true
common_src_main_java_org_broadleafcommerce_common_currency_service_BroadleafCurrencyServiceImpl.java
64
public class EC2RequestSigner { private static final String HTTP_VERB = "GET\n"; private static final String HTTP_REQUEST_URI = "/\n"; private final String secretKey; public EC2RequestSigner(String secretKey) { if (secretKey == null) { throw new IllegalArgumentException("AWS secret key is required!"); } this.secretKey = secretKey; } public void sign(DescribeInstances request, String endpoint) { String canonicalizedQueryString = getCanonicalizedQueryString(request); String stringToSign = HTTP_VERB + endpoint + "\n" + HTTP_REQUEST_URI + canonicalizedQueryString; String signature = signTheString(stringToSign); request.putSignature(signature); } private String signTheString(String stringToSign) { String signature = null; try { signature = RFC2104HMAC.calculateRFC2104HMAC(stringToSign, secretKey); } catch (SignatureException e) { throw new RuntimeException(e); } return signature; } private String getCanonicalizedQueryString(DescribeInstances request) { List<String> components = getListOfEntries(request.getAttributes()); Collections.sort(components); return getCanonicalizedQueryString(components); } private void addComponents(List<String> components, Map<String, String> attributes, String key) { components.add(AwsURLEncoder.urlEncode(key) + "=" + AwsURLEncoder.urlEncode(attributes.get(key))); } private List<String> getListOfEntries(Map<String, String> entries) { List<String> components = new ArrayList<String>(); for (String key : entries.keySet()) { addComponents(components, entries, key); } return components; } /** * @param list * @return */ private String getCanonicalizedQueryString(List<String> list) { Iterator<String> it = list.iterator(); StringBuilder result = new StringBuilder(it.next()); while (it.hasNext()) { result.append("&").append(it.next()); } return result.toString(); } }
0true
hazelcast-cloud_src_main_java_com_hazelcast_aws_security_EC2RequestSigner.java
1,530
public class SingleShardOneReplicaRoutingTests extends ElasticsearchAllocationTestCase { private final ESLogger logger = Loggers.getLogger(SingleShardOneReplicaRoutingTests.class); @Test public void testSingleIndexFirstStartPrimaryThenBackups() { AllocationService strategy = createAllocationService(settingsBuilder().put("cluster.routing.allocation.concurrent_recoveries", 10).build()); logger.info("Building initial routing table"); MetaData metaData = MetaData.builder() .put(IndexMetaData.builder("test").numberOfShards(1).numberOfReplicas(1)) .build(); RoutingTable routingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); ClusterState clusterState = ClusterState.builder().metaData(metaData).routingTable(routingTable).build(); assertThat(routingTable.index("test").shards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(0).size(), equalTo(2)); assertThat(routingTable.index("test").shard(0).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(0).shards().get(0).state(), equalTo(UNASSIGNED)); assertThat(routingTable.index("test").shard(0).shards().get(1).state(), equalTo(UNASSIGNED)); assertThat(routingTable.index("test").shard(0).shards().get(0).currentNodeId(), nullValue()); assertThat(routingTable.index("test").shard(0).shards().get(1).currentNodeId(), nullValue()); logger.info("Adding one node and performing rerouting"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder().put(newNode("node1"))).build(); RoutingTable prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(0).size(), equalTo(2)); assertThat(routingTable.index("test").shard(0).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(0).primaryShard().state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test").shard(0).primaryShard().currentNodeId(), equalTo("node1")); assertThat(routingTable.index("test").shard(0).replicaShards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(0).replicaShards().get(0).state(), equalTo(UNASSIGNED)); assertThat(routingTable.index("test").shard(0).replicaShards().get(0).currentNodeId(), nullValue()); logger.info("Add another node and perform rerouting, nothing will happen since primary shards not started"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node2"))).build(); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable == routingTable, equalTo(true)); logger.info("Start the primary shard (on node1)"); RoutingNodes routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.node("node1").shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(0).size(), equalTo(2)); assertThat(routingTable.index("test").shard(0).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(0).primaryShard().state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(0).primaryShard().currentNodeId(), equalTo("node1")); assertThat(routingTable.index("test").shard(0).replicaShards().size(), equalTo(1)); // backup shards are initializing as well, we make sure that they recover from primary *started* shards in the IndicesClusterStateService assertThat(routingTable.index("test").shard(0).replicaShards().get(0).state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test").shard(0).replicaShards().get(0).currentNodeId(), equalTo("node2")); logger.info("Reroute, nothing should change"); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); assertThat(prevRoutingTable == routingTable, equalTo(true)); logger.info("Start the backup shard"); routingNodes = clusterState.routingNodes(); prevRoutingTable = routingTable; routingTable = strategy.applyStartedShards(clusterState, routingNodes.node("node2").shardsWithState(INITIALIZING)).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(0).size(), equalTo(2)); assertThat(routingTable.index("test").shard(0).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(0).primaryShard().state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(0).primaryShard().currentNodeId(), equalTo("node1")); assertThat(routingTable.index("test").shard(0).replicaShards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(0).replicaShards().get(0).state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(0).replicaShards().get(0).currentNodeId(), equalTo("node2")); logger.info("Kill node1, backup shard should become primary"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).remove("node1")).build(); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(0).size(), equalTo(2)); assertThat(routingTable.index("test").shard(0).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(0).primaryShard().state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(0).primaryShard().currentNodeId(), equalTo("node2")); assertThat(routingTable.index("test").shard(0).replicaShards().size(), equalTo(1)); // backup shards are initializing as well, we make sure that they recover from primary *started* shards in the IndicesClusterStateService assertThat(routingTable.index("test").shard(0).replicaShards().get(0).state(), equalTo(UNASSIGNED)); assertThat(routingTable.index("test").shard(0).replicaShards().get(0).currentNodeId(), nullValue()); logger.info("Start another node, backup shard should start initializing"); clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).put(newNode("node3"))).build(); prevRoutingTable = routingTable; routingTable = strategy.reroute(clusterState).routingTable(); clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build(); assertThat(prevRoutingTable != routingTable, equalTo(true)); assertThat(routingTable.index("test").shards().size(), equalTo(1)); assertThat(routingTable.index("test").shard(0).size(), equalTo(2)); assertThat(routingTable.index("test").shard(0).shards().size(), equalTo(2)); assertThat(routingTable.index("test").shard(0).primaryShard().state(), equalTo(STARTED)); assertThat(routingTable.index("test").shard(0).primaryShard().currentNodeId(), equalTo("node2")); assertThat(routingTable.index("test").shard(0).replicaShards().size(), equalTo(1)); // backup shards are initializing as well, we make sure that they recover from primary *started* shards in the IndicesClusterStateService assertThat(routingTable.index("test").shard(0).replicaShards().get(0).state(), equalTo(INITIALIZING)); assertThat(routingTable.index("test").shard(0).replicaShards().get(0).currentNodeId(), equalTo("node3")); } }
0true
src_test_java_org_elasticsearch_cluster_routing_allocation_SingleShardOneReplicaRoutingTests.java
923
threadPool.generic().execute(new Runnable() { @Override public void run() { try { listener.onResponse(response); } catch (Throwable e) { listener.onFailure(e); } } });
0true
src_main_java_org_elasticsearch_action_support_TransportAction.java
97
public static final class Point { private final float longitude; private final float latitude; /** * Constructs a point with the given latitude and longitude * @param latitude Between -90 and 90 degrees * @param longitude Between -180 and 180 degrees */ Point(float latitude, float longitude) { this.longitude = longitude; this.latitude = latitude; } /** * Longitude of this point * @return */ public float getLongitude() { return longitude; } /** * Latitude of this point * @return */ public float getLatitude() { return latitude; } private com.spatial4j.core.shape.Point getSpatial4jPoint() { return CTX.makePoint(longitude,latitude); } /** * Returns the distance to another point in kilometers * * @param other Point * @return */ public double distance(Point other) { return DistanceUtils.degrees2Dist(CTX.getDistCalc().distance(getSpatial4jPoint(),other.getSpatial4jPoint()),DistanceUtils.EARTH_MEAN_RADIUS_KM); } @Override public String toString() { return "["+latitude+","+longitude+"]"; } @Override public int hashCode() { return new HashCodeBuilder().append(latitude).append(longitude).toHashCode(); } @Override public boolean equals(Object other) { if (this==other) return true; else if (other==null) return false; else if (!getClass().isInstance(other)) return false; Point oth = (Point)other; return latitude==oth.latitude && longitude==oth.longitude; } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Geoshape.java
671
constructors[COLLECTION_TXN_REMOVE_BACKUP] = new ConstructorFunction<Integer, IdentifiedDataSerializable>() { public IdentifiedDataSerializable createNew(Integer arg) { return new CollectionTxnRemoveBackupOperation(); } };
0true
hazelcast_src_main_java_com_hazelcast_collection_CollectionDataSerializerHook.java
54
public class Titan { /** * The version of this Titan graph database * * @return */ public static String version() { return TitanConstants.VERSION; } }
0true
titan-core_src_main_java_com_thinkaurelius_titan_core_Titan.java