_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q173100
OSQLFilterItemField.getCollate
test
public OCollate getCollate(Object doc) { if (collate != null || operationsChain == null || !isFieldChain()) { return collate; } if (!(doc instanceof OIdentifiable)) { return null; } FieldChain chain = getFieldChain(); ODocument lastDoc = ((OIdentifiable) doc).getRecord(); for (int i = 0; i < chain.getItemCount() - 1; i++) { if (lastDoc == null) { return null; } Object nextDoc = lastDoc.field(chain.getItemName(i)); if (nextDoc == null || !(nextDoc instanceof OIdentifiable)) { return null; } lastDoc = ((OIdentifiable) nextDoc).getRecord(); } if (lastDoc == null) { return null; } OClass schemaClass = lastDoc.getSchemaClass(); if (schemaClass == null) { return null; } OProperty property = schemaClass.getProperty(chain.getItemName(chain.getItemCount() - 1)); if (property == null) { return null; } return property.getCollate(); }
java
{ "resource": "" }
q173101
OIdentifier.getStringValue
test
public String getStringValue() { if (value == null) { return null; } if (value.contains("`")) { return value.replaceAll("\\\\`", "`"); } return value; }
java
{ "resource": "" }
q173102
StripedBuffer.advanceProbe
test
private int advanceProbe(int probe) { probe ^= probe << 13; // xorshift probe ^= probe >>> 17; probe ^= probe << 5; this.probe.get().set(probe); return probe; }
java
{ "resource": "" }
q173103
OCommandExecutorSQLDropCluster.execute
test
public Object execute(final Map<Object, Object> iArgs) { if (clusterName == null) throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet"); final ODatabaseDocumentInternal database = getDatabase(); // CHECK IF ANY CLASS IS USING IT final int clusterId = database.getStorage().getClusterIdByName(clusterName); for (OClass iClass : database.getMetadata().getSchema().getClasses()) { for (int i : iClass.getClusterIds()) { if (i == clusterId) // IN USE return false; } } // REMOVE CACHE OF COMMAND RESULTS IF ACTIVE database.getMetadata().getCommandCache().invalidateResultsOfCluster(clusterName); database.dropCluster(clusterId, true); return true; }
java
{ "resource": "" }
q173104
OFileManager.buildJsonFromFile
test
public static ODocument buildJsonFromFile(String filePath) throws IOException { if (filePath == null) { return null; } File jsonFile = new File(filePath); if (!jsonFile.exists()) { return null; } FileInputStream is = new FileInputStream(jsonFile); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); ODocument json = new ODocument(); String jsonText = OFileManager.readAllTextFile(rd); json.fromJSON(jsonText, "noMap"); return json; }
java
{ "resource": "" }
q173105
OSecurityManager.checkPassword
test
public boolean checkPassword(final String iPassword, final String iHash) { if (iHash.startsWith(HASH_ALGORITHM_PREFIX)) { final String s = iHash.substring(HASH_ALGORITHM_PREFIX.length()); return createSHA256(iPassword).equals(s); } else if (iHash.startsWith(PBKDF2_ALGORITHM_PREFIX)) { final String s = iHash.substring(PBKDF2_ALGORITHM_PREFIX.length()); return checkPasswordWithSalt(iPassword, s, PBKDF2_ALGORITHM); } else if (iHash.startsWith(PBKDF2_SHA256_ALGORITHM_PREFIX)) { final String s = iHash.substring(PBKDF2_SHA256_ALGORITHM_PREFIX.length()); return checkPasswordWithSalt(iPassword, s, PBKDF2_SHA256_ALGORITHM); } // Do not compare raw strings against each other, to avoid timing attacks. // Instead, hash them both with a cryptographic hash function and // compare their hashes with a constant-time comparison method. return MessageDigest.isEqual(digestSHA256(iPassword), digestSHA256(iHash)); }
java
{ "resource": "" }
q173106
OSecurityManager.createHash
test
public String createHash(final String iInput, final String iAlgorithm, final boolean iIncludeAlgorithm) { if (iInput == null) throw new IllegalArgumentException("Input string is null"); if (iAlgorithm == null) throw new IllegalArgumentException("Algorithm is null"); final StringBuilder buffer = new StringBuilder(128); final String algorithm = validateAlgorithm(iAlgorithm); if (iIncludeAlgorithm) { buffer.append('{'); buffer.append(algorithm); buffer.append('}'); } final String transformed; if (HASH_ALGORITHM.equalsIgnoreCase(algorithm)) { transformed = createSHA256(iInput); } else if (PBKDF2_ALGORITHM.equalsIgnoreCase(algorithm)) { transformed = createHashWithSalt(iInput, OGlobalConfiguration.SECURITY_USER_PASSWORD_SALT_ITERATIONS.getValueAsInteger(), algorithm); } else if (PBKDF2_SHA256_ALGORITHM.equalsIgnoreCase(algorithm)) { transformed = createHashWithSalt(iInput, OGlobalConfiguration.SECURITY_USER_PASSWORD_SALT_ITERATIONS.getValueAsInteger(), algorithm); } else throw new IllegalArgumentException("Algorithm '" + algorithm + "' is not supported"); buffer.append(transformed); return buffer.toString(); }
java
{ "resource": "" }
q173107
OSecurityManager.isAlgorithmSupported
test
private static boolean isAlgorithmSupported(final String algorithm) { // Java 7 specific checks. if (Runtime.class.getPackage() != null && Runtime.class.getPackage().getImplementationVersion() != null) { if (Runtime.class.getPackage().getImplementationVersion().startsWith("1.7")) { // Java 7 does not support the PBKDF2_SHA256_ALGORITHM. if (algorithm != null && algorithm.equals(PBKDF2_SHA256_ALGORITHM)) { return false; } } } return true; }
java
{ "resource": "" }
q173108
OIndexAbstract.create
test
public OIndexInternal<?> create(final OIndexDefinition indexDefinition, final String clusterIndexName, final Set<String> clustersToIndex, boolean rebuild, final OProgressListener progressListener, final OBinarySerializer valueSerializer) { acquireExclusiveLock(); try { configuration = indexConfigurationInstance(new ODocument().setTrackingChanges(false)); this.indexDefinition = indexDefinition; if (clustersToIndex != null) this.clustersToIndex = new HashSet<>(clustersToIndex); else this.clustersToIndex = new HashSet<>(); // do not remove this, it is needed to remove index garbage if such one exists try { if (apiVersion == 0) { removeValuesContainer(); } } catch (Exception e) { OLogManager.instance().error(this, "Error during deletion of index '%s'", e, name); } indexId = storage.addIndexEngine(name, algorithm, type, indexDefinition, valueSerializer, isAutomatic(), true, version, 1, this instanceof OIndexMultiValues, getEngineProperties(), clustersToIndex, metadata); apiVersion = OAbstractPaginatedStorage.extractEngineAPIVersion(indexId); assert indexId >= 0; assert apiVersion >= 0; onIndexEngineChange(indexId); if (rebuild) fillIndex(progressListener, false); updateConfiguration(); } catch (Exception e) { OLogManager.instance().error(this, "Exception during index '%s' creation", e, name); while (true) try { if (indexId >= 0) storage.deleteIndexEngine(indexId); break; } catch (OInvalidIndexEngineIdException ignore) { doReloadIndexEngine(); } catch (Exception ex) { OLogManager.instance().error(this, "Exception during index '%s' deletion", ex, name); } if (e instanceof OIndexException) throw (OIndexException) e; throw OException.wrapException(new OIndexException("Cannot create the index '" + name + "'"), e); } finally { releaseExclusiveLock(); } return this; }
java
{ "resource": "" }
q173109
OrientGraphQuery.vertices
test
@Override public Iterable<Vertex> vertices() { if (limit == 0) return Collections.emptyList(); OTransaction transaction = ((OrientBaseGraph) graph).getRawGraph().getTransaction(); if (transaction.isActive() && transaction.getEntryCount() > 0 || hasCustomPredicate()) { // INSIDE TRANSACTION QUERY DOESN'T SEE IN MEMORY CHANGES, UNTIL // SUPPORTED USED THE BASIC IMPL String[] classes = allSubClassesLabels(); return new OrientGraphQueryIterable<Vertex>(true, classes); } final StringBuilder text = new StringBuilder(512); // GO DIRECTLY AGAINST E CLASS AND SUB-CLASSES text.append(QUERY_SELECT_FROM); if (((OrientBaseGraph) graph).isUseClassForVertexLabel() && labels != null && labels.length > 0) { // FILTER PER CLASS SAVING CHECKING OF LABEL PROPERTY if (labels.length == 1) // USE THE CLASS NAME text.append(OrientBaseGraph.encodeClassName(labels[0])); else { // MULTIPLE CLASSES NOT SUPPORTED DIRECTLY: CREATE A SUB-QUERY String[] classes = allSubClassesLabels(); return new OrientGraphQueryIterable<Vertex>(true, classes); } } else text.append(OrientVertexType.CLASS_NAME); final List<Object> queryParams = manageFilters(text); if (!((OrientBaseGraph) graph).isUseClassForVertexLabel()) manageLabels(queryParams.size() > 0, text); if (orderBy.length() > 1) { text.append(ORDERBY); text.append(orderBy); text.append(" ").append(orderByDir).append(" "); } if (skip > 0 && skip < Integer.MAX_VALUE) { text.append(SKIP); text.append(skip); } if (limit > 0 && limit < Integer.MAX_VALUE) { text.append(LIMIT); text.append(limit); } final OSQLSynchQuery<OIdentifiable> query = new OSQLSynchQuery<OIdentifiable>(text.toString()); if (fetchPlan != null) query.setFetchPlan(fetchPlan); return new OrientElementIterable<Vertex>(((OrientBaseGraph) graph), ((OrientBaseGraph) graph).getRawGraph().query(query, queryParams.toArray())); }
java
{ "resource": "" }
q173110
OrientGraphQuery.edges
test
@Override public Iterable<Edge> edges() { if (limit == 0) return Collections.emptyList(); if (((OrientBaseGraph) graph).getRawGraph().getTransaction().isActive() || hasCustomPredicate()) // INSIDE TRANSACTION QUERY DOESN'T SEE IN MEMORY CHANGES, UNTIL // SUPPORTED USED THE BASIC IMPL return new OrientGraphQueryIterable<Edge>(false, labels); if (((OrientBaseGraph) graph).isUseLightweightEdges()) return new OrientGraphQueryIterable<Edge>(false, labels); final StringBuilder text = new StringBuilder(512); // GO DIRECTLY AGAINST E CLASS AND SUB-CLASSES text.append(QUERY_SELECT_FROM); if (((OrientBaseGraph) graph).isUseClassForEdgeLabel() && labels != null && labels.length > 0) { // FILTER PER CLASS SAVING CHECKING OF LABEL PROPERTY if (labels.length == 1) // USE THE CLASS NAME text.append(OrientBaseGraph.encodeClassName(labels[0])); else { // MULTIPLE CLASSES NOT SUPPORTED DIRECTLY: CREATE A SUB-QUERY return new OrientGraphQueryIterable<Edge>(false, labels); } } else text.append(OrientEdgeType.CLASS_NAME); List<Object> queryParams = manageFilters(text); if (!((OrientBaseGraph) graph).isUseClassForEdgeLabel()) manageLabels(queryParams.size() > 0, text); final OSQLSynchQuery<OIdentifiable> query = new OSQLSynchQuery<OIdentifiable>(text.toString()); if (fetchPlan != null) query.setFetchPlan(fetchPlan); if (limit > 0 && limit < Integer.MAX_VALUE) query.setLimit(limit); return new OrientElementIterable<Edge>(((OrientBaseGraph) graph), ((OrientBaseGraph) graph).getRawGraph().query(query, queryParams.toArray())); }
java
{ "resource": "" }
q173111
OAbstract2pcTask.getPartitionKey
test
@Override public int[] getPartitionKey() { if (tasks.size() == 1) // ONE TASK, USE THE INNER TASK'S PARTITION KEY return tasks.get(0).getPartitionKey(); // MULTIPLE PARTITIONS final int[] partitions = new int[tasks.size()]; for (int i = 0; i < tasks.size(); ++i) { final OAbstractRecordReplicatedTask task = tasks.get(i); partitions[i] = task.getPartitionKey()[0]; } return partitions; }
java
{ "resource": "" }
q173112
OAbstract2pcTask.getDistributedTimeout
test
@Override public long getDistributedTimeout() { final long to = OGlobalConfiguration.DISTRIBUTED_CRUD_TASK_SYNCH_TIMEOUT.getValueAsLong(); return to + ((to / 2) * tasks.size()); }
java
{ "resource": "" }
q173113
OrientGraph.getFeatures
test
public Features getFeatures() { makeActive(); if (!featuresInitialized) { FEATURES.supportsDuplicateEdges = true; FEATURES.supportsSelfLoops = true; FEATURES.isPersistent = true; FEATURES.supportsVertexIteration = true; FEATURES.supportsVertexIndex = true; FEATURES.ignoresSuppliedIds = true; FEATURES.supportsTransactions = true; FEATURES.supportsVertexKeyIndex = true; FEATURES.supportsKeyIndices = true; FEATURES.isWrapper = false; FEATURES.supportsIndices = true; FEATURES.supportsVertexProperties = true; FEATURES.supportsEdgeProperties = true; // For more information on supported types, please see: // http://code.google.com/p/orient/wiki/Types FEATURES.supportsSerializableObjectProperty = true; FEATURES.supportsBooleanProperty = true; FEATURES.supportsDoubleProperty = true; FEATURES.supportsFloatProperty = true; FEATURES.supportsIntegerProperty = true; FEATURES.supportsPrimitiveArrayProperty = true; FEATURES.supportsUniformListProperty = true; FEATURES.supportsMixedListProperty = true; FEATURES.supportsLongProperty = true; FEATURES.supportsMapProperty = true; FEATURES.supportsStringProperty = true; FEATURES.supportsThreadedTransactions = false; FEATURES.supportsThreadIsolatedTransactions = false; // DYNAMIC FEATURES BASED ON CONFIGURATION FEATURES.supportsEdgeIndex = !isUseLightweightEdges(); FEATURES.supportsEdgeKeyIndex = !isUseLightweightEdges(); FEATURES.supportsEdgeIteration = !isUseLightweightEdges(); FEATURES.supportsEdgeRetrieval = !isUseLightweightEdges(); featuresInitialized = true; } return FEATURES; }
java
{ "resource": "" }
q173114
OAtomicOperation.checkChangesFilledUpTo
test
private static boolean checkChangesFilledUpTo(final FileChanges changesContainer, final long pageIndex) { if (changesContainer == null) { return true; } else if (changesContainer.isNew || changesContainer.maxNewPageIndex > -2) { return pageIndex < changesContainer.maxNewPageIndex + 1; } else return !changesContainer.truncate; }
java
{ "resource": "" }
q173115
OCommandExecutorSQLAbstract.parseTimeout
test
protected boolean parseTimeout(final String w) throws OCommandSQLParsingException { if (!w.equals(KEYWORD_TIMEOUT)) return false; String word = parserNextWord(true); try { timeoutMs = Long.parseLong(word); } catch (NumberFormatException ignore) { throwParsingException("Invalid " + KEYWORD_TIMEOUT + " value set to '" + word + "' but it should be a valid long. Example: " + KEYWORD_TIMEOUT + " 3000"); } if (timeoutMs < 0) throwParsingException("Invalid " + KEYWORD_TIMEOUT + ": value set minor than ZERO. Example: " + KEYWORD_TIMEOUT + " 10000"); word = parserNextWord(true); if (word != null) if (word.equals(TIMEOUT_STRATEGY.EXCEPTION.toString())) timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION; else if (word.equals(TIMEOUT_STRATEGY.RETURN.toString())) timeoutStrategy = TIMEOUT_STRATEGY.RETURN; else parserGoBack(); return true; }
java
{ "resource": "" }
q173116
OCommandExecutorSQLAbstract.parseLock
test
protected String parseLock() throws OCommandSQLParsingException { final String lockStrategy = parserNextWord(true); if (!lockStrategy.equalsIgnoreCase("DEFAULT") && !lockStrategy.equalsIgnoreCase("NONE") && !lockStrategy.equalsIgnoreCase("RECORD")) throwParsingException("Invalid " + KEYWORD_LOCK + " value set to '" + lockStrategy + "' but it should be NONE (default) or RECORD. Example: " + KEYWORD_LOCK + " RECORD"); return lockStrategy; }
java
{ "resource": "" }
q173117
OSystemDatabase.createCluster
test
public void createCluster(final String className, final String clusterName) { final ODatabaseDocumentInternal currentDB = ODatabaseRecordThreadLocal.instance().getIfDefined(); try { final ODatabaseDocumentInternal sysdb = openSystemDatabase(); try { if (!sysdb.existsCluster(clusterName)) { OSchema schema = sysdb.getMetadata().getSchema(); OClass cls = schema.getClass(className); if (cls != null) { cls.addCluster(clusterName); } else { OLogManager.instance().error(this, "createCluster() Class name %s does not exist", null, className); } } } finally { sysdb.close(); } } finally { if (currentDB != null) ODatabaseRecordThreadLocal.instance().set(currentDB); else ODatabaseRecordThreadLocal.instance().remove(); } }
java
{ "resource": "" }
q173118
OAbstractRecordCache.freeCluster
test
public void freeCluster(final int cid) { final Set<ORID> toRemove = new HashSet<ORID>(underlying.size() / 2); final Set<ORID> keys = new HashSet<ORID>(underlying.keys()); for (final ORID id : keys) if (id.getClusterId() == cid) toRemove.add(id); for (final ORID ridToRemove : toRemove) underlying.remove(ridToRemove); }
java
{ "resource": "" }
q173119
OAbstractRecordCache.startup
test
public void startup() { underlying.startup(); Orient.instance().getProfiler() .registerHookValue(profilerPrefix + "current", "Number of entries in cache", METRIC_TYPE.SIZE, new OProfilerHookValue() { public Object getValue() { return getSize(); } }, profilerMetadataPrefix + "current"); }
java
{ "resource": "" }
q173120
OAbstractRecordCache.shutdown
test
public void shutdown() { underlying.shutdown(); if (Orient.instance().getProfiler() != null) { Orient.instance().getProfiler().unregisterHookValue(profilerPrefix + "enabled"); Orient.instance().getProfiler().unregisterHookValue(profilerPrefix + "current"); Orient.instance().getProfiler().unregisterHookValue(profilerPrefix + "max"); } }
java
{ "resource": "" }
q173121
OScriptResultSets.singleton
test
public static OScriptResultSet singleton(Object entity, OScriptTransformer transformer) { return new OScriptResultSet(Collections.singletonList(entity).iterator(), transformer); }
java
{ "resource": "" }
q173122
ORole.grant
test
public ORole grant(final ORule.ResourceGeneric resourceGeneric, String resourceSpecific, final int iOperation) { ORule rule = rules.get(resourceGeneric); if (rule == null) { rule = new ORule(resourceGeneric, null, null); rules.put(resourceGeneric, rule); } rule.grantAccess(resourceSpecific, iOperation); rules.put(resourceGeneric, rule); updateRolesDocumentContent(); return this; }
java
{ "resource": "" }
q173123
ORole.revoke
test
public ORole revoke(final ORule.ResourceGeneric resourceGeneric, String resourceSpecific, final int iOperation) { if (iOperation == PERMISSION_NONE) return this; ORule rule = rules.get(resourceGeneric); if (rule == null) { rule = new ORule(resourceGeneric, null, null); rules.put(resourceGeneric, rule); } rule.revokeAccess(resourceSpecific, iOperation); rules.put(resourceGeneric, rule); updateRolesDocumentContent(); return this; }
java
{ "resource": "" }
q173124
OCommandExecutorSQLDelete.result
test
public boolean result(final Object iRecord) { final ORecordAbstract record = ((OIdentifiable) iRecord).getRecord(); if (record instanceof ODocument && compiledFilter != null && !Boolean.TRUE.equals(this.compiledFilter.evaluate(record, (ODocument) record, getContext()))) { return true; } try { if (record.getIdentity().isValid()) { if (returning.equalsIgnoreCase("BEFORE")) allDeletedRecords.add(record); // RESET VERSION TO DISABLE MVCC AVOIDING THE CONCURRENT EXCEPTION IF LOCAL CACHE IS NOT UPDATED // ORecordInternal.setVersion(record, -1); if (!unsafe && record instanceof ODocument) { // CHECK IF ARE VERTICES OR EDGES final OClass cls = ((ODocument) record).getSchemaClass(); if (cls != null) { if (cls.isSubClassOf("V")) // FOUND VERTEX throw new OCommandExecutionException( "'DELETE' command cannot delete vertices. Use 'DELETE VERTEX' command instead, or apply the 'UNSAFE' keyword to force it"); else if (cls.isSubClassOf("E")) // FOUND EDGE throw new OCommandExecutionException( "'DELETE' command cannot delete edges. Use 'DELETE EDGE' command instead, or apply the 'UNSAFE' keyword to force it"); } } record.delete(); recordCount++; return true; } return false; } finally { if (lockStrategy.equalsIgnoreCase("RECORD")) ((OAbstractPaginatedStorage) getDatabase().getStorage()).releaseWriteLock(record.getIdentity()); } }
java
{ "resource": "" }
q173125
OSQLPredicate.bindParameters
test
public void bindParameters(final Map<Object, Object> iArgs) { if (parameterItems == null || iArgs == null || iArgs.size() == 0) return; for (int i = 0; i < parameterItems.size(); i++) { OSQLFilterItemParameter value = parameterItems.get(i); if ("?".equals(value.getName())) { value.setValue(iArgs.get(i)); } else { value.setValue(iArgs.get(value.getName())); } } }
java
{ "resource": "" }
q173126
FrequencySketch.reset
test
private void reset() { int count = 0; for (int i = 0; i < table.length; i++) { count += Long.bitCount(table[i] & ONE_MASK); table[i] = (table[i] >>> 1) & RESET_MASK; } size = (size >>> 1) - (count >>> 2); }
java
{ "resource": "" }
q173127
FrequencySketch.indexOf
test
private int indexOf(final int item, final int i) { long hash = SEED[i] * item; hash += hash >> 32; return ((int) hash) & tableMask; }
java
{ "resource": "" }
q173128
FrequencySketch.spread
test
private int spread(int x) { x = ((x >>> 16) ^ x) * 0x45d9f3b; x = ((x >>> 16) ^ x) * randomSeed; return (x >>> 16) ^ x; }
java
{ "resource": "" }
q173129
OPropertyImpl.createIndex
test
public OIndex<?> createIndex(final String iType) { acquireSchemaReadLock(); try { return owner.createIndex(getFullName(), iType, globalRef.getName()); } finally { releaseSchemaReadLock(); } }
java
{ "resource": "" }
q173130
OPropertyImpl.dropIndexes
test
@Deprecated public OPropertyImpl dropIndexes() { getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_DELETE); acquireSchemaReadLock(); try { final OIndexManager indexManager = getDatabase().getMetadata().getIndexManager(); final ArrayList<OIndex<?>> relatedIndexes = new ArrayList<OIndex<?>>(); for (final OIndex<?> index : indexManager.getClassIndexes(owner.getName())) { final OIndexDefinition definition = index.getDefinition(); if (OCollections.indexOf(definition.getFields(), globalRef.getName(), new OCaseInsentiveComparator()) > -1) { if (definition instanceof OPropertyIndexDefinition) { relatedIndexes.add(index); } else { throw new IllegalArgumentException( "This operation applicable only for property indexes. " + index.getName() + " is " + index.getDefinition()); } } } for (final OIndex<?> index : relatedIndexes) getDatabase().getMetadata().getIndexManager().dropIndex(index.getName()); return this; } finally { releaseSchemaReadLock(); } }
java
{ "resource": "" }
q173131
OPropertyImpl.getIndex
test
@Deprecated public OIndex<?> getIndex() { acquireSchemaReadLock(); try { Set<OIndex<?>> indexes = owner.getInvolvedIndexes(globalRef.getName()); if (indexes != null && !indexes.isEmpty()) return indexes.iterator().next(); return null; } finally { releaseSchemaReadLock(); } }
java
{ "resource": "" }
q173132
OPropertyImpl.getLinkedClass
test
public OClass getLinkedClass() { acquireSchemaReadLock(); try { if (linkedClass == null && linkedClassName != null) linkedClass = owner.owner.getClass(linkedClassName); return linkedClass; } finally { releaseSchemaReadLock(); } }
java
{ "resource": "" }
q173133
OIndexManagerShared.toStream
test
@Override public ODocument toStream() { internalAcquireExclusiveLock(); try { document.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); try { final OTrackedSet<ODocument> indexes = new OTrackedSet<>(document); for (final OIndex<?> i : this.indexes.values()) { indexes.add(((OIndexInternal<?>) i).updateConfiguration()); } document.field(CONFIG_INDEXES, indexes, OType.EMBEDDEDSET); } finally { document.setInternalStatus(ORecordElement.STATUS.LOADED); } document.setDirty(); return document; } finally { internalReleaseExclusiveLock(); } }
java
{ "resource": "" }
q173134
ORecordAbstract.removeListener
test
protected void removeListener(final ORecordListener listener) { if (_listeners != null) { _listeners.remove(listener); if (_listeners.isEmpty()) _listeners = null; } }
java
{ "resource": "" }
q173135
ODistributedMessageServiceImpl.registerDatabase
test
public ODistributedDatabaseImpl registerDatabase(final String iDatabaseName, ODistributedConfiguration cfg) { final ODistributedDatabaseImpl ddb = databases.get(iDatabaseName); if (ddb != null) return ddb; return new ODistributedDatabaseImpl(manager, this, iDatabaseName, cfg, manager.getServerInstance()); }
java
{ "resource": "" }
q173136
ODistributedMessageServiceImpl.timeoutRequest
test
public void timeoutRequest(final long msgId) { final ODistributedResponseManager asynchMgr = responsesByRequestIds.remove(msgId); if (asynchMgr != null) asynchMgr.timeout(); }
java
{ "resource": "" }
q173137
ODatabaseDocumentEmbedded.copy
test
public ODatabaseDocumentInternal copy() { ODatabaseDocumentEmbedded database = new ODatabaseDocumentEmbedded(getSharedContext().getStorage()); database.init(config, this.sharedContext); String user; if (getUser() != null) { user = getUser().getName(); } else { user = null; } database.internalOpen(user, null, false); database.callOnOpenListeners(); this.activateOnCurrentThread(); return database; }
java
{ "resource": "" }
q173138
ORidBag.tryMerge
test
public boolean tryMerge(final ORidBag otherValue, boolean iMergeSingleItemsOfMultiValueFields) { if (!isEmbedded() && !otherValue.isEmbedded()) { final OSBTreeRidBag thisTree = (OSBTreeRidBag) delegate; final OSBTreeRidBag otherTree = (OSBTreeRidBag) otherValue.delegate; if (thisTree.getCollectionPointer().equals(otherTree.getCollectionPointer())) { thisTree.mergeChanges(otherTree); uuid = otherValue.uuid; return true; } } else if (iMergeSingleItemsOfMultiValueFields) { final Iterator<OIdentifiable> iter = otherValue.rawIterator(); while (iter.hasNext()) { final OIdentifiable value = iter.next(); if (value != null) { final Iterator<OIdentifiable> localIter = rawIterator(); boolean found = false; while (localIter.hasNext()) { final OIdentifiable v = localIter.next(); if (value.equals(v)) { found = true; break; } } if (!found) add(value); } } return true; } return false; }
java
{ "resource": "" }
q173139
ORidBag.replaceWithSBTree
test
private void replaceWithSBTree(OBonsaiCollectionPointer pointer) { delegate.requestDelete(); final OSBTreeRidBag treeBag = new OSBTreeRidBag(); treeBag.setCollectionPointer(pointer); treeBag.setOwner(delegate.getOwner()); for (OMultiValueChangeListener<OIdentifiable, OIdentifiable> listener : delegate.getChangeListeners()) treeBag.addChangeListener(listener); delegate = treeBag; }
java
{ "resource": "" }
q173140
OCommandExecutorUtility.transformResult
test
public static Object transformResult(Object result) { if (java8MethodIsArray == null || !(result instanceof Map)) { return result; } // PATCH BY MAT ABOUT NASHORN RETURNING VALUE FOR ARRAYS. try { if ((Boolean) java8MethodIsArray.invoke(result)) { List<?> partial = new ArrayList(((Map) result).values()); List<Object> finalResult = new ArrayList<Object>(); for (Object o : partial) { finalResult.add(transformResult(o)); } return finalResult; } else { Map<Object, Object> mapResult = (Map) result; List<Object> keys = new ArrayList<Object>(mapResult.keySet()); for (Object key : keys) { mapResult.put(key, transformResult(mapResult.get(key))); } return mapResult; } } catch (Exception e) { OLogManager.instance().error(OCommandExecutorUtility.class, "", e); } return result; }
java
{ "resource": "" }
q173141
OCommandExecutorSQLCreateCluster.execute
test
public Object execute(final Map<Object, Object> iArgs) { if (clusterName == null) throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet"); final ODatabaseDocument database = getDatabase(); final int clusterId = database.getClusterIdByName(clusterName); if (clusterId > -1) throw new OCommandSQLParsingException("Cluster '" + clusterName + "' already exists"); if (blob) { if (requestedId == -1) { return database.addBlobCluster(clusterName); } else { throw new OCommandExecutionException("Request id not supported by blob cluster creation."); } } else { if (requestedId == -1) { return database.addCluster(clusterName); } else { return database.addCluster(clusterName, requestedId, null); } } }
java
{ "resource": "" }
q173142
ODatabasePoolAbstract.close
test
public void close() { lock(); try { if (this.evictionTask != null) { this.evictionTask.cancel(); } for (Entry<String, OReentrantResourcePool<String, DB>> pool : pools.entrySet()) { for (DB db : pool.getValue().getResources()) { pool.getValue().close(); try { OLogManager.instance().debug(this, "Closing pooled database '%s'...", db.getName()); ((ODatabasePooled) db).forceClose(); OLogManager.instance().debug(this, "OK", db.getName()); } catch (Exception e) { OLogManager.instance().debug(this, "Error: %d", e.toString()); } } } } finally { unlock(); } }
java
{ "resource": "" }
q173143
ODatabasePoolAbstract.onStorageUnregistered
test
public void onStorageUnregistered(final OStorage iStorage) { final String storageURL = iStorage.getURL(); lock(); try { Set<String> poolToClose = null; for (Entry<String, OReentrantResourcePool<String, DB>> e : pools.entrySet()) { final int pos = e.getKey().indexOf("@"); final String dbName = e.getKey().substring(pos + 1); if (storageURL.equals(dbName)) { if (poolToClose == null) poolToClose = new HashSet<String>(); poolToClose.add(e.getKey()); } } if (poolToClose != null) for (String pool : poolToClose) remove(pool); } finally { unlock(); } }
java
{ "resource": "" }
q173144
OSQLEngine.getFunctionNames
test
public static Set<String> getFunctionNames() { final Set<String> types = new HashSet<String>(); final Iterator<OSQLFunctionFactory> ite = getFunctionFactories(); while (ite.hasNext()) { types.addAll(ite.next().getFunctionNames()); } return types; }
java
{ "resource": "" }
q173145
OSQLEngine.getCollateNames
test
public static Set<String> getCollateNames() { final Set<String> types = new HashSet<String>(); final Iterator<OCollateFactory> ite = getCollateFactories(); while (ite.hasNext()) { types.addAll(ite.next().getNames()); } return types; }
java
{ "resource": "" }
q173146
OSQLEngine.getCommandNames
test
public static Set<String> getCommandNames() { final Set<String> types = new HashSet<String>(); final Iterator<OCommandExecutorSQLFactory> ite = getCommandFactories(); while (ite.hasNext()) { types.addAll(ite.next().getCommandNames()); } return types; }
java
{ "resource": "" }
q173147
ORecordSerializerBinaryV1.getFieldSizeAndTypeFromCurrentPosition
test
private Tuple<Integer, OType> getFieldSizeAndTypeFromCurrentPosition(BytesContainer bytes) { int fieldSize = OVarIntSerializer.readAsInteger(bytes); OType type = readOType(bytes, false); return new Tuple<>(fieldSize, type); }
java
{ "resource": "" }
q173148
OHttpResponseWrapper.writeStatus
test
public OHttpResponseWrapper writeStatus(final int iHttpCode, final String iReason) throws IOException { response.writeStatus(iHttpCode, iReason); return this; }
java
{ "resource": "" }
q173149
OHttpResponseWrapper.writeHeaders
test
public OHttpResponseWrapper writeHeaders(final String iContentType, final boolean iKeepAlive) throws IOException { response.writeHeaders(iContentType, iKeepAlive); return this; }
java
{ "resource": "" }
q173150
OHttpResponseWrapper.writeRecords
test
public OHttpResponseWrapper writeRecords(final Object iRecords, final String iFetchPlan) throws IOException { response.writeRecords(iRecords, iFetchPlan); return this; }
java
{ "resource": "" }
q173151
OHttpResponseWrapper.writeRecord
test
public OHttpResponseWrapper writeRecord(final ORecord iRecord, final String iFetchPlan) throws IOException { response.writeRecord(iRecord, iFetchPlan, null); return this; }
java
{ "resource": "" }
q173152
OHttpResponseWrapper.send
test
public OHttpResponseWrapper send(final int iCode, final String iReason, final String iContentType, final Object iContent) throws IOException { response.send(iCode, iReason, iContentType, iContent, null); return this; }
java
{ "resource": "" }
q173153
OHttpResponseWrapper.sendStream
test
public OHttpResponseWrapper sendStream(final int iCode, final String iReason, final String iContentType, final InputStream iContent, final long iSize) throws IOException { response.sendStream(iCode, iReason, iContentType, iContent, iSize); return this; }
java
{ "resource": "" }
q173154
OrientDBObject.open
test
public ODatabaseObject open(String name, String user, String password) { return new OObjectDatabaseTx((ODatabaseDocumentInternal) orientDB.open(name, user, password)); }
java
{ "resource": "" }
q173155
ODatabaseDocumentTxPooled.close
test
@Override public void close() { if (isClosed()) return; checkOpenness(); if (ownerPool != null && ownerPool.getConnectionsInCurrentThread(getURL(), userName) > 1) { ownerPool.release(this); return; } try { commit(true); } catch (Exception e) { OLogManager.instance().error(this, "Error on releasing database '%s' in pool", e, getName()); } try { callOnCloseListeners(); } catch (Exception e) { OLogManager.instance().error(this, "Error on releasing database '%s' in pool", e, getName()); } getLocalCache().clear(); if (ownerPool != null) { final ODatabaseDocumentPool localCopy = ownerPool; ownerPool = null; localCopy.release(this); } ODatabaseRecordThreadLocal.instance().remove(); }
java
{ "resource": "" }
q173156
OSBTreeCollectionManagerShared.listenForChanges
test
@Override public UUID listenForChanges(ORidBag collection) { UUID ownerUUID = collection.getTemporaryId(); if (ownerUUID != null) { final OBonsaiCollectionPointer pointer = collection.getPointer(); Map<UUID, OBonsaiCollectionPointer> changedPointers = collectionPointerChanges.get(); if (pointer != null && pointer.isValid()) { changedPointers.put(ownerUUID, pointer); } } return null; }
java
{ "resource": "" }
q173157
OSessionStoragePerformanceStatistic.completeComponentOperation
test
public void completeComponentOperation() { final Component currentComponent = componentsStack.peek(); if (currentComponent == null) return; currentComponent.operationCount--; if (currentComponent.operationCount == 0) { final String componentName = currentComponent.name; PerformanceCountersHolder cHolder = countersByComponent .computeIfAbsent(componentName, k -> currentComponent.type.newCountersHolder()); cHolder.operationsCount++; componentsStack.pop(); makeSnapshotIfNeeded(-1); } }
java
{ "resource": "" }
q173158
OSessionStoragePerformanceStatistic.pushComponentCounters
test
public void pushComponentCounters(Map<String, PerformanceCountersHolder> counters) { if (snapshot == null) return; for (Map.Entry<String, PerformanceCountersHolder> entry : snapshot.countersByComponent.entrySet()) { final String componentName = entry.getKey(); PerformanceCountersHolder holder = counters.computeIfAbsent(componentName, k -> entry.getValue().newInstance()); entry.getValue().pushData(holder); } }
java
{ "resource": "" }
q173159
OSessionStoragePerformanceStatistic.pushWriteCacheCounters
test
public WritCacheCountersHolder pushWriteCacheCounters(WritCacheCountersHolder holder) { if (snapshot == null) return holder; if (snapshot.writCacheCountersHolder == null) return holder; if (holder == null) holder = new WritCacheCountersHolder(); snapshot.writCacheCountersHolder.pushData(holder); return holder; }
java
{ "resource": "" }
q173160
OSessionStoragePerformanceStatistic.pushStorageCounters
test
public StorageCountersHolder pushStorageCounters(StorageCountersHolder holder) { if (snapshot == null) return holder; if (snapshot.storageCountersHolder == null) return holder; if (holder == null) holder = new StorageCountersHolder(); snapshot.storageCountersHolder.pushData(holder); return holder; }
java
{ "resource": "" }
q173161
OSessionStoragePerformanceStatistic.pushWALCounters
test
public WALCountersHolder pushWALCounters(WALCountersHolder holder) { if (snapshot == null) return holder; if (snapshot.walCountersHolder == null) return holder; if (holder == null) holder = new WALCountersHolder(); snapshot.walCountersHolder.pushData(holder); return holder; }
java
{ "resource": "" }
q173162
OSessionStoragePerformanceStatistic.pushComponentCounters
test
public void pushComponentCounters(String name, PerformanceCountersHolder holder) { if (snapshot == null) return; final PerformanceCountersHolder countersHolder = snapshot.countersByComponent.get(name); if (countersHolder != null) { countersHolder.pushData(holder); } }
java
{ "resource": "" }
q173163
OSessionStoragePerformanceStatistic.stopWriteCacheFlushTimer
test
public void stopWriteCacheFlushTimer(int pagesFlushed) { // lazy initialization to prevent memory consumption if (writCacheCountersHolder == null) writCacheCountersHolder = new WritCacheCountersHolder(); final long endTs = nanoTimer.getNano(); final long timeDiff = (endTs - timeStamps.pop()); writCacheCountersHolder.flushOperationsCount++; writCacheCountersHolder.amountOfPagesFlushed += pagesFlushed; writCacheCountersHolder.flushOperationsTime += timeDiff; makeSnapshotIfNeeded(endTs); }
java
{ "resource": "" }
q173164
OSessionStoragePerformanceStatistic.stopFuzzyCheckpointTimer
test
public void stopFuzzyCheckpointTimer() { if (writCacheCountersHolder == null) writCacheCountersHolder = new WritCacheCountersHolder(); final long endTs = nanoTimer.getNano(); final long timeDiff = (endTs - timeStamps.pop()); writCacheCountersHolder.fuzzyCheckpointCount++; writCacheCountersHolder.fuzzyCheckpointTime += timeDiff; makeSnapshotIfNeeded(endTs); }
java
{ "resource": "" }
q173165
OSessionStoragePerformanceStatistic.stopFullCheckpointTimer
test
public void stopFullCheckpointTimer() { final long endTs = nanoTimer.getNano(); final long timeDiff = (endTs - timeStamps.pop()); if (storageCountersHolder == null) storageCountersHolder = new StorageCountersHolder(); storageCountersHolder.fullCheckpointOperationsCount++; storageCountersHolder.fullCheckpointOperationsTime += timeDiff; makeSnapshotIfNeeded(endTs); }
java
{ "resource": "" }
q173166
OSessionStoragePerformanceStatistic.stopCommitTimer
test
public void stopCommitTimer() { final long endTs = nanoTimer.getNano(); final long timeDiff = (endTs - timeStamps.pop()); performanceCountersHolder.commitTime += timeDiff; performanceCountersHolder.commitCount++; makeSnapshotIfNeeded(endTs); }
java
{ "resource": "" }
q173167
OSessionStoragePerformanceStatistic.stopWALRecordTimer
test
public void stopWALRecordTimer(boolean isStartRecord, boolean isStopRecord) { final long endTs = nanoTimer.getNano(); final long timeDiff = (endTs - timeStamps.pop()); if (walCountersHolder == null) walCountersHolder = new WALCountersHolder(); walCountersHolder.logRecordCount++; walCountersHolder.logRecordTime += timeDiff; if (isStartRecord) { walCountersHolder.startRecordCount++; walCountersHolder.startRecordTime += timeDiff; } else if (isStopRecord) { walCountersHolder.stopRecordCount++; walCountersHolder.stopRecordTime += timeDiff; } makeSnapshotIfNeeded(endTs); }
java
{ "resource": "" }
q173168
OSessionStoragePerformanceStatistic.stopWALFlushTimer
test
public void stopWALFlushTimer() { final long endTs = nanoTimer.getNano(); final long timeDiff = (endTs - timeStamps.pop()); if (walCountersHolder == null) walCountersHolder = new WALCountersHolder(); walCountersHolder.flushCount++; walCountersHolder.flushTime += timeDiff; makeSnapshotIfNeeded(endTs); }
java
{ "resource": "" }
q173169
OStatementCache.parse
test
protected static OStatement parse(String statement) throws OCommandSQLParsingException { try { ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined(); InputStream is; if (db == null) { is = new ByteArrayInputStream(statement.getBytes()); } else { try { is = new ByteArrayInputStream(statement.getBytes(db.getStorage().getConfiguration().getCharset())); } catch (UnsupportedEncodingException e2) { OLogManager.instance() .warn(null, "Unsupported charset for database " + db + " " + db.getStorage().getConfiguration().getCharset()); is = new ByteArrayInputStream(statement.getBytes()); } } OrientSql osql = null; if (db == null) { osql = new OrientSql(is); } else { try { osql = new OrientSql(is, db.getStorage().getConfiguration().getCharset()); } catch (UnsupportedEncodingException e2) { OLogManager.instance() .warn(null, "Unsupported charset for database " + db + " " + db.getStorage().getConfiguration().getCharset()); osql = new OrientSql(is); } } OStatement result = osql.parse(); result.originalStatement = statement; return result; } catch (ParseException e) { throwParsingException(e, statement); } catch (TokenMgrError e2) { throwParsingException(e2, statement); } return null; }
java
{ "resource": "" }
q173170
ONodeManager.initReceiveMessages
test
protected void initReceiveMessages() throws IOException { messageThread = new Thread(() -> { while (!Thread.interrupted()) { receiveMessages(); } }); messageThread.setName("OrientDB_DistributedDiscoveryThread"); messageThread.setDaemon(true); messageThread.start(); }
java
{ "resource": "" }
q173171
ONodeManager.initCheckDisconnect
test
protected void initCheckDisconnect() { disconnectTimer = new TimerTask() { public void run() { try { checkIfKnownServersAreAlive(); if (running) { initCheckDisconnect(); } } catch (Exception e) { e.printStackTrace(); } } }; taskScheduler.scheduleOnce(disconnectTimer, discoveryPingIntervalMillis); }
java
{ "resource": "" }
q173172
OrientElement.removeRecord
test
void removeRecord() { checkIfAttached(); final OrientBaseGraph graph = getGraph(); graph.setCurrentGraphInThreadLocal(); graph.autoStartTransaction(); if (checkDeletedInTx()) graph.throwRecordNotFoundException(getIdentity(), "The graph element with id " + getIdentity() + " not found"); try { getRecord().load(); } catch (ORecordNotFoundException e) { graph.throwRecordNotFoundException(getIdentity(), e.getMessage()); } getRecord().delete(); }
java
{ "resource": "" }
q173173
OrientElement.setProperty
test
@Override public void setProperty(final String key, final Object value) { if (checkDeletedInTx()) graph.throwRecordNotFoundException(getIdentity(), "The graph element " + getIdentity() + " has been deleted"); validateProperty(this, key, value); final OrientBaseGraph graph = getGraph(); if (graph != null) graph.autoStartTransaction(); getRecord().field(key, value); if (graph != null) save(); }
java
{ "resource": "" }
q173174
OrientElement.removeProperty
test
@Override public <T> T removeProperty(final String key) { if (checkDeletedInTx()) throw new IllegalStateException("The vertex " + getIdentity() + " has been deleted"); final OrientBaseGraph graph = getGraph(); if (graph != null) graph.autoStartTransaction(); final Object oldValue = getRecord().removeField(key); if (graph != null) save(); return (T) oldValue; }
java
{ "resource": "" }
q173175
OrientElement.checkForClassInSchema
test
protected String checkForClassInSchema(final String className) { if (className == null) return null; OrientBaseGraph graph = getGraph(); if (graph == null) return className; final OSchema schema = graph.getRawGraph().getMetadata().getSchema(); if (!schema.existsClass(className)) { // CREATE A NEW CLASS AT THE FLY try { graph.executeOutsideTx(new OCallable<OClass, OrientBaseGraph>() { @Override public OClass call(final OrientBaseGraph g) { return schema.createClass(className, schema.getClass(getBaseClassName())); } }, "Committing the active transaction to create the new type '", className, "' as subclass of '", getBaseClassName(), "'. The transaction will be reopen right after that. To avoid this behavior create the classes outside the transaction"); } catch (OSchemaException e) { if (!schema.existsClass(className)) throw e; } } else { // CHECK THE CLASS INHERITANCE final OClass cls = schema.getClass(className); if (!cls.isSubClassOf(getBaseClassName())) throw new IllegalArgumentException("Class '" + className + "' is not an instance of " + getBaseClassName()); } return className; }
java
{ "resource": "" }
q173176
OIndexChangesWrapper.wrap
test
public static OIndexCursor wrap(OIndex<?> source, OIndexCursor cursor, long indexRebuildVersion) { if (cursor instanceof OIndexChangesWrapper) return cursor; if (cursor instanceof OSizeable) { return new OIndexChangesSizeable(source, cursor, indexRebuildVersion); } return new OIndexChangesWrapper(source, cursor, indexRebuildVersion); }
java
{ "resource": "" }
q173177
OGraphMLReader.defineVertexAttributeStrategy
test
public OGraphMLReader defineVertexAttributeStrategy(final String iAttributeName, final OGraphMLImportStrategy iStrategy) { vertexPropsStrategy.put(iAttributeName, iStrategy); return this; }
java
{ "resource": "" }
q173178
OGraphMLReader.defineEdgeAttributeStrategy
test
public OGraphMLReader defineEdgeAttributeStrategy(final String iAttributeName, final OGraphMLImportStrategy iStrategy) { edgePropsStrategy.put(iAttributeName, iStrategy); return this; }
java
{ "resource": "" }
q173179
OTransactionRealAbstract.getNewRecordEntriesByClass
test
public List<ORecordOperation> getNewRecordEntriesByClass(final OClass iClass, final boolean iPolymorphic) { final List<ORecordOperation> result = new ArrayList<ORecordOperation>(); if (iClass == null) // RETURN ALL THE RECORDS for (ORecordOperation entry : allEntries.values()) { if (entry.type == ORecordOperation.CREATED) result.add(entry); } else { // FILTER RECORDS BY CLASSNAME for (ORecordOperation entry : allEntries.values()) { if (entry.type == ORecordOperation.CREATED) if (entry.getRecord() != null && entry.getRecord() instanceof ODocument) { if (iPolymorphic) { if (iClass.isSuperClassOf(((ODocument) entry.getRecord()).getSchemaClass())) result.add(entry); } else if (iClass.getName().equals(((ODocument) entry.getRecord()).getClassName())) result.add(entry); } } } return result; }
java
{ "resource": "" }
q173180
OTransactionRealAbstract.getNewRecordEntriesByClusterIds
test
public List<ORecordOperation> getNewRecordEntriesByClusterIds(final int[] iIds) { final List<ORecordOperation> result = new ArrayList<ORecordOperation>(); if (iIds == null) // RETURN ALL THE RECORDS for (ORecordOperation entry : allEntries.values()) { if (entry.type == ORecordOperation.CREATED) result.add(entry); } else // FILTER RECORDS BY ID for (ORecordOperation entry : allEntries.values()) { for (int id : iIds) { if (entry.getRecord() != null && entry.getRecord().getIdentity().getClusterId() == id && entry.type == ORecordOperation.CREATED) { result.add(entry); break; } } } return result; }
java
{ "resource": "" }
q173181
OTransactionRealAbstract.addIndexEntry
test
public void addIndexEntry(final OIndex<?> delegate, final String iIndexName, final OTransactionIndexChanges.OPERATION iOperation, final Object key, final OIdentifiable iValue, boolean clientTrackOnly) { OTransactionIndexChanges indexEntry = indexEntries.get(iIndexName); if (indexEntry == null) { indexEntry = new OTransactionIndexChanges(); indexEntries.put(iIndexName, indexEntry); } if (iOperation == OPERATION.CLEAR) indexEntry.setCleared(); else { OTransactionIndexChangesPerKey changes = indexEntry.getChangesPerKey(key); changes.clientTrackOnly = clientTrackOnly; changes.add(iValue, iOperation); if (iValue == null) return; List<OTransactionRecordIndexOperation> transactionIndexOperations = recordIndexOperations.get(iValue.getIdentity()); if (transactionIndexOperations == null) { transactionIndexOperations = new ArrayList<OTransactionRecordIndexOperation>(); recordIndexOperations.put(iValue.getIdentity().copy(), transactionIndexOperations); } transactionIndexOperations.add(new OTransactionRecordIndexOperation(iIndexName, key, iOperation)); } }
java
{ "resource": "" }
q173182
ODirtyManager.mergeSet
test
private static Set<ORecord> mergeSet(Set<ORecord> target, Set<ORecord> source) { if (source != null) { if (target == null) { return source; } else { if (target.size() > source.size()) { target.addAll(source); return target; } else { source.addAll(target); return source; } } } else { return target; } }
java
{ "resource": "" }
q173183
OCommandExecutorSQLUpdate.result
test
@SuppressWarnings("unchecked") public boolean result(final Object iRecord) { final ODocument record = ((OIdentifiable) iRecord).getRecord(); if (isUpdateEdge() && !isRecordInstanceOf(iRecord, "E")) { throw new OCommandExecutionException("Using UPDATE EDGE on a record that is not an instance of E"); } if (compiledFilter != null) { // ADDITIONAL FILTERING if (!(Boolean) compiledFilter.evaluate(record, null, context)) return false; } parameters.reset(); returnHandler.beforeUpdate(record); boolean updated = handleContent(record); updated |= handleMerge(record); updated |= handleSetEntries(record); updated |= handleIncrementEntries(record); updated |= handleAddEntries(record); updated |= handlePutEntries(record); updated |= handleRemoveEntries(record); if (updated) { handleUpdateEdge(record); record.setDirty(); record.save(); returnHandler.afterUpdate(record); this.updated = true; } return true; }
java
{ "resource": "" }
q173184
OFunctionCall.canExecuteIndexedFunctionWithoutIndex
test
public boolean canExecuteIndexedFunctionWithoutIndex(OFromClause target, OCommandContext context, OBinaryCompareOperator operator, Object right) { OSQLFunction function = OSQLEngine.getInstance().getFunction(name.getStringValue()); if (function instanceof OIndexableSQLFunction) { return ((OIndexableSQLFunction) function) .canExecuteInline(target, operator, right, context, this.getParams().toArray(new OExpression[] {})); } return false; }
java
{ "resource": "" }
q173185
OChainedIndexProxy.prepareKeys
test
private Set<Comparable> prepareKeys(OIndex<?> index, Object keys) { final OIndexDefinition indexDefinition = index.getDefinition(); if (keys instanceof Collection) { final Set<Comparable> newKeys = new TreeSet<Comparable>(); for (Object o : ((Collection) keys)) { newKeys.add((Comparable) indexDefinition.createValue(o)); } return newKeys; } else { return Collections.singleton((Comparable) indexDefinition.createValue(keys)); } }
java
{ "resource": "" }
q173186
OWALSegmentCache.writePage
test
void writePage(ByteBuffer page, long pageIndex) throws IOException { synchronized (lockObject) { lastAccessTime = System.nanoTime(); if (pageIndex >= firstCachedPage && pageIndex <= firstCachedPage + pageCache.size()) { if (pageIndex < firstCachedPage + pageCache.size()) { pageCache.set((int) (pageIndex - firstCachedPage), page); } else { pageCache.add(page); } } else if (pageCache.isEmpty()) { pageCache.add(page); firstCachedPage = pageIndex; } lastWrittenPage = page; lastWrittenPageIndex = pageIndex; if (pageCache.size() * OWALPage.PAGE_SIZE >= bufferSize + OWALPage.PAGE_SIZE) { flushAllBufferPagesExceptLastOne(); } } }
java
{ "resource": "" }
q173187
OWALSegmentCache.readPage
test
byte[] readPage(long pageIndex) throws IOException { synchronized (lockObject) { lastAccessTime = System.nanoTime(); if (pageIndex == lastWrittenPageIndex) { return lastWrittenPage.array(); } if (pageIndex >= firstCachedPage && pageIndex < firstCachedPage + pageCache.size()) { final ByteBuffer buffer = pageCache.get((int) (pageIndex - firstCachedPage)); return buffer.array(); } final ByteBuffer buffer = ByteBuffer.allocate(OWALPage.PAGE_SIZE).order(ByteOrder.nativeOrder()); initFile(); segChannel.position(pageIndex * OWALPage.PAGE_SIZE); readByteBuffer(buffer, segChannel); return buffer.array(); } }
java
{ "resource": "" }
q173188
OWALSegmentCache.truncate
test
void truncate(long pageIndex) throws IOException { synchronized (lockObject) { lastAccessTime = System.nanoTime(); flushBuffer(); lastWrittenPageIndex = -1; lastWrittenPage = null; segChannel.truncate(pageIndex * OWALPage.PAGE_SIZE); } }
java
{ "resource": "" }
q173189
OWALSegmentCache.open
test
public void open() throws IOException { synchronized (lockObject) { lastAccessTime = System.nanoTime(); initFile(); long pagesCount = segChannel.size() / OWALPage.PAGE_SIZE; if (segChannel.size() % OWALPage.PAGE_SIZE > 0) { OLogManager.instance().error(this, "Last WAL page was written partially, auto fix", null); segChannel.truncate(OWALPage.PAGE_SIZE * pagesCount); } firstCachedPage = -1; pageCache.clear(); lastWrittenPage = null; lastWrittenPageIndex = -1; } }
java
{ "resource": "" }
q173190
ODistributedConfiguration.isReplicationActive
test
public boolean isReplicationActive(final String iClusterName, final String iLocalNode) { final Collection<String> servers = getClusterConfiguration(iClusterName).field(SERVERS); if (servers != null && !servers.isEmpty()) { return true; } return false; }
java
{ "resource": "" }
q173191
ODistributedConfiguration.getNewNodeStrategy
test
public NEW_NODE_STRATEGIES getNewNodeStrategy() { final String value = configuration.field(NEW_NODE_STRATEGY); if (value != null) return NEW_NODE_STRATEGIES.valueOf(value.toUpperCase(Locale.ENGLISH)); return NEW_NODE_STRATEGIES.STATIC; }
java
{ "resource": "" }
q173192
ODistributedConfiguration.isExecutionModeSynchronous
test
public Boolean isExecutionModeSynchronous(final String iClusterName) { Object value = getClusterConfiguration(iClusterName).field(EXECUTION_MODE); if (value == null) { value = configuration.field(EXECUTION_MODE); if (value == null) return null; } if (value.toString().equalsIgnoreCase("undefined")) return null; return value.toString().equalsIgnoreCase(EXECUTION_MODE_SYNCHRONOUS); }
java
{ "resource": "" }
q173193
ODistributedConfiguration.isReadYourWrites
test
public Boolean isReadYourWrites(final String iClusterName) { Object value = getClusterConfiguration(iClusterName).field(READ_YOUR_WRITES); if (value == null) { value = configuration.field(READ_YOUR_WRITES); if (value == null) { OLogManager.instance() .warn(this, "%s setting not found for cluster=%s in distributed-config.json", READ_YOUR_WRITES, iClusterName); return true; } } return (Boolean) value; }
java
{ "resource": "" }
q173194
ODistributedConfiguration.getServerClusterMap
test
public Map<String, Collection<String>> getServerClusterMap(Collection<String> iClusterNames, final String iLocalNode, final boolean optimizeForLocalOnly) { if (iClusterNames == null || iClusterNames.isEmpty()) iClusterNames = DEFAULT_CLUSTER_NAME; final Map<String, Collection<String>> servers = new HashMap<String, Collection<String>>(iClusterNames.size()); // TRY TO SEE IF IT CAN BE EXECUTED ON LOCAL NODE ONLY boolean canUseLocalNode = true; for (String p : iClusterNames) { final List<String> serverList = getClusterConfiguration(p).field(SERVERS); if (serverList != null && !serverList.contains(iLocalNode)) { canUseLocalNode = false; break; } } if (optimizeForLocalOnly && canUseLocalNode) { // USE LOCAL NODE ONLY (MUCH FASTER) servers.put(iLocalNode, iClusterNames); return servers; } // GROUP BY SERVER WITH THE NUMBER OF CLUSTERS final Map<String, Collection<String>> serverMap = new HashMap<String, Collection<String>>(); for (String p : iClusterNames) { final List<String> serverList = getClusterConfiguration(p).field(SERVERS); for (String s : serverList) { if (NEW_NODE_TAG.equalsIgnoreCase(s)) continue; Collection<String> clustersInServer = serverMap.get(s); if (clustersInServer == null) { clustersInServer = new HashSet<String>(); serverMap.put(s, clustersInServer); } clustersInServer.add(p); } } if (serverMap.size() == 1) // RETURN THE ONLY SERVER INVOLVED return serverMap; if (!optimizeForLocalOnly) return serverMap; // ORDER BY NUMBER OF CLUSTERS final List<String> orderedServers = new ArrayList<String>(serverMap.keySet()); Collections.sort(orderedServers, new Comparator<String>() { @Override public int compare(final String o1, final String o2) { return ((Integer) serverMap.get(o2).size()).compareTo((Integer) serverMap.get(o1).size()); } }); // BROWSER ORDERED SERVER MAP PUTTING THE MINIMUM SERVER TO COVER ALL THE CLUSTERS final Set<String> remainingClusters = new HashSet<String>(iClusterNames); // KEEPS THE REMAINING CLUSTER TO ADD IN FINAL // RESULT final Set<String> includedClusters = new HashSet<String>(iClusterNames.size()); // KEEPS THE COLLECTION OF ALREADY INCLUDED // CLUSTERS for (String s : orderedServers) { final Collection<String> clusters = serverMap.get(s); if (!servers.isEmpty()) { // FILTER CLUSTER LIST AVOIDING TO REPEAT CLUSTERS ALREADY INCLUDED ON PREVIOUS NODES clusters.removeAll(includedClusters); } servers.put(s, clusters); remainingClusters.removeAll(clusters); includedClusters.addAll(clusters); if (remainingClusters.isEmpty()) // FOUND ALL CLUSTERS break; } return servers; }
java
{ "resource": "" }
q173195
ODistributedConfiguration.getServers
test
public Set<String> getServers(Collection<String> iClusterNames) { if (iClusterNames == null || iClusterNames.isEmpty()) return getAllConfiguredServers(); final Set<String> partitions = new HashSet<String>(iClusterNames.size()); for (String p : iClusterNames) { final List<String> serverList = getClusterConfiguration(p).field(SERVERS); if (serverList != null) { for (String s : serverList) if (!s.equals(NEW_NODE_TAG)) partitions.add(s); } } return partitions; }
java
{ "resource": "" }
q173196
ODistributedConfiguration.isServerContainingAllClusters
test
public boolean isServerContainingAllClusters(final String server, Collection<String> clusters) { if (clusters == null || clusters.isEmpty()) clusters = DEFAULT_CLUSTER_NAME; for (String cluster : clusters) { final List<String> serverList = getClusterConfiguration(cluster).field(SERVERS); if (serverList != null) { if (!serverList.contains(server)) return false; } } return true; }
java
{ "resource": "" }
q173197
ODistributedConfiguration.isServerContainingCluster
test
public boolean isServerContainingCluster(final String server, String cluster) { if (cluster == null) cluster = ALL_WILDCARD; final List<String> serverList = getClusterConfiguration(cluster).field(SERVERS); if (serverList != null) { return serverList.contains(server); } return true; }
java
{ "resource": "" }
q173198
ODistributedConfiguration.getMasterServers
test
public List<String> getMasterServers() { final List<String> serverList = getClusterConfiguration(null).field(SERVERS); if (serverList != null) { // COPY AND REMOVE ANY NEW_NODE_TAG List<String> masters = new ArrayList<String>(serverList.size()); for (String s : serverList) { if (!s.equals(NEW_NODE_TAG)) masters.add(s); } final ROLES defRole = getDefaultServerRole(); final ODocument servers = configuration.field(SERVERS); if (servers != null) { for (Iterator<String> it = masters.iterator(); it.hasNext(); ) { final String server = it.next(); final String roleAsString = servers.field(server); final ROLES role = roleAsString != null ? ROLES.valueOf(roleAsString.toUpperCase(Locale.ENGLISH)) : defRole; if (role != ROLES.MASTER) it.remove(); } } return masters; } return Collections.EMPTY_LIST; }
java
{ "resource": "" }
q173199
ODistributedConfiguration.getAllConfiguredServers
test
public Set<String> getAllConfiguredServers() { final Set<String> servers = new HashSet<String>(); for (String p : getClusterNames()) { final List<String> serverList = getClusterConfiguration(p).field(SERVERS); if (serverList != null) { for (String s : serverList) if (!s.equals(NEW_NODE_TAG)) servers.add(s); } } return servers; }
java
{ "resource": "" }